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 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.FdProjectFileConfirm;
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.IFdProjectFileConfirmService;
import org.jeecg.modules.projectManagement.service.IFdProjectFileSampleService;
import org.jeecg.modules.projectManagement.service.IFdProjectFileValidationService;
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-12
 * @version： V1.0
 */
@RestController
@RequestMapping("/qualityControl/fdQcBiometricSampleAnalysis")
@Slf4j
public class FdQcBiometricSampleAnalysisController {
    @Autowired
    private IFdQcBiometricSampleAnalysisService fdQcBiometricSampleAnalysisService;
    @Resource
    private FdColumnManagementController fdColumnManagementController;
    @Resource
    private FdContractClassMapper fdContractClassMapper;
    @Resource
    private IFdQcBiometricSampleAnalysisItemsService fdQcBiometricSampleAnalysisItemsService;
    @Resource
    private IFdPersonnelService fdPersonnelService;
    @Resource
    private IFdProjectFileCompoundService fdProjectFileCompoundService;
    @Resource
    private IFdQcSampleService fdQcSampleService;
    @Resource
    private IFdProjectFileSampleService fdProjectFileSampleService;
    @Resource
    private IFdProjectFileValidationService fdProjectFileValidationService;
    @Resource
    private IFdProjectFileConfirmService fdProjectFileConfirmService;
    @Resource
    private FdMatrixTypeMapper fdMatrixTypeMapper;
    @Resource
    private IFdQaBiologicalAnalysisVerificationService fdQaBiologicalAnalysisVerificationService;
    @Resource
    private IFdProjectReceivablesService fdProjectReceivablesService;
    @Resource
    private IFdQaBiometricSampleAnalysisService fdQaBiometricSampleAnalysisService;

