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.PriceCoefficientApplyDao;
import com.sifang.modules.flowpath.entity.BondApply;
import com.sifang.modules.flowpath.entity.PriceCoefficientApply;
import com.sifang.modules.flowpath.vo.DistributionGoodsVo;
import com.sifang.modules.flowpath.vo.PriceVo;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
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.Date;
import java.util.List;
import java.util.Map;

@Service
public class PriceCoefficientApplyService extends BaseService {

    @Autowired
    private PriceCoefficientApplyDao priceCoefficientApplyDao;

    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    TaskService taskService;

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

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

    @Transactional(rollbackFor = Exception.class)
    public void savePriceCoefficientApply(PriceVo vo) {
        logger.info(">>>>>>>>>>>>>>>savePriceCoefficientApply  vo:{}", vo);
        User user = UserUtils.getUser();
        String userName = user.getUserName();
        Date date = new Date();
        PriceCoefficientApply apply;
        if (StringUtil.isBlank(vo.getId())) {
            //如果有使用中的零售价系数，则不可在次申请
            long count = priceCoefficientApplyDao.getNormalCount(vo.getMaterialTypeId());
            if (count > 0) {
                throw new RuntimeException(" 请先删除已申请的记录！");
            }
            apply = new PriceCoefficientApply();
            apply.setApplyNumber(PlantformUtils.getOrderNumber());
            apply.setDepartmentId(user.getDepartmentId());
            apply.setDepartmentName(user.getDepartmentName());
        } else {
            apply = priceCoefficientApplyDao.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.setMaterialTypeId(vo.getMaterialTypeId());
        apply.setCoefficient(vo.getCoefficient());
        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.PRICE_COEFFICIENT_APPLY);
            if (rd == null) {
                throw new RuntimeException("流程未定义，不可发布申请");
            }
            String processName="零售价系数申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss");
            String processInstanceId = flowableService.startProcessFlowable(user, apply.getId(), rd, FormUtils.PRICE_COEFFICIENT_APPLY, date, userName,vo.getRemarks(),processName,"");
            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(">>>>>>>>>>>>>>savePriceCoefficientApply>>>>>>>>>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.PRICE_COEFFICIENT_APPLY);
        }
        apply.setStatus(BondApplyConstant.APPLYSTATUS_ONE);
        priceCoefficientApplyDao.save(apply);
    }

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

        apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
        priceCoefficientApplyDao.save(apply);
        //删除流程
        flowableService.deleteApplication(apply.getId(), apply.getProcessInstanceId(), userName, apply.getStatus(), FormUtils.PRICE_COEFFICIENT_APPLY);
    }

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

    }

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

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

    public List<Record> getEffectApply() {
        return priceCoefficientApplyDao.getEffectApply();
    }

}
