package org.jeecg.modules.qualityControl.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.entity.FdContractClass;
import org.jeecg.modules.basedata.entity.FdMatrixType;
import org.jeecg.modules.basedata.entity.FdPersonnel;
import org.jeecg.modules.basedata.mapper.FdContractClassMapper;
import org.jeecg.modules.basedata.mapper.FdMatrixTypeMapper;
import org.jeecg.modules.basedata.service.IFdPersonnelService;
import org.jeecg.modules.financeManage.service.IFdProjectReceivablesService;
import org.jeecg.modules.projectManagement.entity.FdProjectFileCompound;
import org.jeecg.modules.projectManagement.entity.FdProjectFileSample;
import org.jeecg.modules.projectManagement.entity.FdProjectFileValidation;
import org.jeecg.modules.projectManagement.service.IFdProjectFileCompoundService;
import org.jeecg.modules.projectManagement.service.IFdProjectFileSampleService;
import org.jeecg.modules.qualityControl.entity.*;
import org.jeecg.modules.qualityControl.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.sampleAndConsumableManagement.controller.FdColumnManagementController;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 质量保证（生物样本分析）
 * @author： jeecg-boot
 * @date： 2019-06-11
 * @version： V1.0
 */
@RestController
@RequestMapping("/qualityControl/fdQaBiometricSampleAnalysis")
@Slf4j
public class FdQaBiometricSampleAnalysisController {
    @Autowired
    private IFdQaBiometricSampleAnalysisService fdQaBiometricSampleAnalysisService;

    @Resource
    private IFdPersonnelService fdPersonnelService;

    @Resource
    private FdContractClassMapper fdContractClassMapper;

    @Resource
    private FdColumnManagementController fdColumnManagementController;

    @Resource
    private IFdQaBiometricSampleAnalysisItemsService fdQaBiometricSampleAnalysisItemsService;

    @Resource
    private IFdProjectFileCompoundService fdProjectFileCompoundService;

    @Resource
    private IFdProjectFileSampleService fdProjectFileSampleService;

    @Resource
    private IFdQaSampleService fdQaSampleService;

    @Resource
    private FdMatrixTypeMapper fdMatrixTypeMapper;

    @Resource
    private IFdQaBiologicalAnalysisVerificationService fdQaBiologicalAnalysisVerificationService;
    @Resource
    private IFdProjectReceivablesService fdProjectReceivablesService;
    @Resource
    private IFdQcBiometricSampleAnalysisService fdQcBiometricSampleAnalysisService;

