package cn.wise.sc.cement.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.cement.business.entity.*;
import cn.wise.sc.cement.business.mapper.*;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.IndustrialReport;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.ReportDetailVo;
import cn.wise.sc.cement.business.model.SixElementReport;
import cn.wise.sc.cement.business.model.query.*;
import cn.wise.sc.cement.business.model.vo.*;
import cn.wise.sc.cement.business.service.*;
import cn.wise.sc.cement.business.util.CheckCountUtil;
import cn.wise.sc.cement.business.util.ExcelUtil;
import cn.wise.sc.cement.business.util.PageUtil;
import cn.wise.sc.cement.business.util.RedisUtil;
import cn.wise.sc.cement.business.util.weixin.Global;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.models.auth.In;
import lombok.Data;
import net.bytebuddy.description.field.FieldDescription;
import org.apache.commons.io.filefilter.FalseFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-08-24
 */
@Service
public class EntrustServiceImpl extends ServiceImpl<EntrustMapper, Entrust> implements IEntrustService {

    @Resource
    private EntrustMapper entrustMapper;
    @Autowired
    private ISampleTmpService sampleTmpService;
    @Autowired
    private ISysUserService userService;
    @Resource
    private TeamMapper teamMapper;
    @Autowired
    private CommonServiceImpl commonService;
    @Autowired
    private ISampleService sampleService;
    @Resource
    private EntrustApprovalMapper approvalMapper;
    @Autowired
    private ISysLogsService logsService;
    @Autowired
    private ISampleHandleService sampleHandleService;
    @Resource
    private SampleHandleMapper sampleHandleMapper;
    @Autowired
    private ISampleDistributionService distributionService;
    @Resource
    private SampleDistributionMapper distributionMapper;
    @Autowired
    private ISampleCheckService sampleCheckService;
    @Autowired
    private ISampleCheckTeamService sampleCheckTeamService;
    @Autowired
    private IEquipmentUseService equipmentUseService;
    @Resource
    private ProjectMapper projectMapper;
    @Autowired
    RedisUtil redisUtil;
    @Resource
    private SampleMapper sampleMapper;
    @Resource
    private SysApprovalMapper sysApprovalMapper;
    @Resource
    private MethodMapper methodMapper;
    @Resource
    private HandleMapper handleMapper;
    @Autowired
    private ISampleHandleEnclosureService sampleHandleEnclosureService;
    @Resource
    private SampleHandleEnclosureMapper sampleHandleEnclosureMapper;
    @Resource
    private TeamGroupMapper teamGroupMapper;
    @Resource
    private SampleCheckMapper sampleCheckMapper;
    @Resource
    private SampleCheckTeamMapper sampleCheckTeamMapper;
    @Resource
    private EquipmentUseMapper equipmentUseMapper;
    @Resource
    private ClientMapper clientMapper;
    @Autowired
    private ISysUserMessageService userMessageService;
    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private INormProductionService iNormProductionService;
    @Autowired
    private IPrecipriceService iPrecipriceService;
    @Resource
    private EntityEnclosureMapper entityEnclosureMapper;