    /**
     * 分页列表查询
     *
     * @param fdQcBiometricSampleAnalysis
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @RequiresPermissions("url:control-bioanalysis-sample:view")
    @PermissionData(pageComponent="control-bioanalysis-sample")
    public Result<IPage<FdQcBiometricSampleAnalysis>> queryPageList(FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysis,
                                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                    HttpServletRequest req) {
        Result<IPage<FdQcBiometricSampleAnalysis>> result = new Result<IPage<FdQcBiometricSampleAnalysis>>();
        String contractCode = fdQcBiometricSampleAnalysis.getContractCode();
        if (StringUtils.isNotBlank(fdQcBiometricSampleAnalysis.getContractCode())) {
            fdQcBiometricSampleAnalysis.setContractCode(null);
        }
        String qualityControlSheetNumber = fdQcBiometricSampleAnalysis.getQualityControlSheetNumber();
        if (StringUtils.isNotBlank(fdQcBiometricSampleAnalysis.getQualityControlSheetNumber())) {
            fdQcBiometricSampleAnalysis.setQualityControlSheetNumber(null);
        }
        //提交时间范围
        String startTime=fdQcBiometricSampleAnalysis.getStartTime();
        if(StringUtils.isNotBlank(startTime)){
            fdQcBiometricSampleAnalysis.setStartTime(null);
        }
        String endTime=fdQcBiometricSampleAnalysis.getEndTime();
        if(StringUtils.isNotBlank(endTime)){
            fdQcBiometricSampleAnalysis.setEndTime(null);
        }
        QueryWrapper<FdQcBiometricSampleAnalysis> queryWrapper = QueryGenerator.initQueryWrapper(fdQcBiometricSampleAnalysis, req.getParameterMap());
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("contract_code", contractCode);
        }
        if (StringUtils.isNotBlank(qualityControlSheetNumber)) {
            queryWrapper.like("quality_control_sheet_number", qualityControlSheetNumber);
        }
        //获取当前登陆人员
        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(qsa.qc_submission_date,'%Y-%m-%d')",startTime,endTime);
        }
        queryWrapper.eq("qsa.del_flag", "0");
        queryWrapper.orderByDesc("qsa.create_time");
        Page<FdQcBiometricSampleAnalysis> page = new Page<FdQcBiometricSampleAnalysis>(pageNo, pageSize);
        // IPage<FdQcBiometricSampleAnalysis> pageList = fdQcBiometricSampleAnalysisService.page(page, queryWrapper);
        IPage<FdQcBiometricSampleAnalysis> pageList = fdQcBiometricSampleAnalysisService.findByPage(page, queryWrapper);
        // List<FdQcBiometricSampleAnalysis> list = pageList.getRecords();
        // for (FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysis1:list){
        //     //类型名称
        //     String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQcBiometricSampleAnalysis1.getAnalysisType());
        //     fdQcBiometricSampleAnalysis1.setAnalysisTypeName(analysisTypeName);
        // }
        //获取QA状态
        getQaStatus(pageList.getRecords());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
    //根据 项目id 样本号 类型 获取Qa状态
    public void getQaStatus(List<FdQcBiometricSampleAnalysis> sampleAnalysisList){
        if(sampleAnalysisList!=null&&sampleAnalysisList.size()>0){
            for(FdQcBiometricSampleAnalysis sampleAnalysis:sampleAnalysisList){
                FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis=new FdQaBiometricSampleAnalysis();
                fdQaBiometricSampleAnalysis.setPkProjectFile(sampleAnalysis.getPkProjectFile());
                fdQaBiometricSampleAnalysis.setSampleCode(sampleAnalysis.getSampleCode());
                fdQaBiometricSampleAnalysis.setAnalysisType(sampleAnalysis.getAnalysisType());
                FdQaBiometricSampleAnalysis fdQaBiometricSampleAnalysis1=fdQaBiometricSampleAnalysisService.getBySampleCodeAndType(fdQaBiometricSampleAnalysis);
                if(fdQaBiometricSampleAnalysis1!=null){
                    sampleAnalysis.setQaStatus(fdQaBiometricSampleAnalysis1.getQualityStatus());
                }
            }
        }
    }

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

    /**
     * 编辑
     *
     * @param fdQcBiometricSampleAnalysis
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdQcBiometricSampleAnalysis> edit(@RequestBody @Valid FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysis, BindingResult bindingResult) {
        Result<FdQcBiometricSampleAnalysis> result = new Result<FdQcBiometricSampleAnalysis>();
        FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysisEntity = fdQcBiometricSampleAnalysisService.getById(fdQcBiometricSampleAnalysis.getId());
        if (fdQcBiometricSampleAnalysisEntity == 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 = fdQcBiometricSampleAnalysisService.updateById(fdQcBiometricSampleAnalysis);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

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

        return result;
    }

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

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

            //明细
            Map<String,Object> msp = Maps.newHashMap();
            msp.put("pk_qc_biometric_sample_analysis",fdQcBiometricSampleAnalysis.getId());
            msp.put("del_flag","0");
            List<FdQcBiometricSampleAnalysisItems> fdQcBiometricSampleAnalysisItems = (List<FdQcBiometricSampleAnalysisItems>)fdQcBiometricSampleAnalysisItemsService.listByMap(msp);
            //获取对应图片文件
            fdQcBiometricSampleAnalysisService.getPictureUpload(fdQcBiometricSampleAnalysisItems);
            fdQcBiometricSampleAnalysis.setFdQcBiometricSampleAnalysisItemsList(fdQcBiometricSampleAnalysisItems);

            //样本分析
            Map<String,Object> msp1 = Maps.newHashMap();
            msp1.put("pk_qc_sample",fdQcBiometricSampleAnalysis.getId());
            msp1.put("del_flag","0");
            List<FdQcSample> fdQcSampleList = (List<FdQcSample>)fdQcSampleService.listByMap(msp1);
            fdQcBiometricSampleAnalysis.setFdQcSampleList(fdQcSampleList);
            //生物分析负责人
            LambdaQueryWrapper<FdPersonnel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdPersonnel::getId,fdQcBiometricSampleAnalysis.getBioanalyticalPi());
            FdPersonnel p1 = fdPersonnelService.getOne(queryWrapper);
            if(oConvertUtils.isNotEmpty(p1)) {
                fdQcBiometricSampleAnalysis.setBioanalyticalPiName(p1.getName());
            }
            //助理
            LambdaQueryWrapper<FdPersonnel> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(FdPersonnel::getId,fdQcBiometricSampleAnalysis.getAssociateBioanalyticalPi());
            FdPersonnel p2 = fdPersonnelService.getOne(queryWrapper2);
            if(oConvertUtils.isNotEmpty(p2)) {
                fdQcBiometricSampleAnalysis.setAssociateBioanalyticalPiName(p2.getName());
            }
            //qc负责人
            if (fdQcBiometricSampleAnalysis.getResponsibleQc()!=null){
                LambdaQueryWrapper<FdPersonnel> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(FdPersonnel::getId,fdQcBiometricSampleAnalysis.getResponsibleQc());
                FdPersonnel p3 = fdPersonnelService.getOne(queryWrapper3);
                if(oConvertUtils.isNotEmpty(p3)) {
                    fdQcBiometricSampleAnalysis.setResponsibleQcName(p3.getName());
                }
            }
            //合同方名称
//            String contractPartyName = fdColumnManagementController.getContractPartyName(fdQcBiometricSampleAnalysis.getPkContractParty());
//            fdQcBiometricSampleAnalysis.setContractPartyName(contractPartyName);
            result.setResult(fdQcBiometricSampleAnalysis);
            result.setSuccess(true);
        }
        return result;
    }

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdQcBiometricSampleAnalysis> pageList = fdQcBiometricSampleAnalysisService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "质量保证（生物样本分析）列表");
        mv.addObject(NormalExcelConstants.CLASS, FdQcBiometricSampleAnalysis.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<FdQcBiometricSampleAnalysis> listFdQcBiometricSampleAnalysiss = ExcelImportUtil.importExcel(file.getInputStream(), FdQcBiometricSampleAnalysis.class, params);
                for (FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysisExcel : listFdQcBiometricSampleAnalysiss) {
                    fdQcBiometricSampleAnalysisService.save(fdQcBiometricSampleAnalysisExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdQcBiometricSampleAnalysiss.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }



    /**
     * @Author gurui
     * @Description //TODO 添加 质量控制（生物样本分析） 同时添加 项目档案 明细
     * @Date 9:33 2019/6/13
     * @Param [fdQcBiometricSampleAnalysis, bindingResult]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQcBiometricSampleAnalysis>
     **/
    @PostMapping(value = "/addAll")
    @NotDuplicate
    @RequiresPermissions(value = {"control-bioanalysis-sample:add","control-bioanalysis-sample:update"},logical = Logical.OR)
    public Result<FdQcBiometricSampleAnalysis> addAll(@RequestBody @Valid FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysis, BindingResult bindingResult) {
        Result<FdQcBiometricSampleAnalysis> result = new Result<FdQcBiometricSampleAnalysis>();
        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 (fdQcBiometricSampleAnalysis.getFdQcBiometricSampleAnalysisItemsList()==null||fdQcBiometricSampleAnalysis.getFdQcBiometricSampleAnalysisItemsList().size()<1){
                result.error500("操作失败,明细不能为空");
            }
            if (fdQcBiometricSampleAnalysis.getFdQcSampleList()==null||fdQcBiometricSampleAnalysis.getFdQcSampleList().size()<1){
                result.error500("操作失败,分析方法号不能为空");
            }
            //新增才处理
            if(oConvertUtils.isEmpty(fdQcBiometricSampleAnalysis.getId())){
                //验证质量控制单号
                LambdaQueryWrapper<FdQcBiometricSampleAnalysis> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FdQcBiometricSampleAnalysis::getQualityControlSheetNumber,fdQcBiometricSampleAnalysis.getQualityControlSheetNumber());
                queryWrapper.eq(FdQcBiometricSampleAnalysis::getDelFlag,"0");
                List<FdQcBiometricSampleAnalysis> list = fdQcBiometricSampleAnalysisService.list(queryWrapper);
                if ( list!=null && list.size()>0){
                    result.error500("操作失败,质量控制单号不能重复");
                    return result;
                }
            }

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