    /**
     * 分页列表查询
     *
     * @param fdQaBiometricSampleAnalysis
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @RequiresPermissions("url:assurance-bioanalysis-sample:view")
    @PermissionData(pageComponent="assurance-bioanalysis-sample")
    public Result<IPage<FdQaBiometricSampleAnalysis>> queryPageList(FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis,
                                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                    HttpServletRequest req) {
        Result<IPage<FdQaBiometricSampleAnalysis>> result = new Result<IPage<FdQaBiometricSampleAnalysis>>();
        String qualityAssuranceFormNumber = fdQaBiometricSampleAnalysis.getQualityAssuranceFormNumber();
        if (StringUtils.isNotBlank(fdQaBiometricSampleAnalysis.getQualityAssuranceFormNumber())) {
            fdQaBiometricSampleAnalysis.setQualityAssuranceFormNumber(null);
        }
        String contractCode = fdQaBiometricSampleAnalysis.getContractCode();
        if (StringUtils.isNotBlank(fdQaBiometricSampleAnalysis.getContractCode())) {
            fdQaBiometricSampleAnalysis.setContractCode(null);
        }
        //提交时间范围
        String startTime=fdQaBiometricSampleAnalysis.getStartTime();
        if(StringUtils.isNotBlank(startTime)){
            fdQaBiometricSampleAnalysis.setStartTime(null);
        }
        String endTime=fdQaBiometricSampleAnalysis.getEndTime();
        if(StringUtils.isNotBlank(endTime)){
            fdQaBiometricSampleAnalysis.setEndTime(null);
        }
        QueryWrapper<FdQaBiometricSampleAnalysis> queryWrapper = QueryGenerator.initQueryWrapper(fdQaBiometricSampleAnalysis, req.getParameterMap());
        if (StringUtils.isNotBlank(qualityAssuranceFormNumber)) {
            queryWrapper.like("quality_assurance_form_number", qualityAssuranceFormNumber);
        }
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("contract_code", contractCode);
        }
        //获取当前登陆人员
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        //判断是否为空和是否为管理员
        if(StringUtils.isNotBlank(user.getPersonnelId())&&!user.getUsername().equals("admin")){
            queryWrapper.like("pf.personnel_with_authority_ids", user.getPersonnelId());
        }
        //提交日期
        if(StringUtils.isNotBlank(startTime)&&StringUtils.isNotBlank(endTime)){
            queryWrapper.between("date_format(qbsa.qa_submission_date,'%Y-%m-%d')",startTime,endTime);
        }
        queryWrapper.eq("qbsa.del_flag", "0");
        queryWrapper.orderByDesc("qbsa.create_time");
        Page<FdQaBiometricSampleAnalysis> page = new Page<FdQaBiometricSampleAnalysis>(pageNo, pageSize);
        // IPage<FdQaBiometricSampleAnalysis> pageList = fdQaBiometricSampleAnalysisService.page(page, queryWrapper);
        IPage<FdQaBiometricSampleAnalysis> pageList = fdQaBiometricSampleAnalysisService.findByPage(page, queryWrapper);
        // List<FdQaBiometricSampleAnalysis> list = pageList.getRecords();
        // for (FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis1 : list) {
        //     //类型名称
        //     String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQaBiometricSampleAnalysis1.getAnalysisType());
        //     fdQaBiometricSampleAnalysis1.setAnalysisTypeName(analysisTypeName);
        // }
        //获取QC状态
        getQaStatus(pageList.getRecords());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    //根据 项目id 样本号 类型 获取Qa状态
    public void getQaStatus(List<FdQaBiometricSampleAnalysis> sampleAnalysisList){
        if(sampleAnalysisList!=null&&sampleAnalysisList.size()>0){
            for(FdQaBiometricSampleAnalysis sampleAnalysis:sampleAnalysisList){
                FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysis=new FdQcBiometricSampleAnalysis();
                fdQcBiometricSampleAnalysis.setPkProjectFile(sampleAnalysis.getPkProjectFile());
                fdQcBiometricSampleAnalysis.setSampleCode(sampleAnalysis.getSampleCode());
                fdQcBiometricSampleAnalysis.setAnalysisType(sampleAnalysis.getAnalysisType());
                FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysis1=fdQcBiometricSampleAnalysisService.getBySampleCodeAndType(fdQcBiometricSampleAnalysis);
                if(fdQcBiometricSampleAnalysis1!=null){
                    sampleAnalysis.setQcStatus(fdQcBiometricSampleAnalysis1.getQualityStatus());
                }
            }
        }
    }

    /**
     * 添加
     *
     * @param fdQaBiometricSampleAnalysis
     * @return
     */
    @PostMapping(value = "/add")
    @NotDuplicate
    public Result<FdQaBiometricSampleAnalysis> add(@RequestBody @Valid FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis, BindingResult bindingResult) {
        Result<FdQaBiometricSampleAnalysis> result = new Result<FdQaBiometricSampleAnalysis>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdQaBiometricSampleAnalysisService.save(fdQaBiometricSampleAnalysis);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdQaBiometricSampleAnalysis
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdQaBiometricSampleAnalysis> edit(@RequestBody @Valid FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis, BindingResult bindingResult) {
        Result<FdQaBiometricSampleAnalysis> result = new Result<FdQaBiometricSampleAnalysis>();
        FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysisEntity = fdQaBiometricSampleAnalysisService.getById(fdQaBiometricSampleAnalysis.getId());
        if (fdQaBiometricSampleAnalysisEntity == null) {
            result.error500("未找到对应实体");
        } else {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            boolean ok = fdQaBiometricSampleAnalysisService.updateById(fdQaBiometricSampleAnalysis);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<FdQaBiometricSampleAnalysis> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdQaBiometricSampleAnalysis> result = new Result<FdQaBiometricSampleAnalysis>();
        FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis = fdQaBiometricSampleAnalysisService.getById(id);
        if (fdQaBiometricSampleAnalysis == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdQaBiometricSampleAnalysisService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdQaBiometricSampleAnalysis> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdQaBiometricSampleAnalysis> result = new Result<FdQaBiometricSampleAnalysis>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.fdQaBiometricSampleAnalysisService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdQaBiometricSampleAnalysis> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdQaBiometricSampleAnalysis> result = new Result<FdQaBiometricSampleAnalysis>();
        FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis = fdQaBiometricSampleAnalysisService.getById(id);
        if (fdQaBiometricSampleAnalysis == null) {
            result.error500("未找到对应实体");
        } else {
            //化合物
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(FdProjectFileCompound::getProjectId,fdQaBiometricSampleAnalysis.getPkProjectFile());
            queryWrapper1.eq(FdProjectFileCompound::getDelFlag,"0");
            List<FdProjectFileCompound> list1 = fdProjectFileCompoundService.list(queryWrapper1);
            fdQaBiometricSampleAnalysis.setFdProjectFileCompoundList(list1);
            //类型名称
            String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQaBiometricSampleAnalysis.getAnalysisType());
            fdQaBiometricSampleAnalysis.setAnalysisTypeName(analysisTypeName);
            //基质类型
            if(fdQaBiometricSampleAnalysis.getMatrix()!=null&&!fdQaBiometricSampleAnalysis.getMatrix().equals("")){
                List<String> list2 = Arrays.asList(fdQaBiometricSampleAnalysis.getMatrix().split(","));
                List<FdMatrixType> fdMatrixTypes = fdMatrixTypeMapper.selectBatchIds(list2);
                String fdMatrixType = "";
                for (FdMatrixType fdMatrixType1 : fdMatrixTypes) {
                    if (fdMatrixType == "") {
                        fdMatrixType = fdMatrixType1.getName();
                    } else {
                        fdMatrixType += "," + fdMatrixType1.getName();
                    }
                }
                fdQaBiometricSampleAnalysis.setMatrixName(fdMatrixType);
            }

            //明细
            Map<String, Object> msp = Maps.newHashMap();
            msp.put("pk_qa_biometric_sample_analysis", fdQaBiometricSampleAnalysis.getId());
            msp.put("del_flag", "0");
            List<FdQaBiometricSampleAnalysisItems> fdQaBiometricSampleAnalysisItemsList = (List<FdQaBiometricSampleAnalysisItems>) fdQaBiometricSampleAnalysisItemsService.listByMap(msp);
            //获取对应图片文件
            fdQaBiometricSampleAnalysisService.getPictureUpload(fdQaBiometricSampleAnalysisItemsList);
            fdQaBiometricSampleAnalysis.setFdQaBiometricSampleAnalysisItemsList(fdQaBiometricSampleAnalysisItemsList);
//            LambdaQueryWrapper<FdQaBiometricSampleAnalysisItems> queryWrapper2 = new LambdaQueryWrapper<>();
//            queryWrapper2.eq(FdQaBiometricSampleAnalysisItems::getPkQaBiometricSampleAnalysis,fdQaBiometricSampleAnalysis.getId());
//            queryWrapper2.orderByAsc(FdQaBiometricSampleAnalysisItems::getCode);
//            List<FdQaBiometricSampleAnalysisItems> list2 = fdQaBiometricSampleAnalysisItemsService.list(queryWrapper1);
//            fdQaBiometricSampleAnalysis.setFdQaBiometricSampleAnalysisItemsList(list2);
            //生物样本分析
            Map<String, Object> msp1 = Maps.newHashMap();
            msp1.put("pk_qa_sample", fdQaBiometricSampleAnalysis.getId());
            msp1.put("del_flag", "0");
            List<FdQaSample> fdQaSampleList = (List<FdQaSample>) fdQaSampleService.listByMap(msp1);
            fdQaBiometricSampleAnalysis.setFdQaSampleList(fdQaSampleList);
            //生物分析负责人
            LambdaQueryWrapper<FdPersonnel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdPersonnel::getId, fdQaBiometricSampleAnalysis.getBioanalyticalPi());
            FdPersonnel p1 = fdPersonnelService.getOne(queryWrapper);
            if(p1!=null){
                fdQaBiometricSampleAnalysis.setBioanalyticalPiName(p1.getName());
            }
            //助理
            LambdaQueryWrapper<FdPersonnel> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(FdPersonnel::getId, fdQaBiometricSampleAnalysis.getAssociateBioanalyticalPi());
            FdPersonnel p2 = fdPersonnelService.getOne(queryWrapper2);
            if(p2!=null){
                fdQaBiometricSampleAnalysis.setAssociateBioanalyticalPiName(p2.getName());
            }
            //qc负责人
            LambdaQueryWrapper<FdPersonnel> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(FdPersonnel::getId, fdQaBiometricSampleAnalysis.getResponsibleQa());
            FdPersonnel p3 = fdPersonnelService.getOne(queryWrapper3);
            if(p3!=null){
                fdQaBiometricSampleAnalysis.setResponsibleQaName(p3.getName());
            }
            result.setResult(fdQaBiometricSampleAnalysis);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<FdQaBiometricSampleAnalysis> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis = JSON.parseObject(deString, FdQaBiometricSampleAnalysis.class);
                queryWrapper = QueryGenerator.initQueryWrapper(fdQaBiometricSampleAnalysis, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdQaBiometricSampleAnalysis> pageList = fdQaBiometricSampleAnalysisService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "质量保证（生物样本分析）列表");
        mv.addObject(NormalExcelConstants.CLASS, FdQaBiometricSampleAnalysis.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("质量保证（生物样本分析）列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FdQaBiometricSampleAnalysis> listFdQaBiometricSampleAnalysiss = ExcelImportUtil.importExcel(file.getInputStream(), FdQaBiometricSampleAnalysis.class, params);
                for (FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysisExcel : listFdQaBiometricSampleAnalysiss) {
                    fdQaBiometricSampleAnalysisService.save(fdQaBiometricSampleAnalysisExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdQaBiometricSampleAnalysiss.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQaBiometricSampleAnalysis>
     * @Author gurui
     * @Description //TODO 添加 质量保证（生物样本分析） 同时添加 明细
     * @Date 14:56 2019/6/11
     * @Param [fdQaBiometricSampleAnalysis, bindingResult]
     **/
    @PostMapping(value = "/addAll")
    @NotDuplicate
    @RequiresPermissions(value = {"assurance-bioanalysis-sample:add","assurance-bioanalysis-sample:update"},logical = Logical.OR)
    public Result<FdQaBiometricSampleAnalysis> addAll(@RequestBody @Valid FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis, BindingResult bindingResult) {
        Result<FdQaBiometricSampleAnalysis> result = new Result<FdQaBiometricSampleAnalysis>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            if (fdQaBiometricSampleAnalysis.getFdQaBiometricSampleAnalysisItemsList()==null||fdQaBiometricSampleAnalysis.getFdQaBiometricSampleAnalysisItemsList().size()<1){
                result.error500("操作失败,明细不能未空");
                return result;
            }
            if (fdQaBiometricSampleAnalysis.getFdQaSampleList()==null||fdQaBiometricSampleAnalysis.getFdQaSampleList().size()<1){
                result.error500("操作失败,分析方法号不能未空");
                return result;
            }

            //新增执行
            if(oConvertUtils.isEmpty(fdQaBiometricSampleAnalysis.getId())){
                LambdaQueryWrapper<FdQaBiometricSampleAnalysis> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FdQaBiometricSampleAnalysis::getQualityAssuranceFormNumber,fdQaBiometricSampleAnalysis.getQualityAssuranceFormNumber());
                queryWrapper.eq(FdQaBiometricSampleAnalysis::getDelFlag,"0");
                List<FdQaBiometricSampleAnalysis> list = fdQaBiometricSampleAnalysisService.list(queryWrapper);
                if ( list!=null && list.size()>0){
                    result.error500("操作失败,质量保证单号不能重复");
                    return result;
                }

            }
            //根据子表评论判断主表状态
            boolean isOk=true;
            for(FdQaBiometricSampleAnalysisItems items: fdQaBiometricSampleAnalysis.getFdQaBiometricSampleAnalysisItemsList()){
                //如果找到一个不是接受的就是未完成
                if(StringUtils.isEmpty(items.getQaReview())||!items.getQaReview().equals("1")){
                    isOk=false;
                }
            }
            if(isOk){
                fdQaBiometricSampleAnalysis.setQualityStatus(2);
            }else{
                fdQaBiometricSampleAnalysis.setQualityStatus(1);
            }

            //通知PI
            if(StringUtils.isNotBlank(fdQaBiometricSampleAnalysis.getIsNoticePi())&&fdQaBiometricSampleAnalysis.getIsNoticePi().equals("1")){
                //获取方法号
                String sampleCode ="";
                for(FdQaSample fdQaSample:fdQaBiometricSampleAnalysis.getFdQaSampleList()){
                    sampleCode+=fdQaSample.getCode()+";";
                }
                //发送邮件通知
                // String msg="质量保证-生物样本分析：‘"+fdQaBiometricSampleAnalysis.getQualityAssuranceFormNumber()+"’已经填写，请及时回复！";
                String msg="质量控制-方法验证" +
                        "\n合同号："+fdQaBiometricSampleAnalysis.getContractCode()+
                        "\n项目号："+fdQaBiometricSampleAnalysis.getProjectFileNo()+
                        "\n方法号："+sampleCode+
                        "\n已经填写，请及时回复！";
                fdProjectReceivablesService.noticeFinance(fdQaBiometricSampleAnalysis.getBioanalyticalPi(),"回复提醒",msg);
            }

            fdQaBiometricSampleAnalysisService.addAll(fdQaBiometricSampleAnalysis);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }




    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQaBiometricSampleAnalysis>
     * @Author gurui
     * @Description //TODO 根据合同id查询项目档案信息
     * @Date 11:22 2019/7/3
     * @Param [id]
     **/
    @GetMapping(value = "/queryQaBiometricByConId")
    public Result<FdQaBiometricSampleAnalysis> queryQaBiometricByConId(@RequestParam(name = "contractId", required = true) String contractId) {
        Result<FdQaBiometricSampleAnalysis> result = new Result<FdQaBiometricSampleAnalysis>();
        FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis = fdQaBiometricSampleAnalysisService.queryQaBiometricByConId(contractId);
        if (fdQaBiometricSampleAnalysis == null) {
            result.error500("未找到对应实体");
        } else {
            // 分析方法号
            Map<String, Object> msp = Maps.newHashMap();
            msp.put("del_flag", "0");
            msp.put("project_id", fdQaBiometricSampleAnalysis.getPkProjectFile());
            List<FdProjectFileSample> fdProjectFileSampleList = (List<FdProjectFileSample>) fdProjectFileSampleService.listByMap(msp);
            fdQaBiometricSampleAnalysis.setFdProjectFileSampleList(fdProjectFileSampleList);
            //合同方名称
            String contractPartyName = fdColumnManagementController.getContractPartyName(fdQaBiometricSampleAnalysis.getPkContractParty());
            fdQaBiometricSampleAnalysis.setContractPartyName(contractPartyName);
            //基质类型
            List<String> list2 = Arrays.asList(fdQaBiometricSampleAnalysis.getMatrix().split(","));
            List<FdMatrixType> fdMatrixTypes = fdMatrixTypeMapper.selectBatchIds(list2);
            String fdMatrixType = "";
            for (FdMatrixType fdMatrixType1 : fdMatrixTypes) {
                if (fdMatrixType == "") {
                    fdMatrixType = fdMatrixType1.getName();
                } else {
                    fdMatrixType += "," + fdMatrixType1.getName();
                }
            }
            fdQaBiometricSampleAnalysis.setMatrixName(fdMatrixType);
            //生物分析负责人
            if (fdQaBiometricSampleAnalysis.getBioanalyticalPi() != null) {
                LambdaQueryWrapper<FdPersonnel> queryWrapper9 = new LambdaQueryWrapper<>();
                queryWrapper9.eq(FdPersonnel::getId, fdQaBiometricSampleAnalysis.getBioanalyticalPi());
                FdPersonnel p1 = fdPersonnelService.getOne(queryWrapper9);
                fdQaBiometricSampleAnalysis.setBioanalyticalPiName(p1.getName());
            }
            //助理
            if (fdQaBiometricSampleAnalysis.getAssociateBioanalyticalPi() != null) {
                LambdaQueryWrapper<FdPersonnel> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(FdPersonnel::getId, fdQaBiometricSampleAnalysis.getAssociateBioanalyticalPi());
                FdPersonnel p2 = fdPersonnelService.getOne(queryWrapper2);
                fdQaBiometricSampleAnalysis.setAssociateBioanalyticalPiName(p2.getName());
            }
            //qa负责人
            if (fdQaBiometricSampleAnalysis.getResponsibleQa() != null) {
                LambdaQueryWrapper<FdPersonnel> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(FdPersonnel::getId, fdQaBiometricSampleAnalysis.getResponsibleQa());
                FdPersonnel p3 = fdPersonnelService.getOne(queryWrapper3);
                fdQaBiometricSampleAnalysis.setResponsibleQaName(p3.getName());
            }
            //化合物
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdProjectFileCompound::getProjectId, fdQaBiometricSampleAnalysis.getPkProjectFile());
            List<FdProjectFileCompound> list1 = fdProjectFileCompoundService.list(queryWrapper);
            String compoundName = "";
            String pkCompound = "";
            for (FdProjectFileCompound fdProjectFileCompound : list1) {
                if (compoundName == "") {
                    compoundName = fdProjectFileCompound.getCompound();
                    pkCompound = fdProjectFileCompound.getId();
                } else {
                    compoundName += "," + fdProjectFileCompound.getCompound();
                    pkCompound += "," + fdProjectFileCompound.getId();
                }
            }
            fdQaBiometricSampleAnalysis.setCompoundName(compoundName);
            fdQaBiometricSampleAnalysis.setPkCompound(pkCompound);
            fdQaBiometricSampleAnalysis.setFdProjectFileCompoundList(list1);
            //默认化合物 sort为1
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper6 = new LambdaQueryWrapper<>();
            queryWrapper6.eq(FdProjectFileCompound::getProjectId, fdQaBiometricSampleAnalysis.getPkProjectFile());
            queryWrapper6.eq(FdProjectFileCompound::getSort, "1");
            FdProjectFileCompound one = fdProjectFileCompoundService.getOne(queryWrapper6);
            fdQaBiometricSampleAnalysis.setCompound1(one.getCompound());
            fdQaBiometricSampleAnalysis.setCompound1Id(one.getId());
            result.setResult(fdQaBiometricSampleAnalysis);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQaBiometricSampleAnalysis>
     * @Author gurui
     * @Description //TODO  删除 质量保证（生物样本分析） 同时 删除其明细
     * @Date 13:44 2019/7/3
     * @Param [id]
     **/
    @DeleteMapping(value = "/deleteAll")
    @NotDuplicate
    @RequiresPermissions("assurance-bioanalysis-sample:delete")
    public Result<FdQaBiometricSampleAnalysis> deleteAll(@RequestParam(name = "id", required = true) String id) {
        Result<FdQaBiometricSampleAnalysis> result = new Result<FdQaBiometricSampleAnalysis>();
        FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis = fdQaBiometricSampleAnalysisService.getById(id);
        if (fdQaBiometricSampleAnalysis == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdQaBiometricSampleAnalysisService.deleteAll(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }


}
