global without sharing class TransferApplyWebService {
    public TransferApplyWebService() {

    }

    @AuraEnabled
    WebService static String submitApply(String taId) {
        List<TransferApply__c> taList = [
            SELECT Id
                 , Status__c
                 , Add_Approval_Status__c
                 , RecordType.DeveloperName //20201202 ljh add
                 , BeiPinWindow__c //20201202 ljh add
                 , Add_Reason__c // 20210429 1831 you
             FROM TransferApply__c
            WHERE Id = :taId
              FOR UPDATE
        ];

        if (taList.isEmpty()) {
            return '调拨单不存在。';
        }
        TransferApply__c ta = taList[0];
        if(ta.Status__c != '草案中' && ta.Add_Approval_Status__c != '草案中'){
            return '请确认调拨单状态，没有待审批的明细，不能提交';
        }
        List<String> errorList = checkTransferCount(ta.Id);
        if(!errorList.isEmpty()) {
            return String.join(errorList, '\n');
        }
        if(ta.Status__c == '草案中') {

            ta.Status__c = '填写完毕';
        }
        else {
            
            // 20210429 1831 you start
            if(ta.Add_Approval_Status__c == '草案中' && String.isBlank(ta.Add_Reason__c) ){
                return '没有填写追加理由，不能提交';
            }else {// 20210429 1831 you end
        
                ta.Add_Approval_Status__c = '填写完毕';
            }
        }
        //20201202 ljh OCSM_BP5-76 add start
        if(ta.RecordType.DeveloperName == 'AgencyToCenter' && ta.BeiPinWindow__c == null){
            return '请确认审批人，没有审批人（备品总窗口），不能提交';
        }
        //20201202 ljh OCSM_BP5-76 add end
        Savepoint sp = Database.setSavepoint();
        try {
            update ta;
        }
        catch (Exception e) {
            Database.rollback(sp);
            return e.getMessage();
        }
        return '1';
    }
    public static List<String> checkTransferCount(Id taId) {
        List<TransferApplyDetail__c> tadList =  [
            SELECT Id
                 , Asset__r.Ji_Zhong_Guan_Li_Ku_Cun__c
                 , Asset__r.TransferableAbandon_F__c
                 , Asset__r.TransferableRepair_F__c
                 , Asset__r.TransferableLost_F__c
                 , Asset__r.Name
                 , Asset__c
                 , Approved_F__c
                 , TransferType__c
                 , OneToOneAccessory__c
            FROM TransferApplyDetail__c
            WHERE TransferApply__c=:taId
                AND Cancel_Select__c = false
        ];

        Map<Id, Integer> assCountMap = new Map<Id, Integer>(); // assetId->有效库存
        Map<Id, Integer> assetAbanCntMap = new Map<Id, Integer>(); // 非一对一附属品待废弃数统计，保有设备Id->待废弃调拨数量
        Map<Id, Integer> assetRepairCntMap = new Map<Id, Integer>(); // 非一对一附属品待废弃数统计，保有设备Id->待废弃调拨数量
        Map<Id, Integer> assetLostCntMap = new Map<Id, Integer>(); // 非一对一附属品待废弃数统计，保有设备Id->待废弃调拨数量

        Boolean needApprove = false;
        for(TransferApplyDetail__c tad: tadList) {
            if(!tad.Approved_F__c && !tad.OneToOneAccessory__c) {
                Integer cnt = 0;
                if(tad.TransferType__c == '待废弃') {
                    if(assetAbanCntMap.containsKey(tad.Asset__c)){
                        cnt = assetAbanCntMap.get(tad.Asset__c);
                    }
                    cnt += 1;
                    assetAbanCntMap.put(tad.Asset__c, cnt);
                }
                else if(tad.TransferType__c == '待修理'){
                    if(assetRepairCntMap.containsKey(tad.Asset__c)){
                        cnt = assetRepairCntMap.get(tad.Asset__c);
                    }
                    cnt += 1;
                    assetRepairCntMap.put(tad.Asset__c, cnt);
                }
                else if(tad.TransferType__c == '丢失找回'){
                    if(assetLostCntMap.containsKey(tad.Asset__c)){
                        cnt = assetLostCntMap.get(tad.Asset__c);
                    }
                    cnt += 1;
                    assetLostCntMap.put(tad.Asset__c, cnt);
                }
                else {
                    if(assCountMap.containsKey(tad.Asset__c)) {
                        cnt = assCountMap.get(tad.Asset__c);
                    }
                    cnt += 1;
                    assCountMap.put(tad.Asset__c, cnt);
                }
                if(!tad.Approved_F__c) {
                    needApprove = true;
                }
            }
        }
        Set<String> errorList = new Set<String>();
        if(!needApprove) {
            errorList.add('没有需要审批的明细！');
        }
        for(TransferApplyDetail__c tad: tadList) {
            if(assCountMap.containsKey(tad.Asset__c)
                && assCountMap.get(tad.Asset__c) > intValueOf(tad.Asset__r.Ji_Zhong_Guan_Li_Ku_Cun__c)) {
                String msg = tad.Asset__r.Name;
                msg += '：有效库存=' +  intValueOf(tad.Asset__r.Ji_Zhong_Guan_Li_Ku_Cun__c);
                msg += '，调拨数量=' + assCountMap.get(tad.Asset__c) ;
                msg += '，请确认数量后提交';
                errorList.add(msg);
            }
            if(assetRepairCntMap.containsKey(tad.Asset__c)
                && assetRepairCntMap.get(tad.Asset__c) > intValueOf(tad.Asset__r.TransferableRepair_F__c)) {
                String msg = tad.Asset__r.Name;
                msg += '：可调拨数_待修理=' +  intValueOf(tad.Asset__r.TransferableRepair_F__c);
                msg += '，待修理调拨数量=' + assetRepairCntMap.get(tad.Asset__c) ;
                msg += '，请确认数量后提交';
                errorList.add(msg);
            }
            if(assetAbanCntMap.containsKey(tad.Asset__c)
                && assetAbanCntMap.get(tad.Asset__c) > intValueOf(tad.Asset__r.TransferableAbandon_F__c)) {
                String msg = tad.Asset__r.Name;
                msg += '：可调拨数_待废弃=' + intValueOf(tad.Asset__r.TransferableAbandon_F__c);
                msg += '，待废弃调拨数量=' + assetAbanCntMap.get(tad.Asset__c);
                msg += '，请确认数量后提交';
                errorList.add(msg);
            }
            if(assetLostCntMap.containsKey(tad.Asset__c)
                && assetLostCntMap.get(tad.Asset__c) > intValueOf(tad.Asset__r.TransferableLost_F__c)) {
                String msg = tad.Asset__r.Name;
                msg += '：可调拨数_丢失找回=' + intValueOf(tad.Asset__r.TransferableLost_F__c);
                msg += '，待废弃调拨数量=' + assetLostCntMap.get(tad.Asset__c);
                msg += '，请确认数量后提交';
                errorList.add(msg);
            }
        }
        return new List<String>(errorList);
    }

    @AuraEnabled
    WebService static String cancelApply(Id taId) {
        List<TransferApply__c> taList = [
            SELECT Id
                 , Add_Approval_Status__c
                 , Cancel_Reason__c
                 , OwnerId
                 , Status__c
                 , TA_Status__c
                 , Yi_loaner_arranged__c
                 , RecordType.DeveloperName
                 , Request_approval_time__c
             FROM TransferApply__c
            WHERE Id = :taId
              FOR UPDATE
        ];
        
        if (taList.isEmpty()) {
            return '调拨单不存在。';
        }
        TransferApply__c ta = taList[0];
        if(ta.Status__c == '取消') {
            return '已经取消，不能再次取消';
        }
        if(ta.Status__c == '申请中' || ta.Add_Approval_Status__c == '申请中'){
            return '申请中不能取消';
        }
        if(ta.RecordType.DeveloperName == 'InsideCenter' && ta.Request_approval_time__c != null) {
            return '同备品中心内调拨在最终批准之后不可以取消';
        }
        if(ta.TA_Status__c == '已出库' || ta.Yi_loaner_arranged__c > 0) {
            return '已经出库，不能取消';
        }
        if(UserInfo.getUserId() != ta.OwnerId) {
            return '仅创建者可以取消';
        }
        if(String.isBlank(ta.Cancel_Reason__c)) {
            return '必须输入取消理由';
        }
        Savepoint sp = Database.setSavepoint();
        try {
            ta.Status__c = '取消';
            update ta;
        }
        catch (Exception e) {
            Database.rollback(sp);
            return e.getMessage();
        }
        return '1';
    }
    private static Integer intValueOf(Decimal d) {
        if(d == null) {
            return 0;
        }
        return Integer.valueOf(d);
    }
}