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

import com.huigou.cache.DictUtil;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.base.coderule.application.CodeRuleApplication;
import com.huigou.topsun.sap.fixedAssets.application.SapFixedAssetsMoveApplication;
import com.huigou.topsun.sap.fixedAssets.application.SapFixedAssetsMoveItemApplication;
import com.huigou.topsun.sap.fixedAssets.application.SapFixedRetirementApplication;
import com.huigou.topsun.sap.fixedAssets.application.SapFixedRetirementItemApplication;
import com.huigou.topsun.sap.fixedAssets.domain.*;
import com.huigou.topsun.sap.fixedAssets.domain.query.SapFixedAssetsMoveQueryRequest;
import com.huigou.topsun.sap.fixedAssets.domain.query.SapFixedRetirementQueryRequest;
import com.huigou.topsun.sap.fixedAssets.repository.SapFixedAssetsMoveRepository;
import com.huigou.topsun.sap.fixedAssets.repository.SapFixedRetirementItemRepository;
import com.huigou.topsun.sap.fixedAssets.repository.SapFixedRetirementRepository;
import com.huigou.topsun.sap.fixedAssets.repository.TmpFixedRetirementDataRepository;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.doc.attachment.application.AttachmentApplication;
import com.huigou.uasp.bmp.doc.attachment.domain.model.Attachment;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.util.ApplicationContextWrapper;
import com.huigou.util.ClassHelper;
import com.huigou.util.DateUtil;
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 java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther: Lxh
 * @Date: 2024/03/08/16:35
 * @Description:
 */
@Service("sapFixedRetirementApplication")
public class SapFixedRetirementApplicationImpl extends FlowBroker implements SapFixedRetirementApplication {
    @Autowired
    private SapFixedRetirementRepository sapFixedRetirementRepository;
    @Autowired
    private SapFixedRetirementItemApplication sapFixedRetirementItemApplication;
    @Autowired
    private TmpFixedRetirementDataRepository tmpFixedRetirementDataRepository;
    @Autowired
    private SapFixedRetirementItemRepository sapFixedRetirementItemRepository;
    @Autowired
    private AttachmentApplication attachmentApplication;
    @Autowired
    private CodeRuleApplication codeRuleApplication;
    @Override
    public Map<String, Object> getFixedRetirementList(SapFixedRetirementQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "sapFixedRetirement");
        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 SapRetirement getFixedRetirementById(String id) {
        return sapFixedRetirementRepository.findOne(id);
    }

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

    /**
     * 设置任务名称
     */
    @Override
    protected void setTaskDescription(DelegateTask delegateTask) {
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        delegateTask.setDescription(this.getApprovalSubjectName(bizId));
    }

    /**
     * 获取任务标题
     *
     * @param bizId
     * @return
     */
    private String getApprovalSubjectName(String bizId) {
        SapRetirement sapRetirement = this.sapFixedRetirementRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", sapRetirement.getFillinDate());
        //设置标题
        return String.format("%s-%s(%s)", "资产报废及处置", sapRetirement.getBillCode(), fillinDateStr);
    }

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

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

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

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

    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        SapRetirement fixedRetirement = getBizEntity(SapRetirement.class);
        if (fixedRetirement.isNew()) {
            fixedRetirement.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            fixedRetirement = (SapRetirement) commonDomainService.loadAndFillinProperties(fixedRetirement);
        }
        fixedRetirement = sapFixedRetirementRepository.save(fixedRetirement);
        List<SapRetirementItem> items = getBizEntities(SapRetirementItem.class, "items");
        sapFixedRetirementItemApplication.saveSapFixedRetirementItems(fixedRetirement.getId(),items);
        //更新附件ID为主键ID
//        if (!(fixedRetirement.getId().equals(fixedRetirement.getAttbizId()))) {
//            List<Attachment> attachmentList = attachmentApplication.queryAttachments("sapRetirementInfo", fixedRetirement.getAttbizId());
//            for (Attachment attachment : attachmentList) {
//                attachment.setBizId(fixedRetirement.getId());
//                attachmentApplication.saveAttachment(attachment);
//            }
//        }
        return fixedRetirement.getId();
    }


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

              Object codeGenerator = ApplicationContextWrapper.getBean("codeGenerator");
              Method method = codeGenerator.getClass().getMethod("getNextCode", new Class[]{String.class});
              String code = (String) method.invoke(codeGenerator, new Object[]{"sapRetirement"});
              fixedRetirement.setBillCode(code);
              sapFixedRetirementRepository.save(fixedRetirement);
              for (TmpFixedRetirementData data : dataList) {
                  SapRetirementItem sapRetirementItem = new SapRetirementItem();
                  ClassHelper.copyProperties(data, sapRetirementItem);
                  sapRetirementItem.setSapRetirementId(fixedRetirement.getId());
                  sapFixedRetirementItemRepository.save(sapRetirementItem);
              }
          }
      }catch(Exception ex){
          ex.printStackTrace();
      }*/
      return dataList;
    }
}
