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

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.core.oss.OssFileResult;
import com.patzn.lims.core.toolkit.IoUtils;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.equip.dto.LmsEquipCheckDTO;
import com.patzn.lims.equip.entity.*;
import com.patzn.lims.equip.enums.EquipDataStatusEnum;
import com.patzn.lims.equip.enums.EquipFileTypeEnum;
import com.patzn.lims.equip.mapper.LmsEquipCheckMapper;
import com.patzn.lims.equip.service.*;
import com.patzn.lims.equip.vo.LmsEquipCheckManageVO;
import com.patzn.lims.equip.vo.LmsEquipCheckVO;
import com.patzn.lims.res.service.ILmsPropertyService;
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.ArrayUtils;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2017-11-30
 */
@Service
public class LmsEquipCheckServiceImpl extends BaseServiceImpl<LmsEquipCheckMapper, LmsEquipCheck> implements ILmsEquipCheckService {

    @Autowired
    private OssClient ossClient;
    @Autowired
    private ILmsEquipFileService lmsEquipFileService;
    @Autowired
    private IFlowProcessService flowProcessClient;
    @Autowired
    private ILmsEquipCheckService lmsEquipCheckService;
    @Autowired
    private ILmsEquipCheckManageService lmsEquipCheckManageService;

    @Autowired
    private ILmsEquipInfoService lmsEquipInfoService;
    @Autowired
    private ILmsEquipCheckHostoryService lmsEquipCheckHostoryService;

    @Autowired
    private ILmsPropertyService lmsPropertyService;
    @Autowired
    private ILmsEquipCheckDetailService lmsEquipCheckDetailService;

    @Override
    public Page<LmsEquipCheckManageVO> page(Page<LmsEquipCheckManageVO> page, LmsEquipCheckManageVO lmsEquipCheck) {
        lmsEquipCheck.setCompanyId(LoginHelper.getAccount().getCompanyId());
        return page.setRecords(baseMapper.selectEquipCheckList(page, lmsEquipCheck));
    }

    @Override
    public List<LmsEquipCheck> list(LmsEquipCheck lmsEquipCheck) {
        lmsEquipCheck.setTempStatus(EquipDataStatusEnum.REAL.getValue());
        return list(Wrappers.<LmsEquipCheck>query(lmsEquipCheck));
    }

    @Override
    public LmsEquipCheckVO getVOById(Long id) {
        LmsEquipCheckVO lmsEquipCheckVO = new LmsEquipCheckVO();
        LmsEquipCheck lmsEquipCheck = baseMapper.selectById(id);
        //获取文件和详情
        if (null != lmsEquipCheck) {
            lmsEquipCheckVO = lmsEquipCheck.convert(LmsEquipCheckVO.class);
            List<LmsEquipFile> lmsEquipFileList = lmsEquipFileService.list(Wrappers.<LmsEquipFile>query().eq("rel_id", id));
            lmsEquipCheckVO.setLmsEquipFiles(lmsEquipFileList);
            List<LmsEquipCheckManageVO> checkManageVOList = baseMapper.selectVOList(id);
            lmsEquipCheckVO.setLmsEquipCheckManageVO(checkManageVOList);
            List<LmsEquipCheckDetail> details = lmsEquipCheckDetailService.getDetailByCheckId(id);
            if(CollectionUtils.isNotEmpty(details)){
                lmsEquipCheckVO.setDetails(details);
            }
        }

        return lmsEquipCheckVO;
    }

    @Override
    public boolean saveBatchEquipId(Long[] ids, LmsEquipCheckDetail lmsEquipCheckDetail, int t) {
        PtAssert.fail(ArrayUtils.isEmpty(ids), "请选择一条记录");
        PtAssert.fail(StringUtils.isBlank(lmsEquipCheckDetail.getCheckName()) || (null == lmsEquipCheckDetail.getCheckId())
                        || null == lmsEquipCheckDetail.getCheckStartTimePlan() || null == lmsEquipCheckDetail.getCheckEndTimePlan()
                , "请填写必填项");

        for (int i = 0; i < ids.length; i++) {
            lmsEquipCheckDetail.setId(IdWorker.getId());
            lmsEquipCheckDetail.setEquipId(ids[i]);
            lmsEquipCheckDetail.setCheckId(lmsEquipCheckDetail.getCheckId());
            lmsEquipCheckDetailService.save(lmsEquipCheckDetail);
        }
        if(t==1){
            return true;
        }else {
            List<LmsEquipInfo>list= lmsEquipInfoService.list(Wrappers.<LmsEquipInfo>query().in("id",ids));
            String name= list.stream().map(e->(null==e.getLabNum()?"":e.getLabNum())+e.getName()).collect(Collectors.joining(","));
            LmsEquipCheckHostory checkHostory = new LmsEquipCheckHostory();
            checkHostory.setType(0);
            checkHostory.setUname(LoginHelper.getAccount().getUserName());
            checkHostory.setDetails("编辑时新增:"+name);
            checkHostory.setOperation("新增");
                LmsEquipCheck lmsEquipCheck = super.getById(lmsEquipCheckDetail.getCheckId());
                if(null!=lmsEquipCheck){
                    checkHostory.setNum(lmsEquipCheck.getNum());
                    checkHostory.setName(lmsEquipCheck.getName());
                }
            checkHostory.setCheckId(lmsEquipCheckDetail.getCheckId());
            lmsEquipCheckHostoryService.save(checkHostory);

        }
        return true;
    }

