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

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.entity.LmsEquipDeliveryOrder;
import com.patzn.lims.equip.entity.LmsEquipInfo;
import com.patzn.lims.equip.entity.LmsEquipRelDelivery;
import com.patzn.lims.equip.entity.LmsEquipUseRecord;
import com.patzn.lims.equip.mapper.LmsEquipDeliveryOrderMapper;
import com.patzn.lims.equip.service.ILmsEquipDeliveryOrderService;
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.service.ILmsEquipInfoService;
import com.patzn.lims.equip.service.ILmsEquipRelDeliveryService;
import com.patzn.lims.equip.service.ILmsEquipUseRecordService;
import com.patzn.lims.equip.vo.EquipOutSockVO;
import com.patzn.lims.equip.vo.LmsEquipDeliveryOrderVO;
import com.patzn.lims.res.enums.CodeTypeEnum;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 试验耗材出库单表 服务实现类
 * </p>
 *
 * @author wwd
 * @since 2020-03-27
 */
@Service
public class LmsEquipDeliveryOrderServiceImpl extends BaseServiceImpl<LmsEquipDeliveryOrderMapper, LmsEquipDeliveryOrder> implements ILmsEquipDeliveryOrderService {


    @Autowired
    private ILmsCodeRuleService lmsCodeRuleService;
    @Autowired
    private ILmsEquipRelDeliveryService lmsEquipRelDeliveryService;
    @Autowired
    private IFlowProcessService flowProcessService;
    @Autowired
    private ILmsEquipInfoService lmsEquipInfoService;
    @Autowired
    private ILmsEquipUseRecordService lmsEquipUseRecordService;

    @Override
    public Page<LmsEquipDeliveryOrder> page(Page<LmsEquipDeliveryOrder> page, LmsEquipDeliveryOrderVO lmsEquipDeliveryOrder) {
        QueryWrapper wrapper = Wrappers.query(lmsEquipDeliveryOrder);
        //添加申请单编号
        if (StringUtils.isNotBlank(lmsEquipDeliveryOrder.getNum())) {
            wrapper.like("num", lmsEquipDeliveryOrder.getNum());
            lmsEquipDeliveryOrder.setNum(null);
        }
        //添加原因
        if (StringUtils.isNotBlank(lmsEquipDeliveryOrder.getReason())) {
            wrapper.like("reason", lmsEquipDeliveryOrder.getReason());
            lmsEquipDeliveryOrder.setReason(null);
        }
        //添加申请人
        if (StringUtils.isNotBlank(lmsEquipDeliveryOrder.getApplyer())) {
            wrapper.like("applyer", lmsEquipDeliveryOrder.getApplyer());
            lmsEquipDeliveryOrder.setApplyer(null);
        }
        if (StringUtils.isNotBlank(lmsEquipDeliveryOrder.getBeginDate())) {
            wrapper.gt("ctime", DateUtils.getStartOfDay(DateUtils.toDate(lmsEquipDeliveryOrder.getBeginDate())));
            lmsEquipDeliveryOrder.setBeginDate(null);
        }
        if (StringUtils.isNotBlank(lmsEquipDeliveryOrder.getEndDate())) {
            wrapper.lt("ctime", DateUtils.getEndOfDay(DateUtils.toDate(lmsEquipDeliveryOrder.getEndDate())));
            lmsEquipDeliveryOrder.setBeginDate(null);
        }
        //申请时间
        wrapper.orderBy(true,true,"status");
        //申请时间 倒序
        wrapper.orderBy(true,true,"ctime");

        return this.page(page, wrapper);
    }


