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.annotation.TableField;
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.message.handle.ISendMsgHandle;
import org.jeecg.modules.message.handle.enums.SendMsgTypeEnum;
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.FdQaBiologicalAnalysisVerification;
import org.jeecg.modules.qualityControl.entity.FdQaBiologicalAnalysisVerificationItems;
import org.jeecg.modules.qualityControl.entity.FdQaValidation;
import org.jeecg.modules.qualityControl.entity.FdQcBiologicalAnalysisVerification;
import org.jeecg.modules.qualityControl.mapper.FdQaBiologicalAnalysisVerificationItemsMapper;
import org.jeecg.modules.qualityControl.service.IFdQaBiologicalAnalysisVerificationItemsService;
import org.jeecg.modules.qualityControl.service.IFdQaBiologicalAnalysisVerificationService;

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.qualityControl.service.IFdQaValidationService;
import org.jeecg.modules.qualityControl.service.IFdQcBiologicalAnalysisVerificationService;
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/fdQaBiologicalAnalysisVerification")
@Slf4j
public class FdQaBiologicalAnalysisVerificationController {
    @Autowired
    private IFdQaBiologicalAnalysisVerificationService fdQaBiologicalAnalysisVerificationService;

    @Resource
    private IFdPersonnelService fdPersonnelService;

    @Resource
    private FdContractClassMapper fdContractClassMapper;

    @Resource
    private FdColumnManagementController fdColumnManagementController;

    @Resource
    private IFdQaBiologicalAnalysisVerificationItemsService fdQaBiologicalAnalysisVerificationItemsService;

    @Resource
    private IFdProjectFileCompoundService fdProjectFileCompoundService;

    @Resource
    private IFdProjectFileValidationService fdProjectFileValidationService;

    @Resource
    private IFdQaValidationService fdQaValidationService;

    @Resource
    private FdMatrixTypeMapper fdMatrixTypeMapper;
    @Resource
    private IFdProjectReceivablesService fdProjectReceivablesService;

    @Resource
    private IFdQcBiologicalAnalysisVerificationService fdQaBiologicalAnalysisVerification;

