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

import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.equip.entity.*;
import com.patzn.lims.equip.enums.EquipLogDataTypeEnum;
import com.patzn.lims.equip.enums.EquipLogStatusEnum;
import com.patzn.lims.equip.mapper.LmsEquipRepairMapper;
import com.patzn.lims.equip.service.*;
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.LmsEquipRepairDetailVO;
import com.patzn.lims.equip.vo.LmsEquipRepairVO;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 仪器维修信息表 服务实现类
 * </p>
 *
 * @author wwd
 * @since 2020-03-30
 */
@Service
public class LmsEquipRepairServiceImpl extends BaseServiceImpl<LmsEquipRepairMapper, LmsEquipRepair> implements ILmsEquipRepairService {

    @Autowired
    private ILmsEquipRepairService lmsEquipRepairService;


    @Autowired
    private IFlowProcessService flowProcessService;

    @Autowired
    private ILmsEquipRepairDetailService lmsEquipRepairDetailService;


    @Autowired
    private ILmsEquipLogService lmsEquipLogService;

    @Autowired
    private ILmsEquipFileService lmsEquipFileService;

    @Autowired
    private ILmsEquipRepairManageService lmsEquipRepairManageService;

    @Autowired
    private OssClient ossClient;


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


    @Override
    public Page<LmsEquipRepairVO> pageVO(Page<LmsEquipRepairVO> page, LmsEquipRepairVO lmsEquipRepair) {
        lmsEquipRepair.setCompanyId(LoginHelper.getAccount().getCompanyId());
        return page.setRecords(baseMapper.selectListVO(page,lmsEquipRepair));
    }


    @Override
    public LmsEquipRepairVO getTemp(Long[] ids) {
        LmsEquipRepairVO lmsEquipRepairVO = new LmsEquipRepairVO();

        LmsEquipRepair lmsEquipRepair = getOne(Wrappers.<LmsEquipRepair>query().eq("temp_status",0).eq("user_id",LoginHelper.getAccount().getUserId()));
        if (null==lmsEquipRepair){
            LmsEquipRepair repair = new LmsEquipRepair();
            repair.setUserId(LoginHelper.getAccount().getUserId());
            repair.setTempStatus(0);
             save(repair);
            lmsEquipRepair=repair;
        }

        for (Long id:ids) {
            LmsEquipRepairDetail detailVO=new LmsEquipRepairDetail();
            detailVO.setEquipId(id);
            detailVO.setRepairId(lmsEquipRepair.getId());
            lmsEquipRepairDetailService.save(detailVO);

        }

        BeanUtils.copyProperties(lmsEquipRepair, lmsEquipRepairVO);
        LmsEquipRepairDetailVO vo = new LmsEquipRepairDetailVO();
        vo.setRepairId(lmsEquipRepair.getId());
        List<LmsEquipRepairDetailVO> lmsEquipRepairDetailVOList = lmsEquipRepairDetailService.listVO(vo);
        lmsEquipRepairVO.setLmsEquipRepairDetailVOList(lmsEquipRepairDetailVOList);

        return lmsEquipRepairVO;
    }

