package org.jeecg.modules.qualityControl.controller;

import java.text.SimpleDateFormat;
import java.util.*;
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.IFdContractClassService;
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.FdProjectFileValidation;
import org.jeecg.modules.projectManagement.service.IFdProjectFileCompoundService;
import org.jeecg.modules.projectManagement.service.IFdProjectFileValidationService;
import org.jeecg.modules.qualityControl.entity.*;
import org.jeecg.modules.qualityControl.mapper.FdQcBiologicalAnalysisVerificationMapper;
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.transaction.annotation.Transactional;
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/fdQcBiologicalAnalysisVerification")
@Slf4j
@Transactional
public class FdQcBiologicalAnalysisVerificationController {
    @Autowired
    private IFdQcBiologicalAnalysisVerificationService fdQcBiologicalAnalysisVerificationService;

    @Resource
    private FdQcBiologicalAnalysisVerificationMapper fdQcBiologicalAnalysisVerificationMapper;

    @Resource
    private FdMatrixTypeMapper fdMatrixTypeMapper;

    @Resource
    private FdContractClassMapper fdContractClassMapper;

    @Resource
    private IFdQcBiologicalAnalysisVerificationItemsService fdQcBiologicalAnalysisVerificationItemsService;

    @Resource
    private IFdPersonnelService fdPersonnelService;

    @Resource
    private IFdContractClassService fdContractClassService;

    @Resource
    private FdColumnManagementController fdColumnManagementController;

    @Resource
    private IFdProjectFileCompoundService fdProjectFileCompoundService;

    @Resource
    private IFdQcValidationService fdQcValidationService;

    @Resource
    private IFdProjectFileValidationService fdProjectFileValidationService;

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

    @Resource
    private IFdQaQcPictureUploadService iFdQaQcPictureUploadService;

