package com.patzn.lims.equip.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.patzn.cloud.commons.toolkit.DateUtils;
import com.patzn.lims.consume.enums.PurchaseOrderEnum;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.equip.dto.LmsEquipPurchaseDTO;
import com.patzn.lims.equip.entity.LmsEquipPurchase;
import com.patzn.lims.equip.entity.LmsEquipPurchaseDetail;
import com.patzn.lims.equip.enums.EquipDataStatusEnum;
import com.patzn.lims.equip.mapper.LmsEquipPurchaseMapper;
import com.patzn.lims.equip.service.ILmsEquipPurchaseDetailService;
import com.patzn.lims.equip.service.ILmsEquipPurchaseService;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.equip.vo.LmsEquipPurchaseDetailVO;
import com.patzn.lims.equip.vo.LmsEquipPurchaseVO;
import com.patzn.lims.res.entity.LmsBaseDict;
import com.patzn.lims.res.enums.CodeTypeEnum;
import com.patzn.lims.res.service.ILmsBaseDictService;
import com.patzn.lims.res.service.ILmsCodeRuleService;
import com.patzn.lims.workflow.FlowInfo;
import com.patzn.lims.workflow.FlowType;
import com.patzn.lims.workflow.FlowVariables;
import com.patzn.lims.workflow.service.IFlowProcessService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 仪器采购订单表 服务实现类
 * </p>
 *
 * @author wwd
 * @since 2020-03-27
 */
@Service
public class LmsEquipPurchaseServiceImpl extends BaseServiceImpl<LmsEquipPurchaseMapper, LmsEquipPurchase> implements ILmsEquipPurchaseService {

    @Autowired
    private ILmsEquipPurchaseDetailService lmsEquipPurchaseDetailService;
    @Autowired
    private ILmsCodeRuleService lmsCodeRuleService;
    @Autowired
    private ILmsEquipPurchaseService lmsEquipPurchaseService;
    @Autowired
    private ILmsBaseDictService lmsBaseDictService;
    @Autowired
    private IFlowProcessService flowProcessService;


    @Override
    public Page<LmsEquipPurchase> page(Page<LmsEquipPurchase> page, LmsEquipPurchaseDTO lmsEquipPurchase) {
        QueryWrapper<LmsEquipPurchase> wrapper = Wrappers.<LmsEquipPurchase>query(lmsEquipPurchase);

        if (StringUtils.isNotBlank(lmsEquipPurchase.getName())) {
            wrapper.like("name", lmsEquipPurchase.getName());
            lmsEquipPurchase.setName(null);
        }
        wrapper.eq("temp_status", EquipDataStatusEnum.REAL.getValue());
        //添加申请单编号
        if(StringUtils.isNotBlank(lmsEquipPurchase.getNum())) {
            wrapper.like( "num", lmsEquipPurchase.getNum());
            lmsEquipPurchase.setNum(null);
        }

        //添加申请单编号
        if(StringUtils.isNotBlank(lmsEquipPurchase.getApplyName())) {
            wrapper.like( "apply_name", lmsEquipPurchase.getApplyName());
            lmsEquipPurchase.setApplyName(null);
        }
        //添加原因
        if(StringUtils.isNotBlank(lmsEquipPurchase.getApplyReason())) {
            wrapper.like("apply_reason", lmsEquipPurchase.getApplyReason());
            lmsEquipPurchase.setApplyReason(null);
        }
        if(StringUtils.isNotBlank(lmsEquipPurchase.getBeginDate())){
            wrapper.gt("apply_time", DateUtils.getStartOfDay(DateUtils.toDate(lmsEquipPurchase.getBeginDate())));
            lmsEquipPurchase.setBeginDate(null);
        }
        if(StringUtils.isNotBlank(lmsEquipPurchase.getEndDate())){
            wrapper.lt("apply_time", DateUtils.getEndOfDay(DateUtils.toDate(lmsEquipPurchase.getEndDate())));
            lmsEquipPurchase.setBeginDate(null);
        }
        //申请时间
        wrapper.orderBy(true, true,"status");
        //申请时间 倒序
        wrapper.orderBy(true, true,"apply_time");
        return this.page(page, wrapper);
    }

