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

import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.patzn.lims.consume.entity.LmsChemicalPurchaseOrder;
import com.patzn.lims.consume.enums.PurchaseOrderEnum;
import com.patzn.lims.consume.mapper.LmsChemicalPurchaseOrderMapper;
import com.patzn.lims.consume.service.ILmsChemicalPurchaseOrderService;
import com.patzn.lims.consume.service.ILmsChemicalRelPurchaseService;
import com.patzn.lims.consume.vo.LmsChemicalPurchaseOrderVO;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.Account;
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.core.web.LoginHelper;
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.FlowProcess;
import com.patzn.lims.workflow.FlowType;
import com.patzn.lims.workflow.FlowVariables;
import com.patzn.lims.workflow.service.IFlowProcessService;
import org.joda.time.DateTime;
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-21
 */
@Service
public class LmsChemicalPurchaseOrderServiceImpl extends BaseServiceImpl<LmsChemicalPurchaseOrderMapper, LmsChemicalPurchaseOrder> implements ILmsChemicalPurchaseOrderService {

    @Autowired
    private ILmsCodeRuleService lmsCodeRuleService;
    @Autowired
    private ILmsChemicalRelPurchaseService lmsChemicalRelPurchaseService;
    @Autowired
    private IFlowProcessService flowProcessService;

    @Autowired
    private ILmsBaseDictService lmsBaseDictService;