    /**
     * 分页列表查询
     *
     * @param fdQaBiologicalAnalysisVerification
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="assurance-bioanalyticalverification")
    @RequiresPermissions("url:assurance-bioanalyticalverification:view")
    public Result<IPage<FdQaBiologicalAnalysisVerification>> queryPageList(FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification,
                                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                           HttpServletRequest req) {
        Result<IPage<FdQaBiologicalAnalysisVerification>> result = new Result<IPage<FdQaBiologicalAnalysisVerification>>();
        String qualityAssuranceFormNumber = fdQaBiologicalAnalysisVerification.getQualityAssuranceFormNumber();
        if (StringUtils.isNotBlank(fdQaBiologicalAnalysisVerification.getQualityAssuranceFormNumber())) {
            fdQaBiologicalAnalysisVerification.setQualityAssuranceFormNumber(null);
        }
        String contractCode = fdQaBiologicalAnalysisVerification.getContractCode();
        if (StringUtils.isNotBlank(fdQaBiologicalAnalysisVerification.getContractCode())) {
            fdQaBiologicalAnalysisVerification.setContractCode(null);
        }
        //提交时间范围
        String startTime=fdQaBiologicalAnalysisVerification.getStartTime();
        if(StringUtils.isNotBlank(startTime)){
            fdQaBiologicalAnalysisVerification.setStartTime(null);
        }
        String endTime=fdQaBiologicalAnalysisVerification.getEndTime();
        if(StringUtils.isNotBlank(endTime)){
            fdQaBiologicalAnalysisVerification.setEndTime(null);
        }
        QueryWrapper<FdQaBiologicalAnalysisVerification> queryWrapper = QueryGenerator.initQueryWrapper(fdQaBiologicalAnalysisVerification, 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(qbav.qa_submission_date,'%Y-%m-%d')",startTime,endTime);
        }
        queryWrapper.eq("qbav.del_flag", "0");
        queryWrapper.orderByDesc("qbav.create_time");
        Page<FdQaBiologicalAnalysisVerification> page = new Page<FdQaBiologicalAnalysisVerification>(pageNo, pageSize);
        // IPage<FdQaBiologicalAnalysisVerification> pageList = fdQaBiologicalAnalysisVerificationService.page(page, queryWrapper);
        IPage<FdQaBiologicalAnalysisVerification> pageList = fdQaBiologicalAnalysisVerificationService.findByPage(page, queryWrapper);
        // List<FdQaBiologicalAnalysisVerification> list = pageList.getRecords();
        // for (FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification1:list){
        //     //类型名称
        //     String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQaBiologicalAnalysisVerification1.getAnalysisType());
        //     fdQaBiologicalAnalysisVerification1.setAnalysisTypeName(analysisTypeName);
        // }
        //获取QC的状态
        getQcStatus(pageList.getRecords());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /***
     * @Title:临床质量保证查询
            * @Description:TODO
            * @param fdQaBiologicalAnalysisVerification, pageNo, pageSize, req]
            * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.qualityControl.entity.FdQaBiologicalAnalysisVerification>>
            * @exception 
            * @author 陈创
            * @date 2019/11/12 14:35
            * @updatehistory:
     *   2019/11/12 14:35 新增
            */
    @GetMapping(value = "/listClinical")
    @RequiresPermissions("url:clinical-assurance-verification:view")
    @PermissionData(pageComponent="assurance-bioanalyticalverification")
    public Result<IPage<FdQaBiologicalAnalysisVerification>> queryPageListClinical(FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification,
                                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                           HttpServletRequest req) {
        Result<IPage<FdQaBiologicalAnalysisVerification>> result = new Result<IPage<FdQaBiologicalAnalysisVerification>>();
        String qualityAssuranceFormNumber = fdQaBiologicalAnalysisVerification.getQualityAssuranceFormNumber();
        if (StringUtils.isNotBlank(fdQaBiologicalAnalysisVerification.getQualityAssuranceFormNumber())) {
            fdQaBiologicalAnalysisVerification.setQualityAssuranceFormNumber(null);
        }
        String contractCode = fdQaBiologicalAnalysisVerification.getContractCode();
        if (StringUtils.isNotBlank(fdQaBiologicalAnalysisVerification.getContractCode())) {
            fdQaBiologicalAnalysisVerification.setContractCode(null);
        }
        //提交时间范围
        String startTime=fdQaBiologicalAnalysisVerification.getStartTime();
        if(StringUtils.isNotBlank(startTime)){
            fdQaBiologicalAnalysisVerification.setStartTime(null);
        }
        String endTime=fdQaBiologicalAnalysisVerification.getEndTime();
        if(StringUtils.isNotBlank(endTime)){
            fdQaBiologicalAnalysisVerification.setEndTime(null);
        }
        QueryWrapper<FdQaBiologicalAnalysisVerification> queryWrapper = QueryGenerator.initQueryWrapper(fdQaBiologicalAnalysisVerification, 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(qbav.qa_submission_date,'%Y-%m-%d')",startTime,endTime);
        }
        queryWrapper.eq("qbav.del_flag", "0");
        queryWrapper.orderByDesc("qbav.create_time");
        Page<FdQaBiologicalAnalysisVerification> page = new Page<FdQaBiologicalAnalysisVerification>(pageNo, pageSize);
        // IPage<FdQaBiologicalAnalysisVerification> pageList = fdQaBiologicalAnalysisVerificationService.page(page, queryWrapper);
        IPage<FdQaBiologicalAnalysisVerification> pageList = fdQaBiologicalAnalysisVerificationService.findByPage(page, queryWrapper);
        // List<FdQaBiologicalAnalysisVerification> list = pageList.getRecords();
        // for (FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification1:list){
        //     //类型名称
        //     String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQaBiologicalAnalysisVerification1.getAnalysisType());
        //     fdQaBiologicalAnalysisVerification1.setAnalysisTypeName(analysisTypeName);
        // }
        //获取QC的状态
        getQcStatus(pageList.getRecords());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


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

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

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

        return result;
    }

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