    @Override
    public LmsEquipRepairVO getTemp() {
        LmsEquipRepairVO lmsEquipRepairVO = new LmsEquipRepairVO();
        LmsEquipRepair lmsEquipRepair = getOne(Wrappers.<LmsEquipRepair>query().eq("temp_status",0).eq("user_id",LoginHelper.getAccount().getUserId()));

        if (null != lmsEquipRepair){
            BeanUtils.copyProperties(lmsEquipRepair, lmsEquipRepairVO);
            LmsEquipRepairDetailVO vo = new LmsEquipRepairDetailVO();
            vo.setRepairId(lmsEquipRepair.getId());
            List<LmsEquipRepairDetailVO> lmsEquipRepairDetailVOList = lmsEquipRepairDetailService.listVO(vo);
            lmsEquipRepairVO.setLmsEquipRepairDetailVOList(lmsEquipRepairDetailVOList);

            //获取附件
            LmsEquipFile lmsEquipFile = new LmsEquipFile();
            lmsEquipFile.setRelId(lmsEquipRepair.getId());
            List<LmsEquipFile> lmsEquipFileList = lmsEquipFileService.list(lmsEquipFile);
            lmsEquipRepairVO.setLmsEquipFiles(lmsEquipFileList);
        } else {
            LmsEquipRepair repair = new LmsEquipRepair();
            repair.setUserId(LoginHelper.getAccount().getUserId());
            repair.setTempStatus(0);
            lmsEquipRepairService.save(repair);
            BeanUtils.copyProperties(repair, lmsEquipRepairVO);
            //获取附件
            LmsEquipFile lmsEquipFile = new LmsEquipFile();
            lmsEquipFile.setRelId(repair.getId());
            List<LmsEquipFile> lmsEquipFileList = lmsEquipFileService.list(lmsEquipFile);
            lmsEquipRepairVO.setLmsEquipFiles(lmsEquipFileList);
        }
        return  lmsEquipRepairVO;
    }

    public boolean inputNum(Long id,String num){
        LmsEquipRepair lmsEquipRepair = super.getById(id);
        if(null!=lmsEquipRepair.getNum()&&lmsEquipRepair.getNum().equals(num)){
            return 1==super.count(Wrappers.<LmsEquipRepair>query().eq("num",num));
        }else if(null!=lmsEquipRepair.getNum()&&!lmsEquipRepair.getNum().equals(num)){
            return 0==super.count(Wrappers.<LmsEquipRepair>query().eq("num",num));
        }else {
            return 0==super.count(Wrappers.<LmsEquipRepair>query().eq("num",num));
        }
    }

    @Override
    public boolean edit(LmsEquipRepair lmsEquipRepair) {
        PtAssert.fail(null==lmsEquipRepair.getId(),"id不能为空");
        PtAssert.fail(StringUtils.isBlank(lmsEquipRepair.getNum()),"请输入编号");

        PtAssert.fail(!inputNum(lmsEquipRepair.getId(),lmsEquipRepair.getNum()),"编号重复或错误");

        PtAssert.fail(StringUtils.isBlank(lmsEquipRepair.getApplyReason()),"请填写申请原因");

        //提交

        if (Integer.valueOf(1).equals(lmsEquipRepair.getStatus()) || Integer.valueOf(3).equals(lmsEquipRepair.getStatus())) {
            List<LmsEquipRepairDetail> details = lmsEquipRepairDetailService.list(Wrappers.<LmsEquipRepairDetail>query().eq("repair_id", lmsEquipRepair.getId()));
            List<Long> equipIds = new ArrayList<>();
            for (LmsEquipRepairDetail detail :details) {
                PtAssert.fail(StringUtils.isBlank(detail.getBreakdown()),"故障原因不能为空");
                PtAssert.fail(null==detail.getRepairStartTimePlan(),"计划维修开始时间不能为空");
                PtAssert.fail(null==detail.getRepairEndTimePlan(),"计划维修结束时间不能为空");

            }

            lmsEquipRepairService.submit(lmsEquipRepair.getId());
        }

        return lmsEquipRepairService.updateById(lmsEquipRepair);
    }


