package com.sifang.modules.flowpath.service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.utils.CustomerEntryUtil;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.constant.BondApplyConstant;
import com.sifang.modules.flowpath.dao.SubpackageStandardPriceApplyDao;
import com.sifang.modules.flowpath.vo.SubpackageVo;
import com.sifang.modules.flowpath.vo.TimeRange;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.SubconractorSettlementSchemeDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSubconractorSettlementScheme;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSubconractorSettlementSchemeApply;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

//分包保准价申请
@Service
public class SubpackageStandardPriceApplyService extends BaseService {

    @Autowired
    private SubpackageStandardPriceApplyDao standardPriceApplyDao;


    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    TaskService taskService;

    @Autowired
    private SubconractorSettlementSchemeDao schemeDao;

    public void applyList(LayuiPage<Record> page, Map<String, String> map){
        User user=UserUtils.getUser();
        standardPriceApplyDao.applyList(page,map,user);
    }

    public Record getDetailById(String id){
        return standardPriceApplyDao.getDetailById(id);
    }

    public List<Record> getApplyItems(String applyId){
        return standardPriceApplyDao.getApplyItems(applyId);
    }

    //查找没有关联方案的项目
    public List<Record> getProjectName(){
        return standardPriceApplyDao.getProjectName();
    }

    //编辑的时候(除了没有关联方案的项目，还有本申请里面的项目)
    public List<Record> getProjectNameByApply(String applyId){
        return standardPriceApplyDao.getProjectNameByApply(applyId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void  saveStandardPriceApply(SubpackageVo vo){
        logger.info(">>>>>>>>>>saveStandardPriceApply apply:{},size:{}",vo.getId(),vo.getItems().size());
        User user = UserUtils.getUser();
        String userName=user.getUserName();
        Date date=new Date();
        CrmSubconractorSettlementSchemeApply schemeApply;
        if(StringUtil.isBlank(vo.getId())){
            schemeApply=new CrmSubconractorSettlementSchemeApply();
            schemeApply.setId(IdGen.uuid());
            schemeApply.setApplyNumber(PlantformUtils.getOrderNumber());
            schemeApply.setCreateBy(user.getId());
            schemeApply.setCreateName(userName);
            schemeApply.setCreateTime(date);
            schemeApply.setSubmitTime(date);
            schemeApply.setDepartmentId(user.getDepartmentId());
            schemeApply.setDepartmentName(user.getDepartmentName());
        }else {
            schemeApply=standardPriceApplyDao.getByApplyId(vo.getId());
            if(StringUtil.equalsAny(schemeApply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
                throw new RuntimeException("该申请状态不允许修改!");
            }

        }
        schemeApply.setRemarks(vo.getRemarks());

        //已经申请过的项目
        //List<Record> projects=standardPriceApplyDao.getProjectAsApprove(vo.getId());
        List<CrmSubconractorSettlementScheme> items= vo.getItems();
        for(CrmSubconractorSettlementScheme scheme:items){
            //String projectId=scheme.getProjectIds();
            /*List<String> ids= Arrays.asList(projectId.split(","));
            List<String> trIds=null;
            if(StringUtil.isNotBlank(scheme.getTraderIds())){
               trIds = Arrays.asList(scheme.getTraderIds().split(","));
            }*/
            //for(String id:ids){
                /*for(Record r:projects){
                    if(ids.contains(r.getStr("id"))){
                        //判断时间区间
                        TimeRange time1 = new TimeRange(scheme.getCreateTime(),scheme.getEndTime());
                        TimeRange time2 = new TimeRange(r.getDate("create_time"),r.getDate("end_time"));
                        if(time1.isOverlap(time2) ){
                            if(StringUtil.isBlank(r.getStr("trader_ids"))&& StringUtil.isBlank(scheme.getTraderIds())){
                                //时间有重叠 且只适用产品
                                throw new RuntimeException(r.getStr("name")+" 该项目已设置过结算方案，请勿重复设置！");
                            } else if(trIds!= null && trIds.contains(r.getStr("trader_ids"))){
                                throw new RuntimeException(r.getStr("name")+" 该项目已设置过适用代理商结算方案，请勿重复设置！");
                            }
                        }
                    }

           //     }
            }*/
            scheme.setApplyId(schemeApply.getId());
          //  scheme.setCreateTime(date);
            scheme.setStatus("0");
            Long maxVersion=schemeDao.getMaxVersion();
            logger.info(">>>>>>saveCrmSubconractorSettlementScheme  maxVersion:{}",maxVersion);
            String number= CustomerEntryUtil.addZero2(maxVersion+1);
            logger.info(">>>>>>saveCrmSubconractorSettlementScheme  number:{}",number);
            scheme.setNumber(number);
            scheme.setVersion(maxVersion+1);
        }
        if(StringUtil.isBlank(vo.getId())){
            Record rd = FormUtils.getdefLatest(FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION);
            if(rd == null){
                throw  new RuntimeException("流程未定义，不可发布申请");
            }
            String processName="分包标准价申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss");
            String processInstanceId=flowableService.startProcessFlowable(user,schemeApply.getId(),rd,FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION,date,userName,vo.getRemarks(),processName,"");
            logger.info(">>>>>>>>>>>>>>>>>>>>>saveStandardPriceApply  processInstanceId:{}",processInstanceId);
            schemeApply.setProcessInstanceId(processInstanceId);
            schemeApply.setProcessDefId(rd.getStr("id"));

            schemeApply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
            String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
            schemeApply.setTaskName(taskName);

            logger.info(">>>>>>>>>>>>>>>saveStandardPriceApply>>>>>>>>processInstanceId:{},taskName:{}",processInstanceId,taskName);
        }else if(StringUtil.isNotBlank(schemeApply.getProcessInstanceId())){
            Task task = taskService.createTaskQuery().processInstanceId(schemeApply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
            flowableService.approveTask2(task,"编辑后提交",schemeApply.getId(),user, FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION);
        }
        schemeApply.setStatus(BondApplyConstant.APPLYSTATUS_ONE);
        standardPriceApplyDao.save(schemeApply);
        //删除之前保存的
        schemeDao.deleteShame(schemeApply.getId());
        schemeDao.save(items);
    }

    //删除申请
    @Transactional(rollbackFor = Exception.class)
    public void deleteStandardPriceApply(String id){
        logger.info(">>>>>>>>>>>>>deleteStandardPriceApply  id:{}",id);
        User user = UserUtils.getUser();
        String userName= user.getUserName();
        //修改申请状态
        CrmSubconractorSettlementSchemeApply apply=standardPriceApplyDao.getByApplyId(id);
        if(StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
            throw new RuntimeException("申请状态不允许删除!");
        }
        apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
        standardPriceApplyDao.save(apply);
        //删除关联的结算价方案
        schemeDao.deleteShame(apply.getId());
        //删除流程
        flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),userName,apply.getStatus(),FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION);
    }

    //审核通过
    @Transactional(rollbackFor = Exception.class)
    public void examineStandardPriceApplyApprove(String id,String taskId,String content){
        logger.info(">>>>>>>>>>>>>examineStandardPriceApplyApprove  id:{},task:{}",id,taskId);
        User user = UserUtils.getUser();
        CrmSubconractorSettlementSchemeApply apply=standardPriceApplyDao.getByApplyId(id);
        Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.approveTask2(task,content,apply.getId(),user, FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION);
    }

    //驳回
    @Transactional(rollbackFor = Exception.class)
    public void rejectStandardPriceApplyTask(String id,String taskId,String content){
        logger.info(">>>>>>>>>>>>>rejectStandardPriceApplyTask  id:{},task:{}",id,taskId);
        User user = UserUtils.getUser();
        CrmSubconractorSettlementSchemeApply apply=standardPriceApplyDao.getByApplyId(id);
        apply.setContent(content);
        apply.setExamineOpinion(content);
        standardPriceApplyDao.save(apply);

        Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.rejectTask2(task,content,id,user,FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION,apply.getCreateBy());

    }

}
