package com.sifang.modules.flowpath.service;

import com.jfinal.plugin.activerecord.Record;
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.DistributionGoodsApplyDao;
import com.sifang.modules.flowpath.entity.DistributionGoodsApply;
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.util.CrmUtils;
import org.flowable.engine.TaskService;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.LayuiPage;
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.List;
import java.util.Map;


//授信额调整申请
@Service
@Transactional(readOnly = true)
public class DistributionGoodsApplyService  extends BaseService {

    @Autowired
    private DistributionGoodsApplyDao goodsApplyDao;

    @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())) {
            //平台人员
            //获取当前人员所负责代理商
            Record rd = CrmUtils.getByUserId(user);
            String trader_id = rd.getStr("trader_id");
            if (StringUtil.isNotBlank(trader_id)) {
                map.put("traderId", trader_id);
            }
        }
        map.put("traderId",traderId);
        goodsApplyDao.applyList(page,map,user);
    }

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

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

    @Transactional(rollbackFor = Exception.class)
    public void saveDistributionGoods(DistributionGoodsVo vo){
        logger.info(">>>>>>>>>>>>>>>saveDistributionGoods  vo:{}",vo);
        User user = UserUtils.getUser();
        String userName= user.getUserName();
        Date date=new Date();
        DistributionGoodsApply apply;
        if(StringUtil.isBlank(vo.getId())){
            apply=new DistributionGoodsApply();
            apply.setApplyNumber(PlantformUtils.getOrderNumber());
            apply.setDepartmentId(user.getDepartmentId());
            apply.setDepartmentName(user.getDepartmentName());
        }else{
            apply=goodsApplyDao.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());
        apply.setCreateBy(user.getId());
        apply.setCreateName(userName);
        apply.setCreateTime(date);


        if(StringUtil.isBlank(vo.getId())){
            apply.setId(IdGen.uuid());
            Record rd = FormUtils.getdefLatest(FormUtils.DISTRIBUTION_ADJUSTMENT_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.DISTRIBUTION_ADJUSTMENT_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);
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>processInstanceId:{},taskName:{}",processInstanceId,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.DISTRIBUTION_ADJUSTMENT_APPLICATION);
        }
        apply.setStatus(BondApplyConstant.APPLYSTATUS_ONE);
        goodsApplyDao.save(apply);
    }

    //删除申请
    @Transactional(rollbackFor = Exception.class)
    public void deleteDistributionGoodsApply(String id){
        logger.info(">>>>>>>>>>>>>deleteDistributionGoodsApply  id:{}",id);
        User user = UserUtils.getUser();
        String userName= user.getUserName();
        //修改申请状态
        DistributionGoodsApply apply=goodsApplyDao.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);
        goodsApplyDao.save(apply);
        //删除流程
        flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),userName,apply.getStatus(),FormUtils.DISTRIBUTION_ADJUSTMENT_APPLICATION);
    }

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

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