    @Transactional(rollbackFor = Exception.class)
    @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 {
                //保存维修管理
                List<LmsEquipRepairDetail> detailList = lmsEquipRepairDetailService.list(Wrappers.<LmsEquipRepairDetail>query().eq("repair_id", flowInfo.getId()));
                for (LmsEquipRepairDetail detail : detailList) {
                    //保存维修管理信息
                    LmsEquipRepairManage lmsEquipRepairManage = new LmsEquipRepairManage();
                    lmsEquipRepairManage.setDetailId(detail.getId());
                    lmsEquipRepairManage.setStatus(0);//待保养
                    lmsEquipRepairManageService.save(lmsEquipRepairManage);

                    //保存日志信息
                    lmsEquipLogService.saveLogs(detail.getRepairStartTimePlan(), detail.getRepairEndTimePlan(), detail.getEquipId(), detail.getId(), EquipLogStatusEnum.ORDER_REPAIR.getValue(), EquipLogDataTypeEnum.PLAN.getValue());

                    //发送消息提醒
                    if (StringUtils.isNotBlank(detail.getRepairerIds())) {
//                        sendMsg(detail);
                    }
                }
            }
        } else if ("false".equals(status)){
            flowInfo = flowProcessService.complete(taskId);
        } else if ("2".equals(status)) {//技术主管审批通过
            flowVariables.setVariables(map);
            map.put("technicalDirectorAduitPass", true);
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            flowInfo = flowProcessService.complete(flowVariables);
        } else if ("3".equals(status)) {//技术主管审批驳回
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            map.put("technicalDirectorAduitPass", false);
            flowVariables.setVariables(map);
            flowInfo = flowProcessService.complete(flowVariables);
        } else if ("5".equals(status)) {//技术主管审批终止
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            map.put("technicalDirectorAduitPass", false);
            flowVariables.setVariables(map);
            flowInfo = flowProcessService.complete(flowVariables);
        } else {
            flowInfo = null;
        }


        if (null != flowInfo){
            Integer count = updateRepair(flowInfo, status, reason);
            if (null == count){
                return false;
            } else {
                return true;
            }
        } else {return false;}
    }


    private Integer updateRepair(FlowInfo flowInfo, String status, String reason){
        LmsEquipRepair lmsEquipRepair = new LmsEquipRepair();
        lmsEquipRepair.setId(flowInfo.getId());
        if ("success".equals(status) || "false".equals(status)){
            lmsEquipRepair.setStatus(4);
        } else if ("2".equals(status)) {
            //技术主管审批通过
            lmsEquipRepair.setStatus(2);
            lmsEquipRepair.setFirstStepId(LoginHelper.getAccount().getUserId());
            lmsEquipRepair.setFirstStepTime(new Date());
            lmsEquipRepair.setFirstStepAdvice(reason);
            lmsEquipRepair.setFirstStepName(LoginHelper.getAccount().getUserName());
        } else if ("3".equals(status)) {
            //技术主管审批驳回
            lmsEquipRepair.setStatus(3);
            lmsEquipRepair.setFirstStepId(LoginHelper.getAccount().getUserId());
            lmsEquipRepair.setFirstStepTime(new Date());
            lmsEquipRepair.setFirstStepAdvice(reason);
            lmsEquipRepair.setFirstStepName(LoginHelper.getAccount().getUserName());
        } else if ("5".equals(status)) {
            //技术主管审批终止
            lmsEquipRepair.setStatus(5);
            lmsEquipRepair.setFirstStepId(LoginHelper.getAccount().getUserId());
            lmsEquipRepair.setFirstStepTime(new Date());
            lmsEquipRepair.setFirstStepAdvice(reason);
            lmsEquipRepair.setFirstStepName(LoginHelper.getAccount().getUserName());
        } else {
            return null;
        }

        return baseMapper.updateById(lmsEquipRepair);
    }


    @Override
    public boolean add(LmsEquipRepair lmsEquipRepair) {
        PtAssert.fail(!inputNum(lmsEquipRepair.getId(),lmsEquipRepair.getNum()),"编号重复或错误");
        PtAssert.fail(null==lmsEquipRepair.getId(),"id不能为空");
        lmsEquipRepair.setRegisterId(LoginHelper.getAccount().getUserId());
        lmsEquipRepair.setRegisterName(LoginHelper.getAccount().getUserName());
        lmsEquipRepair.setRegisterTime(new Date());
        //提交
        if (Integer.valueOf(1).equals(lmsEquipRepair.getStatus())) {
            List<LmsEquipRepairDetail> details = lmsEquipRepairDetailService.list(Wrappers.<LmsEquipRepairDetail>query().eq("repair_id", lmsEquipRepair.getId()));
            for (LmsEquipRepairDetail detail : details) {
                LmsEquipLog log = new LmsEquipLog();
                log.setEquipId(detail.getEquipId());
                log.setStartTime(detail.getRepairStartTimePlan());
                log.setEndTime(detail.getRepairEndTimePlan());
            }
        }

        LmsEquipRepair repair = new LmsEquipRepair();
        repair.setUserId(LoginHelper.getAccount().getUserId());
        repair.setTempStatus(0);
        LmsEquipRepair temp = lmsEquipRepairService.getOne(Wrappers.<LmsEquipRepair>query().eq("user_id",LoginHelper.getAccount().getUserId())
        .eq("temp_status",0));
        if (null != temp){
            lmsEquipRepair.setId(temp.getId());
            lmsEquipRepair.setTempStatus(1);
            lmsEquipRepairService.updateById(lmsEquipRepair);
        } else {
            lmsEquipRepair.setUserId(LoginHelper.getAccount().getUserId());
            lmsEquipRepair.setTempStatus(1);
            lmsEquipRepairService.save(lmsEquipRepair);
        }

        if (1 == lmsEquipRepair.getStatus()) {
            lmsEquipRepairService.submit(lmsEquipRepair.getId());
        }

        return true;
    }



    @Override
    public boolean submit(Long id) {
        try {
            LmsEquipRepair lmsEquipRepair = baseMapper.selectById(id);
            ArrayList<FlowInfo> flowInfoList = new ArrayList<>();
            Account account = LoginHelper.getAccount();
            //发起流程
            flowInfoList.add(FlowInfo.convertFlowInfo(FlowType.EQUIP_REPAIR,
                    account, lmsEquipRepair.getId(), lmsEquipRepair.getApplyReason()));
            flowProcessService.saveTask(flowInfoList,account);
            //更新状态
            lmsEquipRepair.setStatus(1);
            lmsEquipRepair.setApplyId(LoginHelper.getAccount().getUserId());
            lmsEquipRepair.setApplyName(LoginHelper.getAccount().getUserName());
            lmsEquipRepair.setApplyTime(new Date());
            baseMapper.updateById(lmsEquipRepair);
        } catch (Exception ex) {
            PtAssert.fail("流程提交失败，原因：" + ex.getMessage());
        }

        return true;
    }

    @Override
    public LmsEquipRepairVO getVO(Long id) {
        LmsEquipRepairVO lmsEquipRepairVO = new LmsEquipRepairVO();

        LmsEquipRepair lmsEquipRepair = getById(id);
        if (null != lmsEquipRepair){
            LmsEquipRepairDetailVO lmsEquipRepairDetailVO = new LmsEquipRepairDetailVO();
            lmsEquipRepairDetailVO.setRepairId(lmsEquipRepair.getId());
            List<LmsEquipRepairDetailVO> detailVOList = lmsEquipRepairDetailService.listVO(lmsEquipRepairDetailVO);
            BeanUtils.copyProperties(lmsEquipRepair, lmsEquipRepairVO);
            lmsEquipRepairVO.setLmsEquipRepairDetailVOList(detailVOList);
            //获取附件
            LmsEquipFile lmsEquipFile = new LmsEquipFile();
            lmsEquipFile.setRelId(lmsEquipRepair.getId());
            List<LmsEquipFile> lmsEquipFileList = lmsEquipFileService.list(lmsEquipFile);
            //前端要展示，放入图片路径
            lmsEquipFileList.forEach(e->{
                e.setFilePath( ossClient.getUrl(e.getFilePath()).toString());
            });
            lmsEquipRepairVO.setLmsEquipFiles(lmsEquipFileList);
        }
        return lmsEquipRepairVO;
    }
}
