package org.jeecg.modules.projectManagement.controller;

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 com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
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.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.entity.*;
import org.jeecg.modules.projectManagement.entity.*;
import org.jeecg.modules.basedata.mapper.FdContractClassMapper;
import org.jeecg.modules.basedata.mapper.FdHospitalMapper;
import org.jeecg.modules.basedata.mapper.FdMatrixTypeMapper;
import org.jeecg.modules.basedata.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.projectManagement.service.*;
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-05-28
 * @version： V1.0
 */
@RestController
@RequestMapping("/projectManagement/fdProjectFile")
@Slf4j
public class FdProjectFileController {
    @Autowired
    private IFdProjectFileService fdProjectFileService;

    @Resource
    private IFdProjectFileCompoundService fdProjectFileCompoundService;

    @Resource
    private IFdProjectFileContactsService fdProjectFileContactsService;

    @Resource
    private IFdProjectFileBidpartyService fdProjectFileBidpartyService;

    @Resource
    private IFdProjectFileMembersService fdProjectFileMembersService;

    @Resource
    private IFdProjectFileMethodService fdProjectFileMethodService;

    @Resource
    private IFdProjectFileConfirmService fdProjectFileConfirmService;

    @Resource
    private IFdProjectFileValidationService fdProjectFileValidationService;

    @Resource
    private IFdProjectFileSampleService fdProjectFileSampleService;

    @Resource
    private IFdProjectFileUploadService fdProjectFileUploadService;

    @Resource
    private IFdCustomerService fdCustomerService;

    @Resource
    private IFdContractService fdContractService;

    @Resource
    private FdContractClassMapper fdContractClassMapper;

    @Resource
    private FdMatrixTypeMapper fdMatrixTypeMapper;

    @Resource
    private FdHospitalMapper fdHospitalMapper;

    @Resource
    private IFdPersonnelService fdPersonnelService;
    @Resource
    private IFdCustomerContactsService fdCustomerContactsService;