    @Override
    public LmsEquipCheckVO getTemp() {
        LmsEquipCheckVO lmsEquipCheckVO = new LmsEquipCheckVO();
        LmsEquipCheckVO CheckVO = new LmsEquipCheckVO();
        CheckVO.setUserId(LoginHelper.getAccount().getUserId());
        CheckVO.setTempStatus(EquipDataStatusEnum.TEMP.getValue());
        LmsEquipCheck lmsEquipCheck = lmsEquipCheckService.selectOne(CheckVO);
        if (null != lmsEquipCheck) {
            //获取附件
            lmsEquipCheckVO = lmsEquipCheck.convert(LmsEquipCheckVO.class);
            List<LmsEquipFile> lmsEquipFileList = lmsEquipFileService.list(Wrappers.<LmsEquipFile>query().eq("rel_id", lmsEquipCheck.getId()));
            lmsEquipCheckVO.setLmsEquipFiles(lmsEquipFileList);
            //获取详情
            List<LmsEquipCheckManageVO> list = baseMapper.selectTempVOList(lmsEquipCheck.getId());
            lmsEquipCheckVO.setLmsEquipCheckManageVO(list);


        } else {
            LmsEquipCheck check = new LmsEquipCheck();
            check.setUserId(LoginHelper.getAccount().getUserId());
            check.setTempStatus(EquipDataStatusEnum.TEMP.getValue());
            lmsEquipCheckService.save(check);
            lmsEquipCheckVO = check.convert(LmsEquipCheckVO.class);
            List<LmsEquipFile> lmsEquipFileList = lmsEquipFileService.list(Wrappers.<LmsEquipFile>query().eq("rel_id", lmsEquipCheckVO.getId()));
            lmsEquipCheckVO.setLmsEquipFiles(lmsEquipFileList);
        }

        return lmsEquipCheckVO;
    }

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


    }

    @Override
    public boolean edit(LmsEquipCheckDTO lmsEquipCheck) {
        PtAssert.fail(null==lmsEquipCheck.getLmsEquipCheck().getOrgName()||null==lmsEquipCheck.getLmsEquipCheck().getOrgId(),"没有部门");
        PtAssert.fail(StringUtils.isBlank(lmsEquipCheck.getLmsEquipCheck().getNum()), "请填写编号");
        PtAssert.fail(!inputNum(lmsEquipCheck.getLmsEquipCheck().getId(), lmsEquipCheck.getLmsEquipCheck().getNum()), "编号重复或错误");;
        StringBuilder stringBuilder = new StringBuilder();
        LmsEquipCheck old = super.getById(lmsEquipCheck.getLmsEquipCheck().getId());
        PtAssert.fail(null==old,"原委托单不存在");
       String code=lmsPropertyService.getCompareTimeFormatDifferent(lmsEquipCheck.getLmsEquipCheck(), old, "期间核查单对比", "期间核查主委托修改:");
        PtAssert.fail(lmsEquipCheck.getDetailList().size()==0,"请至少提交一条详情");
        lmsEquipCheck.getDetailList().forEach(dto->{
            PtAssert.fail(StringUtils.isBlank(dto.getCheckName()), "负责人不能为空");
            PtAssert.fail(null == dto.getCheckStartTimePlan(), "计划保养开始时间不能为空");
            PtAssert.fail(null == dto.getCheckEndTimePlan(), "计划保养结束时间不能为空");
            PtAssert.fail(dto.getCheckEndTimePlan().before(dto.getCheckStartTimePlan()), "开始时间不能大于结束时间");
            PtAssert.fail(null == dto.getEquipId(), "提交的核查单中含有不存在找不到该仪器");
                LmsEquipInfo lmsEquipInfo = lmsEquipInfoService.getById(dto.getEquipId());
            PtAssert.fail(null == lmsEquipInfo, "需要查询的仪器不存在");
                LmsEquipCheckDetail lmsOld = lmsEquipCheckDetailService.getById(dto.getId());
            PtAssert.fail(null==lmsOld,"该详情单已被删除");
            stringBuilder.append(lmsPropertyService.getCompareTimeFormatDifferent(dto, lmsOld, "期间核查详情对比", ""+lmsEquipInfo.getLabNum()+lmsEquipInfo.getName() + ":"));
            lmsEquipCheckDetailService.updateById(dto);
        });

        LmsEquipCheckHostory hostory = new LmsEquipCheckHostory();
        hostory.setCheckId(lmsEquipCheck.getLmsEquipCheck().getId());
        hostory.setType(0);
        hostory.setUname(LoginHelper.getAccount().getUserName());
        hostory.setRemark(lmsEquipCheck.getLmsEquipCheck().getRemark());
        hostory.setNum(lmsEquipCheck.getLmsEquipCheck().getNum());
        hostory.setName(lmsEquipCheck.getLmsEquipCheck().getName());
        hostory.setDetails(StringUtils.isBlank(stringBuilder) ? code : stringBuilder.toString());
        if(StringUtils.isBlank(code)&& StringUtils.isBlank(stringBuilder)){

        }else {
            lmsEquipCheckHostoryService.save(hostory);
        }
        hostory.setOperation("修改保养单");
        updateById(lmsEquipCheck.getLmsEquipCheck());
        //提交
        if (Integer.valueOf(1).equals(lmsEquipCheck.getLmsEquipCheck().getStatus())
                || Integer.valueOf(3).equals(lmsEquipCheck.getLmsEquipCheck().getStatus())) {
            submit(lmsEquipCheck.getLmsEquipCheck().getId());
        }

        return true;
    }

    public boolean LmsEquipCheckNum(String num) {
        PtAssert.fail(StringUtils.isBlank(num), "请输入编号");
        return 0 == super.count(Wrappers.<LmsEquipCheck>query().eq("num", num));
    }

    public boolean LmsEquipSubmitCheckNum(String num, Long id) {
        PtAssert.fail(StringUtils.isBlank(num), "请输入编号");
        LmsEquipCheck lmsEquipCheck = super.getById(id);
        if (!lmsEquipCheck.getNum().equals(num)) {
            return 0 == super.count(Wrappers.<LmsEquipCheck>query().eq("num", num));
        }
        return 0 == super.count(Wrappers.<LmsEquipCheck>query().eq("num", num));
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(LmsEquipCheck lmsEquipCheck, int t) {
        PtAssert.fail(StringUtils.isBlank(lmsEquipCheck.getNum()), "请填写编号");
        if (t == 1) {
            PtAssert.fail(!LmsEquipCheckNum(lmsEquipCheck.getNum()), "编号重复");
        } else {
            PtAssert.fail(!LmsEquipSubmitCheckNum(lmsEquipCheck.getNum(), lmsEquipCheck.getId()), "编号重复");
        }
        PtAssert.fail(null == lmsEquipCheck.getId(), "请选择一条记录");
        PtAssert.fail(StringUtils.isBlank(lmsEquipCheck.getName()), "请填写计划名称");
        PtAssert.fail(StringUtils.isBlank(lmsEquipCheck.getOrgName()) || null == lmsEquipCheck.getOrgId(), "请填写部门");
        lmsEquipCheck.setRegisterId(LoginHelper.getAccount().getUserId());
        lmsEquipCheck.setRegisterName(LoginHelper.getAccount().getUserName());
        lmsEquipCheck.setRegisterTime(new Date());
        LmsEquipCheck check = new LmsEquipCheck();
        check.setUserId(LoginHelper.getAccount().getUserId());
        check.setTempStatus(EquipDataStatusEnum.TEMP.getValue());
        LmsEquipCheck temp = lmsEquipCheckService.selectOne(check);
        if (null != temp) {
            lmsEquipCheck.setId(temp.getId());
            lmsEquipCheck.setTempStatus(EquipDataStatusEnum.REAL.getValue());
            lmsEquipCheckService.updateById(lmsEquipCheck);
        } else {
            lmsEquipCheck.setUserId(LoginHelper.getAccount().getUserId());
            lmsEquipCheck.setTempStatus(EquipDataStatusEnum.REAL.getValue());
            lmsEquipCheckService.save(lmsEquipCheck);
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (Integer.valueOf(1).equals(lmsEquipCheck.getStatus())) {
            List<LmsEquipCheckDetail>list =lmsEquipCheckDetailService.list(Wrappers.<LmsEquipCheckDetail>query().eq("check_id",lmsEquipCheck.getId()));
            list.stream().forEach(dto -> {
                PtAssert.fail(StringUtils.isBlank(dto.getCheckName()), "负责人不能为空");
                PtAssert.fail(null == dto.getCheckStartTimePlan(), "计划保养开始时间不能为空");
                PtAssert.fail(null == dto.getCheckEndTimePlan(), "计划保养结束时间不能为空");
                PtAssert.fail(dto.getCheckEndTimePlan().before(dto.getCheckStartTimePlan()), "开始时间不能大于结束时间");
                PtAssert.fail(null == dto.getEquipId(), "提交的核查单中含有不存在找不到该仪器");
                LmsEquipInfo lmsEquipInfo = lmsEquipInfoService.getById(dto.getEquipId());
                PtAssert.fail(null == lmsEquipInfo, "需要查询的仪器不存在");
                LmsEquipCheckDetail lmsOld = lmsEquipCheckDetailService.getById(dto.getId());
                if (t == 1) {
                    stringBuilder.append(lmsEquipInfo.getLabNum() + lmsEquipInfo.getName() + "、");
                } else {
                    stringBuilder.append(lmsPropertyService.getCompareDifferent(dto, lmsOld, "期间核查详情对比", lmsEquipInfo.getName() + ":"));
                    lmsEquipCheckDetailService.updateById(dto);
                }

            });
        }
        if (Integer.valueOf(1).equals(lmsEquipCheck.getStatus())) {
            submit(lmsEquipCheck.getId());
        }
        LmsEquipCheckHostory hostory = new LmsEquipCheckHostory();
        hostory.setCheckId(lmsEquipCheck.getId());
        hostory.setType(0);
        hostory.setUname(LoginHelper.getAccount().getUserName());
        hostory.setRemark(lmsEquipCheck.getRemark());
        hostory.setNum(lmsEquipCheck.getNum());
        hostory.setName(lmsEquipCheck.getName());
        if (t == 1) {
            hostory.setOperation("创建保养单");
            hostory.setDetails("创建详情:" + stringBuilder);
        } else {
            hostory.setOperation("修改保养单");
            hostory.setDetails(stringBuilder.toString());
        }
        lmsEquipCheckHostoryService.save(hostory);
        return true;
    }

    @Override
    public boolean importLmsEquipCheck(MultipartFile file, Long checkId) {
//        Collection<LmsEquipCheckDetailETO> etos = ExcelUtils.readSheetAtOne(LmsEquipCheckDetailETO.class, file, "导入期间核查仪器信息失败");
//        if (CollectionUtils.isEmpty(etos)) {
//            return false;
//        }
//        Set<String> equipName = new HashSet<>();
//        Set<String> equipNum = new HashSet<>();
//        Set<String> equipSpec = new HashSet<>();
//        int i = 1;
//        for (LmsEquipCheckDetailETO eto : etos) {
//            RestAssert.fail(StringUtils.isBlank(eto.getEquipName()), "第"+i+"行请填写仪器名称");
//            RestAssert.fail(StringUtils.isBlank(eto.getEquipNum()), "第"+i+"行请填写仪器编号");
//            RestAssert.fail(StringUtils.isBlank(eto.getSpec()), "第"+i+"行请填写规格型号");
//            RestAssert.fail(StringUtils.isBlank(eto.getCheckName()), "第"+i+"行请填写负责人！");
//            RestAssert.fail(StringUtils.isBlank(eto.getCheckContent()), "第"+i+"行请填写核查内容");
//            RestAssert.fail(StringUtils.isBlank(eto.getCheckStartTimePlan()), "第"+i+"行请填写计划开始时间！");
//            RestAssert.fail(StringUtils.isBlank(eto.getCheckEndTimePlan()), "第"+i+"行请填写计划结束时间！");
//            RestAssert.fail(!DateUtils.isValidDate(eto.getCheckStartTimePlan(), "yyyy-MM-dd"), "第"+i+"行计划开始时间请按照2020-01-01的格式填写");
//            RestAssert.fail(!DateUtils.isValidDate(eto.getCheckEndTimePlan(), "yyyy-MM-dd"), "第"+i+"行计划结束时间请按照2020-01-01的格式填写");
//            RestAssert.fail(DateUtils.toDate(eto.getCheckEndTimePlan()).before(DateUtils.toDate(eto.getCheckStartTimePlan())),"第"+i+"行计划开始时间不能大于计划结束时间");
//            equipName.add(eto.getEquipName());
//            equipNum.add(eto.getEquipNum());
//            equipSpec.add(eto.getSpec());
//            i++;
//        }
//        List<LmsEquipInfo> infoList = lmsEquipInfoService.list(Wrappers.<>query().setSqlSelect("id,name,lab_num,spec").in("name", equipName).in("lab_num", equipNum).in("spec", equipSpec));
//        if (CollectionUtils.isEmpty(infoList)) {
//            RestAssert.fail("导入失败,请输入正确的 仪器编号，型号和仪器名称");
//        }
//        Map<String, Long> map = new HashMap<>();
//        infoList.forEach(e -> map.put(e.getName() + "|" + e.getLabNum() + e.getSpec(), e.getId()));
//        List<LmsEquipCheckDetail> lmsEquipCheckDetails = new ArrayList<>();
//        for (LmsEquipCheckDetailETO eto : etos) {
//            String info = eto.getEquipName() + "|" + eto.getEquipNum() + eto.getSpec();
//            Long equipId = map.get(info);
//            if (null == equipId) {
//                RestAssert.fail(info + "不存在于系统中,请确认后重新输入");
//            }
//            LmsEquipCheckDetail detail = new LmsEquipCheckDetail();
//            detail.setEquipId(equipId);
//            detail.setCheckId(checkId);
//            detail.setCheckContent(eto.getCheckContent());
//            detail.setCheckStartTimePlan(DateUtils.toDate(eto.getCheckStartTimePlan()));
//            detail.setCheckEndTimePlan(DateUtils.toDate(eto.getCheckEndTimePlan()));
//            detail.setCheckName(eto.getCheckName());
//            if (StringUtils.isNotBlank(eto.getRemark())) {
//                detail.setRemark(eto.getRemark());
//            }
//            if (StringUtils.isNotBlank(eto.getCheckRate())) {
//                detail.setCheckRate(eto.getCheckRate());
//            }
//
//            if (StringUtils.isNotBlank(eto.getDecideMethod())) {
//                detail.setDecideMethod(eto.getDecideMethod());
//            }
//            if (StringUtils.isNotBlank(eto.getCheckWays())) {
//                detail.setCheckWays(eto.getCheckWays());
//            }
//            lmsEquipCheckDetails.add(detail);
//
//        }
//        if (CollectionUtils.isNotEmpty(lmsEquipCheckDetails)) {
//            return lmsEquipCheckDetailService.saveBatch(lmsEquipCheckDetails);
//        }
        return true;
    }


    @Override
    public LmsEquipCheckDetail copyInput(Long id) {
        LmsEquipCheckDetail equipCheckDetail = new LmsEquipCheckDetail();
        LmsEquipCheckDetail detail = lmsEquipCheckDetailService.getById(id);
        PtAssert.fail(null == detail, "此条信息不存在,不可复制");
        equipCheckDetail.setCheckEndTimePlan(detail.getCheckEndTimePlan());
        equipCheckDetail.setCheckStartTimePlan(detail.getCheckStartTimePlan());
        equipCheckDetail.setCheckName(detail.getCheckName());
        equipCheckDetail.setCheckContent(detail.getCheckContent());
        equipCheckDetail.setCheckId(detail.getCheckId());
        equipCheckDetail.setRemark(detail.getRemark());

        return equipCheckDetail;


    }

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

        return true;
    }

    @Override
    public List<LmsEquipCheckDetail> vagueInput(String name, String value) {
        switch (name) {
            case "核查内容":
                return baseMapper.selectListContent(value);
            default:
                return null;
        }
    }

    @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)) {
            //技术主管审批通过
            map.put("centerDirectorAduitPass", true);
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            flowVariables.setVariables(map);
            flowInfo = flowProcessClient.complete(flowVariables);
            if (null == flowInfo) {
                PtAssert.fail("确认审批失败！");
                return false;
            } else {
                LmsEquipCheckManage lmsEquipCheckManage = new LmsEquipCheckManage();
                lmsEquipCheckManage.setCheckId(flowInfo.getId());
                lmsEquipCheckManage.setCompanyId(LoginHelper.getAccount().getCompanyId());
                //审批通过
                lmsEquipCheckManage.setStatus(0);
                lmsEquipCheckManageService.save(lmsEquipCheckManage);
            }
        } else if ("false".equals(status)) {
            flowInfo = flowProcessClient.complete(taskId);
        } else if ("2".equals(status)) {
            //技术主管审批通过
            map.put("centerDirectorAduitPass", true);
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            flowVariables.setVariables(map);
            flowInfo = flowProcessClient.complete(flowVariables);
        } else if ("3".equals(status)) {
            //技术主管审批驳回
            map.put("centerDirectorAduitPass", false);
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            flowVariables.setVariables(map);
            flowInfo = flowProcessClient.complete(flowVariables);
        } else if ("5".equals(status)) {
        //技术主管审批终止
        map.put("centerDirectorAduitPass", false);
        map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
        flowVariables.setVariables(map);
        flowInfo = flowProcessClient.complete(flowVariables);
        } else {
            flowInfo = null;
        }

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

    @Override
    public LmsEquipFile uploadFile(MultipartFile file, LmsEquipCheck lmsEquipCheck, int type) {
        PtAssert.fail(null == lmsEquipCheck.getId(), "请选择一条记录");
        Long companyId = LoginHelper.getAccount().getCompanyId();
        LmsEquipCheck check = super.getById(lmsEquipCheck.getId());
        LmsEquipCheckHostory lmsEquipCheckHostory = new LmsEquipCheckHostory();
        lmsEquipCheckHostory.setCheckId(lmsEquipCheck.getId());
        lmsEquipCheckHostory.setDetails("文件名:" + file.getOriginalFilename());
        lmsEquipCheckHostory.setName(null == check.getName() ? "创建前上传" : check.getName());
        lmsEquipCheckHostory.setOrgName(null == check.getOrgName() ? "创建前上传" : check.getName());
        lmsEquipCheckHostory.setUname(LoginHelper.getAccount().getUserName());
        lmsEquipCheckHostory.setNum(null == check.getNum() ? "创建前上传" : check.getNum());
        lmsEquipCheckHostory.setOperation("上传");
        lmsEquipCheckHostory.setType(type);
        lmsEquipCheckHostoryService.save(lmsEquipCheckHostory);
        //区分公司
        return lmsEquipFileService.saveAndUpload(file, "lims", "equip/flow/check/" + companyId + "/", lmsEquipCheck.getId(), EquipFileTypeEnum.CHECK.getValue());
    }

    @Override
    public void downloadFile(Long id, HttpServletResponse response) {
        LmsEquipFile lmsEquipFile = lmsEquipFileService.getById(id);
        String fileUrl = lmsEquipFile.getFilePath();
        String orgFileName = lmsEquipFile.getOrginName().replaceAll("\\s*", "");
        lmsEquipFileService.downloadFile(response, "lims", fileUrl, orgFileName);
    }

    @Override
    public boolean deleteFiles(Long id, Long checkId, int type) {
        Long[] ids = new Long[]{id};
        List<LmsEquipFile> equipFileList = lmsEquipFileService.list(Wrappers.<LmsEquipFile>query().in("id", ids));
        String nameFile = equipFileList.stream().map(e -> e.getOrginName()).collect(Collectors.joining(","));
        LmsEquipCheckHostory history = new LmsEquipCheckHostory();
        LmsEquipCheck lmsEquipCheck = super.getById(checkId);
        PtAssert.fail(null == lmsEquipCheck, "该保养单已被删除,不可上传附件");
        history.setName(null == lmsEquipCheck.getName() ? "创建前删除" : lmsEquipCheck.getName());
        history.setNum(null == lmsEquipCheck.getNum() ? "创建前删除" : lmsEquipCheck.getNum());
        history.setOperation("删除");
        history.setOrgName(lmsEquipCheck.getOrgName());
        history.setDetails("附件名:" + nameFile);
        history.setType(Integer.valueOf(type));
        history.setCheckId(checkId);
        history.setUname(LoginHelper.getAccount().getUserName());
        lmsEquipCheckHostoryService.save(history);
        return lmsEquipFileService.deleteBatch(ids);

    }

    public boolean deleteFile(Long id) {
        LmsEquipFile lmsEquipFile = lmsEquipFileService.getById(id);
        if (null == lmsEquipFile) {
            return false;
        }
        ossClient.deleteObject(lmsEquipFile.getFilePath());
        return lmsEquipFileService.removeById(id);
    }

    @Override
    public LmsEquipCheck selectOne(LmsEquipCheck lmsEquipCheck) {
        return baseMapper.selectOne(Wrappers.<LmsEquipCheck>query(lmsEquipCheck));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Long[] ids) {
        lmsEquipFileService.deleteBatch(ids);
        lmsEquipCheckDetailService.remove(Wrappers.<LmsEquipCheckDetail>query().in("check_id", ids));
        return super.remove(Wrappers.<LmsEquipCheck>query().in("id",ids));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchImplementation(LmsEquipCheckDTO lmsEquipCheckDTO) {
        PtAssert.fail(null==lmsEquipCheckDTO, "请先选择一条记录");
        PtAssert.fail( lmsEquipCheckDTO.getManageList().size()==0, "无数据可实施");
        StringBuilder stringBuilder = new StringBuilder();
        lmsEquipCheckDTO.getManageList().forEach(dto->{
            if (null != dto.getCheckStartTimeAct() && null != dto.getCheckEndTimeAct()) {
                PtAssert.fail(dto.getCheckStartTimeAct().after(dto.getCheckEndTimeAct()), "开始时间不能大于结束时间");
            }
            if (null != dto.getCheckEndTimeAct() && null != dto.getCheckStartTimeAct()) {
                PtAssert.fail(!dto.getCheckEndTimeAct().after(dto.getCheckStartTimeAct()), "结束时间不能小于开始时间");
            }
            PtAssert.fail(null==dto.getCheckId(),"找不到核查详情单");
            LmsEquipCheckDetail detailVO = lmsEquipCheckDetailService.getById(dto.getCheckId());
            LmsEquipInfo lmsEquipInfo =lmsEquipInfoService.getById(detailVO.getEquipId());
            PtAssert.fail(null==lmsEquipInfo,"找不到仪器");
            PtAssert.fail(null==detailVO,"此条信息不存在");
            LmsEquipCheckManage lmsOld=lmsEquipCheckManageService.getOne(dto.getCheckId());
            LmsEquipCheckManage newDto =dto.convert(LmsEquipCheckManage.class);
            if(null!=lmsOld){
                stringBuilder.append(lmsPropertyService.getCompareTimeFormatDifferent(newDto, lmsOld, "期间实施对比", ""+lmsEquipInfo.getLabNum()+lmsEquipInfo.getName()+":"));
                newDto.setId(lmsOld.getId());
                lmsEquipCheckManageService.updateById(newDto);
            }else {
                stringBuilder.append(lmsPropertyService.getCompareTimeFormatDifferent(newDto, new LmsEquipCheckManage(), "期间实施对比", ""+lmsEquipInfo.getLabNum()+lmsEquipInfo.getName()+":"));
                lmsEquipCheckManageService.save(newDto);
            }
        });
        LmsEquipCheck lmsEquipCheck = super.getById(lmsEquipCheckDTO.getLmsEquipCheck().getId());
        PtAssert.fail(null==lmsEquipCheck,"主保养单已被删除");
        LmsEquipCheckHostory lmsEquipMaintainHistory = new LmsEquipCheckHostory();
        lmsEquipMaintainHistory.setCheckId(lmsEquipCheck.getId());
        lmsEquipMaintainHistory.setName(lmsEquipCheck.getName());
        lmsEquipMaintainHistory.setNum(lmsEquipCheck.getNum());
        lmsEquipMaintainHistory.setUname(LoginHelper.getAccount().getUserName());
        lmsEquipMaintainHistory.setType(1);
        lmsEquipMaintainHistory.setOperation("修改");
        if(StringUtils.isNotBlank(stringBuilder)){
            lmsEquipMaintainHistory.setDetails(stringBuilder.toString());
            lmsEquipCheckHostoryService.save(lmsEquipMaintainHistory);
        }
        return true;
    }

    @Override
    public void sendMsg() {
        List<LmsEquipCheck> checkList = baseMapper.selectListByDate();
        for (LmsEquipCheck lmsEquipCheck : checkList) {
            if (null != lmsEquipCheck.getOrgId()) {
                sendMsg(lmsEquipCheck);
            }
        }

    }

    @Override
    public LmsEquipFile uploadFileRow(MultipartFile file, LmsEquipCheck lmsEquipCheck) {
        OssFileResult result = ossClient.upload(file);
        if (null == result) {
            return null;
        }
        LmsEquipFile lmsEquipFile = new LmsEquipFile();
        lmsEquipFile.setRelId(lmsEquipCheck.getId());
        lmsEquipFile.setOrginName(file.getOriginalFilename());
        lmsEquipFile.setFilePath(result.getObjectKey());
        lmsEquipFileService.save(lmsEquipFile);
        return lmsEquipFile;
    }

    @Override
    public Boolean deleteFileBatch(Long[] ids) {
        List<LmsEquipFile> files =   lmsEquipFileService.list(Wrappers.<LmsEquipFile>query().in("id",ids));
        if(CollectionUtils.isNotEmpty(files)){
          List<String> list  =  files.stream().map(e->e.getFilePath()).collect(Collectors.toList());
            lmsEquipFileService.remove(Wrappers.<LmsEquipFile>query().in("id",ids));
            ossClient.deleteObjects(list);
        }
        return true;
    }

    @Override
    public void downloadFiles(Long[] ids, HttpServletResponse response) {
        List<LmsEquipFile> listAttachment = lmsEquipFileService.list(Wrappers.<LmsEquipFile>query().in("id", ids));
        try {
            zipFile(response.getOutputStream(), listAttachment);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downloadRow(Long id, HttpServletResponse response) {
        List<LmsEquipFile> listAttachment = lmsEquipFileService.list(Wrappers.<LmsEquipFile>query().eq("rel_id", id));
        try {
            zipFile(response.getOutputStream(), listAttachment);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void zipFile(OutputStream os, List<LmsEquipFile> listAttachment) throws IOException {
        ZipOutputStream zos = null;
        int i = 1;
        try {
            zos = new ZipOutputStream(os);
            for (LmsEquipFile attachment : listAttachment) {
                int readCount;
                byte[] bytes = new byte[4096];
                zos.putNextEntry(new ZipEntry("("+i+")"+attachment.getOrginName()));
                InputStream is = ossClient.download(attachment.getFilePath());
                try {
                    while ((readCount = is.read(bytes)) != -1) {
                        zos.write(bytes, 0, readCount);
                    }
                } finally {
                    zos.flush();
                    IoUtils.close(is);
                }
                i++;
            }
        } finally {
            IoUtils.close(zos);
        }
    }

    private Integer updateCheck(FlowInfo flowInfo, String status, String reason) {
        LmsEquipCheck lmsEquipCheck = new LmsEquipCheck();
        lmsEquipCheck.setId(flowInfo.getId());
        if ("success".equals(status)) {
            lmsEquipCheck.setStatus(4);
        } else if ("false".equals(status)) {
            lmsEquipCheck.setStatus(3);
        } else if ("2".equals(status)) {
            //中心主任审批通过
            lmsEquipCheck.setStatus(2);
            lmsEquipCheck.setFirstStepId(LoginHelper.getAccount().getUserId());
            lmsEquipCheck.setFirstStepTime(new Date());
            lmsEquipCheck.setFirstStepAdvice(reason);
            lmsEquipCheck.setFirstStepName(LoginHelper.getAccount().getUserName());
        } else if ("3".equals(status)) {
            //中心主任审批驳回
            lmsEquipCheck.setStatus(3);
            lmsEquipCheck.setFirstStepId(LoginHelper.getAccount().getUserId());
            lmsEquipCheck.setFirstStepTime(new Date());
            lmsEquipCheck.setFirstStepAdvice(reason);
            lmsEquipCheck.setFirstStepName(LoginHelper.getAccount().getUserName());
        } else if ("5".equals(status)) {
            //中心主任审批终止
            lmsEquipCheck.setStatus(5);
            lmsEquipCheck.setFirstStepId(LoginHelper.getAccount().getUserId());
            lmsEquipCheck.setFirstStepTime(new Date());
            lmsEquipCheck.setFirstStepAdvice(reason);
            lmsEquipCheck.setFirstStepName(LoginHelper.getAccount().getUserName());
        } else {
            return null;
        }

        return baseMapper.updateById(lmsEquipCheck);
    }

    /**
     * 消息通知
     *
     * @param lmsEquipCheck
     */
    private void sendMsg(LmsEquipCheck lmsEquipCheck) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            StringBuilder content = new StringBuilder();
//            StringBuilder title = new StringBuilder();
//            title.append("期间核查通知:");
//            content.append("计划名称：").append(lmsEquipCheck.getName());
//            content.append("核查部门：").append(lmsEquipCheck.getOrgName());
//            content.append("申请原因:").append(lmsEquipCheck.getApplyReason());
//            content.append("计划核查开始时间:").append(sdf.format(lmsEquipCheck.getCheckStartTimePlan()));
//            content.append("计划核查结束时间:").append(sdf.format(lmsEquipCheck.getCheckEndTimePlan()));
//            MqMsg mqMsg = new MqMsg();
//            mqMsg.setUid(lmsEquipCheck.getRegisterId());
//            mqMsg.setCompanyId(lmsEquipCheck.getCompanyId());
//            mqMsg.setSender(lmsEquipCheck.getRegisterName());
//            mqMsg.setTitle(title.toString());
//            mqMsg.setContent(content.toString());
//            mqMsg.setType(1);
//            mqMsg.setSender("系统发送");
//            mqMsg.setReceiverIds(Lists.newArrayList(lmsEquipCheck.getOrgId()));
//            amqpTemplate.convertAndSend(mqProperties.getTopic().getPushMsg(), mqMsg);
//        } catch (AmqpException e) {
//            logger.error("期间核查发送消息失败", lmsEquipCheck.getName(), e);
//        }
    }
}