    @Override
    public boolean save(boolean approve, String reason) {
        // 修改临时采购池中的采购单 ID 状态
        Account account = LoginHelper.getAccount();
        LmsEquipDeliveryOrder ledo = new LmsEquipDeliveryOrder();
        ledo.setId(IdWorker.getId());
        ledo.setUid(account.getUserId());
        boolean codeRuleBl = (null != lmsCodeRuleService.getCodeRule(CodeTypeEnum.EQUIP_OUT_STOCK));
        if(codeRuleBl){
            ledo.setNum(lmsCodeRuleService.getKey(CodeTypeEnum.EQUIP_OUT_STOCK, new LmsEquipDeliveryOrder().setReason("CK")));
        }else {
            ledo.setNum("YQCK" + ledo.getId());
        }
        ledo.setReason(reason);
        //设置出库类型
        ledo.setType(new Integer(0));
        lmsEquipRelDeliveryService.updateOrderStatusFromTemp(ledo.getId(), approve, 0);
        if (approve) {
            // 提交审批
            ledo.setStatus((Integer) PurchaseOrderEnum.IN_APPROVAL.getValue());
            List<FlowInfo> flowInfoList = new ArrayList<>();
            flowInfoList.add(FlowInfo.convertFlowInfo(FlowType.EQUIP_DELIVERY,
                    account, ledo.getId(), ledo.getReason()));
            flowProcessService.saveTask(flowInfoList,account);
        } else {
            // 待审批
            ledo.setStatus((Integer) PurchaseOrderEnum.WAIT_APPROVAL.getValue());
            // 修改临时采购池中的采购单 ID 状态
        }
        ledo.setApplyer(account.getUserName());
        return this.save(ledo);
    }


    @Override
    public boolean submit(Long id, String reason) {
        //获取单据
        LmsEquipDeliveryOrder order = this.getById(id);
        // 提交审批
        order.setStatus((Integer) PurchaseOrderEnum.IN_APPROVAL.getValue());
        if (StringUtils.isNotBlank(reason)) {
            order.setReason(reason);
        }
        if (updateById(order)) {
            List<FlowInfo> flowInfoList = new ArrayList<>();
            flowInfoList.add(FlowInfo.convertFlowInfo(FlowType.EQUIP_DELIVERY,
                    LoginHelper.getAccount(), order.getId(), order.getReason()));
            flowProcessService.saveTask(flowInfoList,LoginHelper.getAccount());
            return true;
        }
        return false;
    }