    /**
     * 分页列表查询
     *
     * @param fdQcBiologicalAnalysisVerification
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="control-bioanalyticalverification")
    @RequiresPermissions("url:control-bioanalyticalverification:view")
    public Result<IPage<FdQcBiologicalAnalysisVerification>> queryPageList(FdQcBiologicalAnalysisVerification fdQcBiologicalAnalysisVerification,
                                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                           HttpServletRequest req) {
        Result<IPage<FdQcBiologicalAnalysisVerification>> result = new Result<IPage<FdQcBiologicalAnalysisVerification>>();
        String contractCode = fdQcBiologicalAnalysisVerification.getContractCode();
        if (StringUtils.isNotBlank(fdQcBiologicalAnalysisVerification.getContractCode())) {
            fdQcBiologicalAnalysisVerification.setContractCode(null);
        }
        String qualityControlSheetNumber = fdQcBiologicalAnalysisVerification.getQualityControlSheetNumber();
        if (StringUtils.isNotBlank(fdQcBiologicalAnalysisVerification.getQualityControlSheetNumber())) {
            fdQcBiologicalAnalysisVerification.setQualityControlSheetNumber(null);
        }
        //验证类别
        String verificationType = fdQcBiologicalAnalysisVerification.getVerificationType();
        if (StringUtils.isNotBlank(verificationType)) {
            fdQcBiologicalAnalysisVerification.setVerificationType("");
        }
        //提交时间范围
        String startTime=fdQcBiologicalAnalysisVerification.getStartTime();
        if(StringUtils.isNotBlank(startTime)){
            fdQcBiologicalAnalysisVerification.setStartTime(null);
        }
        String endTime=fdQcBiologicalAnalysisVerification.getEndTime();
        if(StringUtils.isNotBlank(endTime)){
            fdQcBiologicalAnalysisVerification.setEndTime(null);
        }
        QueryWrapper<FdQcBiologicalAnalysisVerification> queryWrapper = QueryGenerator.initQueryWrapper(fdQcBiologicalAnalysisVerification, req.getParameterMap());
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("contract_code", contractCode);
        }
        if (StringUtils.isNotBlank(qualityControlSheetNumber)) {
            queryWrapper.like("quality_control_sheet_number", qualityControlSheetNumber);
        }
        //验证类型 区别生物分析与临床
        if (StringUtils.isNotBlank(verificationType)) {
            queryWrapper.eq("verification_type", verificationType);
        }
        //获取当前登陆人员
        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(qav.qc_submission_date,'%Y-%m-%d')",startTime,endTime);
        }

        queryWrapper.eq("qav.del_flag ", "0");
        queryWrapper.orderByDesc("qav.create_time");
        Page<FdQcBiologicalAnalysisVerification> page = new Page<FdQcBiologicalAnalysisVerification>(pageNo, pageSize);
        // IPage<FdQcBiologicalAnalysisVerification> pageList = fdQcBiologicalAnalysisVerificationService.page(page, queryWrapper);
        IPage<FdQcBiologicalAnalysisVerification> pageList = fdQcBiologicalAnalysisVerificationService.findByPage(page, queryWrapper);
        // List<FdQcBiologicalAnalysisVerification> list = pageList.getRecords();
        // for (FdQcBiologicalAnalysisVerification fdQcBiologicalAnalysisVerification1:list){
        //     //类型名称
        //     String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQcBiologicalAnalysisVerification1.getAnalysisType());
        //     fdQcBiologicalAnalysisVerification1.setAnalysisTypeName(analysisTypeName);
        // }
        //获取QA状态
        getQaStatus(pageList.getRecords());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /***
     * @Title:临床控制分页查询
            * @Description:TODO
            * @param fdQcBiologicalAnalysisVerification, pageNo, pageSize, req]
            * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.qualityControl.entity.FdQcBiologicalAnalysisVerification>>
            * @exception 
            * @author 陈创
            * @date 2019/11/12 18:22
            * @updatehistory:
     *   2019/11/12 18:22 新增
            */
    @GetMapping(value = "/listClinical")
    @PermissionData(pageComponent="control-bioanalyticalverification")
    @RequiresPermissions("url:clinical-control-verification:view")
    public Result<IPage<FdQcBiologicalAnalysisVerification>> queryPageListClinical(FdQcBiologicalAnalysisVerification fdQcBiologicalAnalysisVerification,
                                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                           HttpServletRequest req) {
        Result<IPage<FdQcBiologicalAnalysisVerification>> result = new Result<IPage<FdQcBiologicalAnalysisVerification>>();
        String contractCode = fdQcBiologicalAnalysisVerification.getContractCode();
        if (StringUtils.isNotBlank(fdQcBiologicalAnalysisVerification.getContractCode())) {
            fdQcBiologicalAnalysisVerification.setContractCode(null);
        }
        String qualityControlSheetNumber = fdQcBiologicalAnalysisVerification.getQualityControlSheetNumber();
        if (StringUtils.isNotBlank(fdQcBiologicalAnalysisVerification.getQualityControlSheetNumber())) {
            fdQcBiologicalAnalysisVerification.setQualityControlSheetNumber(null);
        }
        //验证类别
        String verificationType = fdQcBiologicalAnalysisVerification.getVerificationType();
        if (StringUtils.isNotBlank(verificationType)) {
            fdQcBiologicalAnalysisVerification.setVerificationType("");
        }
        //提交时间范围
        String startTime=fdQcBiologicalAnalysisVerification.getStartTime();
        if(StringUtils.isNotBlank(startTime)){
            fdQcBiologicalAnalysisVerification.setStartTime(null);
        }
        String endTime=fdQcBiologicalAnalysisVerification.getEndTime();
        if(StringUtils.isNotBlank(endTime)){
            fdQcBiologicalAnalysisVerification.setEndTime(null);
        }
        QueryWrapper<FdQcBiologicalAnalysisVerification> queryWrapper = QueryGenerator.initQueryWrapper(fdQcBiologicalAnalysisVerification, req.getParameterMap());
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("contract_code", contractCode);
        }
        if (StringUtils.isNotBlank(qualityControlSheetNumber)) {
            queryWrapper.like("quality_control_sheet_number", qualityControlSheetNumber);
        }
        //验证类型 区别生物分析与临床
        if (StringUtils.isNotBlank(verificationType)) {
            queryWrapper.eq("verification_type", verificationType);
        }
        //获取当前登陆人员
        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(qav.qc_submission_date,'%Y-%m-%d')",startTime,endTime);
        }
        queryWrapper.eq("qav.del_flag ", "0");
        queryWrapper.orderByDesc("qav.create_time");
        Page<FdQcBiologicalAnalysisVerification> page = new Page<FdQcBiologicalAnalysisVerification>(pageNo, pageSize);
        // IPage<FdQcBiologicalAnalysisVerification> pageList = fdQcBiologicalAnalysisVerificationService.page(page, queryWrapper);
        IPage<FdQcBiologicalAnalysisVerification> pageList = fdQcBiologicalAnalysisVerificationService.findByPage(page, queryWrapper);
        // List<FdQcBiologicalAnalysisVerification> list = pageList.getRecords();
        // for (FdQcBiologicalAnalysisVerification fdQcBiologicalAnalysisVerification1:list){
        //     //类型名称
        //     String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQcBiologicalAnalysisVerification1.getAnalysisType());
        //     fdQcBiologicalAnalysisVerification1.setAnalysisTypeName(analysisTypeName);
        // }
        //获取Qa状态
        getQaStatus(pageList.getRecords());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    //根据 项目id 验证号 类型 获取Qa状态
    public void getQaStatus(List<FdQcBiologicalAnalysisVerification> verificationList){
        if(verificationList!=null&&verificationList.size()>0){
            for(FdQcBiologicalAnalysisVerification verification:verificationList){
                FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification=new FdQaBiologicalAnalysisVerification();
                fdQaBiologicalAnalysisVerification.setPkProjectFile(verification.getPkProjectFile());
                fdQaBiologicalAnalysisVerification.setVerifiCode(verification.getVerifiCode());
                fdQaBiologicalAnalysisVerification.setAnalysisType(verification.getAnalysisType());
                fdQaBiologicalAnalysisVerification.setVerificationType(verification.getVerificationType());
                FdQaBiologicalAnalysisVerification qaBiologicalAnalysisVerification=fdQaBiologicalAnalysisVerificationService.getByVerifiCodeAndType(fdQaBiologicalAnalysisVerification);
                if(qaBiologicalAnalysisVerification!=null){
                    verification.setQaStatus(qaBiologicalAnalysisVerification.getQualityStatus());
                }
            }
        }
    }

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

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

        return result;
    }

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

        return result;
    }

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

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

            //生物分析验证
            Map<String,Object> msp = Maps.newHashMap();
            msp.put("pk_qc_validation",fdQcBiologicalAnalysisVerification.getId());
            msp.put("del_flag","0");
            List<FdQcValidation>  fdQcValidationList= (List<FdQcValidation>)fdQcValidationService.listByMap(msp);
            fdQcBiologicalAnalysisVerification.setFdQcValidationList(fdQcValidationList);
            //明细
            Map<String,Object> msp1 = Maps.newHashMap();
            msp1.put("pk_biological_analysis_verification",fdQcBiologicalAnalysisVerification.getId());
            msp1.put("del_flag","0");
            List<FdQcBiologicalAnalysisVerificationItems> fdQcBiologicalAnalysisVerificationItems = (List<FdQcBiologicalAnalysisVerificationItems>)fdQcBiologicalAnalysisVerificationItemsService.listByMap(msp1);
            //获取对应图片文件
            fdQcBiologicalAnalysisVerificationService.getPictureUpload(fdQcBiologicalAnalysisVerificationItems);
            fdQcBiologicalAnalysisVerification.setFdQcBiologicalAnalysisVerificationItemsList(fdQcBiologicalAnalysisVerificationItems);
            //生物分析负责人
            LambdaQueryWrapper<FdPersonnel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdPersonnel::getId,fdQcBiologicalAnalysisVerification.getBioanalyticalPi());
            FdPersonnel p1 = fdPersonnelService.getOne(queryWrapper);
            if(oConvertUtils.isNotEmpty(p1)){
                fdQcBiologicalAnalysisVerification.setBioanalyticalPiName(p1.getName());
            }
            //助理
            LambdaQueryWrapper<FdPersonnel> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(FdPersonnel::getId,fdQcBiologicalAnalysisVerification.getAssociateBioanalyticalPi());
            FdPersonnel p2 = fdPersonnelService.getOne(queryWrapper2);
            if(oConvertUtils.isNotEmpty(p2)) {
                fdQcBiologicalAnalysisVerification.setAssociateBioanalyticalPiName(p2.getName());
            }
            //qc负责人
            LambdaQueryWrapper<FdPersonnel> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(FdPersonnel::getId,fdQcBiologicalAnalysisVerification.getResponsibleQc());
            FdPersonnel p3 = fdPersonnelService.getOne(queryWrapper3);
            if(oConvertUtils.isNotEmpty(p3)) {
                fdQcBiologicalAnalysisVerification.setResponsibleQcName(p3.getName());
            }
            //合同方名称
