package org.jeecg.modules.projectManagement.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 com.baomidou.mybatisplus.core.conditions.Wrapper;
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.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.controller.FdPersonnelController;
import org.jeecg.modules.basedata.entity.*;
import org.jeecg.modules.basedata.mapper.FdContractClassMapper;
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.entity.*;
import org.jeecg.modules.projectManagement.mapper.FdProjectFileMapper;
import org.jeecg.modules.projectManagement.mapper.FdProjectQuotationMapper;
import org.jeecg.modules.projectManagement.service.*;
import org.jeecg.modules.projectManagement.vo.StatementJOSN;
import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysAnnouncementSend;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysSerialPatternService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.vo.CallResult;
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-20
 * @version： V1.0
 */
@RestController
@RequestMapping("/projectManagement/fdProjectQuotation")
@Slf4j
public class FdProjectQuotationController {
    @Autowired
    private IFdProjectQuotationService fdProjectQuotationService;
    @Autowired
    private IFdProjectQuotationContactsService fdProjectQuotationContactsService;
    @Autowired
    private IFdProjectQuotationCompoundService fdProjectQuotationCompoundService;
    @Autowired
    private IFdProjectQuotationCommentsService fdProjectQuotationCommentsService;
    @Resource
    private IFdCustomerService fdCustomerService;
    @Resource
    private IFdCustomerContactsService fdCustomerContactsService;
    @Resource
    private FdProjectQuotationMapper fdProjectQuotationMapper;
    @Resource
    private FdMatrixTypeMapper fdMatrixTypeMapper;
    @Resource
    private FdContractClassMapper fdContractClassMapper;

    @Resource
    private IFdPersonnelService fdPersonnelService;
    @Resource
    private ISysSerialPatternService sysSerialPatternService;
    @Resource
    private SysRoleController sysRoleController;
    @Resource
    private FdPersonnelController fdPersonnelController;

    @Resource
    private IFdProjectFileMethodService fdProjectFileMethodService;
    @Resource
    private IFdProjectFileConfirmService fdProjectFileConfirmService;
    @Resource
    private IFdProjectFileValidationService fdProjectFileValidationService;
    @Resource
    private IFdProjectFileSampleService fdProjectFileSampleService;

    @Resource
    private IFdProjectFileService fdProjectFileService;
    @Resource
    private FdProjectFileMapper fdProjectFileMapper;


