package com.sifang.modules.flowpath.service;


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.WarrantyDepositAdjustmentApplyDao;
import com.sifang.modules.flowpath.entity.WarrantyDepositAdjustmentApply;
import com.sifang.modules.flowpath.vo.DistributionGoodsVo;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
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 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.Date;
import java.util.Map;

// 质保金调整申请
@Service
public class WarrantyDepositAdjustmentApplyService extends BaseService {

    @Autowired
    private WarrantyDepositAdjustmentApplyDao adjustmentApplyDao;


    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    TaskService taskService;

    @Autowired
    TraderService traderService;

    // 质保金调整申请
    public void applyList(LayuiPage<Record> page, Map<String, String> map){
        User user=UserUtils.getUser();
        String traderId="";
        if (User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())) {  //代理商
            traderId = CrmUtils.getUserRelId(user);
        }else if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            //平台人员
            EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
        }
        map.put("traderId",traderId);
        adjustmentApplyDao.applyList(page,map,user);
    }


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


    @Transactional(rollbackFor = Exception.class)
    public void saveWarrantyDeposit(DistributionGoodsVo vo){
        logger.info(">>>>>>>>>>>>>>>saveWarrantyDeposit  vo:{}",vo);
        User user = UserUtils.getUser();
        String userName=user.getUserName();
        Date date=new Date();
        WarrantyDepositAdjustmentApply apply;
        if(StringUtil.isBlank(vo.getId())){
            apply=new WarrantyDepositAdjustmentApply();
            apply.setApplyNumber(PlantformUtils.getOrderNumber());
            apply.setCreateBy(user.getId());
            apply.setCreateName(userName);
            apply.setCreateTime(date);
            apply.setSubmitTime(date);
            apply.setDepartmentId(user.getDepartmentId());
            apply.setDepartmentName(user.getDepartmentName());
        }else{
            apply=adjustmentApplyDao.getByApplyId(vo.getId());
            if(com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
                throw new RuntimeException("该申请状态不允许修改!");
            }
        }
        apply.setTraderId(vo.getTraderId());
        apply.setAdjustType(vo.getAdjustType());
        apply.setAmount(vo.getAmount());
        apply.setVoucher(vo.getVoucher());
        apply.setRemarks(vo.getRemarks());

        if(StringUtil.isBlank(vo.getId())){
            apply.setId(IdGen.uuid());
            Record rd = FormUtils.getdefLatest(FormUtils.WITHDRAWAL_WARRANTY_APPLICATION);
            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.WITHDRAWAL_WARRANTY_APPLICATION,date,userName,vo.getRemarks(),processName,apply.getTraderId());
            apply.setProcessInstanceId(processInstanceId);
            apply.setProcessDefId(rd.getStr("id"));
            apply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));
            String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
            apply.setTaskName(taskName);
        }else if(StringUtil.isNotBlank(apply.getProcessInstanceId())){
            Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
            flowableService.approveTask2(task,"编辑后提交",apply.getId(),user, FormUtils.WITHDRAWAL_WARRANTY_APPLICATION);
        }
        apply.setStatus(BondApplyConstant.APPLYSTATUS_ONE);
        adjustmentApplyDao.save(apply);
    }


    //删除申请
    @Transactional(rollbackFor = Exception.class)
    public void deleteWarrantyDepositApply(String id){
        logger.info(">>>>>>>>>>>>>deleteWarrantyDepositApply  id:{}",id);
        User user = UserUtils.getUser();
        String userName= user.getUserName();
        //修改申请状态
        WarrantyDepositAdjustmentApply apply=adjustmentApplyDao.getByApplyId(id);
        if(com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
            throw new RuntimeException("申请状态不允许删除!");
        }
        apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
        adjustmentApplyDao.save(apply);
        //删除流程
        flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),userName,apply.getStatus(),FormUtils.WITHDRAWAL_WARRANTY_APPLICATION);
    }

    //审核通过
    @Transactional(rollbackFor = Exception.class)
    public void examineWarrantyDepositApprove(String id,String taskId,String content){
        logger.info(">>>>>>>>>>>>>examineWarrantyDepositApprove  id:{},task:{}",id,taskId);
        User user = UserUtils.getUser();
        WarrantyDepositAdjustmentApply apply=adjustmentApplyDao.getByApplyId(id);
        /*apply.setExamineOpinion(content);
        apply.setOperateUserIds(apply.getOperateUserIds()+","+user.getId());
        adjustmentApplyDao.save(apply);*/
        Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.approveTask2(task,content,apply.getId(),user, FormUtils.WITHDRAWAL_WARRANTY_APPLICATION);
    }

    //驳回
    @Transactional(rollbackFor = Exception.class)
    public void rejectWarrantyDepositTask(String id,String taskId,String content){
        logger.info(">>>>>>>>>>>>>rejectWarrantyDepositTask  id:{},task:{}",id,taskId);
        User user = UserUtils.getUser();
        WarrantyDepositAdjustmentApply apply=adjustmentApplyDao.getByApplyId(id);
        apply.setContent(content);
        adjustmentApplyDao.save(apply);
        Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.rejectTask2(task,content,id,user,FormUtils.WITHDRAWAL_WARRANTY_APPLICATION,apply.getCreateBy());
    }

    @Transactional(rollbackFor = Exception.class)
    public void readApplication(String processInstanceId,String formId,String applicationId,User user){
        flowableService.readApplication(processInstanceId,formId,applicationId,user);
    }
}