    /**
     * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage   <   org.jeecg.modules.projectManagement.entity.FdProjectFile>>
     * @Author gurui
     * @Description //TODO 分页连接查询
     * @Date 14:48 2019/5/29
     * @Param [fdProjectFile, pageNo, pageSize, req]
     **/
    @GetMapping(value = "/list")
    @RequiresPermissions("url:pm-projectArchives:view")
    @PermissionData(pageComponent = "pm-projectArchives")
    public Result<IPage<FdProjectFile>> queryPageList(FdProjectFile fdProjectFile,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        Result<IPage<FdProjectFile>> result = new Result<IPage<FdProjectFile>>();

        String contractCode = fdProjectFile.getContractCode();
        if (StringUtils.isNotBlank(fdProjectFile.getContractCode())) {
            fdProjectFile.setContractCode(null);
        }
        String projectName = fdProjectFile.getProjectName();
        if (StringUtils.isNotBlank(fdProjectFile.getProjectName())) {
            fdProjectFile.setProjectName(null);
        }
        System.out.println(fdProjectFile.getStatus());
        //状态
        String status=fdProjectFile.getStatus();
        if( (status!=null&&!"".equals(status)) || "null".equals(status) ){
            fdProjectFile.setStatus(null);
        }
        //项目经理
        String projectManagerId=fdProjectFile.getProjectManagerId();
        if(StringUtils.isNotBlank(projectManagerId)){
            fdProjectFile.setProjectManagerId(null);
        }

//        if(StringUtils.isNotBlank(fdProjectFile.getStatus())){
//            fdProjectFile.setStatus(null);
//        }
        QueryWrapper<FdProjectFile> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectFile, req.getParameterMap());
        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.orderByDesc("a.create_time");
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("d.code", contractCode);
        }
        if (StringUtils.isNotBlank(projectName)) {
            queryWrapper.like("a.project_name", projectName);
        }
        if(oConvertUtils.isNotEmpty(status)){
            queryWrapper.eq("a.status",status);
        }
        if(StringUtils.isNotBlank(projectManagerId)&&!projectManagerId.equals("null")){
            queryWrapper.eq("a.project_manager_id", projectManagerId);
        }
        Page<FdProjectFile> page = new Page<FdProjectFile>(pageNo, pageSize);
        IPage<FdProjectFile> pageList = fdProjectFileService.findByPage(page, queryWrapper);
        //化合物名称多个
        if(!pageList.getRecords().isEmpty()){
            compoundName(pageList.getRecords());
        }

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
    * @Author chenchuang
    * @Description //TODO 支付信息分页查询
    * @Date 2020/7/23 14:04
    * @Param [fdProjectFile, pageNo, pageSize, req]
    * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.projectManagement.entity.FdProjectFile>>
    */
    @GetMapping(value = "/findInformationByPage")
    @PermissionData(pageComponent = "pm-project-payment-information")
    public Result<IPage<FdProjectFile>> findInformationByPage(FdProjectFile fdProjectFile,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        Result<IPage<FdProjectFile>> result = new Result<IPage<FdProjectFile>>();

        String contractCode = fdProjectFile.getContractCode();
        if (StringUtils.isNotBlank(fdProjectFile.getContractCode())) {
            fdProjectFile.setContractCode(null);
        }
        String projectName = fdProjectFile.getProjectName();
        if (StringUtils.isNotBlank(fdProjectFile.getProjectName())) {
            fdProjectFile.setProjectName(null);
        }
        System.out.println(fdProjectFile.getStatus());
        //状态
        String status=fdProjectFile.getStatus();
        if( (status!=null&&!"".equals(status)) || "null".equals(status) ){
            fdProjectFile.setStatus(null);
        }
        //项目经理
        String projectManagerId=fdProjectFile.getProjectManagerId();
        if(StringUtils.isNotBlank(projectManagerId)){
            fdProjectFile.setProjectManagerId(null);
        }

//        if(StringUtils.isNotBlank(fdProjectFile.getStatus())){
//            fdProjectFile.setStatus(null);
//        }
        QueryWrapper<FdProjectFile> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectFile, req.getParameterMap());
        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.orderByDesc("a.create_time");
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("d.code", contractCode);
        }
        if (StringUtils.isNotBlank(projectName)) {
            queryWrapper.like("a.project_name", projectName);
        }
        if(oConvertUtils.isNotEmpty(status)){
            queryWrapper.eq("a.status",status);
        }
        if(StringUtils.isNotBlank(projectManagerId)&&!projectManagerId.equals("null")){
            queryWrapper.eq("a.project_manager_id", projectManagerId);
        }
        Page<FdProjectFile> page = new Page<FdProjectFile>(pageNo, pageSize);
        IPage<FdProjectFile> pageList = fdProjectFileService.findInformationByPage(page, queryWrapper);
        //化合物名称多个
        if(!pageList.getRecords().isEmpty()){
            compoundName(pageList.getRecords());
        }

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /***
     * @Title:查询项目档案对应的化合物名称多个
            * @Description:TODO
            * @param fdProjectFileList
            * @return void
            * @exception
            * @author 陈创
            * @date 2019/7/4 21:17
            * @updatehistory:
     *   2019/7/4 21:17 查询
            */
    public void compoundName(List<FdProjectFile> fdProjectFileList){
        //项目档案中的化合物
        List<FdProjectFileCompound> projectFileCompoundList = fdProjectFileCompoundService.getBatchByProjectFildIds(fdProjectFileList);
        //循环找到所对应的化合物
        for (FdProjectFile fdProjectFile1 : fdProjectFileList) {
            //储存多个化合物的名称
            String compound="";
            int i = 0;
            for (FdProjectFileCompound fdProjectFileCompound : projectFileCompoundList) {
                //判断此项目档案下的化合物
                if (fdProjectFile1.getId().equals(fdProjectFileCompound.getProjectId())) {
                    if (i == 0) {
                        compound=fdProjectFileCompound.getCompound();
                    }else{
                        compound=compound+","+fdProjectFileCompound.getCompound();
                    }
                    i++;
                }
            }
            fdProjectFile1.setCompound(compound);
        }
    }

    /**
    * @Author chenchuang
    * @Description //TODO 质量控制项目档案数据查询
    * @Date 2020/5/21 13:42
    * @Param [fdProjectFile, pageNo, pageSize, req]
    * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.projectManagement.entity.FdProjectFile>>
    */
    @GetMapping(value = "/validationCodeFindByPage")
    public Result<IPage<FdProjectFile>> validationCodeFindByPage(FdProjectFile fdProjectFile,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        Result<IPage<FdProjectFile>> result = new Result<IPage<FdProjectFile>>();

        String contractCode = fdProjectFile.getContractCode();
        if (StringUtils.isNotBlank(fdProjectFile.getContractCode())) {
            fdProjectFile.setContractCode(null);
        }
        String projectName = fdProjectFile.getProjectName();
        if (StringUtils.isNotBlank(fdProjectFile.getProjectName())) {
            fdProjectFile.setProjectName(null);
        }
        System.out.println(fdProjectFile.getStatus());
        //状态
        String status=fdProjectFile.getStatus();
        if( (status!=null&&!"".equals(status)) || "null".equals(status) ){
            fdProjectFile.setStatus(null);
        }

        //是否输入号码
        boolean isCode=false;
        //项目档案ids
        List<String> fileIds=new ArrayList<>();
        //项目确认号
        String methodCode=fdProjectFile.getConfirmCode();
        //根据方法号获取相关项目档案id
        if(StringUtils.isNotBlank(methodCode)){
            isCode=true;
            fdProjectFile.setConfirmCode(null);
            confirmCode(methodCode,fileIds);//获取项目档案号
        }

        //方法验证号
        String validationCode=fdProjectFile.getValidationCode();
        //根据项目确认号获取项目档案id
        if(StringUtils.isNotBlank(validationCode)){
            isCode=true;
            fdProjectFile.setValidationCode(null);
            validationCode(validationCode,fileIds);//项目档案号
        }

        //样本分析号
        String sampleCode=fdProjectFile.getSampleCode();
        //根据项目确认号获取项目档案id
        if(StringUtils.isNotBlank(sampleCode)){
            isCode=true;
            fdProjectFile.setSampleCode(null);
            sampleCode(sampleCode,fileIds);//项目档案号
        }


        //方法验证号
        // String validationCode=fdProjectFile.getValidationCode();
        // if(StringUtils.isNotBlank(validationCode)){
        //     fdProjectFile.setValidationCode(null);
        // }

        QueryWrapper<FdProjectFile> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectFile, req.getParameterMap());
        queryWrapper.eq("a.status", "1");
        queryWrapper.eq("a.del_flag", "0");
        // queryWrapper.eq("fpfv.del_flag", "0");
        queryWrapper.orderByDesc("a.create_time");
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("d.code", contractCode);
        }
        if (StringUtils.isNotBlank(projectName)) {
            queryWrapper.like("a.project_name", projectName);
        }
        if(oConvertUtils.isNotEmpty(status)){
            queryWrapper.eq("a.status",status);
        }
        // if(StringUtils.isNotBlank(validationCode)){
        //     queryWrapper.like("fpfv.code",validationCode);
        // }
        //是否存在号码的条件筛选
        if(isCode){
            if(fileIds.size()>0){//通过多个档案id查询项目档案
                //去重
                HashSet h2 = new HashSet(fileIds);
                fileIds.clear();
                fileIds.addAll(h2);
                queryWrapper.in("a.id",fileIds);
            }else{//没有查询出来则不查出数据
                queryWrapper.eq("a.id","无");
            }
        }
        Page<FdProjectFile> page = new Page<FdProjectFile>(pageNo, pageSize);
        IPage<FdProjectFile> pageList = fdProjectFileService.findByPage(page, queryWrapper);

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /***
     * @Title:
     * @Description:TODO 项目确认号查询条件处理
     * @param code
     * @return java.util.List<java.lang.String>
     * @exception
     * @author 陈创
     * @date 2020/4/9 15:11
     * @updatehistory:
     *   2020/4/9 15:11 新增
     */
    public void confirmCode(String code,List<String> fileIds){
        //查询方法号下存在的项目档案
        LambdaQueryWrapper<FdProjectFileConfirm> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(FdProjectFileConfirm::getCode,code);
        lambdaQueryWrapper.eq(FdProjectFileConfirm::getDelFlag,"0");
        List<FdProjectFileConfirm> fdProjectFileMethodList=fdProjectFileConfirmService.list(lambdaQueryWrapper);
        //获取对应项目档案id
        if(!fdProjectFileMethodList.isEmpty()&&fdProjectFileMethodList.size()>0){
            for(FdProjectFileConfirm method:fdProjectFileMethodList){
                fileIds.add(method.getProjectId());
            }
        }
    }

    /***
     * @Title:
     * @Description:TODO 方法验证号查询条件处理
     * @param code
     * @return java.util.List<java.lang.String>
     * @exception
     * @author 陈创
     * @date 2020/4/9 15:11
     * @updatehistory:
     *   2020/4/9 15:11 新增
     */
    public void validationCode(String code,List<String> fileIds){
        //查询方法号下存在的项目档案
        LambdaQueryWrapper<FdProjectFileValidation> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(FdProjectFileValidation::getCode,code);
        lambdaQueryWrapper.eq(FdProjectFileValidation::getDelFlag,"0");
        List<FdProjectFileValidation> fdProjectFileMethodList=fdProjectFileValidationService.list(lambdaQueryWrapper);
        //获取对应项目档案id
        if(!fdProjectFileMethodList.isEmpty()&&fdProjectFileMethodList.size()>0){
            for(FdProjectFileValidation method:fdProjectFileMethodList){
                fileIds.add(method.getProjectId());
            }
        }
    }

    /***
     * @Title:
            * @Description:TODO 方法样本号
            * @param [code, fileIds]
            * @return void
            * @exception
            * @author 陈创
            * @date 2020/4/22 10:14
            * @updatehistory:
     *   2020/4/22 10:14 新增
            */
    public void sampleCode(String code,List<String> fileIds){
        //查询方法号下存在的项目档案
        LambdaQueryWrapper<FdProjectFileSample> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(FdProjectFileSample::getCode,code);
        lambdaQueryWrapper.eq(FdProjectFileSample::getDelFlag,"0");
        List<FdProjectFileSample> fdProjectFileMethodList=fdProjectFileSampleService.list(lambdaQueryWrapper);
        //获取对应项目档案id
        if(!fdProjectFileMethodList.isEmpty()&&fdProjectFileMethodList.size()>0){
            for(FdProjectFileSample method:fdProjectFileMethodList){
                fileIds.add(method.getProjectId());
            }
        }
    }

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

    /**
     * 编辑
     *
     * @param fdProjectFile
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdProjectFile> edit(@RequestBody @Valid FdProjectFile fdProjectFile, BindingResult bindingResult) {
        Result<FdProjectFile> result = new Result<FdProjectFile>();
        FdProjectFile fdProjectFileEntity = fdProjectFileService.getById(fdProjectFile.getId());
        if (fdProjectFileEntity == 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;
            }
            fdProjectFileService.updateById(fdProjectFile);

        }

        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     * @Author gurui
     * @Description //TODO 根据id删除所有的
     * @Date 11:09 2019/6/18
     * @Param [id]
     **/
    @DeleteMapping(value = "/delete")
    @NotDuplicate
    @RequiresPermissions("pm-projectArchives:delete")
    public Result<FdProjectFile> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectFile> result = new Result<FdProjectFile>();
        FdProjectFile fdProjectFile = fdProjectFileService.getById(id);
        if (fdProjectFile == null) {
            result.error500("未找到对应实体");
        } else {
            fdProjectFile.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
            fdProjectFileService.updateById(fdProjectFile);
            // fdProjectFileService.deleteAll(id);
            result.success("删除成功!");

        }

        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     * @Author gurui
     * @Description //TODO 根据id删除所有的,可传入多个id,各个id用","隔开
     * @Date 11:11 2019/6/18
     * @Param [ids]
     **/
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdProjectFile> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdProjectFile> result = new Result<FdProjectFile>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.fdProjectFileService.deleteAll(ids);
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     * @Author gurui
     * @Description //TODO 通过id查询
     * @Date 14:47 2019/5/29
     * @Param [id]
     **/
    @GetMapping(value = "/queryById")
    public Result<FdProjectFile> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectFile> result = new Result<FdProjectFile>();
        // FdProjectFile fdProjectFile = fdProjectFileService.getById(id);
        FdProjectFile fdProjectFile = fdProjectFileService.myGetById(id);
        if (fdProjectFile == null) {
            result.error500("未找到对应实体");
        } else {
            //查询合同分类
            if (fdProjectFile.getContractType() != null) {
                List<String> list3 = Arrays.asList(fdProjectFile.getContractType().split(","));
                List<FdContractClass> list = fdContractClassMapper.selectBatchIds(list3);
                String ss = "";
                String ssId = "";
                for (FdContractClass fdContractClass : list) {
                    ss += fdContractClass.getName() + ",";
                    ssId += fdContractClass.getId() + ",";
                }
                if (ss.length() >= 1) {
                    ss = ss.substring(0, ss.length() - 1);
                }
                if (ssId.length() >= 1) {
                    ssId = ssId.substring(0, ssId.length() - 1);
                }
                fdProjectFile.setContractType(ss);
                fdProjectFile.setContractTypeId(ssId);
            }
            //查询基质分类
            if (fdProjectFile.getMatrixType() != null) {
                List<String> list4 = Arrays.asList(fdProjectFile.getMatrixType().split(","));
                List<FdMatrixType> typeList = fdMatrixTypeMapper.selectBatchIds(list4);
                String dd = "";
                String ddId = "";
                for (FdMatrixType fdMatrixType : typeList) {
                    dd += fdMatrixType.getName() + ",";
                    ddId += fdMatrixType.getId() + ",";
                }
                if (dd.length() >= 1) {
                    dd = dd.substring(0, dd.length() - 1);
                }
                if (ddId.length() >= 1) {
                    ddId = ddId.substring(0, ddId.length() - 1);
                }
                fdProjectFile.setMatrixType(dd);
                fdProjectFile.setMatrixTypeId(ddId);
            }
            //医院名单
            if (fdProjectFile.getHospitalName() != null) {
                List<String> list5 = Arrays.asList(fdProjectFile.getHospitalName().split(","));
                List<FdHospital> hospitalList = fdHospitalMapper.selectBatchIds(list5);
                String hh = "";
                String hhId = "";
                for (FdHospital fdHospital : hospitalList) {
                    hh += fdHospital.getName() + ",";
                    hhId += fdHospital.getId() + ",";
                }
                if (hhId.length() > 1) {
                    hh = hh.substring(0, hh.length() - 1);
                }
                if (hh.length() > 1) {
                    hhId = hhId.substring(0, hhId.length() - 1);
                }
                fdProjectFile.setPkHospital(hhId);
                fdProjectFile.setHospitalName(hh);
            }
            //来自人员表
            LambdaQueryWrapper<FdPersonnel> queryBd = new LambdaQueryWrapper<>();
            queryBd.eq(FdPersonnel::getId, fdProjectFile.getBd());
            List<FdPersonnel> list6 = fdPersonnelService.list(queryBd);
            for (FdPersonnel fdPersonnel : list6) {
                fdProjectFile.setBdId(fdPersonnel.getName());
            }
            LambdaQueryWrapper<FdPersonnel> queryclinicalPi = new LambdaQueryWrapper<>();
            queryclinicalPi.eq(FdPersonnel::getId, fdProjectFile.getClinicalPi());
            List<FdPersonnel> list7 = fdPersonnelService.list(queryclinicalPi);
            for (FdPersonnel fdPersonnel : list7) {
                fdProjectFile.setClinicalPiId(fdPersonnel.getName());
            }
            LambdaQueryWrapper<FdPersonnel> queryclinicalPm = new LambdaQueryWrapper<>();
            queryclinicalPm.eq(FdPersonnel::getId, fdProjectFile.getClinicalPm());
            List<FdPersonnel> list8 = fdPersonnelService.list(queryclinicalPm);
            for (FdPersonnel fdPersonnel : list8) {
                fdProjectFile.setClinicalPmId(fdPersonnel.getName());
            }
            LambdaQueryWrapper<FdPersonnel> queryInvestigator = new LambdaQueryWrapper<>();
            queryInvestigator.eq(FdPersonnel::getId, fdProjectFile.getInvestigator());
            List<FdPersonnel> list9 = fdPersonnelService.list(queryInvestigator);
            for (FdPersonnel fdPersonnel : list9) {
                fdProjectFile.setInvestigatorId(fdPersonnel.getName());
            }
            LambdaQueryWrapper<FdPersonnel> queryBioanalyticalPm = new LambdaQueryWrapper<>();
            queryBioanalyticalPm.eq(FdPersonnel::getId, fdProjectFile.getBioanalyticalPm());
            List<FdPersonnel> list10 = fdPersonnelService.list(queryBioanalyticalPm);
            for (FdPersonnel fdPersonnel : list10) {
                fdProjectFile.setBioanalyticalPmId(fdPersonnel.getName());
            }
            LambdaQueryWrapper<FdPersonnel> queryAssistant = new LambdaQueryWrapper<>();
            queryAssistant.eq(FdPersonnel::getId, fdProjectFile.getAssistant());
            List<FdPersonnel> list11 = fdPersonnelService.list(queryAssistant);
            for (FdPersonnel fdPersonnel : list11) {
                fdProjectFile.setAssistantId(fdPersonnel.getName());
            }
            //合同号
            LambdaQueryWrapper<FdContract> queryContract = new LambdaQueryWrapper<>();
            queryContract.eq(FdContract::getId, fdProjectFile.getContractId());
            List<FdContract> list1 = fdContractService.list(queryContract);
            for (FdContract fdContract : list1) {
                fdProjectFile.setContractCode(fdContract.getCode());
            }

            //化合物查询条件
            LambdaQueryWrapper<FdProjectFileCompound> queryCompound = new LambdaQueryWrapper<>();
            queryCompound.eq(FdProjectFileCompound::getProjectId, fdProjectFile.getId());
            queryCompound.eq(FdProjectFileCompound::getDelFlag,"0");
            queryCompound.orderByAsc(FdProjectFileCompound::getSort);
            List<FdProjectFileCompound> compoundList = fdProjectFileCompoundService.list(queryCompound);
            String compound="";
            int i=0;
            for (FdProjectFileCompound compounds : compoundList) {
                if(i==0){
                    compound=compounds.getCompound();
                }else{
                    compound=compound+","+compounds.getCompound();
                }
                i++;
//                if (oConvertUtils.isNotEmpty(compounds.getSort()) && compounds.getSort().equals("1")) {
//                    fdProjectFile.setCompound(compounds.getCompound());
//                }
            }
            fdProjectFile.setCompound(compound);
            //联系人查询条件
            LambdaQueryWrapper<FdProjectFileContacts> queryContacts = new LambdaQueryWrapper<>();
            queryContacts.eq(FdProjectFileContacts::getProjectId, fdProjectFile.getId());
            queryContacts.eq(FdProjectFileContacts::getIsDefault, "1");
            List<FdProjectFileContacts> contactsList = fdProjectFileContactsService.list(queryContacts);
            for (FdProjectFileContacts contacts : contactsList) {
                fdProjectFile.setContactPsn(contacts.getContactPsn());
                fdProjectFile.setContactTel(contacts.getContactTel());
                fdProjectFile.setContactEmail(contacts.getEmail());
            }
            Map<String, Object> msp = Maps.newHashMap();
            msp.put("del_flag", "0");
            msp.put("project_id", fdProjectFile.getId());
//            List<FdProjectFileCompound> fdProjectFileCompounds = (List<FdProjectFileCompound>) fdProjectFileCompoundService.listByMap(msp);
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdProjectFileCompound::getProjectId,fdProjectFile.getId());
            queryWrapper.eq(FdProjectFileCompound::getDelFlag,"0");
            queryWrapper.orderByAsc(FdProjectFileCompound::getSort);
            List<FdProjectFileCompound> fdProjectFileCompounds = fdProjectFileCompoundService.list(queryWrapper);
            fdProjectFile.setFdProjectFileCompoundList(fdProjectFileCompounds);
