package com.sifang.modules.flowpath.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
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.BondLimitApplyDao;
import com.sifang.modules.flowpath.entity.BondLimitApply;
import com.sifang.modules.flowpath.vo.BondLimitApplyVo;
import com.sifang.modules.platform.utils.PlantformUtils;
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.common.utils.StringUtil;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

@Component
public class BondLimitApplyService extends BaseService {

    @Autowired
    private BondLimitApplyDao bondLimitApplyDao;

    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    TaskService taskService;

    //列表数据
    public void applyList(LayuiPage<Record> page, Map<String, String> map){
        User user= UserUtils.getUser();
        String traderId = "";
        if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            //平台人员
            EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
        }
        map.put("traderIds",traderId);
        bondLimitApplyDao.applyList(page,map,user);
    }

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

    @Transactional(rollbackFor = Exception.class)
    public void saveBondLimitApply(BondLimitApplyVo vo){
       logger.info(">>>>>>>>>>>>saveBondLimitApply  vo:{}",vo);
       User user=UserUtils.getUser();
       Date date=new Date();
       BondLimitApply apply;
       if(StringUtil.isBlank(vo.getId())){
           apply=new BondLimitApply();
           apply.setApplyNumber(PlantformUtils.getOrderNumber());
           apply.setDepartmentId(user.getDepartmentId());
           apply.setDepartmentName(user.getDepartmentName());
       }else {
           apply=bondLimitApplyDao.getByApplyId(vo.getId());
           if(StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
               throw new RuntimeException("该申请状态不允许修改!");
           }
       }
        apply.setTraderId(vo.getTraderId());
        apply.setAmount(vo.getAmount());
        apply.setOldAmount(vo.getOldAmount());
        apply.setRemarks(vo.getRemarks());
        apply.setCreateBy(user.getId());
        apply.setCreateName(user.getUserName());
        apply.setCreateTime(date);

        if(StringUtil.isBlank(vo.getId())){
            apply.setId(IdGen.uuid());
            Record rd = FormUtils.getdefLatest(FormUtils.BOND_LIMIT_APPLY);
            if(rd == null){
                throw  new RuntimeException("流程未定义，不可发布申请");
            }
            String traderName=CrmUtils.getTraderNameById(apply.getTraderId());
            String processName="保证金额度申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss")+"("+traderName+")";
            String processInstanceId=flowableService.startProcessFlowable(user,apply.getId(),rd,FormUtils.BOND_LIMIT_APPLY,date,user.getUserName(),vo.getRemarks(),processName,apply.getTraderId());
            apply.setProcessInstanceId(processInstanceId);
            apply.setProcessDefId(rd.getStr("id"));
            String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
            apply.setTaskName(taskName);
            apply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
            logger.info(">>>>>>>>>>>>>>saveBondAdjustApply>>>>>>>>>taskName:{}",taskName);
        }else if(com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.isNotBlank(apply.getProcessInstanceId())){
            Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
            flowableService.approveTask2(task,"编辑后提交",apply.getId(),user, FormUtils.BOND_LIMIT_APPLY);
        }
        apply.setStatus(BondApplyConstant.APPLYSTATUS_ONE);
        bondLimitApplyDao.save(apply);
    }

    public List<Record> getTrader(){
        //获取代理商
        User user = UserUtils.getUser();
        //获取用户关联的代理商
        List<Record> list=bondLimitApplyDao.getTrader(user);
        return list;
    }

    //删除申请
    @Transactional(rollbackFor = Exception.class)
    public void deleteBondLimitApply(String id){
      logger.info(">>>>>>>>>>>>deleteBondLimitApply id:{}",id);
      User user=UserUtils.getUser();
      BondLimitApply apply= bondLimitApplyDao.getByApplyId(id);
        if(StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
            throw new RuntimeException("申请状态不允许删除!");
        }

        apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
        bondLimitApplyDao.save(apply);
        //删除流程
        flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),user.getUserName(),apply.getStatus(),FormUtils.BOND_LIMIT_APPLY);
    }

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

    //驳回
    public void rejectBondLimitApplyApprove(String id,String content){
        logger.info(">>>>>>>>>>>>>>rejectBondLimitApplyApprove id:{},content:{}",id,content);
        User user=UserUtils.getUser();
        BondLimitApply apply= bondLimitApplyDao.getByApplyId(id);
        /*apply.setStatus(BondApplyConstant.APPLYSTATUS_TWO);*/
        apply.setContent(content);
        apply.setExamineOpinion(content);
        bondLimitApplyDao.save(apply);
        Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.rejectTask2(task,content,id,user,FormUtils.BOND_LIMIT_APPLY,apply.getCreateBy());
    }

}