    /**
     * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage       <       org.jeecg.modules.projectManagement.entity.FdProjectQuotation>>
     * @Author gurui
     * @Description //TODO  连接查询展示数据
     * @Date 9:45 2019/5/21
     * @Param [fdProjectQuotation, pageNo, pageSize, req]
     **/
    @GetMapping(value = "/list")
    @RequiresPermissions("url:pm-quotation:view")
    public Result<IPage<FdProjectQuotation>> queryPageList(FdProjectQuotation fdProjectQuotation,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<FdProjectQuotation>> result = new Result<IPage<FdProjectQuotation>>();
        //编码
        String code = fdProjectQuotation.getCode();
        if (StringUtils.isNotBlank(fdProjectQuotation.getCode())) {
            fdProjectQuotation.setCode(null);
        }
        //名称
        String name = fdProjectQuotation.getName();
        if (StringUtils.isNotBlank(name)) {
            fdProjectQuotation.setName(null);
        }
        //申办方id
        String pkCustomerId = fdProjectQuotation.getPkCustomerId();
        if (pkCustomerId != null) {
            if (fdProjectQuotation.getPkCustomerId().equals("null")) {
                fdProjectQuotation.setPkCustomerId(null);
            }
        }
        //化合物名称
        String compoundName = fdProjectQuotation.getCompoundName();
        if (StringUtils.isNotBlank(compoundName)) {
            fdProjectQuotation.setCompoundName(null);
        }
        //关联报价号
        String relationCode= fdProjectQuotation.getRelationCode();
        if(StringUtils.isNotBlank(relationCode)){
            fdProjectQuotation.setRelationCode(null);
        }
        //年份
        String year=fdProjectQuotation.getYear();
        if(StringUtils.isNotBlank(year)){
            fdProjectQuotation.setYear(null);
        }
        //报价类型
        String quotationType=fdProjectQuotation.getQuotationType();
        if(StringUtils.isNotBlank(quotationType)){
            fdProjectQuotation.setQuotationType(null);
        }
        QueryWrapper<FdProjectQuotation> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectQuotation, req.getParameterMap());
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("fpq.code", code);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("fpq.name", name);
        }
        if (StringUtils.isNotBlank(compoundName)) {
            queryWrapper.like("fpq.compound_name", compoundName);
        }
        if(StringUtils.isNotBlank(relationCode)){
            queryWrapper.like("fpq.relation_code",relationCode);
        }
        if(StringUtils.isNotBlank(year)){
            queryWrapper.eq("YEAR(fpq.quotation_date)", year);
        }
        if(StringUtils.isNotBlank(quotationType)&&!quotationType.equals("null")){
            queryWrapper.like("fpq.quotation_type",quotationType);
        }
        queryWrapper.eq("fpq.del_flag", "0");
        queryWrapper.orderByDesc("fpq.create_time");
        queryWrapper.orderByDesc("fpq.code");
        Page<FdProjectQuotation> page = new Page<FdProjectQuotation>(pageNo, pageSize);
        IPage<FdProjectQuotation> pageList = fdProjectQuotationService.findByPage(page, queryWrapper);
        //获取待审核人
        getPendingAuditorNames(pageList);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /***
     * @Title:大分子查询
     * @Description:TODO
     * @param fdProjectQuotation, pageNo, pageSize, req]
     * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage < org.jeecg.modules.projectManagement.entity.FdProjectQuotation>>
     * @exception
     * @author 陈创
     * @date 2019/11/12 18:21
     * @updatehistory:
     *   2019/11/12 18:21 新增
     */
    @GetMapping(value = "/listMacromolecule")
    @RequiresPermissions("url:pm-macromolecule:view")
    public Result<IPage<FdProjectQuotation>> listMacromolecule(FdProjectQuotation fdProjectQuotation,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize,
                                                               HttpServletRequest req) {
        Result<IPage<FdProjectQuotation>> result = new Result<IPage<FdProjectQuotation>>();
        //编码
        String code = fdProjectQuotation.getCode();
        if (StringUtils.isNotBlank(fdProjectQuotation.getCode())) {
            fdProjectQuotation.setCode(null);
        }
        //名称
        String name = fdProjectQuotation.getName();
        if (StringUtils.isNotBlank(name)) {
            fdProjectQuotation.setName(null);
        }
        //申办方id
        String pkCustomerId = fdProjectQuotation.getPkCustomerId();
        if (pkCustomerId != null) {
            if (fdProjectQuotation.getPkCustomerId().equals("null")) {
                fdProjectQuotation.setPkCustomerId(null);
            }
        }
        //化合物名称
        String compoundName = fdProjectQuotation.getCompoundName();
        if (StringUtils.isNotBlank(compoundName)) {
            fdProjectQuotation.setCompoundName(null);
        }
        //关联报价号
        String relationCode= fdProjectQuotation.getRelationCode();
        if(StringUtils.isNotBlank(relationCode)){
            fdProjectQuotation.setRelationCode(null);
        }
        //年份
        String year=fdProjectQuotation.getYear();
        if(StringUtils.isNotBlank(year)){
            fdProjectQuotation.setYear(null);
        }
        //报价类型
        String quotationType=fdProjectQuotation.getQuotationType();
        if(StringUtils.isNotBlank(quotationType)){
            fdProjectQuotation.setQuotationType(null);
        }
        QueryWrapper<FdProjectQuotation> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectQuotation, req.getParameterMap());
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("fpq.code", code);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("fpq.name", name);
        }
        if (StringUtils.isNotBlank(compoundName)) {
            queryWrapper.like("fpq.compound_name", compoundName);
        }
        if(StringUtils.isNotBlank(relationCode)){
            queryWrapper.like("fpq.relation_code",relationCode);
        }
        if(StringUtils.isNotBlank(year)){
            queryWrapper.eq("YEAR(fpq.quotation_date)", year);
        }
        if(StringUtils.isNotBlank(quotationType)&&!quotationType.equals("null")){
            queryWrapper.like("fpq.quotation_type",quotationType);
        }
        queryWrapper.eq("fpq.del_flag", "0");
        queryWrapper.orderByDesc("fpq.create_time");
        queryWrapper.orderByDesc("fpq.code");
        Page<FdProjectQuotation> page = new Page<FdProjectQuotation>(pageNo, pageSize);
        IPage<FdProjectQuotation> pageList = fdProjectQuotationService.findByPage(page, queryWrapper);
        //获取待审核人
        getPendingAuditorNames(pageList);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /***
     * @Title:
     * @Description:TODO 获取待审核人员
     * @param pageList
     * @return void
     * @exception
     * @author 陈创
     * @date 2019/12/19 11:06
     * @updatehistory:
     *   2019/12/19 11:06 查询
     */
    public void getPendingAuditorNames(IPage<FdProjectQuotation> pageList) {
        List<FdProjectQuotation> fdProjectQuotationList = pageList.getRecords();
        if (!fdProjectQuotationList.isEmpty() && fdProjectQuotationList.size() > 0) {
            for (FdProjectQuotation projectQuotation : fdProjectQuotationList) {
                String pendingAuditorName = "";
                //临床部分审核人
                if (projectQuotation.getIsClinicalSectionExamine().equals("0")) {
                    pendingAuditorName += projectQuotation.getClinicalSectionName() + "、";
                }
                //中心价格部分审核人
                if (projectQuotation.getIsCentralPriceExamine().equals("0")) {
                    pendingAuditorName += projectQuotation.getCentralPriceName() + "、";
                }
                //数据统计部分审核人
                if (projectQuotation.getIsDataStatisticsExamine().equals("0")) {
                    pendingAuditorName += projectQuotation.getDataStatisticsName() + "、";
                }
                //PK部分审核人
                if (projectQuotation.getIsPkComputingExamine().equals("0")) {
                    pendingAuditorName += projectQuotation.getPkComputingName() + "、";
                }
                //生物分析部分审核人
                if (projectQuotation.getIsBioanalysisExamine().equals("0")) {
                    pendingAuditorName += projectQuotation.getBioanalysisName() + "、";
                }
                //总经理审核人
                if (projectQuotation.getIsGeneralExamine().equals("0")&&projectQuotation.getGeneralManagerName()!=null) {
                    pendingAuditorName += projectQuotation.getGeneralManagerName();
                }
                if (StringUtils.isEmpty(pendingAuditorName)) {
                    pendingAuditorName = "已结束";
                }
                //记录待审核人
                projectQuotation.setPendingAuditorNames(pendingAuditorName);
            }
        }
    }

    /***
     * @Title:
            * @Description:TODO 工时通过查询条件查询相关报价数据
            * @param fdProjectQuotation, pageNo, pageSize, req]
            * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>>
            * @exception
            * @author 陈创
            * @date 2020/4/8 17:58
            * @updatehistory:
     *   2020/4/8 17:58 新增
            */
    @GetMapping(value = "/queryPageListNoAuthority")
    public Result<IPage<FdProjectQuotation>> queryPageListNoAuthority(FdProjectQuotation fdProjectQuotation,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<FdProjectQuotation>> result = new Result<IPage<FdProjectQuotation>>();
        //编码
        String code = fdProjectQuotation.getCode();
        if (StringUtils.isNotBlank(fdProjectQuotation.getCode())) {
            fdProjectQuotation.setCode(null);
        }
        //名称
        String name = fdProjectQuotation.getName();
        if (StringUtils.isNotBlank(name)) {
            fdProjectQuotation.setName(null);
        }
        //申办方id
        String pkCustomerId = fdProjectQuotation.getPkCustomerId();
        if (pkCustomerId != null) {
            if (fdProjectQuotation.getPkCustomerId().equals("null")) {
                fdProjectQuotation.setPkCustomerId(null);
            }
        }
        //最终申办方名称
        String sponsorName=fdProjectQuotation.getSponsorName();
        if(StringUtils.isNotBlank(sponsorName)){
            fdProjectQuotation.setSponsorName(null);
        }
        //化合物名称
        String compoundName = fdProjectQuotation.getCompoundName();
        if (StringUtils.isNotBlank(compoundName)) {
            fdProjectQuotation.setCompoundName(null);
        }
        //关联报价号
        String relationCode= fdProjectQuotation.getRelationCode();
        if(StringUtils.isNotBlank(relationCode)){
            fdProjectQuotation.setRelationCode(null);
        }

        //是否输入号码
        boolean isCode=false;
        //项目档案ids
        List<String> fileIds=new ArrayList<>();
        //方法号
        String methodCode=fdProjectQuotation.getMethodCode();
        //根据方法号获取相关项目档案id
        if(StringUtils.isNotBlank(methodCode)){
            isCode=true;
            fdProjectQuotation.setMethodCode(null);
            methodCode(methodCode,fileIds);//获取项目档案号
        }
        //项目确认号
        String confirmCode=fdProjectQuotation.getConfirmCode();
        //根据项目确认号获取项目档案id
        if(StringUtils.isNotBlank(confirmCode)){
            isCode=true;
            fdProjectQuotation.setConfirmCode(null);
            confirmCode(confirmCode,fileIds);//项目档案号
        }
        //方法验证号
        String validationCode=fdProjectQuotation.getValidationCode();
        //根据项目确认号获取项目档案id
        if(StringUtils.isNotBlank(validationCode)){
            isCode=true;
            fdProjectQuotation.setValidationCode(null);
            validationCode(validationCode,fileIds);//项目档案号
        }
        //样本分析号
        String sampleCode=fdProjectQuotation.getSampleCode();
        //根据项目确认号获取项目档案id
        if(StringUtils.isNotBlank(sampleCode)){
            isCode=true;
            fdProjectQuotation.setSampleCode(null);
            sampleCode(sampleCode,fileIds);//项目档案号
        }

        //药品名
        //项目档案条件查询
        if(StringUtils.isNotBlank(fdProjectQuotation.getDrugName())){
            selectFild(fdProjectQuotation,fileIds);
            isCode=true;
        }

        //临床方案号
        if(StringUtils.isNotBlank(fdProjectQuotation.getClinicalCode())){
            selectFild(fdProjectQuotation,fileIds);
            isCode=true;
        }


        //根据项目档案id获取报价id
        //报价ids
        List<String> quotationIds=new ArrayList<>();
        if(fileIds.size()>0){
            quotationIds=getQuotationIdByFileIds(fileIds);
        }

        QueryWrapper<FdProjectQuotation> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectQuotation, req.getParameterMap());
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("fpq.code", code);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("fpq.name", name);
        }
        if (StringUtils.isNotBlank(compoundName)) {
            queryWrapper.like("fpq.compound_name", compoundName);
        }
        if(StringUtils.isNotBlank(relationCode)){
            queryWrapper.like("fpq.relation_code",relationCode);
        }
        if(StringUtils.isNotBlank(sponsorName)){
            queryWrapper.like("fpq.sponsor_name",sponsorName);
        }

        //是否存在号码的条件筛选
        if(isCode){
            if(quotationIds.size()>0){//通过号码查询出了报价id
                HashSet h2 = new HashSet(quotationIds);
                quotationIds.clear();
                quotationIds.addAll(h2);
                queryWrapper.in("fpq.id",quotationIds);
            }else{//没有查询出来则不查出数据
                queryWrapper.eq("fpq.id","无");
            }
        }

        queryWrapper.eq("fpq.del_flag", "0");
        queryWrapper.orderByDesc("fpq.create_time");
        queryWrapper.orderByDesc("fpq.code");
        Page<FdProjectQuotation> page = new Page<FdProjectQuotation>(pageNo, pageSize);
        IPage<FdProjectQuotation> pageList = fdProjectQuotationService.findByPage(page, queryWrapper);
        //获取待审核人
        getPendingAuditorNames(pageList);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    //根据查询条件获取项目档案id
    public void selectFild(FdProjectQuotation fdProjectQuotation,List<String> fileIds){
        boolean isSelect=false;
        //根据条件查询项目档案
        LambdaQueryWrapper<FdProjectFile> fileLambdaQueryWrapper=new LambdaQueryWrapper<>();
        fileLambdaQueryWrapper.eq(FdProjectFile::getDelFlag,"0");
        //药品名
        String drugName=fdProjectQuotation.getDrugName();
        if(StringUtils.isNotBlank(drugName)){
            fdProjectQuotation.setDrugName(null);
            fileLambdaQueryWrapper.like(FdProjectFile::getDrugName,drugName);
            isSelect=true;
        }

        //临床方案号
        String clinicalCode=fdProjectQuotation.getClinicalCode();
        if(StringUtils.isNotBlank(clinicalCode)){
            fdProjectQuotation.setClinicalCode(null);
            fileLambdaQueryWrapper.like(FdProjectFile::getClinicalCode,clinicalCode);
            isSelect=true;
        }

        //是否参与了查询条件
        if(isSelect){
            List<FdProjectFile> fdProjectFileList=fdProjectFileMapper.selectList(fileLambdaQueryWrapper);
            if(fdProjectFileList!=null&&fdProjectFileList.size()>0){
                for(FdProjectFile fdProjectFile:fdProjectFileList){
                    fileIds.add(fdProjectFile.getId());
                }
            }
        }

    }

    /***
     * @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 methodCode(String code,List<String> fileIds){
        // List<String> fileIds=new ArrayList<>();
        //查询方法号下存在的项目档案
        LambdaQueryWrapper<FdProjectFileMethod> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(FdProjectFileMethod::getCode,code);
        lambdaQueryWrapper.eq(FdProjectFileMethod::getDelFlag,"0");
        List<FdProjectFileMethod> fdProjectFileMethodList=fdProjectFileMethodService.list(lambdaQueryWrapper);
        //获取对应项目档案id
        if(!fdProjectFileMethodList.isEmpty()&&fdProjectFileMethodList.size()>0){
            for(FdProjectFileMethod method:fdProjectFileMethodList){
                fileIds.add(method.getProjectId());
            }
            // return fileIds;
        }
        // //字符去重
        // if(fileIds.size()>0){
        //     HashSet h = new HashSet(fileIds);
        //     fileIds.clear();
        //     fileIds.addAll(h);
        //     //项目档案数据
        //     List<String> quotationIds=fdProjectQuotationService.getQuotationIdsByfileIds(fileIds);
        //     if(!quotationIds.isEmpty()&&quotationIds.size()>0){
        //         // HashSet h2 = new HashSet(quotationIds);
        //         // quotationIds.clear();
        //         // quotationIds.addAll(h2);
        //         return quotationIds;
        //     }
        // }
        // return null;
    }

    /***
     * @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
     * @return java.util.List<java.lang.String>
     * @exception
     * @author 陈创
     * @date 2020/4/9 15:11
     * @updatehistory:
     *   2020/4/9 15:11 新增
     */
    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());
            }
        }
    }

    /***
     * @Title:
            * @Description:TODO 根据档案id获取报价id
            * @param fileIds
            * @return java.util.List<java.lang.String>
            * @exception
            * @author 陈创
            * @date 2020/4/9 15:35
            * @updatehistory:
     *   2020/4/9 15:35 新增
            */
    public List<String> getQuotationIdByFileIds(List<String> fileIds){
        //字符去重
        if(fileIds.size()>0){
            HashSet h = new HashSet(fileIds);
            fileIds.clear();
            fileIds.addAll(h);
            //项目档案数据
            List<String> quotationIds=fdProjectQuotationService.getQuotationIdsByfileIds(fileIds);
            if(!quotationIds.isEmpty()&&quotationIds.size()>0){
                // HashSet h2 = new HashSet(quotationIds);
                // quotationIds.clear();
                // quotationIds.addAll(h2);
                return quotationIds;
            }
        }
        return null;
    }
    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @Author gurui
     * @Description //TODO 添加
     * @Date 9:47 2019/5/21
     * @Param [fdProjectQuotation, bindingResult]
     **/
    @PostMapping(value = "/add")
    @NotDuplicate
    public Result<FdProjectQuotation> add(@RequestBody @Valid FdProjectQuotation fdProjectQuotation, BindingResult bindingResult) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        try {
            //获取Q300001 SHFL YY
            CallResult<String> resultSerial = sysSerialPatternService.getNextSerial(fdProjectQuotation, "fd_project_quotation_one", "code", true);
            //获取 客户缩写 001
            CallResult<String> resultSerial2 = sysSerialPatternService.getNextSerial(fdProjectQuotation, "fd_project_quotation_two", "code", true);
            if (!resultSerial.isSucceed() || !resultSerial2.isSucceed()) {
                result.error500("获取编码失败");
                return result;
            }
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }

            if (fdProjectQuotation.getId() == null || fdProjectQuotation.getId().equals("")) {
                fdProjectQuotation.setCode(resultSerial.getContent() + resultSerial2.getContent());
            }
            fdProjectQuotationService.saveProjectQuotation(fdProjectQuotation);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @Author gurui
     * @Description //TODO 编辑
     * @Date 9:47 2019/5/21
     * @Param [fdProjectQuotation, bindingResult]
     **/
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdProjectQuotation> edit(@RequestBody @Valid FdProjectQuotation fdProjectQuotation, BindingResult bindingResult) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        FdProjectQuotation fdProjectQuotationEntity = fdProjectQuotationService.getById(fdProjectQuotation.getId());
        if (fdProjectQuotationEntity == 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;
            }
            fdProjectQuotationService.updateQuotation(fdProjectQuotation);
        }

        return result;
    }

    // /**
    //  * 通过id删除
    //  *
    //  * @param id
    //  * @return
    //  */
    // @DeleteMapping(value = "/delete")
    // public Result<FdProjectQuotation> delete(@RequestParam(name = "id", required = true) String id) {
    //     Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
    //     FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.getById(id);
    //     if (fdProjectQuotation == null) {
    //         result.error500("未找到对应实体");
    //         result.setSuccess(false);
    //     } else {
    //         fdProjectQuotation.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
    //         fdProjectQuotationService.updateById(fdProjectQuotation);
    //         result.setSuccess(true);
    //     }
    //
    //     return result;
    // }


    /***
     * @Title:通过id删除
     * @Description:TODO 删除报价以及相关子表数据
     * @param id
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @exception
     * @author 陈创
     * @date 2019/11/1 13:07
     * @updatehistory:
     *   2019/11/1 13:07 新增
     */
    @DeleteMapping(value = "/delete")
    @NotDuplicate
    @RequiresPermissions(value = {"pm-quotation:delete", "pm-macromolecule:delete"}, logical = Logical.OR)
    public Result<FdProjectQuotation> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.getById(id);
        if (fdProjectQuotation == null) {
            result.error500("未找到对应实体");
            result.setSuccess(false);
        } else {
            try {
                // fdProjectQuotation.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
                // fdProjectQuotationService.updateById(fdProjectQuotation);
                //子表删除
                fdProjectQuotationService.deleteProjectQuotation(fdProjectQuotation);
                result.setSuccess(true);
            } catch (Exception e) {
                e.printStackTrace();
                result.error500("操作失败：" + e.getMessage());
            }
        }

        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @Author gurui
     * @Description //TODO 单个或多个删除
     * @Date 9:47 2019/5/21
     * @Param [ids]
     **/
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdProjectQuotation> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            // this.fdProjectQuotationService.deleteProjectQuotation(ids);
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdProjectQuotation> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.getById(id);
        if (fdProjectQuotation == null) {
            result.error500("未找到对应实体");
        } else {
            // //基质类型
            // List<String> list = Arrays.asList(fdProjectQuotation.getMatrixType().split(","));
            // List<FdMatrixType> matrixTypes = fdMatrixTypeMapper.selectBatchIds(list);
            // String matrixType = "";
            // for (FdMatrixType fdMatrixType:matrixTypes){
            //     if (matrixType == ""){
            //         matrixType = fdMatrixType.getName();
            //     }else{
            //         matrixType += ","+fdMatrixType.getName();
            //     }
            // }
            // fdProjectQuotation.setMatrixType(matrixType);
            //
            // //合同类型
            // List<String> list1 = Arrays.asList(fdProjectQuotation.getContractType().split(","));
            // List<FdContractClass> contractClasses = fdContractClassMapper.selectBatchIds(list1);
            // String contractType = "";
            // for (FdContractClass fdContractClass:contractClasses){
            //     if (contractType == ""){
            //         contractType = fdContractClass.getName();
            //     }else{
            //         contractType += ","+fdContractClass.getName();
            //     }
            // }
            // fdProjectQuotation.setContractType(contractType);

            //化合物查询条件
            LambdaQueryWrapper<FdProjectQuotationCompound> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdProjectQuotationCompound::getQuotationId, id);
            queryWrapper.eq(FdProjectQuotationCompound::getDelFlag, "0");
            //查询第一个化合物
            // List<FdProjectQuotationCompound> compoundList = fdProjectQuotationCompoundService.list(queryWrapper);
            //联系人查询条件
            LambdaQueryWrapper<FdProjectQuotationContacts> query = new LambdaQueryWrapper<>();
            query.eq(FdProjectQuotationContacts::getQuotationId, id);
            query.eq(FdProjectQuotationContacts::getIsDefault, "1");
            query.eq(FdProjectQuotationContacts::getDelFlag, "0");
            //商务经理描述查询条件
            LambdaQueryWrapper<FdProjectQuotationComments> queryComments = new LambdaQueryWrapper<>();
            queryComments.eq(FdProjectQuotationComments::getQuotationId, id);
            queryComments.eq(FdProjectQuotationComments::getPersonnelId, fdProjectQuotation.getBusinessManager());
            queryComments.eq(FdProjectQuotationComments::getIsDefault, "1");
            queryComments.eq(FdProjectQuotationComments::getDelFlag, "0");
            List<FdProjectQuotationComments> businesList = fdProjectQuotationCommentsService.list(queryComments);
            //总监
            LambdaQueryWrapper<FdProjectQuotationComments> queryComments2 = new LambdaQueryWrapper<>();
            queryComments2.eq(FdProjectQuotationComments::getQuotationId, id);
            queryComments2.eq(FdProjectQuotationComments::getPersonnelId, fdProjectQuotation.getDirector());
            queryComments2.eq(FdProjectQuotationComments::getIsDefault, "1");
            queryComments2.eq(FdProjectQuotationComments::getDelFlag, "0");
            List<FdProjectQuotationComments> directorList = fdProjectQuotationCommentsService.list(queryComments2);
            //总经理
            LambdaQueryWrapper<FdProjectQuotationComments> queryComments3 = new LambdaQueryWrapper<>();
            queryComments3.eq(FdProjectQuotationComments::getQuotationId, id);
            queryComments3.eq(FdProjectQuotationComments::getPersonnelId, fdProjectQuotation.getGeneralManager());
            queryComments3.eq(FdProjectQuotationComments::getIsDefault, "1");
            queryComments3.eq(FdProjectQuotationComments::getDelFlag, "0");
            List<FdProjectQuotationComments> generalList = fdProjectQuotationCommentsService.list(queryComments3);
            //查询默认联系人
            List<FdProjectQuotationContacts> fdCustomerContactsList = fdProjectQuotationContactsService.list(query);
            //添加联系人到报价单
            for (FdProjectQuotationContacts contacts : fdCustomerContactsList) {
                fdProjectQuotation.setContactPsn(contacts.getContactPsn());
                fdProjectQuotation.setContactTel(contacts.getContactTel());
                fdProjectQuotation.setContactEmail(contacts.getEmail());
            }
            //添加化合物到报价单
            // for (FdProjectQuotationCompound compounds : compoundList) {
            //     fdProjectQuotation.setCompound(compounds.getCompound());
            // }
            //商务经理
            for (FdProjectQuotationComments comments : businesList) {
                fdProjectQuotation.setBusinessManagerMemo(comments.getComments());
            }
            //总监
            for (FdProjectQuotationComments comments : directorList) {
                fdProjectQuotation.setDirectorMemo(comments.getComments());
            }
            //总经理
            for (FdProjectQuotationComments comments : generalList) {
                fdProjectQuotation.setGeneralManagerMemo(comments.getComments());
            }


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

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

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

    /***
     * @Title:保存
     * @Description:TODO
     * @param , bindingResult]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @exception
     * @author 陈创
     * @date 2019/6/5 13:20
     * @updatehistory:
     *   2019/6/5 13:20 新增
     */
    @PostMapping(value = "quotationAdd")
    @NotDuplicate
    @RequiresPermissions(value = {"pm-quotation:add", "pm-quotation:update", "pm-macromolecule:add", "pm-macromolecule:update"}, logical = Logical.OR)
    public Result<FdProjectQuotation> quotationAdd(@RequestBody @Valid FdProjectQuotation fdProjectQuotation, BindingResult bindingResult) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        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(fdProjectQuotation)) {
                throw new RuntimeException("报价单明细不能为空");
            }
            // if (fdProjectQuotation.getQuotationDetailList() == null || fdProjectQuotation.getQuotationDetailList().isEmpty()) {
            //     throw new RuntimeException("报价单对照明细不能为空");
            // }
            // if (fdProjectQuotation.getQuotationCompoundList() == null || fdProjectQuotation.getQuotationCompoundList().isEmpty()) {
            //     throw new RuntimeException("化合物不能为空");
            // }
            // if (fdProjectQuotation.getQuotationContactsList() == null || fdProjectQuotation.getQuotationContactsList().isEmpty()) {
            //     throw new RuntimeException("联系人不能为空");
            // }
            // //获取编码
            // if (fdProjectQuotation.getId() == null || fdProjectQuotation.getId().equals("")) {
            //     //获取Q300001 SHFL YY
            //     CallResult<String> resultSerial = sysSerialPatternService.getNextSerial(fdProjectQuotation, "fd_project_quotation_one", "code", true);
            //     //获取 客户缩写 001
            //     CallResult<String> resultSerial2 = sysSerialPatternService.getNextSerial(fdProjectQuotation, "fd_project_quotation_two", "code", true);
            //     if (!resultSerial.isSucceed() || !resultSerial2.isSucceed()) {
            //         result.error500("获取编码失败");
            //         return result;
            //     }
            //     fdProjectQuotation.setCode(resultSerial.getContent() + resultSerial2.getContent());
            // }
            //获取费用单存在两列费用的名称
            feeCategoryTitle(fdProjectQuotation);
            fdProjectQuotationService.saveProjectQuotation(fdProjectQuotation);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败:" + e.getMessage());
        }
        return result;
    }

    /***
     * @Title:
            * @Description:TODO 获取费用单中存在两列费用的名称
            * @param fdProjectQuotation
            * @return void
            * @exception
            * @author 陈创
            * @date 2020/1/17 15:33
            * @updatehistory:
     *   2020/1/17 15:33 新增
            */
    public void feeCategoryTitle(FdProjectQuotation fdProjectQuotation){
        //模板集合
        List<FdProjectQuotationTemplate> fdProjectQuotationTemplateList=fdProjectQuotation.getQuotationTemplateList();
        if(!fdProjectQuotationTemplateList.isEmpty()&&fdProjectQuotationTemplateList.size()>0){
            Integer count=0;
            for(FdProjectQuotationTemplate fdProjectQuotationTemplate:fdProjectQuotationTemplateList){
                //获取存在两列模板的费用名称
                if(fdProjectQuotationTemplate.getCostColumnNumber()!=null&&fdProjectQuotationTemplate.getCostColumnNumber()==2&&count<=1){
                    fdProjectQuotation.setFeeCategory1Title(fdProjectQuotationTemplate.getFeeCategory1Title());
                    fdProjectQuotation.setFeeCategory2Title(fdProjectQuotationTemplate.getFeeCategory2Title());
                    count++;
                }
            }
        }
    }

    /*
     *
     * 报价单生成合同
     * @author 陈创
     * @date 2019/5/29
     * @param
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     */
    @GetMapping(value = "/contractOfFormation")
    @NotDuplicate
    @RequiresPermissions(value = {"pm-quotation:generation-of-contract", "pm-macromolecule:generation-of-contract"}, logical = Logical.OR)
    public Result<FdProjectQuotation> contractOfFormation(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectQuotation> result = new Result<>();
        FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.getById(id);
        if (fdProjectQuotation == null) {
            result.error500("未找到对应实体");
            result.setSuccess(false);
        } else {
            fdProjectQuotationService.contractOfFormation(id);
            result.setSuccess(true);
        }
        return result;
    }

    /***
     * @Title:状态关闭
     * @Description:TODO
     * @param
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @exception
     * @author 陈创
     * @date 2019/6/3 13:48
     * @updatehistory:
     *   2019/6/3 13:48 修改
     */
    @GetMapping(value = "/close")
    @NotDuplicate
    @RequiresPermissions(value = {"pm-quotation:close", "pm-macromolecule:close"}, logical = Logical.OR)
    public Result<FdProjectQuotation> close(@RequestParam(name = "ids", required = true) List<String> ids) {
        Result<FdProjectQuotation> result = new Result<>();
        String message = "";
        if (ids.isEmpty()) {
            message += "请选择数据</br>";
        }
        Map<String, Object> map = null;
        try {
            //执行service
            map = fdProjectQuotationService.close(ids);
            result.setSuccess(true);
            result.setMessage(message + map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

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

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @Author gurui
     * @Description //TODO 根据项目报价单id删除联系人
     * @Date 15:21 2019/6/13
     * @Param [id]
     **/
    @DeleteMapping(value = "/deleteContracts")
    public Result<FdProjectQuotation> deleteContracts(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.getById(id);
        if (fdProjectQuotation == null) {
            result.error500("未找到对应实体");
            result.setSuccess(false);
        } else {
            fdProjectQuotationService.deleteContracts(id);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @Author gurui
     * @Description //TODO 更据申办方名称查询默认联系人 电话 邮箱 以及联系人集合
     * @Date 16:25 2019/6/17
     * @Param [id]
     **/
    @GetMapping(value = "/queryByCustomerName")
    public Result<FdCustomer> queryByCustomerName(String curId, String name) {
        curId.trim();
        name.trim();//去除空格
        Result<FdCustomer> result = new Result<FdCustomer>();
        //查询项目报价单
        LambdaQueryWrapper<FdCustomer> queryWrapper = new LambdaQueryWrapper<>();
        if (curId != null && !curId.equals("")) {
            queryWrapper.eq(FdCustomer::getId, curId);

            // if (name != null && !name.equals("")) {
            //     queryWrapper.eq(FdCustomer::getName, name);
            // }
            queryWrapper.eq(FdCustomer::getDelFlag, "0");
            List<FdCustomer> list = fdCustomerService.list(queryWrapper);
            for (FdCustomer fdCustomer : list) {
                //查询默认联系人
                LambdaQueryWrapper<FdCustomerContacts> query = new LambdaQueryWrapper<>();
                query.eq(FdCustomerContacts::getPkCustomerId, fdCustomer.getId());
                query.eq(FdCustomerContacts::getIsDefault, "1");
                query.eq(FdCustomerContacts::getDelFlag, "0");
                List<FdCustomerContacts> contactsList1 = fdCustomerContactsService.list(query);
                //添加联系人到报价单
                for (FdCustomerContacts contacts : contactsList1) {
                    fdCustomer.setContacts(contacts.getContactPsn());
                    fdCustomer.setTelephone(contacts.getContectTel());
                    fdCustomer.setEmail(contacts.getEmail());
                    // fdCustomer.setAddress(contacts.getAddress());
                }
                //查询联系人集合
                LambdaQueryWrapper<FdCustomerContacts> query2 = new LambdaQueryWrapper<>();
                query2.eq(FdCustomerContacts::getDelFlag, "0");
                query2.eq(FdCustomerContacts::getPkCustomerId, fdCustomer.getId());
                List<FdCustomerContacts> list2 = fdCustomerContactsService.list(query2);
                //将联系人集合保存到报价单
                fdCustomer.setFdCustomerContactsList(list2);
                result.setResult(fdCustomer);
                result.setSuccess(true);
            }
        }else{
            result.error500("获取客户失败");
        }

        return result;
    }


    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
     * @Author gurui
     * @Description //TODO  批量审核数据
     * @Date 17:41 2019/6/17
     * @Param [ids]
     **/
    @GetMapping(value = "/reviewBatch")
    @NotDuplicate
    @RequiresPermissions(value = {"pm-quotation:to-examine", "pm-macromolecule:to-examine"}, logical = Logical.OR)
    public Result<FdProjectQuotation> reviewBatch(@RequestParam(name = "ids", required = true) List<String> ids) {
        Result<FdProjectQuotation> result = new Result<>();
        String message = "";
        if (ids.isEmpty()) {
            message += "请选择数据</br>";
        }
        Map<String, Object> map = null;
        try {
            //执行service
            map = fdProjectQuotationService.reviewBatch(ids);
            result.setSuccess(true);
            result.setMessage(message + map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @Author gurui
     * @Description //TODO 根据id复制一条一样的数据
     * @Date 13:44 2019/6/26
     * @Param [fdProjectQuotation]
     **/
    @GetMapping(value = "/copy")
    @NotDuplicate
    @RequiresPermissions(value = {"pm-quotation:copy", "pm-macromolecule:copy"}, logical = Logical.OR)
    public Result<FdProjectQuotation> copy(String id, String status, String curId) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        try {
            fdProjectQuotationService.copy(id, status, curId);
            result.success("复制成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败" + e.getMessage());
        }
        return result;
    }

    /***
     * @Title:补充合同复制
     * @Description:TODO
     * @param fdProjectQuotation
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @exception
     * @author 陈创
     * @date 2019/9/18 17:23
     * @updatehistory:
     *   2019/9/18 17:23 新增
     */
    @PostMapping(value = "/supplementaryCopy")
    public Result<FdProjectQuotation> supplementaryCopy(@RequestBody FdProjectQuotation fdProjectQuotation) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        try {
            fdProjectQuotationService.supplementaryCopy(fdProjectQuotation);
            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.FdContract>
     * @Author gurui
     * @Description //TODO 批量弃审核数据 是其状态变为0
     * @Date 9:35 2019/6/28
     * @Param [ids]
     **/
    @GetMapping(value = "/auditBatch")
    @NotDuplicate
    @RequiresPermissions(value = {"pm-quotation:abandoning-trial", "pm-macromolecule:abandoning-trial"}, logical = Logical.OR)
    public Result<FdContract> auditBatch(@RequestParam(name = "ids", required = true) List<String> ids) {
        Result<FdContract> result = new Result<>();
        String message = "";
        if (ids.isEmpty()) {
            message += "请选择数据</br>";
        }
        Map<String, Object> map = null;
        try {
            //执行service
            map = fdProjectQuotationService.auditBatch(ids);
            result.setSuccess(true);
            result.setMessage(message + map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    /***
     * @Title:导出json
     * @Description:TODO
     * @param
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @exception
     * @author 陈创
     * @date 2019/6/29 16:14
     * @updatehistory:
     *   2019/6/29 16:14 新增
     */
    @PostMapping(value = "/export")
    public Result<FdProjectQuotation> export(@RequestBody String id) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        try {
            FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.export(id);
            tempAndFeeOrderByDetail(fdProjectQuotation);
            result.setResult(fdProjectQuotation);
            result.success("导出成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("导出失败" + e.getMessage());
        }
        return result;
    }

    /***
     * @Title:
            * @Description:TODO 根据采样单的填写顺序调整模板顺序和费用单顺序
            * @param fdProjectQuotation
            * @return void
            * @exception
            * @author 陈创
            * @date 2020/2/5 19:59
            * @updatehistory:
     *   2020/2/5 19:59 新增
            */
    public void tempAndFeeOrderByDetail(FdProjectQuotation fdProjectQuotation){
        //采样单集合
        List<FdProjectQuotationDetail> detailList=fdProjectQuotation.getQuotationDetailList();
        //模板集合
        List<FdProjectQuotationTemplate> templateList=fdProjectQuotation.getQuotationTemplateList();
        //费用集合
        List<fdProjectQuotationFee> feeList=fdProjectQuotation.getFdProjectQuotationFeeList();

        //获取调整后的模板集合
        List<FdProjectQuotationTemplate> templateList1=new ArrayList<>();
        templateList1.addAll(templateList);

        //获取调整后的费用单集合
        List<fdProjectQuotationFee> feeList1=new ArrayList<>();
        feeList1.addAll(feeList);

        //先移除生物分析模板
        for(int i=0;i<templateList1.size();i++){
            if(templateList1.get(i).getType().equals("2")||templateList1.get(i).getType().equals("5")||templateList1.get(i).getType().equals("6")){
                templateList1.remove(i);
                i--;
            }
        }
        //先析出生物分析的费用模板
        for(int i=0;i<feeList1.size();i++){
            if(feeList1.get(i).getFeeType().equals("2")||feeList1.get(i).getFeeType().equals("5")||feeList1.get(i).getFeeType().equals("6")){
                feeList1.remove(i);
                i--;
            }
        }

        //循环采样单
        for(FdProjectQuotationDetail detail:detailList){
            String studyType=detail.getStudyType();//研究类型
            String compoundName=detail.getCompoundName();//化合物名称
            String matrixTypeName=detail.getMatrixTypeName();//基质类型名称
            //根据采样单顺序循环获取对应模板
            for(FdProjectQuotationTemplate template:templateList){
                if(template.getType().equals("2")||template.getType().equals("6")){
                    String templateName=template.getName();//模板名称
                    //获取对应采样单的模板
                    if(templateName.indexOf(studyType)!=-1&&templateName.indexOf(compoundName)!=-1&&templateName.indexOf(matrixTypeName)!=-1){
                        templateList1.add(template);
                    }
                }
            }
            //根据采样单顺序循环获取对应模板费用单
            for(fdProjectQuotationFee fee:feeList){
                if(fee.getFeeType().equals("2")||fee.getFeeType().equals("6")){
                    String templateName=fee.getProjectFeeName();//模板费用名称
                    //
                    if(templateName.indexOf(studyType)!=-1&&templateName.indexOf(compoundName)!=-1&&templateName.indexOf(matrixTypeName)!=-1){
                        feeList1.add(fee);
                    }
                }
            }
        }

        //获取耗材模板对象
        for(FdProjectQuotationTemplate template:templateList){
            if(template.getType().equals("5")){
                templateList1.add(template);
            }
            if(template.getType().equals("6")&&template.getName().indexOf("耗材费")!=-1){
                templateList1.add(template);
            }
        }

        //获取耗材费用单对象
        for(fdProjectQuotationFee fee:feeList){
            if(fee.getFeeType().equals("5")){
                feeList1.add(fee);
            }
            if(fee.getFeeType().equals("6")&&fee.getProjectFeeName().indexOf("耗材费")!=-1){
                feeList1.add(fee);
            }
        }

        fdProjectQuotation.setQuotationTemplateList(templateList1);
        fdProjectQuotation.setFdProjectQuotationFeeList(feeList1);

    }

    /***
     * @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 19:57
     * @updatehistory:
     *   2019/7/2 19:57 查询
     */
    @GetMapping(value = "getProjectManagerList")
    public Result<List<FdPersonnel>> getProjectManagerList() {
        Result<List<FdPersonnel>> result = new Result<>();
        List<FdPersonnel> personnelList = fdProjectQuotationService.getProjectManagerList();
        result.setResult(personnelList);
        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/4 10:12
     * @updatehistory:
     *   2019/7/4 10:12 查询
     */
    @GetMapping(value = "getPersonnelByRole")
    public Result<List<FdPersonnel>> getPersonnelByRole() {
        Result<List<FdPersonnel>> result = new Result<>();
        try {
            //查询财务人员
            List<FdPersonnel> personnelList = fdPersonnelService.getPersonnelByRole("09c4bfb12059760a8ada32d4c6826f6a");
            result.setResult(personnelList);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败");
        }
        return result;
    }

    /***
     * @Title:查询树形下拉部门人员数据
     * @Description:TODO
     * @param
     * @return org.jeecg.common.api.vo.Result<java.util.List   <   java.util.Map   <   java.lang.Object   ,   java.lang.Object>>>
     * @exception
     * @author 陈创
     * @date 2019/7/4 14:54
     * @updatehistory:
     *   2019/7/4 14:54 新增
     */
    @GetMapping(value = "getDerPerTreeList")
    public Result<List<Map<Object, Object>>> getDerPerTreeList(String roleId) {
        Result<List<Map<Object, Object>>> result = new Result<>();
        try {
            result.setResult(fdProjectQuotationService.getPersonnelByRole(roleId));
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败");
        }
        return result;
    }

    /***
     * @Title:根据多个角色获取部门分组人员Json
     * @Description:TODO
     * @param roleIds
     * @return org.jeecg.common.api.vo.Result<java.util.List < java.util.Map < java.lang.Object , java.lang.Object>>>
     * @exception
     * @author 陈创
     * @date 2019/9/20 15:49
     * @updatehistory:
     *   2019/9/20 15:49 新增
     */
    @GetMapping(value = "/getDerPerTreeListByRoleIds")
    public Result<List<Map<Object, Object>>> getDerPerTreeListByRoleIds(@RequestParam(name = "roleIds", required = true) List<String> roleIds,@RequestParam(name = "typeName", required = true) String typeName) {
        Result<List<Map<Object, Object>>> result = new Result<>();
        try {
            result.setResult(fdProjectQuotationService.getPersonnelByRoleList(roleIds,typeName));
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败");
        }
        return result;
    }


    /***
     * @Title:详情接口
     * @Description:TODO
     * @param id
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @exception
     * @author 陈创
     * @date 2019/7/8 11:09
     * @updatehistory:
     *   2019/7/8 11:09 查询
     */
    @PostMapping(value = "/view")
    public Result<FdProjectQuotation> view(@RequestBody String id) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        try {

            FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.export(id);
            if (fdProjectQuotation == null) {
                result.error500("未找到实体类");
            } else {
                //化合物查询条件
                // LambdaQueryWrapper<FdProjectQuotationCompound> queryWrapper = new LambdaQueryWrapper<>();
                // queryWrapper.eq(FdProjectQuotationCompound::getDelFlag, "0");
                // queryWrapper.eq(FdProjectQuotationCompound::getQuotationId, id);
                // queryWrapper.eq(FdProjectQuotationCompound::getSort, "1");
                // //查询第一个化合物
                // List<FdProjectQuotationCompound> compoundList = fdProjectQuotationCompoundService.list(queryWrapper);//添加化合物到报价单
                // if (!compoundList.isEmpty()) {
                //     for (FdProjectQuotationCompound compounds : compoundList) {
                //         fdProjectQuotation.setCompound(compounds.getCompound());
                //     }
                // }
                result.setResult(fdProjectQuotation);
                result.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败" + e.getMessage());
        }
        return result;
    }

    /***
     * @Title:报价审核人员进行审核
     * @Description:TODO
     * @param fdProjectQuotation
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @exception
     * @author 陈创
     * @date 2019/7/22 17:16
     * @updatehistory:
     *   2019/7/22 17:16 修改
     */
    @PutMapping(value = "/managerAudit")
    public Result<FdProjectQuotation> managerAudit(@RequestBody FdProjectQuotation fdProjectQuotation) {
        Result<FdProjectQuotation> result = new Result<FdProjectQuotation>();
        FdProjectQuotation fdProjectQuotationEntity = fdProjectQuotationService.getById(fdProjectQuotation.getId());
        boolean isExamine = true;
        if (fdProjectQuotationEntity == null) {
            result.error500("未找到对应实体");
        } else if (fdProjectQuotation.getIsClinicalSectionExamine() != null && fdProjectQuotation.getIsClinicalSectionExamine() != "") {
            //查询得状态不等于null，且状态为审核，且报价类型为小分子
            if (fdProjectQuotationEntity.getIsClinicalSectionExamine() != null && fdProjectQuotationEntity.getIsClinicalSectionExamine().equals("1") && fdProjectQuotationEntity.getType().equals("1")) {
                isExamine = false;
            }
        } else if (fdProjectQuotation.getIsCentralPriceExamine() != null && fdProjectQuotation.getIsCentralPriceExamine() != "" && fdProjectQuotationEntity.getType().equals("1")) {
            if (fdProjectQuotationEntity.getIsCentralPriceExamine() != null && fdProjectQuotationEntity.getIsCentralPriceExamine().equals("1")) {
                isExamine = false;
            }
        } else if (fdProjectQuotation.getIsDataStatisticsExamine() != null && fdProjectQuotation.getIsDataStatisticsExamine() != "" && fdProjectQuotationEntity.getType().equals("1")) {
            if (fdProjectQuotationEntity.getIsDataStatisticsExamine() != null && fdProjectQuotationEntity.getIsDataStatisticsExamine().equals("1")) {
                isExamine = false;
            }
        } else if (fdProjectQuotation.getIsPkComputingExamine() != null && fdProjectQuotation.getIsPkComputingExamine() != "" && fdProjectQuotationEntity.getType().equals("1")) {
            if (fdProjectQuotationEntity.getIsPkComputingExamine() != null && fdProjectQuotationEntity.getIsPkComputingExamine().equals("1")) {
                isExamine = false;
            }
        } else if (fdProjectQuotation.getIsBioanalysisExamine() != null && fdProjectQuotation.getIsBioanalysisExamine() != "") {
            if (fdProjectQuotationEntity.getIsBioanalysisExamine() != null && fdProjectQuotationEntity.getIsBioanalysisExamine().equals("1")) {
                isExamine = false;
            }
        } else if (fdProjectQuotation.getIsGeneralExamine() != null && fdProjectQuotation.getIsGeneralExamine() != "") {
            if (fdProjectQuotationEntity.getIsGeneralExamine() != null && fdProjectQuotationEntity.getIsGeneralExamine().equals("1")) {
                isExamine = false;
            }
        }
        if (isExamine) {
            fdProjectQuotationService.managerAudit(fdProjectQuotation);
        } else {
            result.error500("已经审核");
        }

        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<java.util.List   <   org.jeecg.modules.projectManagement.entity.FdProjectQuotation>>
     * @Author tanj
     * @Description //TODO  报价报表报价总数及员工占比查询
     * @Date 17:21 2019/7/25
     * @Param [fdProjectQuotation]
     **/
    @GetMapping(value = "/totalProportion")
    @RequiresPermissions("url:pm-offerStatements:view")
    public Result<Map<String, Object>> totalProportion(FdProjectQuotation fdProjectQuotation) {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        try {
            List<FdProjectQuotation> quotationList = new ArrayList<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String date = "2017-01-01 00:00:00";
            //  开始时间，结束时间不为空
            if (oConvertUtils.isNotEmpty(fdProjectQuotation.getBegin()) && oConvertUtils.isNotEmpty(fdProjectQuotation.getOver())) {
                quotationList = fdProjectQuotationService.totalProportion(format.parse(fdProjectQuotation.getBegin()), format.parse(fdProjectQuotation.getOver()),fdProjectQuotation);
            } else {
                String da = format.format(new Date());
                //  开始时间为空，结束时间为空
                quotationList = fdProjectQuotationService.totalProportion(format.parse(date), format.parse(da),fdProjectQuotation);
            }
            Map<String, Object> map = Maps.newHashMap();

            map.put("table", quotationList);
            map.put("maps", theName(quotationList));
            result.success("操作成功!");
            result.setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败!" + e.getMessage());
        }
        return result;
    }


    /**
     * @return org.jeecg.common.api.vo.Result<java.util.List   <   org.jeecg.modules.projectManagement.entity.FdProjectQuotation>>
     * @Author tanj
     * @Description //TODO 员工签约及报价占比
     * @Date 20:59 2019/7/25
     * @Param [fdProjectQuotation]
     **/
    @GetMapping(value = "/signed")
    @RequiresPermissions("url:pm-offerStatements:view")
    public Result<Map<String, Object>> signed(FdProjectQuotation fdProjectQuotation) {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        try {
            List<FdProjectQuotation> quotationList = new ArrayList<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = "2017-01-01 00:00:00";
            //  开始时间，结束时间不为空
            if (oConvertUtils.isNotEmpty(fdProjectQuotation.getBegin()) && oConvertUtils.isNotEmpty(fdProjectQuotation.getOver())) {
                quotationList = fdProjectQuotationService.signed(format.parse(fdProjectQuotation.getBegin()), format.parse(fdProjectQuotation.getOver()),fdProjectQuotation);
            } else {
                //  开始时间为空，结束时间为空
                String da = format.format(new Date());
                quotationList = fdProjectQuotationService.signed(format.parse(date), format.parse(da),fdProjectQuotation);
            }
            Map<String, Object> map = Maps.newHashMap();
            map.put("table", quotationList);
            map.put("maps", theName(quotationList));
            result.success("操作成功!");
            result.setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败!" + e.getMessage());
        }
        return result;
    }

    @Autowired
    private ISysUserService sysUserService;

    /**
     * @return org.jeecg.common.api.vo.Result<java.util.List   <   org.jeecg.modules.projectManagement.entity.FdProjectQuotation>>
     * @Author tanj
     * @Description //TODO 按月合计报价数、签约数及占比
     * @Date 20:04 2019/7/25
     * @Param [fdProjectQuotation]
     **/
    @GetMapping(value = "/monthlyGrouping")
    @RequiresPermissions("url:pm-offerStatements:view")
    public Result<Map<String, Object>> monthlyGrouping(FdProjectQuotation fdProjectQuotation) {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        try {
            List<FdProjectQuotation> quotationList = new ArrayList<>();
            if (oConvertUtils.isNotEmpty(fdProjectQuotation.getBegin()) && oConvertUtils.isNotEmpty(fdProjectQuotation.getOver())) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                fdProjectQuotation.setCreateTime(format.parse(fdProjectQuotation.getBegin()));
                Calendar cal = Calendar.getInstance();
                cal.setTime(format.parse(fdProjectQuotation.getBegin()));
                Integer month = cal.get(Calendar.MONTH) + 1;
                cal.setTime(format.parse(fdProjectQuotation.getOver()));
                Integer months = cal.get(Calendar.MONTH) + 1;
                quotationList = fdProjectQuotationService.monthlyGrouping(month.toString(), months.toString(),fdProjectQuotation);
            } else {
                quotationList = fdProjectQuotationService.monthlyGrouping("1", "12",fdProjectQuotation);
            }
            //  返回map
            Map<String, Object> map = Maps.newHashMap();
            map.put("table", quotationList);
            map.put("maps", theName(quotationList));
            result.success("操作成功!");
            result.setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败!" + e.getMessage());
        }
        return result;
    }

    /*public List<StatementJOSN> loader(List<FdProjectQuotation> fdProjectQuotation){
        List<FdProjectQuotation> projectQuotationList = new ArrayList<>();
        for ( FdProjectQuotation fdProjectQuotations : fdProjectQuotation ) {
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", fdProjectQuotations.getCreateBy());
            SysUser one = sysUserService.getOne(queryWrapper);
            FdPersonnel fdPersonnel = fdPersonnelService.getById(one.getPersonnelId());
            if (fdPersonnel != null){
                fdProjectQuotations.setCreateBy(fdPersonnel.getName());
            }
            fdProjectQuotations.setCreateBy(one.getUsername());
            projectQuotationList.add(fdProjectQuotations);
        }

        //  将JSON排列成前台需要的格式
        List<StatementJOSN> statementJOSNList = new ArrayList<>();
        StatementJOSN statementJOSN = null;
        for ( FdProjectQuotation projectQuotation : projectQuotationList ) {
            statementJOSN = new StatementJOSN();
            statementJOSN.setName(projectQuotation.getCreateBy());
            statementJOSN.setTotalQuotation(projectQuotation.getTranslate());
            statementJOSN.setSignUpFor(projectQuotation.getSigning());
            statementJOSN.setRatio(projectQuotation.getProportion());
            statementJOSNList.add(statementJOSN);
        }
        return statementJOSNList;
    }*/

    // public List<Map<String, Object>> theName(List<FdProjectQuotation> fdProjectQuotation) {
    //     List<FdProjectQuotation> projectQuotationList = new ArrayList<>();
    //     for (FdProjectQuotation fdProjectQuotations : fdProjectQuotation) {
    //         QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
    //         queryWrapper.eq("username", fdProjectQuotations.getCreateBy());
    //         SysUser one = sysUserService.getOne(queryWrapper);
    //         if(one!=null){
    //             FdPersonnel fdPersonnel = fdPersonnelService.getById(one.getPersonnelId());
    //             if (fdPersonnel != null) {
    //                 fdProjectQuotations.setCreateBy(fdPersonnel.getName());
    //             }
    //             fdProjectQuotations.setCreateBy(one.getRealname());
    //             projectQuotationList.add(fdProjectQuotations);
    //         }
    //
    //     }
    //     //  将JSON排列成前台需要的格式
    //     List<Map<String, Object>> mapList = new ArrayList<>();
    //     for (FdProjectQuotation projectQuotation : projectQuotationList) {
    //         Map<String, Object> map = Maps.newHashMap();
    //         String name = projectQuotation.getCreateBy();
    //         map.put("name", name);
    //         map.put("报价总数", projectQuotation.getTranslate());
    //         map.put("占比", projectQuotation.getProportion());
    //         if (oConvertUtils.isNotEmpty(projectQuotation.getSigning())) {
    //             map.put("签约", projectQuotation.getSigning());
    //         }
    //         mapList.add(map);
    //     }
    //     return mapList;
    // }

    public List<Map<String, Object>> theName(List<FdProjectQuotation> fdProjectQuotation) {
        //  将JSON排列成前台需要的格式
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (FdProjectQuotation projectQuotation : fdProjectQuotation) {
            Map<String, Object> map = Maps.newHashMap();
            String name = projectQuotation.getProjectManagerName();
            if(StringUtils.isEmpty(name)){
                name="Not BD";
            }
            map.put("name", name);
            map.put("报价总数", projectQuotation.getTranslate());
            map.put("占比", projectQuotation.getProportion());
            if (oConvertUtils.isNotEmpty(projectQuotation.getSigning())) {
                map.put("签约", projectQuotation.getSigning());
            }
            mapList.add(map);
        }
        return mapList;
    }

    @GetMapping(value = "/judge")
    public Result<Boolean> judge(@RequestParam(name = "id") String id) {
        Result<Boolean> result = new Result<Boolean>();
        result.setResult(fdProjectQuotationService.judge(id));
        return result;
    }

    /***
     * @Title:修改状态（公用）
     * @Description:TODO
     * @param ids, status]
     * @return org.jeecg.common.api.vo.Result
     * @exception
     * @author 陈创
     * @date 2019/11/28 16:44
     * @updatehistory:
     *   2019/11/28 16:44 新增
     */
    @GetMapping(value = "/updataStatusShared")
    public Result updataStatusShared(@RequestParam(name = "ids", required = true) List<String> ids, @RequestParam(name = "status", required = true) String status) {
        Result result = new Result();
        try {
            fdProjectQuotationService.updataStatusShared(ids, status);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败：" + e.getMessage());
        }
        return result;
    }

    /***
     * @Title:回转后还需要审核
     * @Description:TODO
     * @param ids, status]
     * @return org.jeecg.common.api.vo.Result
     * @exception
     * @author 陈创
     * @date 2019/11/28 18:14
     * @updatehistory:
     *   2019/11/28 18:14 新增
     */
    @GetMapping(value = "/updataStatusAndPersonnelStatus")
    public Result updateStatusAndPersonnelStatus(@RequestParam(name = "ids", required = true) List<String> ids, @RequestParam(name = "status", required = true) String status) {
        Result result = new Result();
        try {
            fdProjectQuotationService.updateStatusAndPersonnelStatus(ids, status);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败：" + e.getMessage());
        }
        return result;
    }

    /***
     * @Title:
     * @Description:TODO 根据报价id查询相关报价信息
     * @param id
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>
     * @exception
     * @author 陈创
     * @date 2019/12/19 16:40
     * @updatehistory:
     *   2019/12/19 16:40 新增
     */
    @GetMapping(value = "/getQuotationById")
    public Result<FdProjectQuotation> getQuotationById(String id) {
        Result<FdProjectQuotation> result = new Result<>();
        try {
            FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.getQuotationById(id);
            result.setResult(fdProjectQuotation);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败：" + e.getMessage());
        }
        return result;
    }

    /***
     * @Title:再次审核提醒操作
            * @Description:TODO
            * @param fdProjectQuotation
            * @return org.jeecg.common.api.vo.Result
            * @exception 
            * @author 陈创
            * @date 2019/12/20 16:45
            * @updatehistory:
     *   2019/12/20 16:45 新增
            */
    @PostMapping(value = "/reAuditSave")
    public Result reAuditSave(@RequestBody FdProjectQuotation fdProjectQuotation) {
        Result result = new Result();
        try {
            fdProjectQuotationService.reAuditSave(fdProjectQuotation);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:
            * @Description:TODO 关联报价号
            * @param fdProjectQuotation
            * @return org.jeecg.common.api.vo.Result
            * @exception
            * @author 陈创
            * @date 2020/3/6 15:01
            * @updatehistory:
     *   2020/3/6 15:01 新增
            */
    @PutMapping(value = "/updateRelationCode")
    public Result updateRelationCode(@RequestBody FdProjectQuotation fdProjectQuotation){
        Result result = new Result();
        try {
            boolean resultBool=fdProjectQuotationService.updateRelationCode(fdProjectQuotation);
            if(resultBool){
                result.setSuccess(true);
            }else{
                result.error500("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:
            * @Description:TODO 给审核人发送消息通知
            * @param quotationId
            * @return org.jeecg.common.api.vo.Result
            * @exception
            * @author 陈创
            * @date 2020/4/20 17:45
            * @updatehistory:
     *   2020/4/20 17:45 新增
            */
    @GetMapping(value = "/reviewedByMessage")
    public Result reviewedByMessage(@RequestParam(name = "quotationId",required = true) String quotationId){
        Result result=new Result();
        FdProjectQuotation fdProjectQuotation=fdProjectQuotationService.getQuotationById(quotationId);
        if(fdProjectQuotation==null){
            result.error500("未找到实体类");
        }else{
            try {
                fdProjectQuotationService.reviewedByMessage(fdProjectQuotation);
                result.success("操作成功");
            } catch (Exception e) {
                e.printStackTrace();
                result.error500("操作失败："+e.getMessage());
            }
        }
        return result;
    }

    /***
     * @Title:
            * @Description:TODO 报表查询数据
            * @param [fdProjectQuotation, pageNo, pageSize, req]
            * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>>
            * @exception
            * @author 陈创
            * @date 2020/4/23 17:54
            * @updatehistory:
     *   2020/4/23 17:54 新增
            */
    @GetMapping(value = "/getReportPage")
    public Result<IPage<FdProjectQuotation>> getReportPage(FdProjectQuotation fdProjectQuotation,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<FdProjectQuotation>> result = new Result<IPage<FdProjectQuotation>>();
        //开始时间
        String begin=fdProjectQuotation.getBegin();
        if(StringUtils.isNotBlank(begin)){
            fdProjectQuotation.setBegin(null);
        }
        //结束时间
        String over=fdProjectQuotation.getOver();
        if(StringUtils.isNotBlank(over)){
            fdProjectQuotation.setOver(null);
        }

        //实验室地点ids
        List<String> biologicalAnalysisLaboratoryIds=fdProjectQuotation.getBiologicalAnalysisLaboratoryIds();
        if(biologicalAnalysisLaboratoryIds!=null&&biologicalAnalysisLaboratoryIds.size()>0){
            fdProjectQuotation.setBiologicalAnalysisLaboratoryIds(null);
        }

        //临床中心
        List<String> hospitalListIds=fdProjectQuotation.getHospitalListIds();
        if(hospitalListIds!=null&&hospitalListIds.size()>0){
            fdProjectQuotation.setHospitalListIds(null);
        }

        //BD
        List<String> projectManagerIds=fdProjectQuotation.getProjectManagerIds();
        if(projectManagerIds!=null&&projectManagerIds.size()>0){
            fdProjectQuotation.setProjectManagerIds(null);
        }

        //报价类型
        List<String> quotationTypeIds=fdProjectQuotation.getQuotationTypeIds();
        if(quotationTypeIds!=null&&quotationTypeIds.size()>0){
            fdProjectQuotation.setQuotationTypeIds(null);
        }

        //报价人员
        List<String> createByIds=fdProjectQuotation.getCreateByIds();
        if(createByIds!=null&&createByIds.size()>0){
            fdProjectQuotation.setCreateByIds(null);
        }

        //合同类型
        List<String> contractTypeIds=fdProjectQuotation.getContractTypeIds();
        if(contractTypeIds!=null&&contractTypeIds.size()>0){
            fdProjectQuotation.setContractTypeIds(null);
        }

        //状态
        List<String> statusIds=fdProjectQuotation.getStatusIds();
        if(statusIds!=null && statusIds.size()>0){
            fdProjectQuotation.setStatusIds(null);
        }

        //状态
        String status=fdProjectQuotation.getStatus();
        if(StringUtils.isNotBlank(status)){
            fdProjectQuotation.setStatus(null);
        }

        QueryWrapper<FdProjectQuotation> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectQuotation, req.getParameterMap());
//        queryWrapper.between("fpq.create_time",begin,over);
//        queryWrapper.ge("fpq.create_time",begin);
//        queryWrapper.le("fpq.create_time",over);
        queryWrapper.ge("DATE_FORMAT(fpq.create_time, '%Y-%m-%d')",begin);
        queryWrapper.le("DATE_FORMAT(fpq.create_time, '%Y-%m-%d')",over);
        if(biologicalAnalysisLaboratoryIds!=null&&biologicalAnalysisLaboratoryIds.size()>0){
            queryWrapper.in("fpq.biological_analysis_laboratory",biologicalAnalysisLaboratoryIds);
        }
        //临床中心sql拼接
        if(hospitalListIds!=null&&hospitalListIds.size()>0){
            int i=0;
            for(String hospital:hospitalListIds){
                if(i==0){//开始
                    queryWrapper.like("(fpq.hospital_list",hospital);
                }else{//中间
                    queryWrapper.or();
                    queryWrapper.like("fpq.hospital_list",hospital);
                }
                i++;
            }
            queryWrapper.apply("1=1)");
        }

        //Bd
        if(projectManagerIds!=null&&projectManagerIds.size()>0){
            queryWrapper.in("fpq.project_manager",projectManagerIds);
        }

        //报价类型
        if(quotationTypeIds!=null&&quotationTypeIds.size()>0){
            queryWrapper.in("fpq.quotation_type",quotationTypeIds);
        }

        //报价人员
        if(createByIds!=null&&createByIds.size()>0){
            queryWrapper.in("fpq.create_by",createByIds);
        }

        //合同类型sql拼接
        if(contractTypeIds!=null&&contractTypeIds.size()>0){
            int i=0;
            for(String contractType:contractTypeIds){
                if(i==0){//开始
                    queryWrapper.like("(fpq.contract_type",contractType);
                }else{//中间
                    queryWrapper.or();
                    queryWrapper.like("fpq.contract_type",contractType);
                }
                i++;
            }
            queryWrapper.apply("1=1)");
        }

        //多状态
        if(statusIds!=null&&statusIds.size()>0){
            queryWrapper.in("fpq.status",statusIds);
        }

        //状态
        if(StringUtils.isNotBlank(status)){
            queryWrapper.eq("fpq.status",status);
        }


        queryWrapper.eq("fpq.del_flag", "0");
        queryWrapper.orderByDesc("fpq.create_time");
        queryWrapper.orderByDesc("fpq.code");
        Page<FdProjectQuotation> page = new Page<FdProjectQuotation>(pageNo, pageSize);
        IPage<FdProjectQuotation> pageList = fdProjectQuotationService.getReportPage(page, queryWrapper);
        //获取待审核人
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 查询所有报价数据
    * @Date 2020/8/4 15:15
    * @Param []
    * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdProjectQuotation>>
    */
    @GetMapping(value = "/getListNotPage")
    public Result<List<FdProjectQuotation>> getListNotPage(){
        Result<List<FdProjectQuotation>> result=new Result<>();
        LambdaQueryWrapper<FdProjectQuotation> fdProjectQuotationLambdaQueryWrapper=new LambdaQueryWrapper<>();
        fdProjectQuotationLambdaQueryWrapper.eq(FdProjectQuotation::getDelFlag,"0");
        fdProjectQuotationLambdaQueryWrapper.orderByDesc(FdProjectQuotation::getCreateTime);
        fdProjectQuotationLambdaQueryWrapper.orderByDesc(FdProjectQuotation::getCode);
        List<FdProjectQuotation> fdProjectQuotationList=fdProjectQuotationService.list(fdProjectQuotationLambdaQueryWrapper);
        result.setResult(fdProjectQuotationList);
        result.success("操作成功");
        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 写回报价，修改最终申办方名称
    * @Date 2020/8/14 17:53
    * @Param [fdProjectQuotation]
    * @return org.jeecg.common.api.vo.Result
    */
    @PutMapping(value = "/updateSponsorName")
    public Result updateSponsorName(@RequestBody FdProjectQuotation fdProjectQuotation){
        Result result=new Result();
        try {
            fdProjectQuotationService.updateSponsorName(fdProjectQuotation);
            result.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

}