//            List<FdProjectFileContacts> fdProjectFileContacts = (List<FdProjectFileContacts>) fdProjectFileContactsService.listByMap(msp);
//            fdProjectFile.setFdProjectFileContactsList(fdProjectFileContacts);
//            List<FdProjectFileMembers> fdProjectFileMembers = (List<FdProjectFileMembers>) fdProjectFileMembersService.listByMap(msp);
//            fdProjectFile.setFdProjectFileMembersList(fdProjectFileMembers);

            LambdaQueryWrapper<FdProjectFileMembers> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(FdProjectFileMembers::getDelFlag,"0");
            queryWrapper1.eq(FdProjectFileMembers::getProjectId,fdProjectFile.getId());
            queryWrapper1.orderByAsc(FdProjectFileMembers::getMembersIndex);
            List<FdProjectFileMembers> fdProjectFileMembersList = fdProjectFileMembersService.list(queryWrapper1);
            fdProjectFile.setFdProjectFileMembersList(fdProjectFileMembersList);

            LambdaQueryWrapper<FdProjectFileContacts> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(FdProjectFileContacts::getDelFlag,"0");
            queryWrapper2.eq(FdProjectFileContacts::getProjectId,fdProjectFile.getId());
            queryWrapper2.orderByAsc(FdProjectFileContacts::getContactsIndex);
            List<FdProjectFileContacts> fdProjectFileContactsList = fdProjectFileContactsService.list(queryWrapper2);
            fdProjectFile.setFdProjectFileContactsList(fdProjectFileContactsList);

            List<FdProjectFileBidparty> fdProjectFileBidparty = (List<FdProjectFileBidparty>) fdProjectFileBidpartyService.listByMap(msp);
            fdProjectFile.setFdProjectFileBidpartyList(fdProjectFileBidparty);