            //通知PI
            if(StringUtils.isNotBlank(fdQcBiometricSampleAnalysis.getIsNoticePi())&&fdQcBiometricSampleAnalysis.getIsNoticePi().equals("1")){
                //样本号
                String sampleCode ="";
                for(FdQcSample fdQcSample:fdQcBiometricSampleAnalysis.getFdQcSampleList()){
                    sampleCode+=fdQcSample.getCode()+";";
                }
                //发送邮件通知
                // String msg="质量控制-样本分析：‘"+fdQcBiometricSampleAnalysis.getQualityControlSheetNumber()+"’已经填写，请及时回复";
                String msg="质量控制-样本分析" +
                        "\n合同号："+fdQcBiometricSampleAnalysis.getContractCode()+
                        "\n项目号："+fdQcBiometricSampleAnalysis.getProjectFileNo()+
                        "\n方法号："+sampleCode+
                        "\n已经填写，请及时回复！";
                fdProjectReceivablesService.noticeFinance(fdQcBiometricSampleAnalysis.getBioanalyticalPi(),"质量管理-回复提醒",msg);
            }

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

    /**
     * @Author gurui
     * @Description //TODO 根据合同id查询项目档案信息
     * @Date 14:32 2019/7/3
     * @Param [contractId]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQcBiometricSampleAnalysis>
     **/
    @GetMapping(value = "/queryQcBiometricByConId")
    public Result<FdQcBiometricSampleAnalysis> queryQcBiometricByConId(@RequestParam(name = "pkProjectFile", required = true) String pkProjectFile) {
        Result<FdQcBiometricSampleAnalysis> result = new Result<FdQcBiometricSampleAnalysis>();
        FdQcBiometricSampleAnalysis fdQcBiometricSampleAnalysis = fdQcBiometricSampleAnalysisService.queryQcBiometricByConId(pkProjectFile);
        if (fdQcBiometricSampleAnalysis == null) {
            result.error500("未找到对应实体");
        } else {
            // 样本分析号
            Map<String,Object> msp = Maps.newHashMap();
            msp.put("del_flag","0");
            msp.put("project_id",fdQcBiometricSampleAnalysis.getPkProjectFile());
            List<FdProjectFileSample> fdProjectFileSampleList = (List<FdProjectFileSample>)fdProjectFileSampleService.listByMap(msp);
            fdQcBiometricSampleAnalysis.setFdProjectFileSampleList(fdProjectFileSampleList);
            // 方法验证号
            // Map<String,Object> msp2 = Maps.newHashMap();
            // msp.put("del_flag","0");
            // msp.put("project_id",fdQcBiometricSampleAnalysis.getPkProjectFile());
            List<FdProjectFileValidation> fdProjectFileValidations = (List<FdProjectFileValidation>)fdProjectFileValidationService.listByMap(msp);
            fdQcBiometricSampleAnalysis.setFdProjectFileValidationList(fdProjectFileValidations);
            //项目确认号
            List<FdProjectFileConfirm> fdProjectFileConfirmList=(List<FdProjectFileConfirm>)fdProjectFileConfirmService.listByMap(msp);
            fdQcBiometricSampleAnalysis.setFdProjectFileConfirmList(fdProjectFileConfirmList);

            // 合同方名称
            String contractPartyName = fdColumnManagementController.getContractPartyName(fdQcBiometricSampleAnalysis.getPkContractParty());
            fdQcBiometricSampleAnalysis.setContractPartyName(contractPartyName);
            //基质类型
            List<String> list2 = Arrays.asList(fdQcBiometricSampleAnalysis.getMatrix().split(","));
            List<FdMatrixType> fdMatrixTypes = fdMatrixTypeMapper.selectBatchIds(list2);
            String fdMatrixType = "";
            for (FdMatrixType fdMatrixType1:fdMatrixTypes){
                if (fdMatrixType == ""){
                    fdMatrixType = fdMatrixType1.getName();
                }else {
                    fdMatrixType +=","+fdMatrixType1.getName();
                }
            }
            fdQcBiometricSampleAnalysis.setMatrixName(fdMatrixType);
            //生物分析负责人
            if (fdQcBiometricSampleAnalysis.getBioanalyticalPi() != null) {
                LambdaQueryWrapper<FdPersonnel> queryWrapper9 = new LambdaQueryWrapper<>();
                queryWrapper9.eq(FdPersonnel::getId, fdQcBiometricSampleAnalysis.getBioanalyticalPi());
                FdPersonnel p1 = fdPersonnelService.getOne(queryWrapper9);
                fdQcBiometricSampleAnalysis.setBioanalyticalPiName(p1.getName());
            }
            //助理
            if (fdQcBiometricSampleAnalysis.getAssociateBioanalyticalPi() != null) {
                LambdaQueryWrapper<FdPersonnel> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(FdPersonnel::getId, fdQcBiometricSampleAnalysis.getAssociateBioanalyticalPi());
                FdPersonnel p2 = fdPersonnelService.getOne(queryWrapper2);
                fdQcBiometricSampleAnalysis.setAssociateBioanalyticalPiName(p2.getName());
            }
            //qa负责人
            if (fdQcBiometricSampleAnalysis.getResponsibleQc() != null) {
                LambdaQueryWrapper<FdPersonnel> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(FdPersonnel::getId, fdQcBiometricSampleAnalysis.getResponsibleQc());
                FdPersonnel p3 = fdPersonnelService.getOne(queryWrapper3);
                fdQcBiometricSampleAnalysis.setResponsibleQcName(p3.getName());
            }
            //化合物
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(FdProjectFileCompound::getProjectId,fdQcBiometricSampleAnalysis.getPkProjectFile());
            queryWrapper.eq(FdProjectFileCompound::getDelFlag,"0");
            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();
                }
            }
            fdQcBiometricSampleAnalysis.setCompoundName(compoundName);
            fdQcBiometricSampleAnalysis.setPkCompound(pkCompound);
            fdQcBiometricSampleAnalysis.setFdProjectFileCompoundList(list1);
            //默认化合物 sort为1
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper6=new LambdaQueryWrapper<>();
            queryWrapper6.eq(FdProjectFileCompound::getProjectId,fdQcBiometricSampleAnalysis.getPkProjectFile());
            queryWrapper6.eq(FdProjectFileCompound::getSort,"1");
            List<FdProjectFileCompound> one = fdProjectFileCompoundService.list(queryWrapper6);
            if(one!=null&&one.size()>0){
                fdQcBiometricSampleAnalysis.setCompound1(one.get(0).getCompound());
                fdQcBiometricSampleAnalysis.setCompound1Id(one.get(0).getId());
            }
            result.setResult(fdQcBiometricSampleAnalysis);
            result.setSuccess(true);
        }
        return result;
    }

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

        return result;
    }



}
