package com.huigou.topsun.sap.fixedAssets.application.impl;

import com.huigou.cache.DictUtil;
import com.huigou.data.domain.model.CommonDomainConstants;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.sap.fixedAssets.application.SapFixedAssessApplication;
import com.huigou.topsun.sap.fixedAssets.application.SapFixedAssessItemApplication;
import com.huigou.topsun.sap.fixedAssets.domain.*;
import com.huigou.topsun.sap.fixedAssets.domain.query.SapFixedAssessQueryRequest;
import com.huigou.topsun.sap.fixedAssets.repository.*;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.util.ClassHelper;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;

/**
 * @Auther: Lxh
 * @Date: 2024/03/11/16:35
 * @Description:
 */
@Service("sapFixedAssessApplication")
public class SapFixedAssessApplicationImpl extends FlowBroker implements SapFixedAssessApplication {
    @Autowired
    private SapFixedAssessRepository sapFixedAssessRepository;
    @Autowired
    private SapFixedAssessItemApplication sapFixedAssessItemApplication;
    @Autowired
    private TmpFixedAssessDataRepository tmpFixedAssessDataRepository;

    @Override
    public Map<String, Object> getFixedAssessList(SapFixedAssessQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "sapFixedAssess");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        if (queryRequest.getStatus() != null) {
            queryModel.addCriteria(" and t.status =:status");
            queryModel.putParam("status", queryRequest.getStatus());
        }
        if (queryRequest.getBillCode() != null) {
            queryModel.addCriteria(" and t.bill_code =:billCode");
            queryModel.putParam("billCode", queryRequest.getBillCode());
        }
        if (queryRequest.getReason() != null) {
            queryModel.addCriteria(" and t.reason like:reason");
            queryModel.putLikeParam("reason", queryRequest.getReason());
        }
        queryModel.putDictionary("status", DictUtil.getDictionary("bizBillStatus"));
        queryModel.addCriteria(" order by bill_code desc ");
        Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        return map;
    }

    @Override
    public SapFixedAssess getFixedAssessById(String id) {
        return sapFixedAssessRepository.findOne(id);
    }

    @Override
    public void deleteByIds(List<String> ids) {
        ids.forEach(id->{
            sapFixedAssessRepository.delete(id);
        });
    }

    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
        SapFixedAssess fixedAssess = sapFixedAssessRepository.findOne(bizId);
        fixedAssess.setStatusId(status.getId());
        sapFixedAssessRepository.save(fixedAssess);
    }

    @Override
    protected void onAbortProcessInstance(DelegateExecution delegateExecution) {
        super.onAbortProcessInstance(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        SapFixedAssess fixedAssess = sapFixedAssessRepository.findOne(bizId);
        fixedAssess.setStatusId(BizBillStatus.ABORTED.getId());
        sapFixedAssessRepository.save(fixedAssess);
    }

    @Override
    protected void onBack(DelegateTask delegateTask, String destActivityId) {
        super.onBack(delegateTask, destActivityId);
        if ("Apply".equalsIgnoreCase(destActivityId)) {
            String bizId = delegateTask.getExecution().getProcessBusinessKey();
            SapFixedAssess fixedAssess = sapFixedAssessRepository.findOne(bizId);
            fixedAssess.setStatusId(BizBillStatus.APPLYING.getId());
            sapFixedAssessRepository.save(fixedAssess);
        }
    }

    @Override
    protected Map<String, Object> getProcessBizParams(String bizId) {
        return ClassHelper.toMap(sapFixedAssessRepository.getOne(bizId));
    }

    /**
     * 流程撤销事件
     **/
    @Override
    protected void onRecallProcessInstance(DelegateExecution delegateExecution) {
        String bizId = delegateExecution.getProcessBusinessKey();
        // 修改单据状态为申请
        updateStatus(bizId, BizBillStatus.APPLYING);
    }

    /**
     * 任务完成前执行
     */
    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (this.isApplyProcUnit(delegateTask) && this.getApprovalParameter().isAdvanceProcessAction()) {
            updateStatus(bizId, BizBillStatus.APPROVING);
        }
    }

    /**
     * 回收事件
     **/
    @Override
    protected void onWithdraw(DelegateTask delegateTask, String destActivityId) {
        super.onWithdraw(delegateTask, destActivityId);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (destActivityId.equalsIgnoreCase("apply")) {
            updateStatus(bizId, BizBillStatus.APPLYING);
        }
    }

    @Transactional
    private void updateStatus(String bizId, BizBillStatus status) {
        Assert.hasText(bizId, CommonDomainConstants.ID_NOT_BLANK);
        this.commonDomainService.updateStatus(SapFixedAssess.class, bizId, status.getId());
    }

    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        SapFixedAssess fixedAssess = getBizEntity(SapFixedAssess.class);
        if (fixedAssess.isNew()) {
            fixedAssess.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            fixedAssess = (SapFixedAssess) commonDomainService.loadAndFillinProperties(fixedAssess);
        }
        fixedAssess = sapFixedAssessRepository.save(fixedAssess);
        List<SapFixedAssessItem> items = getBizEntities(SapFixedAssessItem.class, "items");
        sapFixedAssessItemApplication.saveSapFixedAssessItems(fixedAssess.getId(),items);
        //更新附件ID为主键ID
//        if (!(fixedAssess.getId().equals(fixedAssess.getAttbizId()))) {
//            List<Attachment> attachmentList = attachmentApplication.queryAttachments("sapAssessInfo", fixedAssess.getAttbizId());
//            for (Attachment attachment : attachmentList) {
//                attachment.setBizId(fixedAssess.getId());
//                attachmentApplication.saveAttachment(attachment);
//            }
//        }
        return fixedAssess.getId();
    }


    @Override
    public  List<TmpFixedAssessData>   importExcelData(String batchNumber)  {
      List<TmpFixedAssessData>  dataList=tmpFixedAssessDataRepository.findByBatchNumber(batchNumber);
      /*try {
         if (dataList.size()>0){
              SapAssess fixedAssess = new SapAssess();
              fixedAssess.setReason("导入");
              fixedAssess.setStatusId(3);
              fixedAssess.setFillinDate(new Date());
              Operator operator = getOperator();
              fixedAssess.setDefaultValues(new OrgUnit(operator.getFullId(), operator.getFullName()));
              // String billCode= codeRuleApplication.getNextCode("","sapAssess","");

              Object codeGenerator = ApplicationContextWrapper.getBean("codeGenerator");
              Method method = codeGenerator.getClass().getMethod("getNextCode", new Class[]{String.class});
              String code = (String) method.invoke(codeGenerator, new Object[]{"sapAssess"});
              fixedAssess.setBillCode(code);
              sapFixedAssessRepository.save(fixedAssess);
              for (TmpFixedAssessData data : dataList) {
                  SapAssessItem sapAssessItem = new SapAssessItem();
                  ClassHelper.copyProperties(data, sapAssessItem);
                  sapAssessItem.setSapAssessId(fixedAssess.getId());
                  sapFixedAssessItemRepository.save(sapAssessItem);
              }
          }
      }catch(Exception ex){
          ex.printStackTrace();
      }*/
      return dataList;
    }
}