    @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);
        //状态（0草稿、1审批中、2待出库，3审批未通过 ，4已完成）
        if ("2".equals(status)) {
            //审批通过
            map.put("technicalDirectorAduitPass", true);
            flowVariables.setVariables(map);
            flowInfo = flowProcessService.complete(flowVariables);

        } else if ("3".equals(status)) {
            //终止
            map.put("technicalDirectorAduitPass", false);
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            flowVariables.setVariables(map);
            flowInfo = flowProcessService.complete(flowVariables);
        } else if ("5".equals(status)) {
            //驳回
            map.put("technicalDirectorAduitPass", false);
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            flowVariables.setVariables(map);
            flowInfo = flowProcessService.complete(flowVariables);
        } else {
            flowInfo = null;
        }
        if (null != flowInfo) {
            Integer count = updateDelivery(flowInfo, status, reason);
            if (null == count) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    private Integer updateDelivery(FlowInfo flowInfo, String status, String reason) {
        LmsEquipDeliveryOrder delivery = new LmsEquipDeliveryOrder();
        delivery.setId(flowInfo.getId());
        if ("2".equals(status)) {
            //技术主管审批通过
            delivery.setStatus(2);
            delivery.setPostil(reason);
            delivery.setApproval(LoginHelper.getAccount().getUserName());
            //修改
        } else if ("3".equals(status)) {
            //技术主管审批终止
            delivery.setStatus(3);
            delivery.setPostil(reason);
            delivery.setApproval(LoginHelper.getAccount().getUserName());
        } else if ("5".equals(status)) {
            //技术主管审批驳回
            delivery.setStatus(5);
            delivery.setPostil(reason);
            delivery.setApproval(LoginHelper.getAccount().getUserName());
        } else {
            return null;
        }
        if (lmsEquipRelDeliveryService.modifyStatusByOrderId(delivery.getId(), delivery.getStatus())) {
            return baseMapper.updateById(delivery);
        }
        return 0;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean outStockById(Long id, EquipOutSockVO vo) {
        //获取单据
        LmsEquipDeliveryOrder order = getById(id);
        order.setStatus(4);//出库完成
        //获取出库单明细
        updateById(order);
        //判断明细是否存在
        List<LmsEquipRelDelivery> lstDeliveryDetails =
                lmsEquipRelDeliveryService.list(Wrappers.<LmsEquipRelDelivery>query().eq("order_id", id));
        if (lstDeliveryDetails == null || lstDeliveryDetails.size() == 0) {
            PtAssert.fail("请选择出库单存在问题！");
        }
        lstDeliveryDetails.stream().forEach(c -> {
            //  审批状态 0、待提交 ，1、审批中 ，2.待出库，4，完成  3 审批驳回
            if (c.getState() == 2) {
                //修改出单明细
                LmsEquipRelDelivery dlTemp = new LmsEquipRelDelivery();
                dlTemp.setId(c.getId());
                dlTemp.setStatus(1);//状态 0、等待出库 1、出库 -1 临时
                dlTemp.setState(4);
                dlTemp.setGrantName(vo.getGrantName());//发放人
                dlTemp.setApplyName(vo.getApplyer());//领用人
                lmsEquipRelDeliveryService.updateById(dlTemp);

                //修改台账设备状态}
                LmsEquipInfo equipInfo = lmsEquipInfoService.getById(c.getEquipId());
                if (equipInfo != null) {
                    LmsEquipInfo equipTemp = new LmsEquipInfo();
                    equipTemp.setId(equipInfo.getId());
                    //使用状态（0闲置，1在用，2保养中，3维修中，4已报废）
                    equipTemp.setStatus(1);
                    equipTemp.setExpectedDate(c.getUseEndTime());
                    lmsEquipInfoService.updateById(equipTemp);
                }
                //创建使用记录
                LmsEquipUseRecord lmsEquipUseRecord = new LmsEquipUseRecord();
                lmsEquipUseRecord.setId(IdWorker.getId());
                lmsEquipUseRecord.setRegisterId(LoginHelper.getAccount().getUserId());
                lmsEquipUseRecord.setRegisterName(StringUtils.isNoneEmpty(vo.getGrantName()) ? vo.getGrantName() : LoginHelper.getAccount().getUserName());//发放人
                lmsEquipUseRecord.setRegisterTime(vo.getApplyDate());
                lmsEquipUseRecord.setUseDate(vo.getApplyDate());//使用日期
                lmsEquipUseRecord.setEquipId(c.getEquipId());
                lmsEquipUseRecord.setEquipNum(c.getEquipNum());
                lmsEquipUseRecord.setStatus(1);//草稿
                lmsEquipUseRecord.setReason(c.getUses());
                lmsEquipUseRecord.setPerformanceStart(vo.getPerformance());
                lmsEquipUseRecord.setUseStartTime(c.getUseStartTime());
                lmsEquipUseRecord.setUseEndTime(c.getUseEndTime());
                // lmsEquipUseRecord.setUserId(c.getUid());
                lmsEquipUseRecord.setUserName(StringUtils.isNoneEmpty(vo.getApplyer()) ? vo.getApplyer() : c.getApplyName());//领取人
                lmsEquipUseRecord.setRegisterId(c.getApplyId());
                lmsEquipUseRecord.setRemark(vo.getRemark());
                lmsEquipUseRecord.setUseApplyer(c.getApplyName());//使用申请人
                lmsEquipUseRecord.setProductPlace(equipInfo.getProductPlace());
                //设置是否归还
                lmsEquipUseRecord.setIsReturn(0);
                lmsEquipUseRecord.setType(1);
                lmsEquipUseRecordService.save(lmsEquipUseRecord);
                lmsEquipUseRecord.setId(null);
                lmsEquipUseRecord.setStatus(0);//草稿
                lmsEquipUseRecord.setType(0);
                lmsEquipUseRecordService.save(lmsEquipUseRecord);
            }
        });
        return true;
    }
}