    @Value("${weixin.systemUrl}")
    private String systemUrl;
    /**
     * 委托分页
     *
     * @param pageQuery
     * @param startDate
     * @param endDate
     * @param status
     * @param clientName
     * @param projectName
     * @return
     */
    @Override
    public BaseResponse<IPage<EntrustVo>> getPage(PageQuery pageQuery, String startDate, String endDate, Integer status,
                                                  String clientName, String projectName, String projectCode, Integer isUrgent) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("status", status);
        params.put("clientName", clientName);
        params.put("projectName", projectName);
        params.put("projectCode", projectCode);
        params.put("isUrgent", isUrgent);
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }
        if (!approvalIdList.contains(loginUser.getId())) {
            params.put("userId", loginUser.getId());
        }
        Page<EntrustVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        IPage<EntrustVo> pages = entrustMapper.getPage(page, params);
        List<EntrustVo> list = pages.getRecords();
        if (list != null && list.size() > 0) {
            for (EntrustVo entrustVo : list) {
                QueryWrapper<SampleTmp> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("entrust_id", entrustVo.getId());
                List<SampleTmp> sampleTmpList = sampleTmpService.list(queryWrapper);
                //检测项目名称
                String sampleNames = "";
                if (sampleTmpList != null && sampleTmpList.size() > 0) {
                    //样品名称 列表中的拼接
                    for (SampleTmp sampleTmp : sampleTmpList) {
                        sampleNames = sampleNames.equals("") ? sampleTmp.getName() : (sampleNames + "、" + sampleTmp.getName());
                    }
                    entrustVo.setSampleNames(sampleNames);
                    //检测项 和检测依据 列表里只显示第一个样品的
                    SampleTmp sampleTmp = sampleTmpList.get(0);
                    String teamIds = sampleTmp.getTeamIds();
                    String checkTeam = "";
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            Team team = teamMapper.selectById(Integer.valueOf(teamId));
                            if (team != null) {
                                checkTeam = checkTeam.equals("") ? team.getName() : (checkTeam + "、" + team.getName());
                            }
                        }
                    }
                    entrustVo.setCheckTeam(checkTeam);
                    entrustVo.setCheckMethodNumber(sampleTmp.getMethodNumbers());
                }

                //查询报告,如果有上传的委托报告，用户可已进行下载
                QueryWrapper<EntityEnclosure> wrapper = new QueryWrapper<>();
                wrapper.eq("entity_type", EntityEnclosure.EntityType.ENTRUST_REPORT);
                wrapper.eq("entity_id", entrustVo.getId());
                wrapper.eq("is_deleted", 1);
                List<EntityEnclosure> entityEnclosureList = entityEnclosureMapper.selectList(wrapper);
                if(entityEnclosureList != null && entityEnclosureList.size()>0 ){
                    EntityEnclosure entityEnclosure = entityEnclosureList.get(0);
                    entrustVo.setAlias(entityEnclosure.getAlias());
                    entrustVo.setEnclosureUrl(entityEnclosure.getPdfUrl());
                    entrustVo.setExtName(entityEnclosure.getExtName());
                }
            }
        }
        pages.setRecords(list);
        return BaseResponse.okData(pages);
    }

    /**
     * 置顶取消置顶
     *
     * @param id 委托表id
     * @return
     */
    public BaseResponse<String> setTopping(Integer id) {
        if (id == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        Entrust entrust = entrustMapper.selectById(id);
        if (entrust == null) {
            return BaseResponse.errorMsg("数据错误");
        }
        String msg = "";
        if (entrust.getCreateTime().isEqual(entrust.getUpdateTime())) {
            entrust.setUpdateTime(LocalDateTime.now());
            msg = "置顶成功";
        } else {
            entrust.setUpdateTime(entrust.getCreateTime());
            msg = "取消置顶成功";
        }
        entrustMapper.updateById(entrust);
        return BaseResponse.okMsg(msg);
    }


    /**
     * 新增委托
     *
     * @param query
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<Entrust> create(EntrustQuery query) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (query.getClientId() == null) {
            return BaseResponse.errorMsg("请选择委托单位");
        }
        if (query.getProjectId() == null || StringUtils.isEmpty(query.getProjectCode())) {
            if (StringUtils.isEmpty(query.getProjectName())) {
                return BaseResponse.errorMsg("请填写项目名称或选择已有项目");
            }
        }
        if (StringUtils.isEmpty(query.getSendName()) || StringUtils.isEmpty(query.getSendPhone())) {
            return BaseResponse.errorMsg("请填写送样人信息");
        }
        Entrust entrust = new Entrust();
        BeanUtils.copyProperties(query, entrust);
        //生成委托编号
//        String entrustCode = commonService.createNo("WT", entrustMapper.counts());
        entrust.setEntrustCode(null)
                .setUserId(loginUser.getId())
                .setStatus(0)
                .setIsDelete(1)
                .setIsHandle(0)
                .setIsDistribution(0)
                .setCreateTime(LocalDateTime.now())
                .setUpdateTime(entrust.getCreateTime())
                .setSampleNum(query.getSampleTmpList().size());
        entrustMapper.insert(entrust);
        if (query.getSampleTmpList() != null && query.getSampleTmpList().size() > 0) {
            List<SampleTmp> sampleTmpList = new ArrayList<>();
            for (SampleTmpQuery sampleTmpQuery : query.getSampleTmpList()) {
                SampleTmp sampleTmp = new SampleTmp();
                BeanUtils.copyProperties(sampleTmpQuery, sampleTmp);
                String teamIds = sampleTmpQuery.getTeamIds(); //选择的检测项id集合
                BigDecimal charge = new BigDecimal("0.00");
                if (teamIds != null) {
                    String[] teamIdS = teamIds.split("、");
                    List<String> teamNameList = new ArrayList<>();
                    for (String teamId : teamIdS) {
                        Team team = teamMapper.selectById(Integer.valueOf(teamId));
                        if (team != null) {
                            if(!teamNameList.contains(teamId)){
                                charge = charge.compareTo(BigDecimal.ZERO) == 0 ? team.getCharge() : (charge.add(team.getCharge()));
                                teamNameList.add(team.getName());
                            }
                        }
                    }
                    //选择Mg必须选择Ca；选择Al必须选择Fe
                    if(teamNameList.contains("MgO")){
                        if(!teamNameList.contains("CaO")){
                            return BaseResponse.errorMsg("选择MgO必须要选择CaO");
                        }
                    }
                    if(teamNameList.contains("Al<sub>2</sub>O<sub>3</sub>")){
                        if(!teamNameList.contains("Fe<sub>2</sub>O<sub>3</sub>")){
                            return BaseResponse.errorMsg("选择Al2O3必须要选择Fe2O3");
                        }
                    }
                    //选择比表面积必须选择密度
                    if(teamNameList.contains("比表面积")){
                        QueryWrapper<Team> teamQW = new QueryWrapper<>();
                        teamQW.eq("name", "密度");
                        Team teamMD = teamMapper.selectOne(teamQW);
                        if(teamMD == null){
                            return BaseResponse.errorMsg("请联系管理员配置密度检测项");
                        }
                        if(!teamNameList.contains("密度")){
                            return BaseResponse.errorMsg("选择比表面积必须选择密度");
                        }
                    }
                }
                //如果为加急委托，产值是正常的3倍
                if(entrust.getIsUrgent()==1){
                    charge = charge.multiply(new BigDecimal(3));
                }
                sampleTmp.setEntrustId(entrust.getId())
                        .setCharge(charge)
                        .setCreateTime(LocalDateTime.now());
                sampleTmpList.add(sampleTmp);
            }
            sampleTmpService.saveBatch(sampleTmpList);
        }else{
            return BaseResponse.errorMsg("样品及检测项不可为空");
        }
        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "提交了委托单", null);
        //消息推送
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }
        String userIds = "";
        for(Integer approvalId : approvalIdList ){
            SysUser approvalUser = userService.getById(approvalId);
            if(approvalUser == null){
                return BaseResponse.errorMsg("委托评审信息错误");
            }
            BaseResponse wrapper = userMessageService.sendMessage(approvalId, "您有一条新的委托单申请等待评审",entrust.getId(), SysUserMessage.MessageType.ENTRUST);
            if(wrapper.getCode() != 200){
                return wrapper;
            }
            if(StringUtils.isNotBlank(approvalUser.getWxId())){
                userIds = userIds.equals("")?approvalUser.getWxId():userIds+"|"+approvalUser.getWxId();
            }
        }
        //发送企业微信消息内容
        String content="你好！"+loginUser.getName()+"向您申请了一条委托，请前往\n" +
               systemUrl+"进行评审。";
        System.out.println("**************************content**********************");
        System.out.println(content);
        weiXinService.sendTextMessage(userIds, content);

        return BaseResponse.okData(entrust);
    }

    /**
     * 委托详情
     *
     * @param id
     * @return
     */
    @Override
    public BaseResponse<EntrustVo> getDtail(Integer id) {
        if (id == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        EntrustVo entrustVo = entrustMapper.getDetail(id);
        if (entrustVo.getStatus() != 0) {
            QueryWrapper<Sample> sampleWrapper = new QueryWrapper<>();
            sampleWrapper.eq("entrust_id", entrustVo.getId());
            sampleWrapper.orderByAsc("id");
            List<Sample> sampleList = sampleService.list(sampleWrapper);
            List<SampleVo> sampleVoList = new ArrayList<>();
            List<SampleVo> sampleHandleVoList = new ArrayList<>();
            if (sampleList != null && sampleList.size() > 0) {
                for (Sample sample : sampleList) {
                    SampleVo sampleVo = new SampleVo();
                    BeanUtils.copyProperties(sample, sampleVo);
                    String teamIds = sample.getTeamIds();
                    String teamName = "";
                    List<SampleDistributionTeamVo> sampleNoDistributionTeamVoList = new ArrayList<>();
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            TeamVo teamVo = teamMapper.getDetail(Integer.valueOf(teamId));
                            if (teamVo != null) {
                                teamName = teamName.equals("") ? teamVo.getName() : (teamName + "、" + teamVo.getName());
                                SampleDistributionTeamVo distributionTeamVo = new SampleDistributionTeamVo();
                                distributionTeamVo.setTeamGroupId(teamVo.getGroupId());
                                distributionTeamVo.setTeamGroupName(teamVo.getGroupName());
                                distributionTeamVo.setTeamId(teamVo.getId());
                                distributionTeamVo.setTeamName(teamVo.getName());
                                sampleNoDistributionTeamVoList.add(distributionTeamVo);
                            }
                        }
                    }
                    sampleVo.setTeamName(teamName);
                    //评审人员可以查看所有的检测项内容
                    List<SampleDistributionTeamVo> sampleDistributionTeamVoList =
                            distributionMapper.getDistributionTeamList(sample.getId(), null);
                    if (sampleDistributionTeamVoList != null && sampleDistributionTeamVoList.size() > 0) {
                        sampleVo.setSampleDistributionTeamVoList(sampleDistributionTeamVoList);
                    } else {
                        sampleVo.setSampleDistributionTeamVoList(sampleNoDistributionTeamVoList);
                    }
                    sampleVoList.add(sampleVo);
                    //样品处理列表只展示主样信息
                    if (sample.getIsParallel() != 0) {
                        if (sample.getCementCode().equals(sample.getParallelCode())) {
                            sampleHandleVoList.add(sampleVo);
                        }
                    } else {
                        sampleHandleVoList.add(sampleVo);
                    }
                }
            }
            entrustVo.setSampleList(sampleVoList);//样品列表（展示平行样样品）
            entrustVo.setSampleHandleList(sampleHandleVoList);//处理样品列表（不展示平行样样品）
            //委托评审意见
            QueryWrapper<EntrustApproval> approvalWrapper = new QueryWrapper<>();
            approvalWrapper.eq("entrust_id", entrustVo.getId());
            approvalWrapper.orderByDesc("id");
            List<EntrustApproval> approvalList = approvalMapper.selectList(approvalWrapper);
            EntrustApproval approval = approvalList.get(0);
            entrustVo.setOpinion(approval.getOpinion());
        } else {
            QueryWrapper<SampleTmp> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("entrust_id", entrustVo.getId());
            List<SampleTmp> sampleTmpList = sampleTmpService.list(queryWrapper);
            List<SampleTmpVo> sampleTmpVoList = new ArrayList<>();
            if (sampleTmpList != null && sampleTmpList.size() > 0) {
                for (SampleTmp sampleTmp : sampleTmpList) {
                    SampleTmpVo sampleTmpVo = new SampleTmpVo();
                    BeanUtils.copyProperties(sampleTmp, sampleTmpVo);
                    String teamIds = sampleTmp.getTeamIds();
                    String teamName = "";
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            Team team = teamMapper.selectById(Integer.valueOf(teamId));
                            if (team != null) {
                                team.getName();
                                teamName = teamName.equals("") ? team.getName() : (teamName + "、" + team.getName());
                            }
                        }
                    }
                    sampleTmpVo.setTeamName(teamName);
                    sampleTmpVoList.add(sampleTmpVo);
                }
            }
            entrustVo.setSampleTmpList(sampleTmpVoList);
        }

        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        userMessageService.checkMessage(loginUser.getId(), id, SysUserMessage.MessageType.ENTRUST);
        return BaseResponse.okData(entrustVo);
    }


    @Override
    public BaseResponse<EntrustVo> getDetailCapacity(Integer id) {
        if (id == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        EntrustVo entrustVo = entrustMapper.getDetail(id);
        if (entrustVo.getStatus() != 0) {
            QueryWrapper<Sample> sampleWrapper = new QueryWrapper<>();
            sampleWrapper.eq("entrust_id", entrustVo.getId());
            sampleWrapper.orderByAsc("id");
            List<Sample> sampleList = sampleService.list(sampleWrapper);
            List<SampleVo> sampleVoList = new ArrayList<>();
            List<SampleVo> sampleHandleVoList = new ArrayList<>();
            if (sampleList != null && sampleList.size() > 0) {
                for (Sample sample : sampleList) {
                    SampleVo sampleVo = new SampleVo();
                    BeanUtils.copyProperties(sample, sampleVo);
                    String teamIds = sample.getTeamIds();
                    String teamName = "";
                    List<SampleDistributionTeamVo> sampleNoDistributionTeamVoList = new ArrayList<>();
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            TeamVo teamVo = teamMapper.getDetail(Integer.valueOf(teamId));
                            if (teamVo != null && "1".equals(teamVo.getQualifications())) {
                                teamName = teamName.equals("") ? teamVo.getName() : (teamName + "、" + teamVo.getName());
                                SampleDistributionTeamVo distributionTeamVo = new SampleDistributionTeamVo();
                                distributionTeamVo.setTeamGroupId(teamVo.getGroupId());
                                distributionTeamVo.setTeamGroupName(teamVo.getGroupName());
                                distributionTeamVo.setTeamId(teamVo.getId());
                                distributionTeamVo.setTeamName(teamVo.getName());
                                sampleNoDistributionTeamVoList.add(distributionTeamVo);
                            }
                        }
                    }
                    sampleVo.setTeamName(teamName);
                    //评审人员可以查看所有的检测项内容
                    List<SampleDistributionTeamVo> sampleDistributionTeamVoList =
                            distributionMapper.getDistributionTeamList(sample.getId(), null);
                    if (sampleDistributionTeamVoList != null && sampleDistributionTeamVoList.size() > 0) {
                        sampleVo.setSampleDistributionTeamVoList(sampleDistributionTeamVoList);
                    } else {
                        sampleVo.setSampleDistributionTeamVoList(sampleNoDistributionTeamVoList);
                    }
                    sampleVoList.add(sampleVo);
                    //样品处理列表只展示
                    if (sample.getIsParallel() == 1) {
                        if (sample.getCementCode().equals(sample.getParallelCode())) {
                            sampleHandleVoList.add(sampleVo);
                        }
                    } else {
                        sampleHandleVoList.add(sampleVo);
                    }
                }
            }
            entrustVo.setSampleList(sampleVoList);//样品列表（展示平行样样品）
            entrustVo.setSampleHandleList(sampleHandleVoList);//处理样品列表（不展示平行样样品）
        } else {
            QueryWrapper<SampleTmp> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("entrust_id", entrustVo.getId());
            List<SampleTmp> sampleTmpList = sampleTmpService.list(queryWrapper);
            List<SampleTmpVo> sampleTmpVoList = new ArrayList<>();
            if (sampleTmpList != null && sampleTmpList.size() > 0) {
                for (SampleTmp sampleTmp : sampleTmpList) {
                    SampleTmpVo sampleTmpVo = new SampleTmpVo();
                    BeanUtils.copyProperties(sampleTmp, sampleTmpVo);
                    String teamIds = sampleTmp.getTeamIds();
                    String teamName = "";
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            Team team = teamMapper.selectById(Integer.valueOf(teamId));
                            if (team != null && 1 == team.getQualifications()) {
                                team.getName();
                                teamName = teamName.equals("") ? team.getName() : (teamName + "、" + team.getName());
                            }
                        }
                    }
                    sampleTmpVo.setTeamName(teamName);
                    sampleTmpVoList.add(sampleTmpVo);
                }
            }
            entrustVo.setSampleTmpList(sampleTmpVoList);
        }
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        userMessageService.checkMessage(loginUser.getId(), id, SysUserMessage.MessageType.ENTRUST);
        return BaseResponse.okData(entrustVo);
    }
    /**
     * 详情-基本信息
     *
     * @param id
     * @return
     */
    public BaseResponse<EntrustVo> getBaseDtail(Integer id) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }
        if (!approvalIdList.contains(loginUser.getId())) {
            return BaseResponse.errorMsg("权限不足");
        }
        if (id == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        EntrustVo entrustVo = entrustMapper.getDetail(id);
        if (entrustVo.getStatus() != 0) {
            QueryWrapper<Sample> sampleWrapper = new QueryWrapper<>();
            sampleWrapper.eq("entrust_id", entrustVo.getId());
            sampleWrapper.orderByAsc("id");
            List<Sample> sampleList = sampleService.list(sampleWrapper);
            List<SampleVo> sampleVoList = new ArrayList<>();
            if (sampleList != null && sampleList.size() > 0) {
                for (Sample sample : sampleList) {
                    SampleVo sampleVo = new SampleVo();
                    BeanUtils.copyProperties(sample, sampleVo);
                    String teamIds = sample.getTeamIds();
                    String teamName = "";
                    List<SampleDistributionTeamVo> sampleNoDistributionTeamVoList = new ArrayList<>();
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            TeamVo teamVo = teamMapper.getDetail(Integer.valueOf(teamId));
                            if (teamVo != null) {
                                teamName = teamName.equals("") ? teamVo.getName() : (teamName + "、" + teamVo.getName());
                                SampleDistributionTeamVo distributionTeamVo = new SampleDistributionTeamVo();
                                distributionTeamVo.setTeamGroupId(teamVo.getGroupId());
                                distributionTeamVo.setTeamGroupName(teamVo.getGroupName());
                                distributionTeamVo.setTeamId(teamVo.getId());
                                distributionTeamVo.setTeamName(teamVo.getName());
                                sampleNoDistributionTeamVoList.add(distributionTeamVo);
                            }
                        }
                    }
                    sampleVo.setTeamName(teamName);
                    sampleVo.setSampleDistributionTeamVoList(sampleNoDistributionTeamVoList);
                    sampleVoList.add(sampleVo);
                }
            }
            entrustVo.setSampleList(sampleVoList);//样品列表（展示平行样样品）

            //查询报告,如果有上传的委托报告，用户可已进行下载
            QueryWrapper<EntityEnclosure> wrapper = new QueryWrapper<>();
            wrapper.eq("entity_type", EntityEnclosure.EntityType.ENTRUST_REPORT);
            wrapper.eq("entity_id", entrustVo.getId());
            wrapper.eq("is_deleted", 1);
            List<EntityEnclosure> entityEnclosureList = entityEnclosureMapper.selectList(wrapper);
            if(entityEnclosureList != null && entityEnclosureList.size()>0 ){
                EntityEnclosure entityEnclosure = entityEnclosureList.get(0);
                entrustVo.setAlias(entityEnclosure.getAlias());
                entrustVo.setEnclosureUrl(entityEnclosure.getPdfUrl());
                entrustVo.setExtName(entityEnclosure.getExtName());
            }
        }else{
            QueryWrapper<SampleTmp> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("entrust_id", entrustVo.getId());
            List<SampleTmp> sampleTmpList = sampleTmpService.list(queryWrapper);
            List<SampleTmpVo> sampleTmpVoList = new ArrayList<>();
            if (sampleTmpList != null && sampleTmpList.size() > 0) {
                for (SampleTmp sampleTmp : sampleTmpList) {
                    SampleTmpVo sampleTmpVo = new SampleTmpVo();
                    BeanUtils.copyProperties(sampleTmp, sampleTmpVo);
                    String teamIds = sampleTmp.getTeamIds();
                    String teamName = "";
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            Team team = teamMapper.selectById(Integer.valueOf(teamId));
                            if (team != null) {
                                team.getName();
                                teamName = teamName.equals("") ? team.getName() : (teamName + "、" + team.getName());
                            }
                        }
                    }
                    sampleTmpVo.setTeamName(teamName);
                    sampleTmpVoList.add(sampleTmpVo);
                }
            }
            entrustVo.setSampleTmpList(sampleTmpVoList);
        }
        return BaseResponse.okData(entrustVo);
    }

    /**
     * 详情-样品处理信息
     *
     * @param id
     * @return
     */
    public BaseResponse<List<SampleHandleVo>> getSampleHandleDtail(Integer id) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }
        if (!approvalIdList.contains(loginUser.getId())) {
            return BaseResponse.errorMsg("权限不足");
        }
        if (id == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<SampleHandleVo> sampleHandleList = sampleHandleMapper.getSampleHandleList(params);



        if (sampleHandleList != null && sampleHandleList.size() > 0) {
            for (SampleHandleVo shVo : sampleHandleList) {

                Handle handle = handleMapper.selectById(shVo.getHandleId());
                if (handle == null) {
                    return BaseResponse.errorMsg("选择的处理项信息有误");
                }
                String contentName = handle.getName();

                /*String contentName = "";
                if (shVo.getContent() != null) {
                    String[] handIdS = shVo.getContent().split("、");
                    List<SampleHandleEnclosure> sampleHandleEnclosureList = new ArrayList<>();
                    for (String handleId : handIdS) {
                        Handle handle = handleMapper.selectById(Integer.valueOf(handleId));
                        if (handle == null) {
                            return BaseResponse.errorMsg("选择的处理项信息有误");
                        }
                        contentName = contentName.equals("") ? handle.getName() : contentName + "、" + handle.getName();
                    }
                }*/
                shVo.setContentName(contentName);
            }
        }
        return BaseResponse.okData(sampleHandleList);
    }

    /**
     * 详情-样品处理信息-附件列表
     *
     * @param sampleHandleId 样品处理表id
     * @return
     */
    public BaseResponse<List<SampleHandleEnclosureVo>> getSampleHandleDtailEnclosureList(Integer sampleHandleId) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }
        if (!approvalIdList.contains(loginUser.getId())) {
            return BaseResponse.errorMsg("权限不足");
        }
        if (sampleHandleId == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("sampleHandleId", sampleHandleId);
        List<SampleHandleEnclosureVo> list = sampleHandleEnclosureMapper.getList(params);
        return BaseResponse.okData(list);
    }

    /**
     * 详情-检测任务信息
     *
     * @param id
     * @return
     */
    public BaseResponse<List<SampleVo>> getSampleCheckDtail(Integer id) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }
        if (!approvalIdList.contains(loginUser.getId())) {
            return BaseResponse.errorMsg("权限不足");
        }
        if (id == null) {
            return BaseResponse.errorMsg("参数错误");
        }

        Entrust entrust = entrustMapper.selectById(id);
        if (entrust == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        List<Sample> sampleList = sampleMapper.getSampleCheckList(id);
        List<SampleVo> sampleVoList = new ArrayList<>();

        if (sampleList != null && sampleList.size() > 0) {
            for (Sample sample : sampleList) {
                SampleVo sampleVo = new SampleVo();
                BeanUtils.copyProperties(sample, sampleVo);
                List<SampleDistributionTeamVo> sampleDistributionTeamVoList =
                        distributionMapper.getDistributionTeamList(sample.getId(), null);
                /*//判断是否为平行样
                List<SampleDistributionTeamVo> sampleDistributionTeamVoList = null;
                if (sample.getIsParallel() == 0) {
                    //检测人员只能看到自己则的检测内容
                    sampleDistributionTeamVoList =
                            distributionMapper.getDistributionTeamList(sample.getId(), null, null);
                } else if (sample.getIsParallel() == 1) {
                    List<Sample> sampleList1 = sampleMapper.getByCementCode(entrust.getId(), sample.getCementCode());
                    //检测人员只能看到自己则的检测内容
                    if (sampleList1.size() == 2) {
                        sampleDistributionTeamVoList =
                                distributionMapper.getDistributionTeamList(sampleList1.get(0).getId(), sampleList1.get(1).getId(), null);
                    } else {
                        sampleDistributionTeamVoList =
                                distributionMapper.getDistributionTeamList(sample.getId(), null, null);
                    }
                }*/
                if (sampleDistributionTeamVoList != null && sampleDistributionTeamVoList.size() > 0) {
                    sampleVo.setSampleDistributionTeamVoList(sampleDistributionTeamVoList);
                }
                sampleVoList.add(sampleVo);
            }
        }
        return BaseResponse.okData(sampleVoList);
    }

    @Override
    public List<SixElementReport> getSampleSixElementCheck(Integer entrustId) {

        return sampleCheckMapper.getSampleSixElementCheck(entrustId);

    }

    @Override
    public List<IndustrialReport> getSampleIndustrialCheck(Integer entrustId) {

        return sampleCheckMapper.getSampleIndustrialCheck(entrustId);
    }


    /**
     * 获取样品表里最大的平行样编号
     *
     * @return
     */
    @Override
    public BaseResponse<String> getMaxCementCode() {
        Object obj = redisUtil.getString("maxCementCode");
        String maxCementCode = "";
        String regex = "[0-9]{2}\\-[0-9]{4}";
        if (obj == null || !obj.toString().matches(regex)) {
            maxCementCode = sampleMapper.getMaxCementCode();
        } else {
            maxCementCode = obj.toString();
        }
        //校验获取的最大本所编号
        SimpleDateFormat sdf = new SimpleDateFormat("yy");
        Date date = new Date();
        String yesrString = sdf.format(date);
        if (maxCementCode == null) {  //如果数据库没有本所编号，初始化本所编号
            maxCementCode = yesrString + "-0000";
        } else {
            String yearStr = commonService.getIntegerYear(maxCementCode);
            if (!yearStr.equals(yesrString)) { //如果数据库本所编号年份和当前不一样，初始化本所编号
                maxCementCode = yesrString + "-0000";
            }
        }
        System.out.println("redis获取最大值时的最大本所编号*******************************************" + maxCementCode);
        redisUtil.setString("maxCementCode", maxCementCode);
        return BaseResponse.okData(maxCementCode);
    }

    /**
     * 委托评审
     *
     * @param query
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<String> approval(ApprovalQuery query) {
        if (query.getId() == null || query.getIsAgree() == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }
        if (!approvalIdList.contains(loginUser.getId())) {
            return BaseResponse.errorMsg("没有评审权限");
        }
        EntrustVo entrustVo = entrustMapper.getDetail(query.getId());
        if (entrustVo == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        if (entrustVo.getStatus() != 0) {
            return BaseResponse.errorMsg("当前状态不允许评审");
        }
        Entrust entrust = entrustMapper.selectById(entrustVo.getId());
        //如果项目id或者项目编号为空，根据项目名称获取项目信息
        if (StringUtils.isEmpty(entrust.getProjectCode())) {
            ProjectVo projectVo = projectMapper.getByName(entrust.getProjectName());
            if (projectVo == null) {
                return BaseResponse.errorMsg("请添加项目信息");
            }
            entrust.setProjectId(projectVo.getId())
                    .setProjectCode(projectVo.getCode())
                    .setProjectName(projectVo.getName());
        }
        if (query.getIsAgree() == 1) { //通过
            if (StringUtils.isEmpty(query.getProjectType())) {
                return BaseResponse.errorMsg("请选择项目类型");
            }
            if (query.getSampleList() != null && query.getSampleList().size() > 0) {
                List<Sample> sampleList = new ArrayList<>();
                String maxCementCode = ""; //最大本所编号对应的平行样编号
                //当前平行样编号最大值
                Integer integerMaxCode = commonService.getIntegerCode(getMaxCementCode().getData());
                for (SampleQuery sampleQuery : query.getSampleList()) {
                    if (StringUtils.isEmpty(sampleQuery.getCementCode())) {
                        return BaseResponse.errorMsg("本所编号不能为空");
                    }
                    String regex = "[0-9]{2}\\-[0-9]{4}";
                    if(!sampleQuery.getCementCode().matches(regex) ||  sampleQuery.getCementCode().length() != getMaxCementCode().getData().length()){
                        return BaseResponse.errorMsg("本所编号格式不符合规范");
                    }
                    //前端传入的本所编号
                    Integer cementCodeInteger = commonService.getIntegerCode(sampleQuery.getCementCode());
                    if (cementCodeInteger <= integerMaxCode) {
                        return BaseResponse.errorMsg("本所编号必须大于最大值");
                    }
                    if(sampleQuery.getIsParallel() == null){
                        return BaseResponse.errorMsg("请选择是否需要平行样");
                    }
                    if (sampleQuery.getIsParallel() == 0) { //非平行样
                        maxCementCode = sampleQuery.getCementCode();
                        Sample sample = new Sample();
                        BeanUtils.copyProperties(sampleQuery, sample);
                        sample.setId(null)
                                .setSampleId(sampleQuery.getId())
                                .setStatus(0)  //样品状态为未领用状态
                                .setCreateTime(LocalDateTime.now())
                                .setIsHandle(0)//样品处理未完成状态
                                .setIsDistribution(0)//任务派发未完成状态
                                .setIsCheck(0)//样品校核未完成状态
                                .setOutputValue(sample.getCharge()) //产值不用评审人员修改
                                .setParallelCode(sampleQuery.getCementCode());
                        sampleList.add(sample);
                    }else{  //是平行样
                        if (sampleQuery.getIsParallel() < 2 ){
                            return BaseResponse.errorMsg("平行样数量至少2条");
                        }
                        if (sampleQuery.getIsParallel() > 4 ){
                            return BaseResponse.errorMsg("平行样数量最多4条");
                        }
                        for(int i=0; i<sampleQuery.getIsParallel(); i++){
                            integerMaxCode = cementCodeInteger > integerMaxCode ? cementCodeInteger : integerMaxCode+1;
                            String yearStr = commonService.getIntegerYear(sampleQuery.getCementCode());
                            maxCementCode = yearStr + "-" + commonService.getCementCode(integerMaxCode);
                            Sample sample = new Sample();
                            BeanUtils.copyProperties(sampleQuery, sample);
                            sample.setId(null)
                                    .setSampleId(sampleQuery.getId())
                                    .setStatus(0)  //样品状态为未领用状态
                                    .setCreateTime(LocalDateTime.now())
                                    .setIsHandle(0)//样品处理未完成状态
                                    .setIsDistribution(0)//任务派发未完成状态
                                    .setIsCheck(0)//样品校核未完成状态
                                    .setParallelCode(maxCementCode);
                            sampleList.add(sample);
                        }
                    }
                }
                sampleService.saveBatch(sampleList);
                //最大的平行样编号放入redis
                System.out.println("审批时的最大本所编号*******************************************" + maxCementCode);
                redisUtil.setString("maxCementCode", maxCementCode);
            }
            entrust.setStatus(1).setProjectType(query.getProjectType());
            //审批后生成委托编号
            String entrustCode = entrust.getProjectCode()+"_"+query.getSampleList().get(0).getCementCode();
            entrust.setEntrustCode(entrustCode);
            logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "修改评审状态为“通过”", null);
            //*****************************以上为评审接口******************
            //*****************************样品处理派发合并到评审接口中******************
            List<Sample> sampleList = sampleMapper.getSampleList(entrustVo.getId());
            String userIds = "";
            List<Integer> userIdList = new ArrayList<>();
            for (Sample sample : sampleList) {
                //样品的处理项
//                List<Integer> handleUserIds = new ArrayList<>();
                String teamIds = sample.getTeamIds();
                if (teamIds != null) {
                    String[] teamIdS = teamIds.split("、");
                    List<Integer> handleIds = new ArrayList<>();
                    for (String teamId : teamIdS) {
                        TeamVo teamVo = teamMapper.getDetail(Integer.valueOf(teamId));
                        if (teamVo != null) {
                           HandleVo handleVo = handleMapper.getDetail(teamVo.getHandleId());
                           if(handleVo != null && !userIdList.contains(handleVo.getUserId())){
                               userIdList.add(handleVo.getUserId());
                           }
                            //样品处理表 同一个样品多个相同处理项时 去重。
	                        if(handleVo != null && !handleIds.contains(handleVo.getId())){
		                        SampleHandle sampleHandle = new SampleHandle();
		                        sampleHandle.setSampleId(sample.getId())
				                        .setUserId(handleVo.getUserId())
				                        .setHandleId(handleVo.getId())
				                        .setPlanFinishDate(null)    //样品处理要求完成放到了委托表，评审的时候直接设定
//				                        .setStatus(0)
				                        .setCreateTime(LocalDateTime.now())
                                        .setStatus(1)  //直接默认接收
                                        .setAcceptTime(LocalDateTime.now());
		                        sampleHandleMapper.insert(sampleHandle);
		                        if(sampleHandle.getHandleId() != null){
			                        Handle handle = handleMapper.selectById(sampleHandle.getHandleId());
			                        if (handle == null) {
				                        return BaseResponse.errorMsg("选择的处理项信息有误");
			                        }
			                        SampleHandleEnclosure sampleHandleEnclosure = new SampleHandleEnclosure();
			                        sampleHandleEnclosure.setSampleHandleId(sampleHandle.getId())
					                        .setHandleId(handle.getId())
					                        .setUserId(sampleHandle.getUserId())
					                        .setCreateTime(LocalDateTime.now())
					                        .setStatus(0)
					                        .setAlias(handle.getName());
			                        sampleHandleEnclosureMapper.insert(sampleHandleEnclosure);
			                        //获取产值信息
			                        QueryWrapper<NormProduction> queryWrapper = new QueryWrapper<>();
			                        queryWrapper.eq("assess_id", handle.getId());
			                        queryWrapper.eq("type", 0);
			                        queryWrapper.eq("status", 1);
			                        NormProduction normProduction = iNormProductionService.getOne(queryWrapper);
			                        if(normProduction == null){
				                        return BaseResponse.errorMsg("联系管理员.配置产值信息!");
			                        }
		                        }
		                        //消息推送
		                        BaseResponse wrapper = userMessageService.sendMessage(sampleHandle.getUserId(), "您有一条样品处理信息等待处理",entrust.getId(), SysUserMessage.MessageType.ENTRUST);
		                        if(wrapper.getCode() != 200){
			                        return wrapper;
		                        }

		                        SysUser handleUser = userService.getById(sampleHandle.getUserId());
		                        if(handleUser == null){
			                        return BaseResponse.errorMsg("样品处理人信息错误");
		                        }
		                        if(StringUtils.isNotBlank(handleUser.getWxId()) && !userIdList.contains(handleUser.getId())){
			                        userIds = userIds.equals("")?handleUser.getWxId():userIds+"|"+handleUser.getWxId();
		                        }
	                        }
                        }
                    }
                }
            }
            //委托表改成已发送样品处理，状态改为样品处理状态中
            entrust.setIsHandle(1)
                    .setStatus(3)
                    .setFinishDate(query.getFinishDate());
            logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "发送样品处理任务", null);

            //发送企业微信消息内容
            String content="你好！您有一条新的样品处理任务，请前往\n"+systemUrl +"进行接受。";
            weiXinService.sendTextMessage(userIds, content);

        } else if (query.getIsAgree() == 2) {  //驳回
            entrust.setStatus(2);
            logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "修改评审状态为“驳回”", null);
        } else {
            return BaseResponse.errorMsg("请选择正确按钮");
        }
        //记录审批信息
        EntrustApproval entrustApproval = new EntrustApproval();
        entrustApproval.setEntrustId(entrust.getId())
                .setUserId(loginUser.getId())
                .setOpinion(query.getAuditReason())
                .setStatus(query.getIsAgree())
                .setCreateTime(LocalDateTime.now())
                .setRemark(null);
        approvalMapper.insert(entrustApproval);
        entrustMapper.updateById(entrust);
        //处理消息
        userMessageService.dealMessage(loginUser.getId(), entrust.getId(), SysUserMessage.MessageType.ENTRUST);
        return BaseResponse.okMsg("审批完成");
    }

    /**
     * 发送样品处理任务
     *
     * @param query
     * @return
     */
    /*@Transactional
    @Override
    public BaseResponse<String> handle(HandleQuery query) {
        if (query.getId() == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        Entrust entrust = entrustMapper.selectById(query.getId());
        if (entrust == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        if (entrust.getStatus() != 1) {
            return BaseResponse.errorMsg("当前状态不允许样品处理");
        }
        String userIds = "";
        List<Integer> userIdList = new ArrayList<>();
        if (query.getSampleHandleQueryList() != null && query.getSampleHandleQueryList().size() > 0) {
            List<SampleHandleQuery> sampleHandleQueryList = query.getSampleHandleQueryList();
            for (SampleHandleQuery sampleHandleQuery : sampleHandleQueryList) {
                //样品处理表
                SampleHandle sampleHandle = new SampleHandle();
                if (sampleHandleQuery.getSampleId() == null) {
                    return BaseResponse.errorMsg("样品信息错误");
                }
                if (sampleHandleQuery.getUserId() == null) {
                    return BaseResponse.errorMsg("请选择处理人");
                }
                if (StringUtils.isEmpty(sampleHandleQuery.getContent())) {
                    return BaseResponse.errorMsg("请选择处理项");
                }
                if (sampleHandleQuery.getPlanFinishDate() == null) {
                    return BaseResponse.errorMsg("请选择要求完成日期");
                }
                BeanUtils.copyProperties(sampleHandleQuery, sampleHandle);
                sampleHandle.setStatus(0).setCreateTime(LocalDateTime.now());
                sampleHandleMapper.insert(sampleHandle);
                //样品处理项附件表
                if (sampleHandle.getContent() != null) {
                    String[] handIdS = sampleHandle.getContent().split("、");
                    List<SampleHandleEnclosure> sampleHandleEnclosureList = new ArrayList<>();
                    for (String handleId : handIdS) {
                        Handle handle = handleMapper.selectById(Integer.valueOf(handleId));
                        if (handle == null) {
                            return BaseResponse.errorMsg("选择的处理项信息有误");
                        }
                        SampleHandleEnclosure sampleHandleEnclosure = new SampleHandleEnclosure();
                        sampleHandleEnclosure.setSampleHandleId(sampleHandle.getId())
                                .setHandleId(handle.getId())
                                .setUserId(sampleHandle.getUserId())
                                .setCreateTime(LocalDateTime.now())
                                .setStatus(0)
                                .setAlias(handle.getName());
                        sampleHandleEnclosureList.add(sampleHandleEnclosure);
                        //获取产值信息
                        QueryWrapper<NormProduction> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("assess_id", handle.getId());
                        queryWrapper.eq("type", 0);
                        queryWrapper.eq("status", 1);
                        NormProduction normProduction = iNormProductionService.getOne(queryWrapper);
                        if(normProduction == null){
                            return BaseResponse.errorMsg("联系管理员.配置产值信息!");
                        }
                    }
                    sampleHandleEnclosureService.saveBatch(sampleHandleEnclosureList);
                }
                //消息推送
                BaseResponse wrapper = userMessageService.sendMessage(sampleHandle.getUserId(), "您有一条样品处理信息等待处理",entrust.getId(), SysUserMessage.MessageType.ENTRUST);
                if(wrapper.getCode() != 200){
                    return wrapper;
                }

                SysUser handleUser = userService.getById(sampleHandle.getUserId());
                if(handleUser == null){
                    return BaseResponse.errorMsg("样品处理人信息错误");
                }
                if(StringUtils.isNotBlank(handleUser.getWxId()) && !userIdList.contains(handleUser.getId())){
                    userIdList.add(handleUser.getId());
                    userIds = userIds.equals("")?handleUser.getWxId():userIds+"|"+handleUser.getWxId();
                }
            }
        }
        //委托表改成已发送样品处理，状态改为样品处理状态中
        entrust.setIsHandle(1)
                .setStatus(3);
        entrustMapper.updateById(entrust);
        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "发送样品处理任务", null);

        //发送企业微信消息内容
        String content="你好！您有一条新的样品处理任务，请前往\n"+Global.systemUrl +"进行接受。";
        weiXinService.sendTextMessage(userIds, content);
        return BaseResponse.okMsg("已发送样品处理任务");
    }
*/
    /**
     * 样品处理任务分页
     *
     * @param pageQuery
     * @param projectCode
     * @return
     */
    @Override
    public BaseResponse<IPage<EntrustVo>> getSampleHandlePage(PageQuery pageQuery, String projectCode) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("projectCode", projectCode);
        params.put("userId", loginUser.getId());

        Page<EntrustVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        IPage<EntrustVo> pages = entrustMapper.getSampleHandlePage(page, params);
        List<EntrustVo> list = pages.getRecords();
        if (list != null && list.size() > 0) {
            for (EntrustVo entrustVo : list) {
                List<Sample> sampleList = sampleMapper.getSampleList(entrustVo.getId());
                //样品名称名称
                String sampleNames = "";
                //处理项名称
                String handleNames = "";
                if (sampleList != null && sampleList.size() > 0) {
                    //样品名称 列表中的拼接
                    for (Sample sample : sampleList) {
                        sampleNames = sampleNames.equals("") ? sample.getName() : (sampleNames + "、" + sample.getName());
                    }
                    //处理项表里只显示第一个样品的
                    Sample sample = sampleList.get(0);
                    QueryWrapper<SampleHandle> shWrapper = new QueryWrapper<>();
                    shWrapper.eq("sample_id", sample.getId());
                    List<SampleHandle> shList = sampleHandleMapper.selectList(shWrapper);
                    if (shList != null && shList.size() > 0) {
                        for (SampleHandle sampleHandle : shList) {
                            if (sampleHandle.getHandleId() != null) {
                                    Handle handle = handleMapper.selectById(sampleHandle.getHandleId());
                                    if (handle != null) {
                                        handleNames = handleNames.equals("") ? handle.getName() : (handleNames + "、" + handle.getName());
                                    }

                            }
                        }
                    }
                    //第一个样品的最早接受时间
                    LocalDateTime acceptTime = sampleHandleMapper.getNo1AcceptTime(sample.getId());
                    entrustVo.setAcceptTime(acceptTime);
                }
                entrustVo.setHandleNames(handleNames);
                entrustVo.setSampleNames(sampleNames);
            }
        }
        pages.setRecords(list);
        return BaseResponse.okData(pages);
    }

    /**
     * 样品处理任务列表
     *
     * @param id 委托表id
     * @return
     */
    @Override
    public BaseResponse<Map<String, Object>> getSampleHandleList(Integer id) {
        Map<String, Object> map = new HashMap<>();
        Entrust entrust = entrustMapper.selectById(id);
        if (entrust == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        LoginUser loginUser = userService.getLoginUser();
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("userId", loginUser.getId());
        List<SampleHandleVo> sampleHandleList = sampleHandleMapper.getSampleHandleList(params);
        Integer handleStatus = null;
        if (sampleHandleList != null && sampleHandleList.size() > 0) {
            for (SampleHandleVo shVo : sampleHandleList) {
                if (handleStatus != null && handleStatus != shVo.getStatus()) {
                    return BaseResponse.errorMsg("接受或完成的状态信息错误");
                }
                handleStatus = shVo.getStatus() == 1 ? 1 : (shVo.getStatus() == 2 ? 2 : 0);

                Handle handle = handleMapper.selectById(shVo.getHandleId());
                if (handle == null) {
                    return BaseResponse.errorMsg("选择的处理项信息有误");
                }
                String contentName = handle.getName();

              /*  String contentName = "";
                if (shVo.getContent() != null) {
                    String[] handIdS = shVo.getContent().split("、");
                    List<SampleHandleEnclosure> sampleHandleEnclosureList = new ArrayList<>();
                    for (String handleId : handIdS) {
                        Handle handle = handleMapper.selectById(Integer.valueOf(handleId));
                        if (handle == null) {
                            return BaseResponse.errorMsg("选择的处理项信息有误");
                        }
                        contentName = contentName.equals("") ? handle.getName() : contentName + "、" + handle.getName();
                    }
                }*/
                shVo.setContentName(contentName);
            }
        }
        entrust.setIsHandle(handleStatus); //0显示接受按钮，1显示完成按钮（可以上传附件），2和null不显示按钮
        map.put("entrust", entrust);
        map.put("sampleHandleList", sampleHandleList);
        return BaseResponse.okData(map);
    }

    /**
     * 接受样品处理任务
     *
     * @param ids 委托单
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<String> acceptHandle(Integer[] ids) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (ids == null || ids.length <= 0) {
            return BaseResponse.errorMsg("参数错误");
        }
        List<SampleHandle> sampleHandleList = new ArrayList<>();
        for (Integer id : ids) {
            SampleHandle sampleHandle = sampleHandleMapper.selectById(id);
            if (sampleHandle == null) {
                return BaseResponse.errorMsg("信息错误");
            }
            if (sampleHandle.getStatus() != 0) {
                return BaseResponse.errorMsg("状态错误");
            }
            if (loginUser.getId() != sampleHandle.getUserId()) {
                return BaseResponse.errorMsg("请登录样品处理人账号操作");
            }
            sampleHandle.setStatus(1).setAcceptTime(LocalDateTime.now());
            sampleHandleList.add(sampleHandle);
        }
        sampleHandleService.updateBatchById(sampleHandleList);
        //记录委托单日志
        Sample sample = sampleService.getById(sampleHandleList.get(0).getSampleId());
        if (sample == null) {
            return BaseResponse.errorMsg("样品信息错误");
        }
        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, sample.getEntrustId(), "接受样品处理任务", null);
        //处理消息
        userMessageService.dealMessage(loginUser.getId(), sample.getEntrustId(), SysUserMessage.MessageType.ENTRUST);
        return BaseResponse.okMsg("已接受样品处理任务");
    }

    /**
     * 数据上传列表
     *
     * @param sampleHandleId 样品处理表id
     * @return
     */
    public BaseResponse<List<SampleHandleEnclosureVo>> getSampleHandleEnclosureList(Integer sampleHandleId) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("sampleHandleId", sampleHandleId);
        params.put("userId", loginUser.getId());
        List<SampleHandleEnclosureVo> list = sampleHandleEnclosureMapper.getList(params);
        return BaseResponse.okData(list);
    }

    /**
     * 样品处理数据上传附件
     *
     * @param query
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<SampleHandleEnclosure> uploadEnclosureCL(SampleHandleEnclosureQuery query) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (query == null || query.getId() == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        SampleHandleEnclosure sampleHandleEnclosure = sampleHandleEnclosureMapper.selectById(query.getId());
        if (sampleHandleEnclosure == null) {
            return BaseResponse.errorMsg("数据错误");
        }
        sampleHandleEnclosure.setEnclosureUrl(query.getEnclosureUrl())
                .setExtName(query.getExtName())
                .setUpdateTime(LocalDateTime.now())
                .setPdfUrl(query.getPdfUrl())
                .setStatus(1);
        if (StringUtils.isEmpty(query.getEnclosureUrl())) {
            sampleHandleEnclosure.setStatus(2); //上传失败
        }
        sampleHandleEnclosureMapper.updateById(sampleHandleEnclosure);
        return BaseResponse.okData(sampleHandleEnclosure);
    }

    /**
     * 样品处理详情
     *
     * @param id
     * @return
     */
    @Override
    public BaseResponse<SampleHandleVo> getHandleDtail(Integer id) {
        SampleHandleVo sampleHandleVo = sampleHandleMapper.getDetail(id);
        return BaseResponse.okData(sampleHandleVo);
    }

    /**
     * 完成样品处理任务
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NESTED)
    @Override
    public BaseResponse<String> finishHandle(Integer[] ids) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (ids == null || ids.length <= 0) {
            return BaseResponse.errorMsg("参数错误");
        }
        Entrust entrust = null;
        for (Integer id : ids) {
            SampleHandle sampleHandle = sampleHandleMapper.selectById(id);
            if (sampleHandle == null) {
                return BaseResponse.errorMsg("信息错误");
            }
            if (sampleHandle.getStatus() != 1 && sampleHandle.getStatus() != 2) {
                return BaseResponse.errorMsg("状态错误");
            }
            if (loginUser.getId() != sampleHandle.getUserId()) {
                return BaseResponse.errorMsg("请登录样品处理人账号操作");
            }
            sampleHandle.setStatus(2).setFinishTime(LocalDateTime.now());
            sampleHandleMapper.updateById(sampleHandle);

            //判断该委托单下的所有样品的处理 及 处理项是否全部完成
            Sample sample = sampleMapper.selectById(sampleHandle.getSampleId());
            if (sample == null) {
                return BaseResponse.errorMsg("样品信息错误");
            }
            entrust = entrustMapper.selectById(sample.getEntrustId());
            if (entrust == null) {
                return BaseResponse.errorMsg("委托信息错误");
            }
            //计算产值
            if (sampleHandle.getHandleId() != null) {
                try {
                    iPrecipriceService.createPreciprice(sampleHandle.getUserId(),entrust.getId(),sampleHandle.getHandleId(),0,sample.getId(),false);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    return BaseResponse.errorMsg(e.getMessage());
                }
            }
            QueryWrapper<SampleHandle> sampleHandleWrapper = new QueryWrapper<>();
            sampleHandleWrapper.eq("sample_id", sample.getId());
            sampleHandleWrapper.ne("status", 2);
            List<SampleHandle> sampleHandleIngList = sampleHandleMapper.selectList(sampleHandleWrapper);
            if (sampleHandleIngList == null || sampleHandleIngList.size() == 0) {
                if (sample.getIsParallel() == 0) {
                    sample.setIsHandle(1); //样品处理全部完成
                    sampleMapper.updateById(sample);
                } else{
                    List<Sample> sampleList1 = sampleMapper.getByCementCode(entrust.getId(), sample.getCementCode());
                    if(sampleList1.size() < 2 ){
                        return BaseResponse.errorMsg("平行样样品数量信息错误");
                    }
                    // 如果是平行样，平行样的状态也改成已处理完成
                    for (Sample sam : sampleList1) {
                        sam.setIsHandle(1);
                        sampleMapper.updateById(sam);
                    }
                }
            }
            if (entrust != null) {
              /*  if (entrust.getStatus() != 3) {
                    return BaseResponse.errorMsg("委托单状态错误");
                }*/
                List<Sample> sampleList = sampleMapper.getNoHandleList(sample.getEntrustId());
                if (sampleList == null || sampleList.size() == 0) {
                    entrust.setStatus(4);
                }
                entrustMapper.updateById(entrust);
            }
        }
        if (entrust == null) {
            return BaseResponse.errorMsg("委托信息错误");
        }
        //记录委托单日志
        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "完成样品处理任务", null);
        return BaseResponse.okMsg("已完成样品处理任务");
    }

    /**
     * 派发检测项目任务
     *
     * @param query
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<String> distribution(DistributionQuery query) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (query.getId() == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        Entrust entrust = entrustMapper.selectById(query.getId());
        if (entrust == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        if (entrust.getStatus() != 4) {
            return BaseResponse.errorMsg("当前状态不允许派发");
        }
        String userIds = "";
        List<Integer> userIdList = new ArrayList<>();
        if (query.getSampleDistributionQueryList() != null && query.getSampleDistributionQueryList().size() > 0) {
            List<SampleDistributionQuery> sampleDistributionQueryList = query.getSampleDistributionQueryList();
            List<SampleDistribution> sampleDistributionList = new ArrayList<>();
            List<Sample> sampleList = new ArrayList<>();
            for (SampleDistributionQuery distributionQuery : sampleDistributionQueryList) {
                if (distributionQuery == null || distributionQuery.getSampleId() == null) {
                    return BaseResponse.errorMsg("样品信息错误");
                }
                if (distributionQuery.getSampleDistributionTeamQueryList() != null && distributionQuery.getSampleDistributionTeamQueryList().size() > 0) {
                    List<SampleDistributionTeamQuery> sampleDistributionTeamQueryList = distributionQuery.getSampleDistributionTeamQueryList();
                    for (SampleDistributionTeamQuery distributionTeamQuery : sampleDistributionTeamQueryList) {
                        if (distributionTeamQuery == null || distributionTeamQuery.getTeamId() == null ||
                                distributionTeamQuery.getTeamGroupId() == null) {
                            return BaseResponse.errorMsg("检测项信息错误");
                        }
                        if (distributionTeamQuery.getUserId() == null) {
                            return BaseResponse.errorMsg("请选择检测人员");
                        }
                        SampleDistribution sampleDistribution = new SampleDistribution();
                        sampleDistribution.setSampleId(distributionQuery.getSampleId())
                                .setTeamGroupId(distributionTeamQuery.getTeamGroupId())
                                .setTeamId(distributionTeamQuery.getTeamId())
                                .setUserId(distributionTeamQuery.getUserId())
//                                .setStatus(0)
                                .setCreateTime(LocalDateTime.now())
                                .setStatus(1)  //直接接收检测任务
                                .setAcceptTime(LocalDateTime.now());
                        sampleDistributionList.add(sampleDistribution);

                        //获取产值信息
                        QueryWrapper<NormProduction> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("assess_id", distributionTeamQuery.getTeamGroupId());
                        queryWrapper.eq("type", 1);
                        queryWrapper.eq("status", 1);
                        NormProduction normProduction = iNormProductionService.getOne(queryWrapper);
                        if(normProduction == null){
                            return BaseResponse.errorMsg("联系管理员.配置产值信息!");
                        }
                        //消息推送
                        BaseResponse wrapper = userMessageService.sendMessage(distributionTeamQuery.getUserId(), "您有一条样品检测信息等待接受",entrust.getId(), SysUserMessage.MessageType.ENTRUST);
                        if(wrapper.getCode() != 200){
                            return wrapper;
                        }
                        SysUser distributionUser = userService.getById(distributionTeamQuery.getUserId());
                        if(distributionUser == null){
                            return BaseResponse.errorMsg("样品检测人信息错误");
                        }
                        if(StringUtils.isNotBlank(distributionUser.getWxId()) && !userIdList.contains(distributionUser.getId())){
                            userIdList.add(distributionUser.getId());
                            userIds = userIds.equals("")?distributionUser.getWxId():userIds+"|"+distributionUser.getWxId();
                        }
                    }
                }
                Sample sample = sampleService.getById(distributionQuery.getSampleId());
                if (sample == null) {
                    return BaseResponse.errorMsg("样品信息错误");
                }
                sample.setStatus(1); //样品状态改成已领用状态
                sampleList.add(sample);
            }
            distributionService.saveBatch(sampleDistributionList);
            sampleService.updateBatchById(sampleList);
        }
        entrust.setStatus(5).setIsDistribution(1);
        entrustMapper.updateById(entrust);
        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "派发检测项目任务", null);
        //发送企业微信消息内容
        String content="你好！您有一条新的样品检测任务，请前往\n" +
                systemUrl +"进行接受。";
        weiXinService.sendTextMessage(userIds, content);
        return BaseResponse.okMsg("已派发检测项目任务");
    }


    /**
     * 派发任务分页
     *
     * @param pageQuery
     * @param projectName
     * @param projectCode
     * @return
     */
    @Override
    public BaseResponse<IPage<EntrustVo>> getSampleDistributionPage(PageQuery pageQuery, String projectName,
                                                                    String projectCode) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("projectName", projectName);
        params.put("projectCode", projectCode);
        params.put("userId", loginUser.getId());
        Page<EntrustVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        IPage<EntrustVo> pages = entrustMapper.getSampleDistributionPage(page, params);
        List<EntrustVo> list = pages.getRecords();
        if (list != null && list.size() > 0) {
            for (EntrustVo entrustVo : list) {
                List<Sample> sampleList = sampleMapper.getSampleList(entrustVo.getId());
                //检测项目名称
                String sampleNames = "";
                if (sampleList != null && sampleList.size() > 0) {
                    //样品名称 列表中的拼接
                    for (Sample sample : sampleList) {
                        sampleNames = sampleNames.equals("") ? sample.getName() : (sampleNames + "、" + sample.getName());
                    }
                    //检测项 和检测依据 列表里只显示第一个样品的
                    Sample sample = sampleList.get(0);
                    String teamIds = sample.getTeamIds();
                    String checkTeam = "";
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            Team team = teamMapper.selectById(Integer.valueOf(teamId));
                            if (team != null) {
                                checkTeam = checkTeam.equals("") ? team.getName() : (checkTeam + "、" + team.getName());
                            }
                        }
                    }
                    entrustVo.setCheckTeam(checkTeam);
                    entrustVo.setCheckMethodNumber(sample.getMethodNumbers());
                }
                entrustVo.setSampleNames(sampleNames);
            }
        }
        pages.setRecords(list);
        return BaseResponse.okData(pages);
    }

    /**
     * 检测通知单详情
     *
     * @param id 委托表id
     * @return
     */
    @Override
    public BaseResponse<Map<String, Object>> getSampleDistributionList(Integer id) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        Map<String, Object> map = new HashMap<>();
        Entrust entrust = entrustMapper.selectById(id);
        if (entrust == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        List<Sample> sampleList = sampleMapper.getSampleCheckList(id);
        List<SampleVo> sampleVoList = new ArrayList<>();
        Integer distributionStatus = null;
        if (sampleList != null && sampleList.size() > 0) {
            for (Sample sample : sampleList) {
                SampleVo sampleVo = new SampleVo();
                BeanUtils.copyProperties(sample, sampleVo);
                List<SampleDistributionTeamVo> sampleDistributionTeamVoList =
                        distributionMapper.getDistributionTeamList(sample.getId(), loginUser.getId());
                if (sampleDistributionTeamVoList != null && sampleDistributionTeamVoList.size() > 0) {
                    sampleVo.setSampleDistributionTeamVoList(sampleDistributionTeamVoList);
                    for (SampleDistributionTeamVo sdVo : sampleDistributionTeamVoList) {
                        if (distributionStatus != null && distributionStatus != sdVo.getStatus()) {
                            return BaseResponse.errorMsg("接受或完成的状态信息错误");
                        }
                        distributionStatus = sdVo.getStatus() == 1 ? 1 : (sdVo.getStatus() == 2 ? 2 : 0);
                    }
                    //一个平行样样品 主样和副样不能为同一个用户检测
                    sampleVoList.add(sampleVo);
                }

            }
        }
        entrust.setIsDistribution(distributionStatus); //0显示接受按钮，1显示完成按钮（可以上传附件），2和null不显示按钮
        map.put("entrust", entrust);
        map.put("sampleVoList", sampleVoList);
        return BaseResponse.okData(map);
    }

    /**
     * 接受检测项目任务
     *
     * @param ids 样品派发表id
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<String> acceptDistribution(Integer[] ids) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (ids == null || ids.length <= 0) {
            return BaseResponse.errorMsg("参数错误");
        }

        List<SampleDistribution> sampleHandleList = new ArrayList<>();
        for (Integer id : ids) {
            SampleDistribution distribution = distributionMapper.selectById(id);
            if (distribution == null) {
                return BaseResponse.errorMsg("信息错误");
            }
            if (distribution.getStatus() != 0) {
                return BaseResponse.errorMsg("状态错误");
            }
            distribution.setStatus(1).setAcceptTime(LocalDateTime.now());
            sampleHandleList.add(distribution);
        }
        distributionService.updateBatchById(sampleHandleList);

        Sample sample = sampleService.getById(sampleHandleList.get(0).getSampleId());
        if (sample == null) {
            return BaseResponse.errorMsg("样品信息错误");
        }
        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, sample.getEntrustId(), "接受检测项目任务", null);
        //处理消息
        userMessageService.dealMessage(loginUser.getId(), sample.getEntrustId(), SysUserMessage.MessageType.ENTRUST);
        return BaseResponse.okMsg("已接受检测项目任务");
    }

    /**
     * 检测项目上传附件
     *
     * @param query
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<SampleDistribution> uploadEnclosurePF(SampleDistributionEnclosureQuery query) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (query == null || query.getId() == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        SampleDistribution sampleDistribution = distributionMapper.selectById(query.getId());
        if (sampleDistribution == null) {
            return BaseResponse.errorMsg("数据错误");
        }
        sampleDistribution.setEnclosureUrl(query.getEnclosureUrl())
                .setExtName(query.getExtName())
                .setAlias(query.getAlias())
                .setUpdateTime(LocalDateTime.now());
        distributionMapper.updateById(sampleDistribution);
        return BaseResponse.okData(sampleDistribution);
    }


    /**
     * 完成检测项目任务
     *
     * @param ids 样品派发表id
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<String> finishDistribution(Integer[] ids) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (ids == null || ids.length <= 0) {
            return BaseResponse.errorMsg("参数错误");
        }
        Entrust entrust = null;
        //样品计算过产值的List
        List<Integer> sampleIdS = new ArrayList<>();
        for (Integer id : ids) {
            SampleDistribution distribution = distributionMapper.selectById(id);
            if (distribution == null) {
                return BaseResponse.errorMsg("信息错误");
            }
            if (distribution.getStatus() != 1 && distribution.getStatus() != 2) {
                return BaseResponse.errorMsg("状态错误");
            }
            distribution.setStatus(2).setFinishTime(LocalDateTime.now());
            distributionMapper.updateById(distribution);
            //判断该委托单下的所有样品的检测 及 检测项是否全部完成
            Sample sample = sampleMapper.selectById(distribution.getSampleId());
            if (sample == null) {
                return BaseResponse.errorMsg("样品信息错误");
            }
            QueryWrapper<SampleDistribution> sampleDistributionWrapper = new QueryWrapper<>();
            sampleDistributionWrapper.eq("sample_id", sample.getId());
            sampleDistributionWrapper.ne("status", 2);
            List<SampleDistribution> sampleDistributionIngList = distributionMapper.selectList(sampleDistributionWrapper);
            if (sampleDistributionIngList == null || sampleDistributionIngList.size() == 0) {
                sample.setIsDistribution(1);//样品检测全部完成
            }
            sampleMapper.updateById(sample);
            entrust = entrustMapper.selectById(sample.getEntrustId());
            if (entrust != null) {
                /*if (entrust.getStatus() != 5) {
                    return BaseResponse.errorMsg("委托单状态错误");
                }*/
                List<Sample> sampleList = sampleMapper.getNoDistributionList(sample.getEntrustId());
                if (sampleList == null || sampleList.size() == 0) {
                    entrust.setStatus(6);
                }
                entrustMapper.updateById(entrust);
                //计算产值
                if(!sampleIdS.contains(sample.getId())){
                    List<SampleDistributionTeamVo> sampleDistributionTeamGroupVoList = distributionMapper.getDistributionTeamGroupList(sample.getId(), loginUser.getId());
                    if (sampleDistributionTeamGroupVoList != null && sampleDistributionTeamGroupVoList.size() > 0) {
                        for (SampleDistributionTeamVo sdVo : sampleDistributionTeamGroupVoList) {
                            try {
                                iPrecipriceService.createPreciprice(sdVo.getUserId(),entrust.getId(),sdVo.getTeamGroupId(),1,sample.getId(),false);
                            }catch (Exception e){
                                return BaseResponse.errorMsg(e.getMessage());
                            }
                        }
                    }
                    sampleIdS.add(sample.getId());
                }
            }
        }
        if (entrust == null) {
            return BaseResponse.errorMsg("委托信息错误");
        }

        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "完成检测项目任务", null);
        return BaseResponse.okMsg("已完成检测项目任务");
    }

    /**
     * 数据校核分页
     *
     * @param pageQuery
     * @param startDate
     * @param endDate
     * @param status
     * @param clientId
     * @param projectName
     * @param projectCode
     * @return
     */
    @Override
    public BaseResponse<IPage<EntrustVo>> getCheckPage(PageQuery pageQuery, String startDate, String endDate, Integer status,
                                                       Integer clientId, String projectName, String projectCode) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("status", status);
        params.put("clientId", clientId);
        params.put("projectName", projectName);
        params.put("projectCode", projectCode);
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("数据校核");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("数据校核信息错误");
        }
        if (!approvalIdList.contains(loginUser.getId())) {
            return BaseResponse.errorMsg("当前登录账号没有数据校核权限");
        }
        Page<EntrustVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        IPage<EntrustVo> pages = entrustMapper.getCheckPage(page, params);
        List<EntrustVo> list = pages.getRecords();
        if (list != null && list.size() > 0) {
            for (EntrustVo entrustVo : list) {
                QueryWrapper<SampleTmp> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("entrust_id", entrustVo.getId());
                List<SampleTmp> sampleTmpList = sampleTmpService.list(queryWrapper);
                //检测项目名称
                String sampleNames = "";
                if (sampleTmpList != null && sampleTmpList.size() > 0) {
                    //样品名称 列表中的拼接
                    for (SampleTmp sampleTmp : sampleTmpList) {
                        sampleNames = sampleNames.equals("") ? sampleTmp.getName() : (sampleNames + "、" + sampleTmp.getName());
                    }
                    entrustVo.setSampleNames(sampleNames);
                    //检测项 和检测依据 列表里只显示第一个样品的
                    SampleTmp sampleTmp = sampleTmpList.get(0);
                    String teamIds = sampleTmp.getTeamIds();
                    String checkTeam = "";
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            Team team = teamMapper.selectById(Integer.valueOf(teamId));
                            if (team != null) {
                                checkTeam = checkTeam.equals("") ? team.getName() : (checkTeam + "、" + team.getName());
                            }
                        }
                    }
                    entrustVo.setCheckTeam(checkTeam);
                    entrustVo.setCheckMethodNumber(sampleTmp.getMethodNumbers());
                }
            }
        }
        pages.setRecords(list);
        return BaseResponse.okData(pages);
    }

    /**
     * 数据校核详情列表
     *
     * @param id 委托表id
     * @return
     */
    @Override
    public BaseResponse<Map<String, Object>> getCheckList(Integer id) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        Map<String, Object> map = new HashMap<>();
        Entrust entrust = entrustMapper.selectById(id);
        if (entrust == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        List<Sample> sampleList = sampleMapper.getCheckSampleList(id);
        List<SampleVo> sampleVoList = new ArrayList<>();
        if (sampleList != null && sampleList.size() > 0) {
            for (Sample sample : sampleList) {
                SampleVo sampleVo = new SampleVo();
                BeanUtils.copyProperties(sample, sampleVo);
                List<SampleDistributionTeamVo> sampleDistributionTeamVoList = distributionMapper.getDistributionTeamList(sample.getId(), null);
                if (sampleDistributionTeamVoList != null && sampleDistributionTeamVoList.size() > 0) {
                    //判断是否为平行样
                    if (sample.getIsParallel() != 0) {
                        List<Sample> sampleList1 = sampleMapper.getByCementCode(entrust.getId(), sample.getCementCode());
                        //检测人员只能看到自己则的检测内容
                        if (sampleList1.size() > 1) {
                            for(Sample sample1 : sampleList1){
                                List<SampleDistributionTeamVo> sampleDistributionTeamVoList2 = distributionMapper.getDistributionTeamList(sample1.getId(), null);
                                if (sampleDistributionTeamVoList2.size() == sampleDistributionTeamVoList.size()) {
                                    for (int i = 0; i < sampleDistributionTeamVoList.size(); i++) {
                                        SampleDistributionTeamVo sdtvo = sampleDistributionTeamVoList.get(i);
                                        if(!sdtvo.getUserName().contains(sampleDistributionTeamVoList2.get(i).getUserName())){
                                            sdtvo.setUserName(sdtvo.getUserName() + "、" + sampleDistributionTeamVoList2.get(i).getUserName());
                                        }
                                    }
                                }
                            }
                        } else {
                            sampleDistributionTeamVoList =
                                    distributionMapper.getDistributionTeamList(sample.getId(), null);
                        }
                    }
                    sampleVo.setSampleDistributionTeamVoList(sampleDistributionTeamVoList);
                } else {
                    sampleVo.setSampleDistributionTeamVoList(null);
                }
                sampleVoList.add(sampleVo);
            }
        }
        map.put("entrust", entrust);
        map.put("sampleVoList", sampleVoList);
        return BaseResponse.okData(map);
    }

    /**
     * 样品检测项校核详情
     *
     * @param cementCode 本所编号
     * @return
     */
    public BaseResponse<List<SampleCheckVo>> getCheckDetail(String cementCode) {
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录账号");
        }
        if (StringUtils.isEmpty(cementCode)) {
            return BaseResponse.errorMsg("参数错误");
        }

        QueryWrapper<Sample> sampleQW = new QueryWrapper<>();
        sampleQW.eq("cement_code", cementCode);
        List<Sample> sampleList = sampleMapper.selectList(sampleQW);

        List<SampleCheckVo> sampleCheckVoList = new ArrayList<>();
        if (sampleList != null && sampleList.size() > 0) {
            Sample sampleOne = sampleList.get(0);
            if (sampleOne == null) {
                return BaseResponse.errorMsg("样品信息错误");
            }
            Entrust entrust = entrustMapper.selectById(sampleOne.getEntrustId());
            if (entrust == null) {
                return BaseResponse.errorMsg("委托单信息错误");
            }
            //根据样品 和派发任务表 找到都有哪些检测组
            List<SampleCheckGroupVo> sampleCheckGroupVoList = distributionMapper.getSampleCheckGroupList(sampleOne.getId());
            if (sampleCheckGroupVoList != null && sampleCheckGroupVoList.size() > 0) {
                for (SampleCheckGroupVo sampleCheckGroupVo : sampleCheckGroupVoList) {
                    QueryWrapper<SampleCheck> sampleCheckQW = new QueryWrapper<>();
                    sampleCheckQW.eq("entrust_id", entrust.getId());
                    sampleCheckQW.eq("cement_code", cementCode);
                    sampleCheckQW.eq("team_group_id", sampleCheckGroupVo.getTeamGroupId());
                    List<SampleCheck> sampleCheckList = sampleCheckMapper.selectList(sampleCheckQW);

                    if (sampleCheckList != null && sampleCheckList.size() > 0) {   //参与校核计算的
                        SampleCheck sampleCheck = sampleCheckList.get(0);
                        SampleCheckVo sampleCheckVo = new SampleCheckVo();
                        sampleCheckVo.setId(sampleCheck.getId());
                        sampleCheckVo.setEntrustId(entrust.getId());
                        sampleCheckVo.setSampleName(sampleOne.getName());
                        sampleCheckVo.setCementCode(cementCode);
                        sampleCheckVo.setTeamGroupId(sampleCheck.getTeamGroupId());
                        sampleCheckVo.setTeamGroupName(sampleCheck.getTeamGroupName());
                        sampleCheckVo.setCountResults(sampleCheck.getCountResults());
                        sampleCheckVo.setCountError(sampleCheck.getCountError());
                        sampleCheckVo.setIsParallel(sampleOne.getIsParallel());
                        QueryWrapper<SampleCheckTeam> sampleCheckTeamQW = new QueryWrapper<>();
                        sampleCheckTeamQW.eq("check_id", sampleCheck.getId());
                        List<SampleCheckTeam> sampleCheckTeamList = sampleCheckTeamMapper.selectList(sampleCheckTeamQW);
                        List<SampleCheckTeamVo> sctVoList = new ArrayList<>();
                        if (sampleCheckTeamList != null && sampleCheckTeamList.size() > 0) {
                            for (SampleCheckTeam sampleCheckTeam : sampleCheckTeamList) {
                                SampleCheckTeamVo sampleCheckTeamVo = new SampleCheckTeamVo();
                                sampleCheckTeamVo.setId(sampleCheckTeam.getId());
                                sampleCheckTeamVo.setCheckId(sampleCheck.getId());
                                sampleCheckTeamVo.setSampleId(sampleCheckTeam.getSampleId());
                                sampleCheckTeamVo.setSampleId(sampleCheckTeam.getSampleId());
                                //本所编号 展示的是平行样编号
                                sampleCheckTeamVo.setParallelCode(sampleCheckTeam.getParallelCode());
                                sampleCheckTeamVo.setUserId(sampleCheckTeam.getUserId());
                                SysUser sysUser = userService.getById(sampleCheckTeam.getUserId());
                                sampleCheckTeamVo.setUserName(sysUser.getName());
                                sampleCheckTeamVo.setEquipmentId(sampleCheckTeam.getEquipmentId());
                                sampleCheckTeamVo.setEquipmentName(sampleCheckTeam.getEquipmentName());
                                sampleCheckTeamVo.setInputResult(sampleCheckTeam.getInputResult());
                                sampleCheckTeamVo.setCountResult(sampleCheckTeam.getCountResult());
                                sctVoList.add(sampleCheckTeamVo);
                            }
                        }
                        sampleCheckVo.setSampleCheckGroupVoList(sctVoList);
                        sampleCheckVoList.add(sampleCheckVo);
                    }else{         //未参与校核计算的
                        SampleCheckVo sampleCheckVo = new SampleCheckVo();
                        sampleCheckVo.setEntrustId(entrust.getId());
                        sampleCheckVo.setSampleName(sampleOne.getName());
                        sampleCheckVo.setCementCode(cementCode);
                        sampleCheckVo.setTeamGroupId(sampleCheckGroupVo.getTeamGroupId());
                        sampleCheckVo.setTeamGroupName(sampleCheckGroupVo.getTeamGroupName());
                        TeamGroup teamGroup = teamGroupMapper.selectById(sampleCheckGroupVo.getTeamGroupId());
                        if (teamGroup == null) {
                            return BaseResponse.errorMsg("检测组信息错误");
                        }
                        //根据检测组id返回检测组对应的所有检测项信息
//                        List<String> checkResutlList = teamMapper.getByGroup(teamGroup.getId());
                        List<Map<String,String>> checkResutlList2 =  teamMapper.getListByGroup(teamGroup.getId());
                        JSONArray jsonArray = new JSONArray();
                        for(Map<String,String> cr : checkResutlList2){
                            jsonArray.add(cr);
                        }
                        String checkResut_String = JSON.toJSON(jsonArray).toString();
                        System.out.println(checkResut_String);
                        sampleCheckVo.setCountResults(checkResut_String);



                        sampleCheckVo.setIsParallel(sampleOne.getIsParallel());
                        List<SampleCheckTeamVo> sctVoList = new ArrayList<>();
                        for (Sample sample : sampleList) {
                            SampleCheckTeamVo sampleCheckTeamVo = new SampleCheckTeamVo();
                            sampleCheckTeamVo.setCheckId(null);
                            sampleCheckTeamVo.setSampleId(sample.getId());
                            //本所编号 展示的是平行样编号
                            sampleCheckTeamVo.setParallelCode(sample.getParallelCode());
                            QueryWrapper<SampleDistribution> sdWrapper = new QueryWrapper<>();
                            sdWrapper.eq("sample_id", sample.getId());
                            sdWrapper.eq("team_group_id", sampleCheckGroupVo.getTeamGroupId());
                            List<SampleDistribution> sdList = distributionMapper.selectList(sdWrapper);
                            SampleDistribution sampleDistribution = sdList.get(0);
                            SysUser sysUser = userService.getById(sampleDistribution.getUserId());
                            sampleCheckTeamVo.setUserId(sampleDistribution.getUserId());
                            sampleCheckTeamVo.setUserName(sysUser.getName());
                            sampleCheckTeamVo.setInputResult(teamGroup.getCheckElement());
                            sctVoList.add(sampleCheckTeamVo);
                        }
                        sampleCheckVo.setSampleCheckGroupVoList(sctVoList);
                        sampleCheckVoList.add(sampleCheckVo);
                    }
                }
            }
        }
        return BaseResponse.okData(sampleCheckVoList);
    }


    /**
     * 根据样品id，检测组id，检测人id 查询任务检测附件信息
     *
     * @param sampleId
     * @param teamGroupId
     * @param userId
     * @return
     */
    public BaseResponse<List<SampleDistribution>> getEnclosureList(Integer sampleId, Integer teamGroupId, Integer userId) {
        QueryWrapper<SampleDistribution> sdQueryWrapper = new QueryWrapper<>();
        sdQueryWrapper.eq("sample_id", sampleId);
        sdQueryWrapper.eq("team_group_id", teamGroupId);
        sdQueryWrapper.eq("user_id", userId);
        List<SampleDistribution> sdList = distributionMapper.selectList(sdQueryWrapper);
        return BaseResponse.okData(sdList);
    }


    /**
     * 校核计算
     *
     * @param query
     * @return
     */
    @Override
    @Transactional
    public BaseResponse<Map<String, Object>> checkCount(CheckCountQuery query) {
        if (query == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        Entrust entrust = entrustMapper.selectById(query.getEntrustId());
        if (entrust == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        if (entrust.getStatus() < 6) {
            return BaseResponse.errorMsg("当前状态不允许校核");
        }
        entrust.setStatus(7); //校核中状态
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录用户");
        }

        if (query.getCementCode() == null) {
            return BaseResponse.errorMsg("本所编号不能为空");
        }
        if (query.getTeamGroupId() == null || StringUtils.isEmpty(query.getTeamGroupName())) {
            return BaseResponse.errorMsg("请选择检测组");
        }
        SampleCheck check = null;
        //保存校核表信息
        if(query.getId() == null){
            check = new SampleCheck();
            check.setEntrustId(entrust.getId())
                    .setCementCode(query.getCementCode())
                    .setTeamGroupId(query.getTeamGroupId())
                    .setTeamGroupName(query.getTeamGroupName())
                    .setCountResults(null)
                    .setCountError(null)
                    .setIsParallel(query.getIsParallel())
                    .setCreateTime(LocalDateTime.now());
            sampleCheckMapper.insert(check);
        }else{
            check = sampleCheckMapper.selectById(query.getId());
        }
        //返回信息：样品的计算结果集合
        Map<String, Object> countResultMap = new HashMap<>();
        if (query.getSampleList() != null && query.getSampleList().size() > 0) {
            //通过检测组获取检测项信息
            List<String> checkResutlList = teamMapper.getByGroup(check.getTeamGroupId());
            //该检测项的每个样品的检测计算结果集合
            List<Map<String, String>> resultMapList = new ArrayList<>();
            for (CheckCountSampleQuery sampleQuery : query.getSampleList()) {
                if(sampleQuery.getSmapleId() == null){
                    return BaseResponse.errorMsg("样品信息错误");
                }
                if(StringUtils.isEmpty(sampleQuery.getParallelCode())){
                    return BaseResponse.errorMsg("请传入平行样编号");
                }
                if(sampleQuery.getUserId() == null){
                    return BaseResponse.errorMsg("请传入检测人id");
                }
                if(sampleQuery.getEquipmentId() == null || StringUtils.isEmpty(sampleQuery.getEquipmentName())){
                    return BaseResponse.errorMsg("请传选择检测设备");
                }
                if(sampleQuery.getIntputResult() == null){
                    return BaseResponse.errorMsg("请输入检测数据");
                }
                JSONArray inputResult_jsonArray = commonService.mapToJSONArray(sampleQuery.getIntputResult());
                String inputResult_String = JSON.toJSON(inputResult_jsonArray).toString();
                System.out.println(inputResult_String);
                //计算检测结果
                Map<String, String> resultMap = commonService.checkCount(checkResutlList, sampleQuery.getIntputResult());
                resultMapList.add(resultMap);
                JSONArray resultMap_jsonArray = commonService.mapToJSONArray(resultMap);
                String resultMap_String = JSON.toJSON(resultMap_jsonArray).toString();
                System.out.println(resultMap_String);
                //保存校核检测组检测项信息
                SampleCheckTeam sampleCheckTeam = null;
                if(sampleQuery.getId() == null){
                    sampleCheckTeam = new SampleCheckTeam();
                    sampleCheckTeam.setCheckId(check.getId())
                            .setSampleId(sampleQuery.getSmapleId())
                            .setParallelCode(sampleQuery.getParallelCode())
                            .setUserId(sampleQuery.getUserId())
                            .setEquipmentId(sampleQuery.getEquipmentId())
                            .setEquipmentName(sampleQuery.getEquipmentName())
                            .setInputResult(inputResult_String)
                            .setCountResult(resultMap_String)
                            .setCreateTime(LocalDateTime.now());
                    sampleCheckTeamMapper.insert(sampleCheckTeam);
                    //添加设备使用记录  设备使用记录表 equipment_use
                    EquipmentUse equipmentUse2 = new EquipmentUse();
                    SysUser sysUser = userService.getById(sampleCheckTeam.getUserId());
                    equipmentUse2.setEquipmentId(sampleCheckTeam.getEquipmentId())
                            .setUserId(sampleCheckTeam.getUserId())
                            .setUserName(sysUser.getName())
                            .setUseDate(LocalDate.now())
                            .setProjectId(entrust.getProjectId())
                            .setProjectName(entrust.getProjectName())
                            .setProjectCode(entrust.getProjectCode())
                            .setTestItem(check.getTeamGroupName())
                            .setCreateTime(LocalDateTime.now())
                            .setRemark("委托派发-数据校核");
                    equipmentUseMapper.insert(equipmentUse2);
                }else{
                    sampleCheckTeam = sampleCheckTeamMapper.selectById(sampleQuery.getId());
                    sampleCheckTeam.setCheckId(check.getId())
                            .setInputResult(inputResult_String)
                            .setCountResult(resultMap_String);
                    sampleCheckTeamMapper.updateById(sampleCheckTeam);
                }
            }
            countResultMap.put("resultMapList", resultMapList);
            //计算最终计算结果  和 结果误差值
            Map<String,String> groupMap = new HashMap<>();   //"L.O.I":"1,2,3,4..."
            if(resultMapList != null && resultMapList.size()>0){
                for (String name : checkResutlList) {
                    if (name.equals("L.O.I")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("SiO<sub>2</sub>")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name, (groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))?
                                    map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("Al<sub>2</sub>O<sub>3</sub>+TiO<sub>2</sub>")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("Al<sub>2</sub>O<sub>3</sub>")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("Fe<sub>2</sub>O<sub>3</sub>")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("CaO")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("MgO")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("TiO<sub>2</sub>")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("K<sub>2</sub>O")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("Na<sub>2</sub>O")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("SO<sub>3</sub>")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("Cl")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("合量")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("KH")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("SM")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else if (name.equals("AM")) {
                        for(Map<String, String> map : resultMapList){
                            groupMap.put(name,(groupMap == null || groupMap.size()==0 ||
                                    groupMap.get(name) == null ||  groupMap.get(name).equals(""))
                                    ?map.get(name):groupMap.get(name)+","+map.get(name));
                        }
                    } else {
                        groupMap.put(name, "0");
                    }
                }
            }
            //计算平行样的平均值  最大误差值
        Map<String,Map<String,String>> mapResult = CheckCountUtil.countParallelAvgError(groupMap);
        if(mapResult != null){
            Map<String,String> countResults= mapResult.get("countResults");
            JSONArray countResults_jsonArray = commonService.mapToJSONArray(countResults);
            String countResults_String = JSON.toJSON(countResults_jsonArray).toString();
            System.out.println(countResults_String);
            Map<String,String> countError= mapResult.get("countError");
            JSONArray countError_jsonArray = commonService.mapToJSONArray(countError);
            String countError_String = JSON.toJSON(countError_jsonArray).toString();
            System.out.println(countError_String);
            check.setCountResults(countResults_String);
            check.setCountError(countError_String);
            sampleCheckMapper.updateById(check);
            countResultMap.put("countResults", countResults_String);
            countResultMap.put("countError", countError_String);
        }
    }
        Boolean ret = true; //全部校核计算完成
        List<SampleCheckGroupVo> sampleCheckGroupVoList = distributionMapper.getSampleCheckGroupList( query.getSampleList().get(0).getSmapleId());
        for(SampleCheckGroupVo groupVo : sampleCheckGroupVoList){
            QueryWrapper<SampleCheck> sampleCheckQW = new QueryWrapper<>();
            sampleCheckQW.eq("entrust_id", entrust.getId());
            sampleCheckQW.eq("cement_code", query.getCementCode());
            sampleCheckQW.eq("team_group_id", groupVo.getTeamGroupId());
            List<SampleCheck> sampleCheckList = sampleCheckMapper.selectList(sampleCheckQW);
            if(sampleCheckList == null || sampleCheckList.size()==0){
                ret = false; //有一个检测组没有校核，证明校核没有完成
            }
        }
        //如果检测组的校核全部完成
        if(ret){
            //更新样品表状态为已经校核状态 is_check 0未处理 1处理完成
            QueryWrapper<Sample> sampleQW = new QueryWrapper<>();
            sampleQW.eq("cement_code", query.getCementCode());
            List<Sample> sampleList = sampleMapper.selectList(sampleQW);
            if (sampleList != null && sampleList.size() > 0) {
                for (Sample sample : sampleList) {
                    sample.setIsCheck(1);
                    sampleMapper.updateById(sample);
                }
            }
        }

        //如果是保存并完成按钮，检测委托单中其他样品是否都是保存冰完成状态，如果是，委托单为检测完成状态
        List<Sample> sampleNoCheckList = sampleMapper.getNoCheckList(entrust.getId());
        if (sampleNoCheckList == null || sampleNoCheckList.size() == 0) {
            entrust.setStatus(8);
            //校核完成之后 ，提醒评审人员查看
            List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
            if (approvalIdList == null) {
                return BaseResponse.errorMsg("委托评审信息错误");
            }
            String userIds = "";
            for(Integer approvalId : approvalIdList ){
                SysUser approvalUser = userService.getById(approvalId);
                if(approvalUser == null){
                    return BaseResponse.errorMsg("委托评审信息错误");
                }
                BaseResponse wrapper = userMessageService.sendMessage(approvalId, "您有一条委托单校核完成",entrust.getId(), SysUserMessage.MessageType.ENTRUST);
                if(wrapper.getCode() != 200){
                    return wrapper;
                }
                if(StringUtils.isNotBlank(approvalUser.getWxId())){
                    userIds = userIds.equals("")?approvalUser.getWxId():userIds+"|"+approvalUser.getWxId();
                }
            }
            //发送企业微信消息内容
            String content="你好！"+"委托单号"+entrust.getEntrustCode()+"已校核完成，请前往\n" +
                    systemUrl +"进行查看。";
            weiXinService.sendTextMessage(userIds, content);

        }
        entrustMapper.updateById(entrust);
        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "数据校核", null);

        iPrecipriceService.updateStatusByEntrustId(entrust.getId());
        return BaseResponse.okData(countResultMap);
    }


    /**
     * 数据校核
     *
     * @param
     * @return
     */
  /*  @Transactional
    @Override
    public BaseResponse<String> check(CheckQuery query) {
        if (query.getId() == null) {
            return BaseResponse.errorMsg("参数错误");
        }
        Entrust entrust = entrustMapper.selectById(query.getId());
        entrust.setStatus(7);
        if (entrust == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        if (entrust.getStatus() < 6) {
            return BaseResponse.errorMsg("当前状态不允许校核");
        }
        LoginUser loginUser = userService.getLoginUser();
        if (loginUser == null) {
            return BaseResponse.errorMsg("请登录用户");
        }
        String cementCode = "";
        if (query.getSampleCheckTeamQueryList() != null && query.getSampleCheckTeamQueryList().size() > 0) {
            List<SampleCheckTeamQuery> sctQueryList = query.getSampleCheckTeamQueryList();
            for (SampleCheckTeamQuery sctQuery : sctQueryList) {
                if (sctQuery == null || sctQuery.getCementCode() == null) {
                    return BaseResponse.errorMsg("检测组或样品信息错误");
                }
                if (sctQuery.getTeamGroupId() == null || StringUtils.isEmpty(sctQuery.getTeamGroupName())) {
                    return BaseResponse.errorMsg("请选择检测组");
                }
                cementCode = sctQuery.getCementCode(); //获取本所编号用于判断委托单和样品表状态
                //保存校核表信息
                SampleCheck check = new SampleCheck();
                check.setEntrustId(entrust.getId())
                        .setCementCode(sctQuery.getCementCode())
                        .setTeamGroupId(sctQuery.getTeamGroupId())
                        .setTeamGroupName(sctQuery.getTeamGroupName())
                        .setCountResult(JSON.toJSONString(sctQuery.getEndResult()))
                        .setMainMap(JSON.toJSONString(sctQuery.getMainMap()))
                        .setSecondaryMap(JSON.toJSONString(sctQuery.getSecondaryMap()))
                        .setIsParallel(sctQuery.getIsParallel())
                        .setCreateTime(LocalDateTime.now());
                sampleCheckMapper.insert(check);

                //保存校核检测组检测项信息
//				List<SampleCheckTeam> sampleCheckTeamList = new ArrayList<>();
                SampleCheckTeam sampleCheckTeam = new SampleCheckTeam();
                sampleCheckTeam.setCheckId(check.getId())
                        .setSampleId(sctQuery.getMainSampleId())
                        .setParallelCode(sctQuery.getMainParallelCode())
                        .setUserId(sctQuery.getMainUserId())
                        .setEquipmentId(sctQuery.getMainEquipmentId())
                        .setEquipmentName(sctQuery.getMainEquipmentName())
                        .setInputResult(JSON.toJSONString(sctQuery.getMainResult()))
                        .setCreateTime(LocalDateTime.now());
                sampleCheckTeamMapper.insert(sampleCheckTeam);
                //添加设备使用记录  设备使用记录表 equipment_use
                EquipmentUse equipmentUse = new EquipmentUse();
                SysUser sysUser = userService.getById(sampleCheckTeam.getUserId());
                equipmentUse.setEquipmentId(sampleCheckTeam.getEquipmentId())
                        .setUserId(sampleCheckTeam.getUserId())
                        .setUserName(sysUser.getName())
                        .setUseDate(LocalDate.now())
                        .setProjectId(entrust.getProjectId())
                        .setProjectName(entrust.getProjectName())
                        .setProjectCode(entrust.getProjectCode())
                        .setTestItem(check.getTeamGroupName())
                        .setCreateTime(LocalDateTime.now())
                        .setRemark("委托派发-数据校核");
                equipmentUseMapper.insert(equipmentUse);
                if (check.getIsParallel() == 1) {
                    SampleCheckTeam sampleCheckTeam2 = new SampleCheckTeam();
                    sampleCheckTeam2.setCheckId(check.getId())
                            .setSampleId(sctQuery.getSecondarySampleId())
                            .setParallelCode(sctQuery.getSecondaryParallelCode())
                            .setUserId(sctQuery.getSecondaryUserId())
                            .setEquipmentId(sctQuery.getSecondaryEquipmentId())
                            .setEquipmentName(sctQuery.getSecondaryEquipmentName())
                            .setInputResult(JSON.toJSONString(sctQuery.getSecondaryResult()))
                            .setCreateTime(sampleCheckTeam.getCreateTime());
                    sampleCheckTeamMapper.insert(sampleCheckTeam2);
                    //添加设备使用记录  设备使用记录表 equipment_use
                    EquipmentUse equipmentUse2 = new EquipmentUse();
                    SysUser sysUser2 = userService.getById(sampleCheckTeam2.getUserId());
                    equipmentUse2.setEquipmentId(sampleCheckTeam2.getEquipmentId())
                            .setUserId(sampleCheckTeam2.getUserId())
                            .setUserName(sysUser2.getName())
                            .setUseDate(LocalDate.now())
                            .setProjectId(entrust.getProjectId())
                            .setProjectName(entrust.getProjectName())
                            .setProjectCode(entrust.getProjectCode())
                            .setTestItem(check.getTeamGroupName())
                            .setCreateTime(LocalDateTime.now())
                            .setRemark("委托派发-数据校核");
                    equipmentUseMapper.insert(equipmentUse2);
                }
            }
        }
        //更新样品表状态为已经校核状态 is_check 0未处理 1处理完成
        QueryWrapper<Sample> sampleQW = new QueryWrapper<>();
        sampleQW.eq("cement_code", cementCode);
        List<Sample> sampleList = sampleMapper.selectList(sampleQW);
        if (sampleList != null && sampleList.size() > 0) {
            for (Sample sample : sampleList) {
                sample.setIsCheck(1);
                sampleMapper.updateById(sample);
            }
        }

        //如果是保存并完成按钮，检测委托单中其他样品是否都是保存冰完成状态，如果是，委托单为检测完成状态
        List<Sample> sampleNoCheckList = sampleMapper.getNoCheckList(entrust.getId());
        if (sampleNoCheckList == null || sampleNoCheckList.size() == 0) {
            entrust.setStatus(8);
        }
        entrustMapper.updateById(entrust);
        logsService.saveLog(SysLogs.ObjType.ENTRUST_LOG, entrust.getId(), "数据校核", null);
        return BaseResponse.okMsg("数据校核完成");
    }*/

    @Override
    public BaseResponse<IPage<EntrustVo>> getReportPage(PageQuery pageQuery, String startDate, String endDate, Integer clientId, String projectName, String projectCode) {

        Map<String, Object> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("reportStatus", 4);
        params.put("clientId", clientId);
        params.put("projectName", projectName);
        params.put("projectCode", projectCode);
        params.put("projectType", "常规项目");
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }
        Page<EntrustVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        IPage<EntrustVo> pages = entrustMapper.getPage(page, params);
        List<EntrustVo> list = pages.getRecords();

        if (list != null && list.size() > 0) {
            for (EntrustVo entrustVo : list) {
                QueryWrapper<SampleTmp> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("entrust_id", entrustVo.getId());
                List<SampleTmp> sampleTmpList = sampleTmpService.list(queryWrapper);
                //检测项目名称
                String sampleNames = "";
                if (sampleTmpList != null && sampleTmpList.size() > 0) {
                    //样品名称 列表中的拼接
                    for (SampleTmp sampleTmp : sampleTmpList) {
                        sampleNames = "".equals(sampleNames) ? sampleTmp.getName() : (sampleNames + "、" + sampleTmp.getName());
                    }
                    entrustVo.setSampleNames(sampleNames);
                    //检测项 和检测依据 列表里只显示第一个样品的
                    SampleTmp sampleTmp = sampleTmpList.get(0);
                    String teamIds = sampleTmp.getTeamIds();
                    String checkTeam = "";
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            Team team = teamMapper.selectById(Integer.valueOf(teamId));
                            if (team != null) {
                                checkTeam = "".equals(checkTeam) ? team.getName() : (checkTeam + "、" + team.getName());
                            }
                        }
                    }
                    entrustVo.setCheckTeam(checkTeam);
                    entrustVo.setCheckMethodNumber(sampleTmp.getMethodNumbers());
                }

                //查询报告,如果有上传的委托报告，用户可已进行下载
                QueryWrapper<EntityEnclosure> wrapper = new QueryWrapper<>();
                wrapper.eq("entity_type", EntityEnclosure.EntityType.ENTRUST_REPORT);
                wrapper.eq("entity_id", entrustVo.getId());
                wrapper.eq("is_deleted", 1);
                List<EntityEnclosure> entityEnclosureList = entityEnclosureMapper.selectList(wrapper);
                if(entityEnclosureList != null && entityEnclosureList.size()>0 ){
                    EntityEnclosure entityEnclosure = entityEnclosureList.get(0);
                    entrustVo.setAlias(entityEnclosure.getAlias());
                    entrustVo.setEnclosureUrl(entityEnclosure.getEnclosureUrl());
                    entrustVo.setExtName(entityEnclosure.getExtName());
                }
            }
        }
        pages.setRecords(list);
        return BaseResponse.okData(pages);
    }

    @Override
    public ReportDetailVo getReportDetail(Integer entrustId) {

        List<EntrustReport> list = entrustMapper.getReportDetail(entrustId);

        String teamKey = "CACHE:TEAM";
        String methodKey = "CACHE:METHOD";

        //缓存 60s
        if (!redisUtil.existsKey(teamKey)) {
            List<Team> teams = teamMapper.selectList(new QueryWrapper<>());
            String value = JSON.toJSONString(teams);
            redisUtil.setString(teamKey, value, 60);
        }
        if (!redisUtil.existsKey(methodKey)) {
            List<Method> methods = methodMapper.selectList(new QueryWrapper<>());
            String value = JSON.toJSONString(methods);
            redisUtil.setString(methodKey, value, 60);
        }
        List<Team> teams = JSON.parseArray(redisUtil.getString(teamKey) + "", Team.class);
        List<Method> methods = JSON.parseArray(redisUtil.getString(methodKey) + "", Method.class);
        list.forEach(arg -> {
            String teamIds = arg.getTeamIds();
            String[] teamSplit = teamIds.split("、");
            for (String idStr : teamSplit) {
                int id = Integer.parseInt(idStr);
                teams.forEach(opt -> {
                    if (opt.getId() == id && 1 == opt.getQualifications()) {
                        if (StrUtil.isBlank(arg.getTeamName())) {
                            arg.setTeamName(opt.getName());
                        } else {
                            arg.setTeamName(arg.getTeamName() + "、" + opt.getName());
                        }
                    }
                });
            }
            String methodNumbers = arg.getMethodNumbers();
            String[] methodSplit = methodNumbers.split("、");
            for (String idStr : methodSplit) {
                String id = Integer.parseInt(idStr) + "";
                methods.forEach(opt -> {
                    if (id.equals(opt.getNumber())) {
                        if (StrUtil.isBlank(arg.getMethodName())) {
                            arg.setMethodName(opt.getName() + "  " + opt.getStandard());
                        } else {
                            arg.setMethodName(arg.getMethodName() + "、" + opt.getName() + "  " + opt.getStandard());
                        }
                    }
                });
            }
        });

        if (list.size() != 0) {
            //过滤 id==null 和 projectType != '常规项目'
            List<EntrustReport> normalList = list.stream()
                    .filter(arg -> arg.getId() != null && "常规项目".equals(arg.getProjectType()))
                    .collect(Collectors.toList());
            return initReportDetailVo(normalList);
        }

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> deleteById(Integer id) {

        if (id == null || id <= 0) {
            return BaseResponse.errorMsg("id编号不能为空!");
        }
        Entrust entrust = this.getById(id);
        entrust.setIsDelete(0);
        boolean b = this.updateById(entrust);
        return BaseResponse.okData(b);
    }


    @Override
    public BaseResponse<IPage<EntrustVo>> getQualityPage(PageQuery pageQuery, String startDate, String endDate, Integer clientId, String projectName, String projectCode) {


        Map<String, Object> params = new HashMap<>(9);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("status", 8);
        params.put("clientId", clientId);
        params.put("projectName", projectName);
        params.put("projectCode", projectCode);
        params.put("projectType", "质量控制");
        List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("委托评审");
        if (approvalIdList == null) {
            return BaseResponse.errorMsg("委托评审信息错误");
        }

        Page<EntrustVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        IPage<EntrustVo> pages = entrustMapper.getPage(page, params);
        List<EntrustVo> list = pages.getRecords();

        if (list != null && list.size() > 0) {
            for (EntrustVo entrustVo : list) {
                QueryWrapper<SampleTmp> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("entrust_id", entrustVo.getId());
                List<SampleTmp> sampleTmpList = sampleTmpService.list(queryWrapper);
                //检测项目名称
                String sampleNames = "";
                if (sampleTmpList != null && sampleTmpList.size() > 0) {
                    //样品名称 列表中的拼接
                    for (SampleTmp sampleTmp : sampleTmpList) {
                        sampleNames = "".equals(sampleNames) ? sampleTmp.getName() : (sampleNames + "、" + sampleTmp.getName());
                    }
                    entrustVo.setSampleNames(sampleNames);
                    //检测项 和检测依据 列表里只显示第一个样品的
                    SampleTmp sampleTmp = sampleTmpList.get(0);
                    String teamIds = sampleTmp.getTeamIds();
                    String checkTeam = "";
                    if (teamIds != null) {
                        String[] teamIdS = teamIds.split("、");
                        for (String teamId : teamIdS) {
                            Team team = teamMapper.selectById(Integer.valueOf(teamId));
                            if (team != null) {
                                checkTeam = "".equals(checkTeam) ? team.getName() : (checkTeam + "、" + team.getName());
                            }
                        }
                    }
                    entrustVo.setCheckTeam(checkTeam);
                    entrustVo.setCheckMethodNumber(sampleTmp.getMethodNumbers());
                }
            }
        }
        pages.setRecords(list);
        return BaseResponse.okData(pages);
    }

    @Override
    public QualityDetailVo getQualityDetail(Integer entrustId) {

        List<QualityDetail> qualityDetails = entrustMapper.getQualityDetail(entrustId);
        if (qualityDetails.size() == 0) {
            return null;
        }
        //处理inputValue
        qualityDetails.forEach(arg -> arg.setInputResult(mapStringToMap(arg.getInputResult())));

        QualityDetail firstQualityDetail = qualityDetails.get(0);
        QualityDetailVo qualityDetailVo = new QualityDetailVo();
        BeanUtil.copyProperties(firstQualityDetail, qualityDetailVo);
        //获取clientId和userName
        String userCacheKey = "CACHE:USER";
        String clientCacheKey = "CACHE:CLIENT";
        //缓存 60s
        if (!redisUtil.existsKey(userCacheKey)) {
            List<SysUser> users = userService.list();
            String value = JSON.toJSONString(users);
            redisUtil.setString(userCacheKey, value, 60);
        }
        if (!redisUtil.existsKey(clientCacheKey)) {
            List<Client> clients = clientMapper.selectList(new QueryWrapper<>());
            String value = JSON.toJSONString(clients);
            redisUtil.setString(clientCacheKey, value, 60);
        }
        List<SysUser> sysUsers = JSON.parseArray(redisUtil.getString(userCacheKey) + "", SysUser.class);
        List<Client> clients = JSON.parseArray(redisUtil.getString(clientCacheKey) + "", Client.class);
        //关联委托方
        clients.stream()
                .filter(opt -> opt.getId().intValue() == firstQualityDetail.getClientId())
                .findFirst().ifPresent(opt -> qualityDetailVo.setClientName(opt.getName()));
        //关联检测者名字
        qualityDetails.forEach(arg -> sysUsers.stream()
                .filter(opt -> opt.getId().intValue() == arg.getUserId())
                .findFirst().ifPresent(opt -> arg.setUserName(opt.getName())));
        //为每个检测组 创建实体
        qualityDetails.stream()
                .map(QualityDetail::getTeamGroupName)
                .collect(Collectors.toSet())
                .forEach(arg -> {
                    //遍历每个检测组名字 创建检测组集合
                    QualityDetailVo.QualityTeamGroup qualityTeamGroup = new QualityDetailVo.QualityTeamGroup();
                    qualityTeamGroup.setTeamGroupName(arg);
                    qualityDetailVo.getQualityTeamGroups().add(qualityTeamGroup);
                    List<QualityDetail> collect = qualityDetails.stream()
                            //找到当前检测组下的是要样品
                            .filter(opt -> opt.getTeamGroupName().equals(arg))
                            .collect(Collectors.toList());
                    collect.forEach(opt -> qualityTeamGroup.setTeamGroupId(opt.getTeamGroupId()));
                    collect.stream()
                            .map(QualityDetail::getSampleName)
                            .collect(Collectors.toSet())
                            .forEach(opt -> {
                                //拿到了样品名字和检测组名字 开始创建Vo对象
                                QualityDetailVo.QualitySample qualitySample =
                                        new QualityDetailVo.QualitySample();
                                qualitySample.setSampleName(opt);
                                qualityTeamGroup.getQualitySamples().add(qualitySample);
                                qualityDetails.forEach(param -> {
                                    //找到检测组和样品相同的详情
                                    if (param.getTeamGroupName().equals(arg) && param.getSampleName().equals(opt)) {
                                        QualityDetailVo.SampleOriginal sampleOriginal = new QualityDetailVo.SampleOriginal();
                                        sampleOriginal.setCementCode(param.getEntrustCode());
                                        sampleOriginal.setTeamValues(param.getInputResult());
                                        sampleOriginal.setUserName(param.getUserName());
                                        sampleOriginal.setUserId(param.getUserId());
                                        qualitySample.getSampleOriginals().add(sampleOriginal);
                                        qualitySample.setCementCode(param.getCementCode());
                                        qualitySample.setSampleCode(param.getSampleCode());
                                        qualitySample.setSampleForm(param.getSampleForm());
                                        qualitySample.setSampleId(param.getSampleId());
                                    }
                                });
                            });
                });

        return qualityDetailVo;
    }


    private String mapStringToMap(String str) {


        List<MapObj> mapObjs = JSON.parseArray(str, MapObj.class);
        Map<String,String> map = new HashMap<>();
        mapObjs.forEach(arg->map.put(arg.getName(),arg.getValue()));

        return JSON.toJSONString(map);


    }

    @Data
    public static class MapObj{
        String name;
        String value;
    }



    /**
     * 根据样品检测列表获取报告管理首页
     *
     * @param source 样品检测
     * @return ReportDetailVo
     */
    private ReportDetailVo initReportDetailVo(List<EntrustReport> source) {

        if (source.size() == 0) {
            return null;
        }

        ReportDetailVo rts = new ReportDetailVo();
        EntrustReport firstReportDetail = source.get(0);
        //初始化标准信息
        rts.setPrintDate(DateUtil.format(new Date(), "yyyy年MM月dd日"));
        rts.setSender(firstReportDetail.getSendName());
        rts.setSendDate(DateUtil.format(firstReportDetail.getSendTime(), "yyyy年MM月dd日"));
        rts.setProjectName(firstReportDetail.getProjectName());
        rts.setSendName("\\");
        //获取检测项目、检测仪器、检测依据
        rts.setEquipmentNames(new HashSet<>(source.size()));
        rts.setSampleNames(new HashSet<>(source.size()));
        rts.setMethodNames(new HashSet<>(source.size()));
        rts.setTeamNames(new HashSet<>(source.size()));
        Set<Integer> equipmentIds = new HashSet<>(source.size());
        source.forEach(arg -> {
            equipmentIds.add(arg.getEquipmentId());
            //获取使用的设备id
            //关联检测项目
            if (StrUtil.isNotBlank(arg.getTeamName())) {
                String[] teamSplits = arg.getTeamName().split("、");
                for (String teamName : teamSplits) {
                    rts.getTeamNames().add(teamName);
                }
            }
            //关联检测依据
            if (StrUtil.isNotBlank(arg.getMethodName())) {
                String[] methodSplits = arg.getMethodName().split("、");
                for (String methodName : methodSplits) {
                    rts.getMethodNames().add(methodName);
                }
            }
            //关联样品名
            if (StrUtil.isNotBlank(arg.getName())) {
                rts.getSampleNames().add(arg.getName());
            }

        });
        rts.setSampleNum(rts.getSampleNames().size());

        //关联仪器名字 去重
        List<String> equipmentNames = equipmentUseMapper.getEquipmentNamesByEquipmentIds(equipmentIds);
        equipmentNames.forEach(arg -> rts.getEquipmentNames().add(arg));

        //关联送样单位名字
        String clientKey = "CACHE:CLIENT";
        if (!redisUtil.existsKey(clientKey)) {
            List<Client> clients = clientMapper.selectList(null);
            redisUtil.setString(clientKey, JSON.toJSONString(clients), 60);
        }
        List<Client> clients = JSON.parseArray(redisUtil.getString(clientKey) + "", Client.class);
        if (clients.size() == 0) {
            log.error("=================送养单位表中没有任何数据!==================");
        } else {
            clients.stream().filter(arg -> arg.getId().intValue() == firstReportDetail.getClientId())
                    .findFirst().ifPresent(arg -> rts.setSendName(arg.getName()));
        }
        return rts;
    }

    /**
     * 委托列表导出
     */
    @Override
    public void export(String startDate, String endDate, Integer status,
                       Integer clientId, String projectName, String projectCode,
                       String fileName, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("status", status);
        params.put("clientId", clientId);
        params.put("projectName", projectName);
        params.put("projectCode", projectCode);
        List<Map<String, Object>> list = entrustMapper.exportList(params);

        if (!CollectionUtils.isEmpty(list)) {
            Map<String, Object> map = list.get(0);
            String[] headers = new String[map.size() + 1];
            headers[0] = "序号";
            headers[1] = "委托编号";
            headers[2] = "是否加急";
            headers[3] = "项目名称";
            headers[4] = "项目编号";
            headers[5] = "委托人";
            headers[6] = "委托单位";
            headers[7] = "委托日期";
            headers[8] = "样品数量";
            headers[9] = "检测项目";
            headers[10] = "检测依据编号";
            headers[11] = "状态";

            List<Object[]> datas = new ArrayList<>(headers.length);
            for (Map<String, Object> m : list) {
                //获取委托单的检测项目  检测依据编号
                //根据委托编号id 获取所有样品的检测项目 和 检测依据编号
                Integer entrustId = Integer.valueOf(m.get("entrustId").toString());
                System.out.println(entrustId);
                QueryWrapper<SampleTmp> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("entrust_id", entrustId);
                List<SampleTmp> sampleTmpList = sampleTmpService.list(queryWrapper);

//                String sampleNames = "";
                /**
                 * 检测项目名称
                 * 格式：
                 * 样品1：Mad、Vad、Cao
                 * 样品2：Mad、Vad、Cao
                 * 样品3：Mad、Vad、Cao
                 */
                String checkTeamStr = "";
                /**
                 * 检测依据编号
                 * 格式：
                 * 样品1：0012、0013
                 * 样品2：0014、0015
                 * 样品3：0016、0017
                 */
                String checkMethodStr = "";
                if (sampleTmpList != null && sampleTmpList.size() > 0) {
                    //样品名称 列表中的拼接
                    for (SampleTmp sampleTmp : sampleTmpList) {
//                        sampleNames = sampleNames.equals("") ? sampleTmp.getName() : (sampleNames + "、" + sampleTmp.getName());
                        String teamIds = sampleTmp.getTeamIds();
                        String checkTeam = "";
                        String checkMethod = "";
                        if (teamIds != null) {
                            String[] teamIdS = teamIds.split("、");
                            for (String teamId : teamIdS) {
                                Team team = teamMapper.selectById(Integer.valueOf(teamId));
                                if (team != null && team.getQualifications() == 1) {
                                    checkTeam = checkTeam.equals("") ? team.getName() : (checkTeam + "、" + team.getName());
                                    Method method = methodMapper.selectById(team.getMethodId());
                                    if (method != null) {
                                        checkMethod = checkMethod.equals("") ? method.getNumber() : (checkMethod + "、" + method.getNumber());
                                    }
                                }
                            }
                        }
                        String spampe_checkTeam = sampleTmp.getName() + "：" + checkTeam;
                        checkTeamStr = checkTeamStr.equals("") ? spampe_checkTeam : (checkTeamStr + "\n" + spampe_checkTeam);
                        String spampe_checkMethod = sampleTmp.getName() + "：" + checkMethod;
                        checkMethodStr = checkMethodStr.equals("") ? spampe_checkMethod : (checkMethodStr + "\n" + spampe_checkMethod);
                    }
                }
                Object[] objects = new Object[headers.length];
                for (int j = 0; j < headers.length; j++) {
                    String obj = "";
                    if (j == 9) {
                        obj = checkTeamStr;
                    } else if (j == 10) {
                        obj = checkMethodStr;
                    } else {
                        obj = m.get(headers[j])!= null? m.get(headers[j]).toString() : "" ;
                        //如果序号带小数点 去除.0,保留整数
                        if (j == 0) {
                            obj = obj.split("\\.")[0];
                        }
                    }
                    objects[j] = obj;
                }
                datas.add(objects);
            }
            ExcelUtil.excelExport(
                    fileName == null || fileName.trim().length() <= 0 ? "委托列表" : fileName, headers,
                    datas, response);
        }
    }


}