    @Override
    public LmsEquipPurchase selectOne(LmsEquipPurchase purchase) {
        return baseMapper.selectOne(Wrappers.query(purchase));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(LmsEquipPurchase lmsEquipPurchase, Long sendUserId, Account account) {
        boolean codeRuleBl = (null != lmsCodeRuleService.getCodeRule(CodeTypeEnum.EQUIP_PURCHASE));
        if(codeRuleBl && StringUtils.isBlank(lmsEquipPurchase.getNum())){
            lmsEquipPurchase.setNum(lmsCodeRuleService.getKey(CodeTypeEnum.EQUIP_PURCHASE, lmsEquipPurchase));
        }else if(!codeRuleBl && StringUtils.isBlank(lmsEquipPurchase.getNum())) {
            PtAssert.fail("您没有配置 仪器采购编号 请填写仪器采购编号 或前往系统管理-设置编号规则");
        }
        lmsEquipPurchase.setRegisterId(LoginHelper.getAccount().getUserId());
        lmsEquipPurchase.setRegisterName(LoginHelper.getAccount().getUserName());
        lmsEquipPurchase.setRegisterTime(new Date());
        LmsEquipPurchase purchase = new LmsEquipPurchase();
        purchase.setUserId(LoginHelper.getAccount().getUserId());
        purchase.setTempStatus(0);
        LmsEquipPurchase temp = lmsEquipPurchaseService.selectOne(purchase);
        if (null != temp) {
            //if(temp.getNum().equals(lmsEquipPurchase.getNum())){
            PtAssert.fail(lmsEquipPurchaseService.list(Wrappers.<LmsEquipPurchase>query().eq("num", lmsEquipPurchase.getNum())).size() > 0, "采购申请编号已经存在重复!");
            //}
            lmsEquipPurchase.setId(temp.getId());
            lmsEquipPurchase.setTempStatus(1);

            lmsEquipPurchaseService.updateById(lmsEquipPurchase);
        } else {
            lmsEquipPurchase.setUserId(LoginHelper.getAccount().getUserId());
            lmsEquipPurchase.setTempStatus(1);
            //验证申请单号唯一性能
            PtAssert.fail(lmsEquipPurchaseService.list(Wrappers.<LmsEquipPurchase>query().eq("num", lmsEquipPurchase.getNum())).size() > 0, "采购申请编号已经存在重复!");
            lmsEquipPurchaseService.save(lmsEquipPurchase);
        }

        //提交
        if (1 == lmsEquipPurchase.getStatus()) {
            lmsEquipPurchaseService.submit(lmsEquipPurchase.getId(),sendUserId);
        }

        return true;
    }

    @Override
    public LmsEquipPurchaseVO getTempVO() {
        LmsEquipPurchaseVO lmsEquipPurchaseVO = new LmsEquipPurchaseVO();
        LmsEquipPurchase purchase = new LmsEquipPurchase();
        purchase.setUserId(LoginHelper.getAccount().getUserId());
        purchase.setTempStatus(EquipDataStatusEnum.TEMP.getValue());
        LmsEquipPurchase lmsEquipPurchase = selectOne(purchase);
        if (null != lmsEquipPurchase) {
            lmsEquipPurchaseVO = lmsEquipPurchase.convert(LmsEquipPurchaseVO.class);
            LmsEquipPurchaseDetailVO vo = new LmsEquipPurchaseDetailVO();
            vo.setPurchaseId(lmsEquipPurchase.getId());
            List<LmsEquipPurchaseDetailVO> lmsEquipPurchaseDetailVOS = lmsEquipPurchaseDetailService.listVO(vo);
            lmsEquipPurchaseVO.setLmsEquipPurchaseDetailVOList(lmsEquipPurchaseDetailVOS);
        } else {
            LmsEquipPurchase purchase1 = new LmsEquipPurchase();
            purchase1.setUserId(LoginHelper.getAccount().getUserId());
            purchase1.setTempStatus(EquipDataStatusEnum.TEMP.getValue());
            save(purchase1);

            lmsEquipPurchaseVO = purchase1.convert(LmsEquipPurchaseVO.class);
        }

        return lmsEquipPurchaseVO;
    }



    @Override
    public boolean submit(Long id,Long sendUserId) {
        try {
            LmsEquipPurchase lmsEquipPurchase = baseMapper.selectById(id);
            List<FlowInfo> flowInfoList = new ArrayList<>();
            Account account = LoginHelper.getAccount();
            //查询字典看是否需要二级审批
            List<LmsBaseDict> dicts = lmsBaseDictService.getNameByType("仪器采购是否需要二级审批");
            if(CollectionUtils.isNotEmpty(dicts) && Objects.equals("是",dicts.get(0).getName())){
                flowInfoList.add(FlowInfo.convertFlowInfo(FlowType.EQUIP_PURCHASE_ORDER,
                        account, lmsEquipPurchase.getId(), lmsEquipPurchase.getApplyReason()));
                if(null != sendUserId){
//                    //发送消息
//                    lmsMsgService.sendMsg("/lims/equip_purchase","请前往-系统管理-工作流管理-我的任务中查看详情,请确保您处于工作组中。",
//                            "新的仪器采购申请需要您的审批",LoginHelper.getAccount(), Lists.newArrayList(sendUserId));
                }
            }else{
                flowInfoList.add(FlowInfo.convertFlowInfo(FlowType.EQUIP_PURCHASE_ORDER,
                        account, lmsEquipPurchase.getId(), lmsEquipPurchase.getApplyReason()));
            }
            flowProcessService.saveTask(flowInfoList,account);
            //更新采购单状态
            lmsEquipPurchase.setStatus(1);
            lmsEquipPurchase.setApplyId(LoginHelper.getAccount().getUserId());
            lmsEquipPurchase.setApplyName(LoginHelper.getAccount().getUserName());
            lmsEquipPurchase.setApplyTime(new Date());
            baseMapper.updateById(lmsEquipPurchase);
        } catch (Exception ex) {
            PtAssert.fail("流程提交失败，原因：" + ex.getMessage());
        }

        return true;
    }



    @Override
    public LmsEquipPurchaseVO getVOById(Long id) {
        LmsEquipPurchaseVO lmsEquipPurchaseVO = new LmsEquipPurchaseVO();
        LmsEquipPurchase purchase = getById(id);
        if (null != purchase) {
            LmsEquipPurchaseDetailVO vo = new LmsEquipPurchaseDetailVO();
            vo.setPurchaseId(purchase.getId());
            List<LmsEquipPurchaseDetailVO> lmsEquipPurchaseDetailVOS = lmsEquipPurchaseDetailService.listVO(vo);
            lmsEquipPurchaseVO = purchase.convert(LmsEquipPurchaseVO.class);
            lmsEquipPurchaseVO.setLmsEquipPurchaseDetailVOList(lmsEquipPurchaseDetailVOS);
        }
        return lmsEquipPurchaseVO;
    }

    @Override
    public boolean approve(String taskId, String status, String reason) {
//        FlowVariables flowVariables = new FlowVariables(taskId);
//        FlowInfo flowInfo = null;
//        Map<String, Object> map = new HashMap<>(2);
//        if ("success".equals(status)) {
//            // 确认审批完成
//            flowInfo = flowProcessService.complete(taskId);
//            if (null == flowInfo) {
//                PtAssert.fail("确认审批失败！");
//                return false;
//            } else {
//                //仪器资产入库
//
//            }
//        } else if ("false".equals(status)) {
//            flowInfo = flowProcessClient.complete(taskId).servcieData();
//        } else if ("2".equals(status)) {
//            //技术主管审批通过
//            map.put("technicalDirectorAduitPass", true);
//            flowVariables.setVariables(map);
//            flowInfo = flowProcessClient.complete(flowVariables);
//        } else if ("6".equals(status)) {
//            //技术主管审批驳回
//            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
//            map.put("technicalDirectorAduitPass", false);
//            flowVariables.setVariables(map);
//            flowInfo = flowProcessClient.complete(flowVariables);
//        } else if ("10".equals(status)) {
//            //终止
//            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
//            map.put("technicalDirectorAduitPass", false);
//            flowVariables.setVariables(map);
//            flowInfo = flowProcessClient.complete(flowVariables);
//        } else if ("3".equals(status)) {
//            //中心主任审批通过
//            map.put("centerDirectorAduitPass", true);
//            flowVariables.setVariables(map);
//            flowInfo = flowProcessClient.complete(flowVariables);
//        } else if ("7".equals(status)) {
//            //中心主任废除
//            map.put("centerDirectorAduitPass", false);
//            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
//            flowVariables.setVariables(map);
//            flowInfo = flowProcessClient.complete(flowVariables);
//        } else if ("4".equals(status)) {
//            //设备验收审批通过
//            map.put("equipManagerAduitPass", true);
//            flowVariables.setVariables(map);
//            flowInfo = flowProcessClient.complete(flowVariables);
//        } else if ("8".equals(status)) {
//            //设备验收废除
//            map.put("equipManagerAduitPass", false);
//            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
//            flowVariables.setVariables(map);
//            flowInfo = flowProcessClient.complete(flowVariables);
//        } else if ("5".equals(status)) {
//            //归档完成
//            flowInfo = flowProcessClient.notifyApplyer(taskId, "").servcieData();
//        } else {
//            flowInfo = null;
//        }
//
//        if (null != flowInfo) {
//            Integer count = updatePurchase(flowInfo, status, reason);
//            if (null == count) {
//                return false;
//            } else {
//                return true;
//            }
//        } else {
//            return false;
//        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean approveFlow(String flowId, String allow, String postil,Long id,Long  sendUserId) {
        Account account = LoginHelper.getAccount();
        FlowVariables flowVariables = new FlowVariables();
        flowVariables.setTaskId(flowId);
        FlowInfo flowInfo = null;
        Map<String, Object> map = new HashMap<>(2);
        if ("6".equals(allow)) {
            //实验室主任驳回
            map.put("technicalDirectorAduitPass", true);
            map.put("centerManager", false);
        } else if ("2".equals(allow)) {
            //判断是新数据还是旧数据
            PtAssert.fail(null == id,"采购单id未传");
            LmsEquipPurchase order = super.getById(id);
            PtAssert.fail(null == order || null == order.getApplyTime(),"采购单查询为空");
            boolean oldBl = false;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date faban = sdf.parse("2019-08-24 09:00:00");
                if(order.getApplyTime().getTime() < faban.getTime()){
                    oldBl = true;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //查询字典看是否需要二级审批
            List<LmsBaseDict> dicts = lmsBaseDictService.getNameByType("仪器采购是否需要二级审批");
            if(CollectionUtils.isNotEmpty(dicts) && Objects.equals("是",dicts.get(0).getName()) && !oldBl){
                //实验室主任通过,流程继续，改为二级审批
                map.put("technicalDirectorAduitPass", false);
                map.put("centerManager", true);
//                lmsMsgService.sendMsg("/lims/equip_purchase_order","新的仪器采购审批需要您进行审批,请确认您在工作组中",
//                        "新的仪器采购审批通知",account,Lists.newArrayList(sendUserId));
            }else{
                //实验室主任通过,流程结束，采购单状态为待采购
                map.put("technicalDirectorAduitPass", true);
                map.put("centerManager", false);
            }
        } else if("10".equals(allow)){
            //实验室主任终止
            map.put("technicalDirectorAduitPass", true);
            map.put("centerManager", false);
        }
        map.put(FlowInfo.APPLY_ID, account.getUserId());
        flowVariables.setVariables(map);
        flowInfo = flowProcessService.complete(flowVariables);
        PtAssert.fail(null == flowInfo, "确认审批失败！");
        if (null != flowInfo) {
            Integer count = updatePurchase(flowInfo, allow, postil);
            if (null == count) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean approveManager(String flowId, String allow, String postil) {
        FlowVariables flowVariables = new FlowVariables();
        flowVariables.setTaskId(flowId);
        FlowInfo flowInfo = null;
        Map<String, Object> map = new HashMap<>(2);
        Account account = LoginHelper.getAccount();
        PurchaseOrderEnum purchaseOrderEnum = null;
        if ("2".equals(allow) || "6".equals(allow) || "10".equals(allow)) {
            map.put("centerManagerPass", true);
            map.put(FlowInfo.APPLY_ID, account.getUserId());
            flowVariables.setVariables(map);
            flowInfo = flowProcessService.complete(flowVariables);
        }
        PtAssert.fail(null == flowInfo, "确认审批失败！");
        if (null != flowInfo) {
            Integer count = updatePurchaseManager(flowInfo, allow, postil);
            if (null == count) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }


    private Integer updatePurchaseManager(FlowInfo flowInfo, String status, String reason) {
        LmsEquipPurchase purchase = new LmsEquipPurchase();
        purchase.setId(flowInfo.getId());
        if ("success".equals(status) || "false".equals(status)) {
            //流程结束
            purchase.setStatus(9);
        } else if ("2".equals(status)) {
            //中心主任审批通过
            purchase.setStatus(2);
            purchase.setSecondStepId(LoginHelper.getAccount().getUserId());
            purchase.setSecondStepTime(new Date());
            purchase.setSecondStepAdvice(reason);
            purchase.setSecondStepName(LoginHelper.getAccount().getUserName());
        } else if ("6".equals(status)) {
            //中心主任驳回
            purchase.setStatus(6);
            purchase.setSecondStepId(LoginHelper.getAccount().getUserId());
            purchase.setSecondStepTime(new Date());
            purchase.setSecondStepAdvice(reason);
            purchase.setSecondStepName(LoginHelper.getAccount().getUserName());
        } else if ("10".equals(status)) {
            //中心主任废除
            purchase.setStatus(10);
            purchase.setSecondStepId(LoginHelper.getAccount().getUserId());
            purchase.setSecondStepTime(new Date());
            purchase.setSecondStepAdvice(reason);
            purchase.setSecondStepName(LoginHelper.getAccount().getUserName());
        } else {
            return null;
        }

        return baseMapper.updateById(purchase);
    }


    private Integer updatePurchase(FlowInfo flowInfo, String status, String reason) {
        LmsEquipPurchase purchase = new LmsEquipPurchase();
        purchase.setId(flowInfo.getId());
        LmsEquipPurchase db = getById(flowInfo.getId());
        Account account = LoginHelper.getAccount();
        if ("success".equals(status) || "false".equals(status)) {
            //流程结束
            purchase.setStatus(9);
        } else if ("2".equals(status)) {
            //
            //判断是新数据还是旧数据
            PtAssert.fail(null == flowInfo.getId(),"采购单id未传");
            LmsEquipPurchase order = super.getById(flowInfo.getId());
            PtAssert.fail(null == order || null == order.getApplyTime(),"采购单查询为空");
            boolean oldBl = false;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date faban = sdf.parse("2019-08-24 09:00:00");
                if(order.getApplyTime().getTime() < faban.getTime()){
                    oldBl = true;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //查询字典看是否需要二级审批
            List<LmsBaseDict> dicts = lmsBaseDictService.getNameByType("仪器采购是否需要二级审批");
            if(CollectionUtils.isEmpty(dicts) || Objects.equals("否",dicts.get(0).getName()) || oldBl){
                purchase.setStatus(2);
            }
            purchase.setFirstStepId(LoginHelper.getAccount().getUserId());
            purchase.setFirstStepTime(new Date());
            purchase.setFirstStepAdvice(reason);
            purchase.setFirstStepName(LoginHelper.getAccount().getUserName());
//            lmsMsgService.sendMsg("/lims/equip_purchase_order","申请单编号："+db.getNum()+"审批通过",
//                    "新的仪器采购审批通知",account,null);
        } else if ("6".equals(status)) {
            //技术主管审批驳回
            purchase.setStatus(6);
            purchase.setFirstStepId(LoginHelper.getAccount().getUserId());
            purchase.setFirstStepTime(new Date());
            purchase.setFirstStepAdvice(reason);
            purchase.setFirstStepName(LoginHelper.getAccount().getUserName());
//            lmsMsgService.sendMsg("/lims/equip_purchase_order","申请单编号："+db.getNum()+"被驳回",
//                    "新的仪器采购审批通知",account,null);
        } else if ("10".equals(status)) {
            //终止
            purchase.setStatus(10);
            purchase.setFirstStepId(LoginHelper.getAccount().getUserId());
            purchase.setFirstStepTime(new Date());
            purchase.setFirstStepAdvice(reason);
            purchase.setFirstStepName(LoginHelper.getAccount().getUserName());
//            lmsMsgService.sendMsg("/lims/equip_purchase_order","申请单编号："+db.getNum()+"被终止",
//                    "新的仪器采购审批通知",account,null);
        } else if ("3".equals(status)) {
            //中心主任审批通过
            purchase.setStatus(3);
            purchase.setSecondStepId(LoginHelper.getAccount().getUserId());
            purchase.setSecondStepTime(new Date());
            purchase.setSecondStepAdvice(reason);
            purchase.setSecondStepName(LoginHelper.getAccount().getUserName());
        } else if ("7".equals(status)) {
            //中心主任废除
            purchase.setStatus(7);
            purchase.setSecondStepId(LoginHelper.getAccount().getUserId());
            purchase.setSecondStepTime(new Date());
            purchase.setSecondStepAdvice(reason);
            purchase.setSecondStepName(LoginHelper.getAccount().getUserName());
        } else if ("4".equals(status)) {
            //设备验收审批通过
            purchase.setStatus(4);
        } else if ("8".equals(status)) {
            //设备验收废除
            purchase.setStatus(8);
        } else if ("5".equals(status)) {
            //归档完成
            purchase.setStatus(5);
        } else {
            return null;
        }

        return baseMapper.updateById(purchase);
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean toManagerCheck(String flowId, String allow, String postil) {
        return true;
    }
}