    @Override
    public Page<LmsChemicalPurchaseOrder> page(Page<LmsChemicalPurchaseOrder> page, LmsChemicalPurchaseOrder lmsChemicalPurchaseOrder) {
        QueryWrapper<LmsChemicalPurchaseOrder> wrapper = Wrappers.<LmsChemicalPurchaseOrder>query(lmsChemicalPurchaseOrder);
        return this.page(page, wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(String remark, Long sendUserId,Account account) {
        LmsChemicalPurchaseOrder lcpo = new LmsChemicalPurchaseOrder();
        lcpo.setId(IdWorker.getId());
        //生成编号
        if (null != lmsCodeRuleService.getCodeRule(CodeTypeEnum.CHEMICAL_PURCHASE)) {
            lcpo.setNum(lmsCodeRuleService.getKey(CodeTypeEnum.CHEMICAL_PURCHASE, lcpo));
        }else {
            lcpo.setNum("PN" + lcpo.getId());
        }
        lcpo.setRemark(remark);
        // 修改临时采购池中的采购单 ID 状态
        lmsChemicalRelPurchaseService.updateOrderStatus(lcpo.getId(), account.getUserId());
       // 待审批
        lcpo.setStatus(PurchaseOrderEnum.WAIT_APPROVAL.getValue());
        lcpo.setApplyer(account.getUserName());
        return this.save(lcpo);
    }


    @Override
    public Page<LmsChemicalPurchaseOrderVO> pageVO(Page page, LmsChemicalPurchaseOrderVO vo) {
        return baseMapper.selectPageVOList(page,vo);
    }


    @Override
    public Page<LmsChemicalPurchaseOrderVO> pageWaitPurchase(Page page, LmsChemicalPurchaseOrderVO lmsChemicalPurchaseOrder) {
        List<Integer> statusList = new ArrayList<>();
        statusList.add(PurchaseOrderEnum.WAIT_PURCHASE.getValue());
        statusList.add(PurchaseOrderEnum.PURCHASEING.getValue());
        statusList.add(PurchaseOrderEnum.STOCK_WAIT.getValue());
        statusList.add(PurchaseOrderEnum.STOCK_PART.getValue());
        return this.pageByStatusList(page, lmsChemicalPurchaseOrder,statusList);
    }

    @Override
    public List<FlowProcess> submitPurchaseFlow(Long[] ids, Long sendUserId,Account account) {

        if (ArrayUtils.isEmpty(ids)) {
            return null;
        }
        List<LmsChemicalPurchaseOrder> lcpoList = this.list(Wrappers.<LmsChemicalPurchaseOrder>query().in("id", ids));
        if (CollectionUtils.isEmpty(lcpoList)) {
            return null;
        }
        //List<LmsChemicalPurchaseOrder> list = new ArrayList<>();
        List<FlowInfo> flowInfoList = new ArrayList<>();
        for (LmsChemicalPurchaseOrder lcpo : lcpoList) {
            // 工作量信息
            flowInfoList.add(FlowInfo.convertFlowInfo(FlowType.CHEMICAL_PURCHASE_ORDER,
                    account, lcpo.getId(), lcpo.getRemark()));
            // 设置采购单状态为采购中
            // lcpo = new LmsChemicalPurchaseOrder();
            //lcpo.setId(lcpo.getId());
            lcpo.setApplyer(account.getUserName());
            lcpo.setStatus(PurchaseOrderEnum.IN_APPROVAL.getValue());
            //list.add(lcpo);
        }
        this.updateBatchById(lcpoList);
        if(null != sendUserId){
            //发送消息
//            lmsMsgService.sendMsg("/lims/chemical_purchase","请前往-系统管理-工作流管理-我的任务中查看详情,请确保您处于工作组中。",
//                    "新的耗材采购申请需要您的审批",LoginHelper.getAccount(), Lists.newArrayList(sendUserId));
        }
        return flowProcessService.saveTask(flowInfoList,account);
    }

    public Page<LmsChemicalPurchaseOrderVO> pageByStatusList(Page<LmsChemicalPurchaseOrderVO> page, LmsChemicalPurchaseOrderVO vo, List<Integer> statusList) {
        return page.setRecords(baseMapper.pageByStatusList(page, vo,statusList));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean approveFlow(String flowId, String allow, String postil,Long id,Long userId) {
        PurchaseOrderEnum purchaseOrderEnum = null;
        Account account = LoginHelper.getAccount();
        FlowVariables flowVariables = new FlowVariables();
        flowVariables.setTaskId(flowId);
        FlowInfo flowInfo = null;
        Map<String, Object> map = new HashMap<>(2);
        LmsChemicalPurchaseOrder order = this.getById(id);
        if(null == order){
            return false;
        }
        if ("5".equals(allow)) {
            //实验室主任驳回
            map.put("centerDirectorAduitPass", true);
            map.put("centerManager", false);
            purchaseOrderEnum = PurchaseOrderEnum.APPROVAL_REJECT;
        } else if ("3".equals(allow)) {
            //判断是新数据还是旧数据
            PtAssert.fail(null == id,"采购单id未传");
            PtAssert.fail(null == order || null == order.getCtime(),"采购单查询为空");
            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.getCtime().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("centerDirectorAduitPass", false);
                map.put("centerManager", true);
                purchaseOrderEnum = PurchaseOrderEnum.IN_APPROVAL;
                if(null != userId){
                    //发送消息
//                    lmsMsgService.sendMsg("/lims/equip_purchase","请前往-系统管理-工作流管理-我的任务中查看详情,请确保您处于工作组中。",
//                            "新的耗材采购申请需要您的审批",LoginHelper.getAccount(), Lists.newArrayList(userId));
                }
//                order.setFirstApprovalId(account.getUserId());
//                order.setFirstApproval(account.getUserName());
//                order.setFirstApprovalDate(new Date());
            }else{
                //实验室主任通过,流程结束，采购单状态为待采购
                map.put("centerDirectorAduitPass", true);
                map.put("centerManager", false);
                purchaseOrderEnum = PurchaseOrderEnum.WAIT_PURCHASE;
            }
        } else if("2".equals(allow)){
            //实验室主任终止
            map.put("centerDirectorAduitPass", true);
            map.put("centerManager", false);
            purchaseOrderEnum = PurchaseOrderEnum.APPROVAL_FAILED;
        }
        map.put(FlowInfo.APPLY_ID, account.getUserId());
        flowVariables.setVariables(map);
        flowInfo = flowProcessService.complete(flowVariables);
        PtAssert.fail(null == flowInfo, "确认审批失败！");
        PtAssert.fail(!this.postil(account, postil, purchaseOrderEnum,order), "采购单状态设置失败请重试！");
        return null != flowInfo;
    }
    public boolean postil(Account account,String postil, PurchaseOrderEnum purchaseOrderEnum,LmsChemicalPurchaseOrder lcpo) {
        LmsChemicalPurchaseOrder tempLcpo = new LmsChemicalPurchaseOrder();
        tempLcpo.setId(lcpo.getId());
        // 追加批注内容
        StringBuffer tempPostil = new StringBuffer();
        if (null != lcpo.getPostil()) {
            tempPostil.append(lcpo.getPostil()).append(" | ");
        }
        tempPostil.append(postil).append("【");
        tempPostil.append(account.getUserName()).append(", ");
        tempPostil.append(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        tempPostil.append("】");
        tempLcpo.setPostil(tempPostil.toString());
        if (null != purchaseOrderEnum) {
            // 完成审核进入待采购状态
            tempLcpo.setStatus(purchaseOrderEnum.getValue());
        }
        if(purchaseOrderEnum.getValue()==(5)){
//            lmsMsgService.sendMsg("/lims/chemical_purchase_order","订单编号："+lcpo.getNum()+"被驳回",
//                    "新的耗材采购审批通知",account,null);
        }else if(purchaseOrderEnum.getValue()==(3)){
//            lmsMsgService.sendMsg("/lims/chemical_purchase_order","订单编号："+lcpo.getNum()+"审批通过",
//                    "新的耗材采购审批通知",account,null);
        }else if(purchaseOrderEnum.getValue()==(2)){
//            lmsMsgService.sendMsg("/lims/chemical_purchase_order","订单编号："+lcpo.getNum()+"被终止",
//                    "新的耗材采购审批通知",account,null);
        }
        return super.updateById(tempLcpo);
    }

}