//            String contractPartyName = fdColumnManagementController.getContractPartyName(fdQcBiologicalAnalysisVerification.getPkContractParty());
//            fdQcBiologicalAnalysisVerification.setContractPartyName(contractPartyName);
            result.setResult(fdQcBiologicalAnalysisVerification);
            result.setSuccess(true);
        }
        return result;
    }



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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdQcBiologicalAnalysisVerification> pageList = fdQcBiologicalAnalysisVerificationService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "质量控制（生物分析验证）列表");
        mv.addObject(NormalExcelConstants.CLASS, FdQcBiologicalAnalysisVerification.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<FdQcBiologicalAnalysisVerification> listFdQcBiologicalAnalysisVerifications = ExcelImportUtil.importExcel(file.getInputStream(), FdQcBiologicalAnalysisVerification.class, params);
                for (FdQcBiologicalAnalysisVerification fdQcBiologicalAnalysisVerificationExcel : listFdQcBiologicalAnalysisVerifications) {
                    fdQcBiologicalAnalysisVerificationService.save(fdQcBiologicalAnalysisVerificationExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdQcBiologicalAnalysisVerifications.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 10:02 2019/6/13
     * @Param [fdQcBiologicalAnalysisVerification, bindingResult]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQcBiologicalAnalysisVerification>
     **/
    @PostMapping(value = "/addAll")
    @NotDuplicate
    //生物分析、临床质量控制新增和修改权限
    @RequiresPermissions(value ={"control-bioanalyticalverification:add","control-bioanalyticalverification:update","clinical-control-verification:add","clinical-control-verification:update"},logical = Logical.OR)
    public Result<FdQcBiologicalAnalysisVerification> addAll(@RequestBody @Valid FdQcBiologicalAnalysisVerification fdQcBiologicalAnalysisVerification, BindingResult bindingResult) {
        Result<FdQcBiologicalAnalysisVerification> result = new Result<FdQcBiologicalAnalysisVerification>();
        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 (fdQcBiologicalAnalysisVerification.getFdQcBiologicalAnalysisVerificationItemsList()==null||fdQcBiologicalAnalysisVerification.getFdQcBiologicalAnalysisVerificationItemsList().size()<1){
                result.error500("操作失败,明细不能为空");
                return result;
            }
            if (fdQcBiologicalAnalysisVerification.getFdQcValidationList()==null||fdQcBiologicalAnalysisVerification.getFdQcValidationList().size()<1){
                result.error500("操作失败,方法验证号不能为空");
                return result;
            }
            //新增才处理
            if(oConvertUtils.isEmpty(fdQcBiologicalAnalysisVerification.getId())){
                LambdaQueryWrapper<FdQcBiologicalAnalysisVerification> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FdQcBiologicalAnalysisVerification::getQualityControlSheetNumber,fdQcBiologicalAnalysisVerification.getQualityControlSheetNumber());
                queryWrapper.eq(FdQcBiologicalAnalysisVerification::getDelFlag,"0");
                List<FdQcBiologicalAnalysisVerification> list = fdQcBiologicalAnalysisVerificationService.list(queryWrapper);
                if ( list!=null && list.size()>0 ){
                    result.error500("操作失败,质量控制单号不能重复");
                    return result;
                }
            }

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

            //通知PI
            if(StringUtils.isNotBlank(fdQcBiologicalAnalysisVerification.getIsNoticePi())&&fdQcBiologicalAnalysisVerification.getIsNoticePi().equals("1")){
                //获取方法号
                String validaCode ="";
                for(FdQcValidation fdQcValidation:fdQcBiologicalAnalysisVerification.getFdQcValidationList()){
                    validaCode+=fdQcValidation.getCode()+";";
                }
                //发送邮件通知
                String msg="质量控制-方法验证" +
                        "\n合同号："+fdQcBiologicalAnalysisVerification.getContractCode()+
                        "\n项目号："+fdQcBiologicalAnalysisVerification.getProjectFileNo()+
                        "\n方法号："+validaCode+
                        "\n已经填写，请及时回复！";
                if(fdQcBiologicalAnalysisVerification.getVerificationType().equals("1")){
                    //生物分析验证
                    fdProjectReceivablesService.noticeFinance(fdQcBiologicalAnalysisVerification.getBioanalyticalPi(),"质量管理-回复提醒",msg);
                }else{
                    //临床验证
                    fdProjectReceivablesService.noticeFinance(fdQcBiologicalAnalysisVerification.getClinicalPi(),"质量管理-回复提醒",msg);
                }
            }

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


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


    /**
     * @Author gurui
     * @Description //TODO 删除 质量控制（生物分析验证）同时删除其明细
     * @Date 14:19 2019/7/3
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQcBiologicalAnalysisVerification>
     **/
    @DeleteMapping(value = "/deleteAll")
    @NotDuplicate
    //生物分析、临床质量控制删除权限
    @RequiresPermissions(value = {"control-bioanalyticalverification:delete","clinical-control-verification:delete"},logical = Logical.OR)
    public Result<FdQcBiologicalAnalysisVerification> deleteAll(@RequestParam(name = "id", required = true) String id) {
        Result<FdQcBiologicalAnalysisVerification> result = new Result<FdQcBiologicalAnalysisVerification>();
        FdQcBiologicalAnalysisVerification fdQcBiologicalAnalysisVerification = fdQcBiologicalAnalysisVerificationService.getById(id);
        if (fdQcBiologicalAnalysisVerification == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdQcBiologicalAnalysisVerificationService.deleteAll(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }



}