        return result;
    }

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

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdQaBiologicalAnalysisVerification> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdQaBiologicalAnalysisVerification> result = new Result<FdQaBiologicalAnalysisVerification>();
        FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification = fdQaBiologicalAnalysisVerificationService.getById(id);
        if (fdQaBiologicalAnalysisVerification == null) {
            result.error500("未找到对应实体");
        } else {
            //化合物
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(FdProjectFileCompound::getProjectId,fdQaBiologicalAnalysisVerification.getPkProjectFile());
            queryWrapper1.eq(FdProjectFileCompound::getDelFlag,"0");
            List<FdProjectFileCompound> list1 = fdProjectFileCompoundService.list(queryWrapper1);
            fdQaBiologicalAnalysisVerification.setFdProjectFileCompoundList(list1);
            //类型名称
            String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQaBiologicalAnalysisVerification.getAnalysisType());
            fdQaBiologicalAnalysisVerification.setAnalysisTypeName(analysisTypeName);
            //明细
//            Map<String,Object> msp = Maps.newHashMap();
//            msp.put("pk_biological_analysis_verification",fdQaBiologicalAnalysisVerification.getId());
//            msp.put("del_flag","0");
//            List<FdQaBiologicalAnalysisVerificationItems> fdQaBiologicalAnalysisVerificationItems =  (List<FdQaBiologicalAnalysisVerificationItems>)fdQaBiologicalAnalysisVerificationItemsService.listByMap(msp);
//            fdQaBiologicalAnalysisVerification.setFdQaBiologicalAnalysisVerificationItemsList(fdQaBiologicalAnalysisVerificationItems);
            List<FdQaBiologicalAnalysisVerificationItems> fdQaBiologicalAnalysisVerificationItemsList = fdQaBiologicalAnalysisVerificationItemsService.findOrderByCode(fdQaBiologicalAnalysisVerification.getId());
            //获取对应图片文件
            fdQaBiologicalAnalysisVerificationService.getPictureUpload(fdQaBiologicalAnalysisVerificationItemsList);
            fdQaBiologicalAnalysisVerification.setFdQaBiologicalAnalysisVerificationItemsList(fdQaBiologicalAnalysisVerificationItemsList);
            //生物样本分析验证
            Map<String,Object> msp1 = Maps.newHashMap();
            msp1.put("pk_qa_validation",fdQaBiologicalAnalysisVerification.getId());
            msp1.put("del_flag","0");
            List<FdQaValidation> fdQaValidationList =  (List<FdQaValidation>)fdQaValidationService.listByMap(msp1);
            fdQaBiologicalAnalysisVerification.setFdQaValidationList(fdQaValidationList);
            //生物分析负责人
            LambdaQueryWrapper<FdPersonnel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdPersonnel::getId,fdQaBiologicalAnalysisVerification.getBioanalyticalPi());
            FdPersonnel p1 = fdPersonnelService.getOne(queryWrapper);
            if(oConvertUtils.isNotEmpty(p1)){
                fdQaBiologicalAnalysisVerification.setBioanalyticalPiName(p1.getName());
            }
            //助理
            LambdaQueryWrapper<FdPersonnel> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(FdPersonnel::getId,fdQaBiologicalAnalysisVerification.getAssociateBioanalyticalPi());
            FdPersonnel p2 = fdPersonnelService.getOne(queryWrapper2);
            if (oConvertUtils.isNotEmpty(p2)){
                fdQaBiologicalAnalysisVerification.setAssociateBioanalyticalPiName(p2.getName());
            }
            //qc负责人
            LambdaQueryWrapper<FdPersonnel> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(FdPersonnel::getId,fdQaBiologicalAnalysisVerification.getResponsibleQa());
            FdPersonnel p3 = fdPersonnelService.getOne(queryWrapper3);
            if (oConvertUtils.isNotEmpty(p3)){
                fdQaBiologicalAnalysisVerification.setResponsibleQaName(p3.getName());
            }
            //基质类型
            if(fdQaBiologicalAnalysisVerification.getMatrix()!=null&&!fdQaBiologicalAnalysisVerification.getMatrix().equals("")){
                List<String> list2 = Arrays.asList(fdQaBiologicalAnalysisVerification.getMatrix().split(","));
                List<FdMatrixType> fdMatrixTypes = fdMatrixTypeMapper.selectBatchIds(list2);
                String fdMatrixType = "";
                for (FdMatrixType fdMatrixType1:fdMatrixTypes){
                    if (fdMatrixType == ""){
                        fdMatrixType = fdMatrixType1.getName();
                    }else {
                        fdMatrixType +=","+fdMatrixType1.getName();
                    }
                }
                fdQaBiologicalAnalysisVerification.setMatrixName(fdMatrixType);
            }
            result.setResult(fdQaBiologicalAnalysisVerification);
            result.setSuccess(true);
        }
        return result;
    }

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdQaBiologicalAnalysisVerification> pageList = fdQaBiologicalAnalysisVerificationService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "质量保证（生物分析验证）列表");
        mv.addObject(NormalExcelConstants.CLASS, FdQaBiologicalAnalysisVerification.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<FdQaBiologicalAnalysisVerification> listFdQaBiologicalAnalysisVerifications = ExcelImportUtil.importExcel(file.getInputStream(), FdQaBiologicalAnalysisVerification.class, params);
                for (FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerificationExcel : listFdQaBiologicalAnalysisVerifications) {
                    fdQaBiologicalAnalysisVerificationService.save(fdQaBiologicalAnalysisVerificationExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdQaBiologicalAnalysisVerifications.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 14:56 2019/6/11
     * @Param [fdQaBiologicalAnalysisVerification, bindingResult]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQaBiologicalAnalysisVerification>
     **/
    @PostMapping(value = "/addAll")
    @NotDuplicate
    //生物分析、临床质量保证新增修改权限
    @RequiresPermissions(value = {"assurance-bioanalyticalverification:add","assurance-bioanalyticalverification:update","clinical-assurance-verification:add","clinical-assurance-verification:update"},logical = Logical.OR)
    public Result<FdQaBiologicalAnalysisVerification> addAll(@RequestBody @Valid FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification, BindingResult bindingResult) {
        Result<FdQaBiologicalAnalysisVerification> result = new Result<FdQaBiologicalAnalysisVerification>();
        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 (fdQaBiologicalAnalysisVerification.getFdQaBiologicalAnalysisVerificationItemsList()==null||fdQaBiologicalAnalysisVerification.getFdQaBiologicalAnalysisVerificationItemsList().size()<1){
                result.error500("操作失败,明细不能未空");
                return result;
            }
            if (fdQaBiologicalAnalysisVerification.getFdQaValidationList()==null&&fdQaBiologicalAnalysisVerification.getFdQaValidationList().size()<1){
                result.error500("操作失败,方法验证号不能未空");
                return result;
            }

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

            }

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

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

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

    /**
     * @Author gurui
     * @Description //TODO 根据合同id 查询项目档案相关信息
     * @Date 14:07 2019/7/3
     * @Param [contractId]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQaBiologicalAnalysisVerification>
     **/
    @GetMapping(value = "/queryQaBiologicalByConId")
    public Result<FdQaBiologicalAnalysisVerification> queryQaBiologicalByConId(@RequestParam(name = "contractId", required = true) String contractId) {
        Result<FdQaBiologicalAnalysisVerification> result = new Result<FdQaBiologicalAnalysisVerification>();

        FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification = fdQaBiologicalAnalysisVerificationService.queryQaBiologicalByConId(contractId);
        if (fdQaBiologicalAnalysisVerification == null) {
            result.error500("未找到对应实体");
        } else {
            //生物分析验证号
            Map<String,Object> msp = Maps.newHashMap();
            msp.put("del_flag","0");
            msp.put("project_id",fdQaBiologicalAnalysisVerification.getPkProjectFile());
            List<FdProjectFileValidation> fdProjectFileValidationList = (List<FdProjectFileValidation>)fdProjectFileValidationService.listByMap(msp);
            fdQaBiologicalAnalysisVerification.setFdProjectFileValidationList(fdProjectFileValidationList);
            //合同方名称
            String contractPartyName = fdColumnManagementController.getContractPartyName(fdQaBiologicalAnalysisVerification.getPkContractParty());
            fdQaBiologicalAnalysisVerification.setContractPartyName(contractPartyName);
            //基质类型
            List<String> list2 = Arrays.asList(fdQaBiologicalAnalysisVerification.getMatrix().split(","));
            List<FdMatrixType> fdMatrixTypes = fdMatrixTypeMapper.selectBatchIds(list2);
            String fdMatrixType = "";
            for (FdMatrixType fdMatrixType1:fdMatrixTypes){
                if (fdMatrixType == ""){
                    fdMatrixType = fdMatrixType1.getName();
                }else {
                    fdMatrixType +=","+fdMatrixType1.getName();
                }
            }
            fdQaBiologicalAnalysisVerification.setMatrixName(fdMatrixType);
            //生物分析负责人
            if (fdQaBiologicalAnalysisVerification.getBioanalyticalPi()!=null){
                LambdaQueryWrapper<FdPersonnel> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FdPersonnel::getId,fdQaBiologicalAnalysisVerification.getBioanalyticalPi());
                FdPersonnel p1 = fdPersonnelService.getOne(queryWrapper);
                fdQaBiologicalAnalysisVerification.setBioanalyticalPiName(p1.getName());
            }
            //助理
            if (fdQaBiologicalAnalysisVerification.getAssociateBioanalyticalPi()!=null){
                LambdaQueryWrapper<FdPersonnel> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(FdPersonnel::getId,fdQaBiologicalAnalysisVerification.getAssociateBioanalyticalPi());
                FdPersonnel p2 = fdPersonnelService.getOne(queryWrapper2);
                if (p2!=null){
                    fdQaBiologicalAnalysisVerification.setAssociateBioanalyticalPiName(p2.getName());
                }
            }
            //qa负责人
            if (fdQaBiologicalAnalysisVerification.getResponsibleQa()!=null){
                LambdaQueryWrapper<FdPersonnel> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(FdPersonnel::getId,fdQaBiologicalAnalysisVerification.getResponsibleQa());
                FdPersonnel p3 = fdPersonnelService.getOne(queryWrapper3);
                fdQaBiologicalAnalysisVerification.setResponsibleQaName(p3.getName());
            }
            //化合物
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(FdProjectFileCompound::getProjectId,fdQaBiologicalAnalysisVerification.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();
                }
            }
            fdQaBiologicalAnalysisVerification.setCompoundName(compoundName);
            fdQaBiologicalAnalysisVerification.setPkCompound(pkCompound);
            fdQaBiologicalAnalysisVerification.setFdProjectFileCompoundList(list1);
            //默认化合物 sort为1
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper6=new LambdaQueryWrapper<>();
            queryWrapper6.eq(FdProjectFileCompound::getProjectId,fdQaBiologicalAnalysisVerification.getPkProjectFile());
            queryWrapper6.eq(FdProjectFileCompound::getSort,"1");
            FdProjectFileCompound one = fdProjectFileCompoundService.getOne(queryWrapper6);
            fdQaBiologicalAnalysisVerification.setCompound1(one.getCompound());
            fdQaBiologicalAnalysisVerification.setCompound1Id(one.getId());
            result.setResult(fdQaBiologicalAnalysisVerification);
            result.setSuccess(true);
        }
        return result;
    }




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

        return result;
    }

    @GetMapping(value = "/getQCReviewByDict")
    public Result<FdQaBiologicalAnalysisVerification> getQCReviewByDict(@RequestParam(name = "id", required = true) String id) {
        Result<FdQaBiologicalAnalysisVerification> result = new Result<FdQaBiologicalAnalysisVerification>();
        FdQaBiologicalAnalysisVerification fdQaBiologicalAnalysisVerification = fdQaBiologicalAnalysisVerificationService.getById(id);
        if (fdQaBiologicalAnalysisVerification == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(fdQaBiologicalAnalysisVerification);
            result.setSuccess(true);
        }
        return result;
    }



}