//            List<FdProjectFileMethod> fdProjectFileMethods = (List<FdProjectFileMethod>) fdProjectFileMethodService.listByMap(msp);
//            fdProjectFile.setFdProjectFileMethodList(fdProjectFileMethods);
//            List<FdProjectFileConfirm> fdProjectFileConfirms = (List<FdProjectFileConfirm>) fdProjectFileConfirmService.listByMap(msp);
//            fdProjectFile.setFdProjectFileConfirmList(fdProjectFileConfirms);
//            List<FdProjectFileValidation> fdProjectFileValidations = (List<FdProjectFileValidation>) fdProjectFileValidationService.listByMap(msp);
//            fdProjectFile.setFdProjectFileValidationList(fdProjectFileValidations);
//            List<FdProjectFileSample> fdProjectFileSamples = (List<FdProjectFileSample>) fdProjectFileSampleService.listByMap(msp);
//            fdProjectFile.setFdProjectFileSampleList(fdProjectFileSamples);

            LambdaQueryWrapper<FdProjectFileMethod> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(FdProjectFileMethod::getProjectId,fdProjectFile.getId());
            queryWrapper3.orderByAsc(FdProjectFileMethod::getSort);
            List<FdProjectFileMethod> fdProjectFileMethodList = fdProjectFileMethodService.list(queryWrapper3);
            fdProjectFile.setFdProjectFileMethodList(fdProjectFileMethodList);

            LambdaQueryWrapper<FdProjectFileConfirm> queryWrapper4 = new LambdaQueryWrapper<>();
            queryWrapper4.eq(FdProjectFileConfirm::getProjectId,fdProjectFile.getId());
            queryWrapper4.orderByAsc(FdProjectFileConfirm::getSort);
            List<FdProjectFileConfirm> fdProjectFileConfirmList = fdProjectFileConfirmService.list(queryWrapper4);
            fdProjectFile.setFdProjectFileConfirmList(fdProjectFileConfirmList);

            LambdaQueryWrapper<FdProjectFileValidation> queryWrapper5 = new LambdaQueryWrapper<>();
            queryWrapper5.eq(FdProjectFileValidation::getProjectId,fdProjectFile.getId());
            queryWrapper5.orderByAsc(FdProjectFileValidation::getSort);
            List<FdProjectFileValidation> fdProjectFileValidationList = fdProjectFileValidationService.list(queryWrapper5);
            fdProjectFile.setFdProjectFileValidationList(fdProjectFileValidationList);

            LambdaQueryWrapper<FdProjectFileSample> queryWrapper6 = new LambdaQueryWrapper<>();
            queryWrapper6.eq(FdProjectFileSample::getProjectId,fdProjectFile.getId());
            queryWrapper6.orderByAsc(FdProjectFileSample::getSort);
            List<FdProjectFileSample> fdProjectFileSampleList = fdProjectFileSampleService.list(queryWrapper6);
            fdProjectFile.setFdProjectFileSampleList(fdProjectFileSampleList);

            List<FdProjectFileUpload> fdProjectFileUploads = (List<FdProjectFileUpload>) fdProjectFileUploadService.listByMap(msp);
            fdProjectFile.setFdProjectFileUploadList(fdProjectFileUploads);

            result.setResult(fdProjectFile);
            result.setSuccess(true);
        }
        return result;
    }

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdProjectFile> pageList = fdProjectFileService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "项目档案列表");
        mv.addObject(NormalExcelConstants.CLASS, FdProjectFile.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<FdProjectFile> listFdProjectFiles = ExcelImportUtil.importExcel(file.getInputStream(), FdProjectFile.class, params);
                for (FdProjectFile fdProjectFileExcel : listFdProjectFiles) {
                    fdProjectFileService.save(fdProjectFileExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdProjectFiles.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     * @Author gurui
     * @Description //TODO 保存所有的表
     * @Date 10:21 2019/5/29
     * @Param [fdProjectFile, bindingResult]
     **/
    @PostMapping(value = "/addProjectFile")
    @NotDuplicate
    @RequiresPermissions(value = {"pm-projectArchives:add","pm-projectArchives:update"},logical = Logical.OR)
    public Result<FdProjectFile> addProjectFile(@RequestBody @Valid FdProjectFile fdProjectFile, BindingResult bindingResult) {
        Result<FdProjectFile> result = new Result<FdProjectFile>();
        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 (oConvertUtils.isEmpty(fdProjectFile)) {
                throw new RuntimeException("项目档案不能为空");
            }
            //项目成员不能为空
            if(fdProjectFile.getFdProjectFileMembersList().isEmpty()||fdProjectFile.getFdProjectFileMembersList().size()<=0){
                result.setSuccess(true);
                result.setMessage("pm.project.archives.project.members.At.least.one");
                return result;
            }
            LambdaQueryWrapper<FdProjectFile> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(FdProjectFile::getContractId,fdProjectFile.getContractId());
            lambdaQueryWrapper.eq(FdProjectFile::getDelFlag,"0");
            lambdaQueryWrapper.eq(FdProjectFile::getProjectFileNo,fdProjectFile.getProjectFileNo());
            FdProjectFile fdProjectFile1=fdProjectFileService.getOne(lambdaQueryWrapper);
            //新增时进入
            if(oConvertUtils.isEmpty(fdProjectFile.getId())){
                if(fdProjectFile1!=null){
                    // throw new RuntimeException("项目档案已经存在现有合同");
                    result.error500("项目档案已经存在现有合同");
                    return result;
                }
                //查询是否有相同合同号
                // int size=fdProjectFileService.fileContractIdentical(fdProjectFile.getContractId());
                // if(size>0){
                //
                // }
            }else{//修改时进入
                if(fdProjectFile1!=null&&!fdProjectFile1.getId().equals(fdProjectFile.getId())){
                    // throw new RuntimeException("项目档案已经存在现有合同");
                    result.error500("项目档案已经存在现有合同");
                    return result;
                }
            }
            fdProjectFileService.addProjectFile(fdProjectFile);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     * @Author gurui
     * @Description //TODO 根据id删除化合物
     * @Date 17:26 2019/6/13
     * @Param [id]
     **/
    @DeleteMapping(value = "/deleteCompound")
    public Result<FdProjectFile> deleteCompound(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectFile> result = new Result<FdProjectFile>();
        FdProjectFile fdProjectFile = fdProjectFileService.getById(id);
        if (fdProjectFile == null) {
            result.error500("未找到对应实体");
        } else {
            fdProjectFileService.deleteCompound(id);

            result.success("删除成功!");

        }

        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     * @Author gurui
     * @Description //TODO 根据id删除联系人
     * @Date 17:26 2019/6/13
     * @Param [id]
     **/
    @DeleteMapping(value = "/deleteContracts")
    public Result<FdProjectFile> deleteContracts(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectFile> result = new Result<FdProjectFile>();
        FdProjectFile fdProjectFile = fdProjectFileService.getById(id);
        if (fdProjectFile == null) {
            result.error500("未找到对应实体");
        } else {
            fdProjectFileService.deleteContracts(id);
            result.success("删除成功!");
        }

        return result;
    }

    /***
     * @Title:查询成员
     * @Description:TODO
     * @param
     * @return org.jeecg.common.api.vo.Result<java.util.List < org.jeecg.modules.basedata.entity.FdPersonnel>>
     * @exception
     * @author 陈创
     * @date 2019/7/2 14:12
     * @updatehistory:
     *   2019/7/2 14:12 新增
     */
    @GetMapping(value = "getPersonnelList")
    public Result<List<FdPersonnel>> getPersonnelList() {
        Result<List<FdPersonnel>> result = new Result<>();
        List<FdPersonnel> fdPersonnelList = fdProjectFileService.getPersonnelList();
        result.setResult(fdPersonnelList);
        return result;
    }


    /**
     * @Author gurui
     * @Description //TODO  弃审核数据,使其状态为0
     * @Date 19:51 2019/7/4
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     **/
    @GetMapping(value = "/auditBatch")
    public Result<FdProjectFile> auditBatch(@RequestParam(name="ids",required = true) List<String> ids){
        Result<FdProjectFile> result=new Result<>();
        String message="";
        if(ids.isEmpty()){
            message+="请选择数据</br>";
        }
        Map<String,Object> map= null;
        try {
            //执行service
            map = fdProjectFileService.auditBatch(ids);
            result.setSuccess(true);
            result.setMessage(message+map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO 审核数据,使其状态为1
     * @Date 19:51 2019/7/4
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     **/
    @GetMapping(value = "/reviewBatch")
    public Result<FdProjectFile> reviewBatch(@RequestParam(name="ids",required = true) List<String> ids){
        Result<FdProjectFile> result=new Result<>();
        String message="";
        if(ids.isEmpty()){
            message+="请选择数据</br>";
        }
        Map<String,Object> map= null;
        try {
            //执行service
            map = fdProjectFileService.reviewBatch(ids);
            result.setSuccess(true);
            result.setMessage(message+map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * @Author gurui
     * @Description //TODO 状态关闭,使其状态为2
     * @Date 19:50 2019/7/4
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     **/
    @GetMapping(value = "/closeBatch")
    public Result<FdProjectFile> closeBatch(@RequestParam(name="ids",required = true) List<String> ids){
        Result<FdProjectFile> result=new Result<>();
        String message="";
        if(ids.isEmpty()){
            message+="请选择数据</br>";
        }
        Map<String,Object> map= null;
        try {
            //执行service
            map = fdProjectFileService.closeBatch(ids);
            result.setSuccess(true);
            result.setMessage(message+map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO 根据id复制一条信息
     * @Date 9:14 2019/7/5
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     **/
    @PostMapping(value = "/copy")
    @NotDuplicate
    public Result<FdProjectFile> copy(@RequestBody String id) {
        Result<FdProjectFile> result = new Result<>();
        try {
            fdProjectFileService.copy(id);
            result.success("复制成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }


    /**
     * @Author gurui
     * @Description //TODO  查询项目档案各个状态下的数量 以及总数量
     * @Date 下午 1:58 23/9/2019
     * @Param []
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectFile>
     **/
    @GetMapping(value = "/queryStatusNum")
    public Result<FdProjectFile> queryStatusNum() {
        Result<FdProjectFile> result = new Result<FdProjectFile>();
        //分别获取不同状态下的项目档案数量
        Integer status0 = fdProjectFileService.queryStatus0();
        Integer status1 = fdProjectFileService.queryStatus1();
        Integer status2 = fdProjectFileService.queryStatus2();
        Integer status3 = fdProjectFileService.queryStatus3();
        Integer status4 = fdProjectFileService.queryStatus4();
        //总数量
        int sum = status0+status1+status2+status3+status4;
        //存入集合 0未启动1进行中2已完结3已交付4挂起
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map0 = new HashMap<>();
        map0.put("x","未启动");
        map0.put("y",status0);
        Map<String,Object> map1 = new HashMap<>();
        map1.put("x","进行中");
        map1.put("y",status1);
        Map<String,Object> map2 = new HashMap<>();
        map2.put("x","已完结");
        map2.put("y",status2);
        Map<String,Object> map3 = new HashMap<>();
        map3.put("x","已交付");
        map3.put("y",status3);
        Map<String,Object> map4 = new HashMap<>();
        map4.put("x","挂起");
        map4.put("y",status4);
        list.add(map0);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        FdProjectFile fdProjectFile = new FdProjectFile();
        fdProjectFile.setStatusList(list);
        fdProjectFile.setSum(sum);
        if (fdProjectFile == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(fdProjectFile);
            result.setSuccess(true);
        }
        return result;
    }

    /***
     * @Title:选择合同的id查询档案对象
            * @Description:TODO
            * @param contractId
            * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdProjectFile>>
            * @exception 
            * @author 陈创
            * @date 2019/12/6 11:37
            * @updatehistory:
     *   2019/12/6 11:37 新增
            */
    @GetMapping("/selectContractById")
    public Result<FdProjectFile> selectContractById(String contractId){
        Result<FdProjectFile> result=new Result<>();

        try {
            FdProjectFile fdProjectFile= fdProjectFileService.selectContractById(contractId);
            result.setResult(fdProjectFile);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }



}
