package org.jeecg.modules.projectManagement.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.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.entity.*;
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.message.entity.MailAttacch;
import org.jeecg.modules.message.handle.ISendMsgHandle;
import org.jeecg.modules.message.handle.enums.SendMsgTypeEnum;
import org.jeecg.modules.projectManagement.entity.*;
import org.jeecg.modules.projectManagement.service.*;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.MultiValueMap;
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： gurui
 * @date： 2019-05-22
 * @version： V1.0
 */
@RestController
@RequestMapping("/projectManagement/fdContract")
@Slf4j
public class FdContractController {
    @Autowired
    private IFdContractService fdContractService;

    @Resource
    private IFdContractService contractService;

    @Resource
    private IFdContractCompoundService fdContractCompoundService;

    @Resource
    private IFdContractContactsService fdContractContactsService;

    @Resource
    private IFdProjectQuotationService fdProjectQuotationService;

    @Resource
    private IFdCustomerService fdCustomerService;

    @Resource
    private IFdContractClauseService fdContractClauseService;
    @Resource
    private IFdMatrixTypeService fdMatrixTypeService;

    @Resource
    private IFdPersonnelService iFdPersonnelService;

    @Resource
    private IFdContractProportionService iFdContractProportionService;

    /**
     * 分页列表查询
     *
     * @param fdContract
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<FdContract>> queryPageList(FdContract fdContract, FdContractBidparty fdContractBidparty,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Result<IPage<FdContract>> result = new Result<IPage<FdContract>>();
        String sourceQuotationCode = fdContract.getSourceQuotationCode();
        //对来源报价单号查询
        if(StringUtils.isNotBlank(fdContract.getSourceQuotationCode())){
            fdContract.setSourceQuotationCode(null);
        }
        String code = fdContract.getCode();
        if (StringUtils.isNotBlank(fdContract.getCode())) {
            fdContract.setCode(null);
        }
        String projectName = fdContract.getProjectName();
        if (StringUtils.isNotBlank(fdContract.getProjectName())) {
            fdContract.setProjectName(null);
        }
        String bidParty = fdContractBidparty.getId();
        if (StringUtils.isNotBlank(fdContractBidparty.getId())) {
            fdContractBidparty.setId(null);
        }
        //状态
        String status = fdContract.getStatus();
        if (StringUtils.isNotBlank(fdContract.getStatus())) {
            fdContract.setStatus(null);
        }

        Date createDate=fdContract.getCreateTime();
        if(createDate!=null){
            fdContract.setCreateTime(null);
        }

        //合同方
        String contractParty=fdContract.getContractParty();
        if(StringUtils.isNotBlank(contractParty)){
            fdContract.setContractParty(null);
        }
        //申办方
        String pkCustomerId=fdContract.getPkCustomerId();
        if(StringUtils.isNotBlank(pkCustomerId)){
            fdContract.setPkCustomerId(null);
        }

        QueryWrapper<FdContract> queryWrapper = QueryGenerator.initQueryWrapper(fdContract, req.getParameterMap());
        queryWrapper.eq("fc.del_flag", "0");
        queryWrapper.orderByDesc("fc.create_time");
        // queryWrapper.eq("fcc.sort","1");
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("fc.code", code);
        }
        if (StringUtils.isNotBlank(projectName)) {
            queryWrapper.like("fc.project_name", projectName);
        }
        if (StringUtils.isNotBlank(bidParty)) {
            queryWrapper.like("fcb.id", bidParty);
        }
        if(StringUtils.isNotBlank(status)){
            queryWrapper.eq("fc.status",status);
        }
        if(StringUtils.isNotBlank(sourceQuotationCode)){
            queryWrapper.like("fc.source_quotation_code",sourceQuotationCode);
        }
        if(createDate!=null){
            queryWrapper.eq("fc.create_time",createDate);
        }
        if(StringUtils.isNotBlank(contractParty)){
            queryWrapper.eq("fc.contract_party",contractParty);
        }
        if(StringUtils.isNotBlank(pkCustomerId)){
            queryWrapper.eq("fc.pk_customer_id",pkCustomerId);
        }
        //按时间排序
        queryWrapper.orderByDesc("fc.create_time");
        Page<FdContract> page = new Page<FdContract>(pageNo, pageSize);
        IPage<FdContract> pageList = fdContractService.findByPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 分页列表查询
     *
     * @param fdContract
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list1")
    @RequiresPermissions("url:pm-contract:view")
    public Result<IPage<FdContract>> queryPageList1(FdContract fdContract, FdContractBidparty fdContractBidparty,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Result<IPage<FdContract>> result = new Result<IPage<FdContract>>();
        String sourceQuotationCode = fdContract.getSourceQuotationCode();
        //对来源报价单号查询
        if(StringUtils.isNotBlank(fdContract.getSourceQuotationCode())){
            fdContract.setSourceQuotationCode(null);
        }
        String code = fdContract.getCode();
        if (StringUtils.isNotBlank(fdContract.getCode())) {
            fdContract.setCode(null);
        }
        String projectName = fdContract.getProjectName();
        if (StringUtils.isNotBlank(fdContract.getProjectName())) {
            fdContract.setProjectName(null);
        }
        String bidParty = fdContractBidparty.getId();
        if (StringUtils.isNotBlank(fdContractBidparty.getId())) {
            fdContractBidparty.setId(null);
        }
        //状态
        String status = fdContract.getStatus();
        if (StringUtils.isNotBlank(fdContract.getStatus())) {
            fdContract.setStatus(null);
        }

        //关联报价号
        String relationCode=fdContract.getRelationCode();
        if(StringUtils.isNotBlank(relationCode)){
            fdContract.setRelationCode(null);
        }

        Date createDate=fdContract.getCreateTime();
        if(createDate!=null){
            fdContract.setCreateTime(null);
        }
        //合同方
        String contractParty=fdContract.getContractParty();
        if(StringUtils.isNotBlank(contractParty)){
            fdContract.setContractParty(null);
        }
        //申办方
        String pkCustomerId=fdContract.getPkCustomerId();
        if(StringUtils.isNotBlank(pkCustomerId)){
            fdContract.setPkCustomerId(null);
        }

        //签署开始时间
        String begin=fdContract.getBegin();
        if(StringUtils.isNotBlank(begin)){
            fdContract.setBegin(null);
        }
        //签署结束时间
        String over=fdContract.getOver();
        if(StringUtils.isNotBlank(over)){
            fdContract.setOver(null);
        }

        //创建日期开始时间
        String createTimeStart=fdContract.getCreateTimeStart();
        if(StringUtils.isNotBlank(createTimeStart)){
            fdContract.setCreateTimeStart(null);
        }
        //创建日期结束时间
        String createTimeEnd=fdContract.getCreateTimeEnd();
        if(StringUtils.isNotBlank(createTimeEnd)){
            fdContract.setCreateTimeEnd(null);
        }

        QueryWrapper<FdContract> queryWrapper = QueryGenerator.initQueryWrapper(fdContract, req.getParameterMap());
        queryWrapper.eq("fc.del_flag", "0");
        queryWrapper.orderByDesc("fc.create_time");
        // queryWrapper.eq("fcc.sort","1");
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("fc.code", code);
        }
        if (StringUtils.isNotBlank(projectName)) {
            queryWrapper.like("fc.project_name", projectName);
        }
        if (StringUtils.isNotBlank(bidParty)) {
            queryWrapper.like("fcb.id", bidParty);
        }
        if(StringUtils.isNotBlank(status)){
            queryWrapper.eq("fc.status",status);
        }
        if(StringUtils.isNotBlank(sourceQuotationCode)){
            queryWrapper.like("fc.source_quotation_code",sourceQuotationCode);
        }
        if(StringUtils.isNotBlank(relationCode)){
            queryWrapper.like("fpq.relation_code",relationCode);
        }
        if(createDate!=null){
            queryWrapper.eq("fc.create_time",createDate);
        }

        if(StringUtils.isNotBlank(contractParty)&&!contractParty.equals("null")){
            queryWrapper.eq("fc.contract_party",contractParty);
        }
        if(StringUtils.isNotBlank(pkCustomerId)&&!pkCustomerId.equals("null")){
            queryWrapper.eq("fc.pk_customer_id",pkCustomerId);
        }
        //签署日期范围查询
        if(StringUtils.isNotBlank(begin)&&StringUtils.isNotBlank(over)&&!begin.equals("null")&&!over.equals("null")){
            queryWrapper.between("fc.sign_date",begin,over);
        }
        //创建日期范围查询
        if(StringUtils.isNotBlank(createTimeStart)&&StringUtils.isNotBlank(createTimeEnd)&&!createTimeStart.equals("null")&&!createTimeEnd.equals("null")){
            queryWrapper.between("fc.create_time",createTimeStart,createTimeEnd);
        }
        //按时间排序
        queryWrapper.orderByDesc("fc.create_time");
        Page<FdContract> page = new Page<FdContract>(pageNo, pageSize);
        IPage<FdContract> pageList = fdContractService.findByPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }






    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
     * @Author gurui
     * @Description //TODO 添加
     * @Date 11:56 2019/5/23
     * @Param [fdContract, bindingResult]
     **/
    @PostMapping(value = "/add")
    @NotDuplicate
    public Result<FdContract> add(@RequestBody @Valid FdContract fdContract, BindingResult bindingResult) {
        Result<FdContract> result = new Result<FdContract>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdContractService.save(fdContract);
            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.FdContract>
     * @Author gurui
     * @Description //TODO 编辑
     * @Date 11:57 2019/5/23
     * @Param [fdContract, bindingResult]
     **/
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdContract> edit(@RequestBody @Valid FdContract fdContract, BindingResult bindingResult) {
        Result<FdContract> result = new Result<FdContract>();
        FdContract fdContractEntity = fdContractService.getById(fdContract.getId());
        if (fdContractEntity == 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;
            }
            try {
                fdContractService.updateContract(fdContract);
                result.success("修改成功!");
            } catch (Exception e) {
                e.printStackTrace();
                log.info(e.getMessage());
                result.error500("操作失败：" + e.getMessage());
            }


        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    @NotDuplicate
    @RequiresPermissions("pm-contract:delete")
    public Result<FdContract> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdContract> result = new Result<FdContract>();
        FdContract fdContract = fdContractService.getById(id);
        if (fdContract == null) {
            result.error500("未找到对应实体");
        } else {
            try {
                fdContract.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
                fdContractService.updateDelById(fdContract);
//                fdContractService.updateById(fdContract);
                //fdContractService.removeById(id);
                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 单个或多个删除
     * @Date 12:00 2019/5/23
     * @Param [ids]
     **/
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdContract> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdContract> result = new Result<FdContract>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            try {
                this.fdContractService.deleteContract(ids);
                result.success("删除成功!");
            } catch (Exception e) {
                e.printStackTrace();
                log.info(e.getMessage());
                result.error500("操作失败：" + e.getMessage());
            }
        }
        return result;
    }

    /**
     * 通过id查询 包括子表数据相关
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/getById")
    public Result<FdContract> getById(@RequestParam(name = "id", required = true) String id) {
        Result<FdContract> result = new Result<FdContract>();
        FdContract fdContract = fdContractService.getById(id);
        if (fdContract == null) {
            result.error500("未找到对应实体");
        } else {
            //截取基质类型id
            String[] martxClassIds = fdContract.getNatrixType().split(",");
            //根据基质类型id获取相关信息
            List<FdMatrixType> fdMatrixTypeList = fdMatrixTypeService.selectBatchIds(martxClassIds);
            //合同类型名称
            String martxClassName = "";
            //循环获取名称
            for (FdMatrixType fdMatrixType : fdMatrixTypeList) {
                if (martxClassName == "") {
                    martxClassName = fdMatrixType.getName();
                } else {
                    martxClassName += "、" + fdMatrixType.getName();
                }
            }
            fdContract.setMatrixTypeName(martxClassName);
            //化合物查询条件
            LambdaQueryWrapper<FdContractCompound> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdContractCompound::getContractId,id);
            queryWrapper.eq(FdContractCompound::getDelFlag,"0");
            queryWrapper.orderByAsc(FdContractCompound::getSort);
            //查询第一个化合物
            List<FdContractCompound> compoundList=fdContractCompoundService.list(queryWrapper);
            //联系人查询条件
            LambdaQueryWrapper<FdContractContacts> query = new LambdaQueryWrapper<>();
            query.eq(FdContractContacts::getContractId,id);
            query.eq(FdContractContacts::getIsDefault,"1");
            query.eq(FdContractContacts::getDelFlag,"0");
            //查询默认联系人
            List<FdContractContacts> fdCustomerContactsList = fdContractContactsService.list(query);
            //添加联系人到报价单
            for ( FdContractContacts contacts : fdCustomerContactsList ) {
                fdContract.setContactPsn(contacts.getContactPsn());
                fdContract.setContactTel(contacts.getContactTel());
                fdContract.setContactEmail(contacts.getEmail());
            }
            //添加化合物到报价单
            String compound="";
            int i=0;
            for(FdContractCompound compounds:compoundList){
                if(i==0){
                    compound=compounds.getCompound();
                }else{
                    compound=compound+","+compounds.getCompound();
                }
                i++;
            }
            fdContract.setCompound(compound);
            //客户查询条件
            LambdaQueryWrapper<FdCustomer> queryCustomer = new LambdaQueryWrapper<>();
            queryCustomer.eq(FdCustomer::getId,fdContract.getPkCustomerId());
            List<FdCustomer> fdCustomerList = fdCustomerService.list(queryCustomer);
            for (FdCustomer fdCustomer:fdCustomerList){
                fdContract.setPkCustomerId(fdCustomer.getId());
                fdContract.setCustomerName(fdCustomer.getName());
                fdContract.setBidParty(fdCustomer.getName());
                fdContract.setAbbreviation(fdCustomer.getAbbreviation());
            }

            Map<String, Object> msp = Maps.newHashMap();
            msp.put("del_flag","0");
            msp.put("contract_id",fdContract.getId());
            List<FdContractContacts> fdContractContacts = (List<FdContractContacts>) fdContractContactsService.listByMap(msp);
            fdContract.setContractContactsList(fdContractContacts);
            // List<FdContractCompound> fdContractCompounds = (List<FdContractCompound>) fdContractCompoundService.listByMap(msp);
            fdContract.setContractCompoundList(compoundList);
            List<FdContractClause> fdContractClauses = (List<FdContractClause>) fdContractClauseService.listByMap(msp);
            fdContract.setContractClauseList(fdContractClauses);

            //获取bd名称
            FdPersonnel fdPersonnel=iFdPersonnelService.getById(fdContract.getProjectManagerId());
            if(fdPersonnel!=null){
                fdContract.setProjectManagerName(fdPersonnel.getName());
            }
            //获取报价类型
            FdProjectQuotation fdProjectQuotation=fdProjectQuotationService.getById(fdContract.getQuotationId());
            if(fdProjectQuotation!=null){
                fdContract.setQuotationTypeId(fdProjectQuotation.getQuotationType());
                fdContract.setQuotationTypeName(fdProjectQuotation.getQuotationTypeName());
            }

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


    // public Result<FdContract> getContractById(@RequestParam(name = "id", required = true) String id){
    //     Result<FdContract> result=new Result<>();
    //     try {
    //         FdContract fdContract=fdContractService.getById(id);
    //         if(fdContract==null){
    //             result.error500("未找到对应实体类");
    //         }else{
    //
    //         }
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    //
    //     return result;
    // }

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

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


    /**
     * @Author gurui
     * @Description //TODO 添加合同档案同时添加 申办方 化合物 合同条款 联系人 比例设置 明细
     * @Date 11:26 2019/6/14
     * @Param [fdContract, bindingResult]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
     **/
    @PostMapping(value = "/addAll")
    @NotDuplicate
    @RequiresPermissions("pm-contract:update")
    public Result<FdContract> addAll(@RequestBody @Valid FdContract fdContract, BindingResult bindingResult) {
        Result<FdContract> result = new Result<FdContract>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdContractService.saveAll(fdContract);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败:"+e.getMessage());
        }
        return result;
    }



    /**
     * @Author gurui
     * @Description //TODO 根据合同档案来源报价单id 查询 报价单模板
     * @Date 11:59 2019/5/31
     * @Param [quotationId]
     * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.basedata.entity.FdQuotationTemplate>>
     **/
    @GetMapping(value = "/findQuotationTemplate")
    public Result<List<FdQuotationTemplate>> findQuotationTemplate(String quotationId){
        Result<List<FdQuotationTemplate>> result = new Result<>();
        result.setResult(fdContractService.findQuotationTemplate(quotationId));
        return  result;
    }

    /***
     * @Title:状态关闭
            * @Description:TODO
            * @param ids
            * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
            * @exception
            * @author 陈创
            * @date 2019/6/5 9:35
            * @updatehistory:
     *   2019/6/5 9:35 批量修改
            */
    @GetMapping(value = "/closeBatch")
    @NotDuplicate
    @RequiresPermissions("pm-contract:close")
    public Result<FdContract> closeBatch(@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 = fdContractService.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 17:02 2019/6/13
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
     **/
    @DeleteMapping(value = "/deleteCompound")
    public Result<FdContract> deleteCompound(@RequestParam(name = "id", required = true) String id) {
        Result<FdContract> result = new Result<FdContract>();
        FdContract fdContract = fdContractService.getById(id);
        if (fdContract == null) {
            result.error500("未找到对应实体");
        } else {
            try {
                fdContractService.deleteCompound(id);
                //fdContractService.removeById(id);
                result.success("删除成功!");
            } catch (Exception e) {
                e.printStackTrace();
                log.info(e.getMessage());
                result.error500("操作失败：" + e.getMessage());
            }
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO 根据id删除联系人
     * @Date 18:02 2019/6/13
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
     **/
    @DeleteMapping(value = "/deleteContracts")
    public Result<FdContract> deleteContracts(@RequestParam(name = "id", required = true) String id) {
        Result<FdContract> result = new Result<FdContract>();
        FdContract fdContract = fdContractService.getById(id);
        if (fdContract == null) {
            result.error500("未找到对应实体");
        } else {
            try {
                fdContractService.deleteContracts(id);
                //fdContractService.removeById(id);
                result.success("删除成功!");
            } catch (Exception e) {
                e.printStackTrace();
                log.info(e.getMessage());
                result.error500("操作失败：" + e.getMessage());
            }
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO 弃审核数据,使其状态为0
     * @Date 10:20 2019/6/28
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
     **/
    @GetMapping(value = "/auditBatch")
    @NotDuplicate
    @RequiresPermissions("pm-contract:abandoning-trial")
    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 = fdContractService.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 10:20 2019/6/28
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
     **/
    @GetMapping(value = "/reviewBatch")
    @NotDuplicate
    @RequiresPermissions("pm-contract:to-examine")
    public Result<FdContract> reviewBatch(@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 = fdContractService.reviewBatch(ids);
            result.setSuccess(true);
            result.setMessage(message+map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    @RequestMapping(value = "/contractReport")
    @RequiresPermissions("url:pm-contract-report:view")
    public Result<List<FdContract>> contractReport(String startDate,String endDate){
        Result<List<FdContract>> result=new Result<>();
        try {
            List<FdContract> fdContractList=fdContractService.contractReport(startDate,endDate);
            result.setResult(fdContractList);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:合同导出word数据json
            * @Description:TODO
            * @param
            * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdContract>
            * @exception 
            * @author 陈创
            * @date 2019/9/16 16:10
            * @updatehistory:
     *   2019/9/16 16:10 新增
            */
    @GetMapping(value = "/exportJson")
    public Result<FdContract> exportJson(String contractId){
        Result<FdContract> result=new Result<>();
        FdContract fdContract=fdContractService.exportJson(contractId);
        try {
            result.setResult(fdContract);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:合同导入
            * @Description:TODO
            * @param fdContract
            * @return org.jeecg.common.api.vo.Result
            * @exception 
            * @author 陈创
            * @date 2019/11/25 10:25
            * @updatehistory:
     *   2019/11/25 10:25 新增
            */
    @PostMapping("/contractImport")
    public Result contractImport(@RequestBody FdContract fdContract){
        Result result=new Result();
        try {
            fdContractService.contractImport(fdContract);
            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/29 10:20
            * @updatehistory:
     *   2019/11/29 10:20 新增
            */
    @GetMapping("/updateStatusShared")
    public Result updateStatusShared(@RequestParam(name="ids",required = true) List<String> ids,@RequestParam(name="status",required = true)String status){
        Result result=new Result();
        try {
            fdContractService.updateStatusShared(ids,status);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:
            * @Description:TODO 双签通知
            * @param givePerson, contractId, receiverIds]
            * @return org.jeecg.common.api.vo.Result
            * @exception
            * @author 陈创
            * @date 2020/3/11 15:33
            * @updatehistory:
     *   2020/3/11 15:33 新增
            */
    @GetMapping(value = "/notificationPm")
    public Result notificationPm(@RequestParam(name="givePerson",required = true)String givePerson,
                                 @RequestParam(name="contractId",required = true)String contractId,
                                 @RequestParam(name="receiverIds",required = true)List<String> receiverIds){
        Result result=new Result();
        try {
            fdContractService.notificationPm(givePerson,contractId,receiverIds);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    public Result<FdContract> getFdContractInformationByCid(String cId){
        Result<FdContract> result=new Result<>();
        try {
            FdContract fdContractById=fdContractService.getById(cId);
            if(fdContractById==null){
                result.error500("未找到对应实体");
            }else{

            }
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /***
     * @Title:
            * @Description:TODO 附件上传下载
            * @param request, response]
            * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.message.entity.MailAttacch>>
            * @exception
            * @author 陈创
            * @date 2020/4/17 17:16
            * @updatehistory:
     *   2020/4/17 17:16 新增
            */
    @PostMapping(value = "multipartFile")
    public Result<List<MailAttacch>> multipartFile(HttpServletRequest request, HttpServletResponse response){
        Result<List<MailAttacch>> result=new Result<>();
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            String bizPath = "file";
            String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

//            MultipartFile mff = multipartRequest.getFile("file1");// 获取上传文件对象
//            MultipartFile mff2 = multipartRequest.getFile("file2");// 获取上传文件对象
            MultiValueMap<String,MultipartFile> files =multipartRequest.getMultiFileMap();

            List<MailAttacch> mailAttacchList=new ManagedList<>();//获取邮件格式的附件对象集合
            for(int i=0;i<files.size();i++){
                MultipartFile mf = files.getFirst("file"+i);// 获取上传文件对象
//            MultipartFile mf=multipartRequest.getFile("file1");
                String orgName = mf.getOriginalFilename();// 获取文件名
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
                String savePath = file.getPath() + File.separator + fileName;
                File savefile = new File(savePath);
                FileCopyUtils.copy(mf.getBytes(), savefile);
                String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
                if (dbpath.contains("\\")) {
                    dbpath = dbpath.replace("\\", "/");
                }
                //下载附件对象
                MailAttacch mailAttacch= download(savePath,orgName);
                mailAttacchList.add(mailAttacch);
            }
//            List<MailAttacch> mailAttacchList= download(savePath,orgName);
            result.setSuccess(true);
            result.setResult(mailAttacchList);
        } catch (IOException e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /***
     * @Title:
            * @Description:TODO 下载附件
            * @param [savePath, newFileName] 下载地址与文件名
            * @return java.util.List<org.jeecg.modules.message.entity.MailAttacch>
            * @exception
            * @author 陈创
            * @date 2020/4/17 17:18
            * @updatehistory:
     *   2020/4/17 17:18 新增
            */
    public MailAttacch download(String savePath,String newFileName){
        File newFile = new File(savePath);
        byte[] data = null;
        try {
            FileInputStream fis = new FileInputStream(newFile);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            data = baos.toByteArray();
            fis.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MailAttacch attachs=new MailAttacch();
        attachs.setFileName(newFileName);
        attachs.setFileContent(data);
//        List<MailAttacch> mailAttacchList=new ArrayList<>();
//        mailAttacchList.add(attachs);
        return attachs;
        // fdContractService.peopleSendMsg("17887951939@163.com","1479142272@qq.com","测试",);
        // aa(mailAttacchList);
    }


    /***
     * @Title:
            * @Description:TODO 发送邮件通知
            * @param [fdContract] 合同邮件相关信息
            * @return org.jeecg.common.api.vo.Result
            * @exception
            * @author 陈创
            * @date 2020/4/17 17:18
            * @updatehistory:
     *   2020/4/17 17:18 新增
            */
    @PostMapping(value = "/emailEnclosureNotificationPm")
    public Result emailEnclosureNotificationPm(@RequestBody FdContract fdContract){
        Result result=new Result();
        try {
            fdContractService.emailEnclosureNotificationPm(fdContract);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    public void aa(List<MailAttacch> attachs){
        ISendMsgHandle sendMsgHandle = null;
        try {
            sendMsgHandle = (ISendMsgHandle) Class.forName(SendMsgTypeEnum.EMAIL.getImplClass()).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发起邮件通知
        try {
            sendMsgHandle.SendMsgAndFile("1479142272@qq.com","1479142272@qq.com","测试",attachs);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("检查通知人员的邮箱是否有误");
        }
    }


    /***
     * @Title:
            * @Description:TODO 合同报表（统计图与统计表）
            * @param [fdContract]
            * @return org.jeecg.common.api.vo.Result<java.util.Map<java.lang.String,java.lang.Object>>
            * @exception
            * @author 陈创
            * @date 2020/4/26 10:47
            * @updatehistory:
     *   2020/4/26 10:47 新增
            */
    @GetMapping(value = "/totalProportion")
    @RequiresPermissions("url:pm-offerStatements:view")
    public Result<Map<String, Object>> totalProportion(FdContract fdContract) {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        try {
            List<FdContract> fdContractList = new ArrayList<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String date = "2017-01-01 00:00:00";
            //  开始时间，结束时间不为空
            if (oConvertUtils.isNotEmpty(fdContract.getBegin()) && oConvertUtils.isNotEmpty(fdContract.getOver())) {
                fdContractList = fdContractService.totalProportionContract(format.parse(fdContract.getBegin()), format.parse(fdContract.getOver()),fdContract);
            } else {
                String da = format.format(new Date());
                //  开始时间为空，结束时间为空
                fdContractList = fdContractService.totalProportionContract(format.parse(date), format.parse(da),fdContract);
            }
            Map<String, Object> map = Maps.newHashMap();

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

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



    @GetMapping(value = "/getReportPageContract")
    public Result<IPage<FdContract>> getReportPage(FdContract fdContract,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<FdContract>> result = new Result<>();
        //开始时间
        String begin=fdContract.getBegin();
        if(StringUtils.isNotBlank(begin)){
            fdContract.setBegin(null);
        }
        //结束时间
        String over=fdContract.getOver();
        if(StringUtils.isNotBlank(over)){
            fdContract.setOver(null);
        }

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

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

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

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

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

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

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

        QueryWrapper<FdContract> queryWrapper = QueryGenerator.initQueryWrapper(fdContract, req.getParameterMap());
//        queryWrapper.between("fc.create_time",begin,over);
        queryWrapper.ge("DATE_FORMAT(fc.create_time, '%Y-%m-%d')",begin);
        queryWrapper.le("DATE_FORMAT(fc.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("fc.project_manager_id",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("(fc.contract_type",contractType);
                }else{//中间
                    queryWrapper.or();
                    queryWrapper.like("fc.contract_type",contractType);
                }
                i++;
            }
            queryWrapper.apply("1=1)");
        }

        //状态
        // if(StringUtils.isNotBlank(status)){
        //     queryWrapper.eq("fpq.status",status);
        // }
        queryWrapper.eq("fc.del_flag", "0");
        queryWrapper.orderByDesc("fpq.create_time");
        queryWrapper.orderByDesc("fpq.code");
        Page<FdContract> page = new Page<FdContract>(pageNo, pageSize);
        IPage<FdContract> pageList = fdContractService.getReportPageContract(page, queryWrapper);
        //获取化合物名称和生物分析 临床比例
        getContractCoumpoundName(pageList.getRecords());
        //获取待审核人
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    //获取化合物名称和生物分析 临床比例
    public void getContractCoumpoundName(List<FdContract> fdContractList){
        //获取全部合同的化合物
        LambdaQueryWrapper<FdContractCompound> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FdContractCompound::getDelFlag,"0");
        lambdaQueryWrapper.orderByAsc(FdContractCompound::getSort);
        List<FdContractCompound> fdContractCompoundList=fdContractCompoundService.list(lambdaQueryWrapper);
        //获取合同比例
        List<FdContractProportion> fdContractProportionList=iFdContractProportionService.list();
            //循环查询出的合同
            for(FdContract fdContract:fdContractList){
                /////获取化合物名称
                String compoundName="";
                //是否有值
                if(fdContractCompoundList!=null&&fdContractCompoundList.size()>0){
                    //循环所有化合物
                    for(FdContractCompound compound:fdContractCompoundList){
                        //根据合同id找到对应的化合物
                        if(fdContract.getId().equals(compound.getContractId())){
                            if(compoundName.equals("")){
                                compoundName=compound.getCompound();
                            }else{
                                compoundName=compoundName+","+compound.getCompound();
                            }
                        }
                    }
                }
                fdContract.setCompoundName(compoundName);
                ///////////获取生物分析和临床比例
                if(fdContractProportionList!=null&&fdContractProportionList.size()>0){
                    for(FdContractProportion proportion:fdContractProportionList){
                        //根据合同id找到对应的比例
                        if(fdContract.getId().equals(proportion.getContractId())){
                            if(proportion.getProportionItem().equals("生物分析")){
                                fdContract.setBioanalysisProportion(proportion.getTotalMoney());
                            }
                            if(proportion.getProportionItem().equals("临床项目")){
                                fdContract.setClinicalProportion(proportion.getTotalMoney());
                            }
                        }
                    }
                }
            }

    }

    @GetMapping(value = "/getContractExport")
    public Result<List<FdContract>> getContractExport(FdContract fdContract){
        Result<List<FdContract>> result=new Result<>();
        try {
            List<FdContract> contractList=fdContractService.getContractExport(fdContract);
            result.setResult(contractList);
            result.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 根据项目档案获取唯一合同数据集合
    * @Date 2020/5/28 13:30
    * @Param []
    * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdContract>>
    */
    @GetMapping(value = "/getContractGroupById")
    public Result<List<FdContract>> getContractGroupById(){
        Result<List<FdContract> > result=new Result<>();
        try {
            List<FdContract> fdContractList=fdContractService.getContractGroupById();
            result.setResult(fdContractList);
            result.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    @GetMapping(value = "/getContractExportAll")
    public Result<List<FdContract>> getContractExportAll(FdContract fdContract, FdContractBidparty fdContractBidparty,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        Result<List<FdContract>> result = new Result<List<FdContract>>();
        String sourceQuotationCode = fdContract.getSourceQuotationCode();
        //对来源报价单号查询
        if(StringUtils.isNotBlank(fdContract.getSourceQuotationCode())){
            fdContract.setSourceQuotationCode(null);
        }
        String code = fdContract.getCode();
        if (StringUtils.isNotBlank(fdContract.getCode())) {
            fdContract.setCode(null);
        }
        String projectName = fdContract.getProjectName();
        if (StringUtils.isNotBlank(fdContract.getProjectName())) {
            fdContract.setProjectName(null);
        }
        String bidParty = fdContractBidparty.getId();
        if (StringUtils.isNotBlank(fdContractBidparty.getId())) {
            fdContractBidparty.setId(null);
        }
        //状态
        String status = fdContract.getStatus();
        if (StringUtils.isNotBlank(fdContract.getStatus())) {
            fdContract.setStatus(null);
        }

        //关联报价号
        String relationCode=fdContract.getRelationCode();
        if(StringUtils.isNotBlank(relationCode)){
            fdContract.setRelationCode(null);
        }

        Date createDate=fdContract.getCreateTime();
        if(createDate!=null){
            fdContract.setCreateTime(null);
        }
        //合同方
        String contractParty=fdContract.getContractParty();
        if(StringUtils.isNotBlank(contractParty)){
            fdContract.setContractParty(null);
        }
        //申办方
        String pkCustomerId=fdContract.getPkCustomerId();
        if(StringUtils.isNotBlank(pkCustomerId)){
            fdContract.setPkCustomerId(null);
        }

        //签署开始时间
        String begin=fdContract.getBegin();
        if(StringUtils.isNotBlank(begin)){
            fdContract.setBegin(null);
        }
        //签署结束时间
        String over=fdContract.getOver();
        if(StringUtils.isNotBlank(over)){
            fdContract.setOver(null);
        }

        //创建日期开始时间
        String createTimeStart=fdContract.getCreateTimeStart();
        if(StringUtils.isNotBlank(createTimeStart)){
            fdContract.setCreateTimeStart(null);
        }
        //创建日期结束时间
        String createTimeEnd=fdContract.getCreateTimeEnd();
        if(StringUtils.isNotBlank(createTimeEnd)){
            fdContract.setCreateTimeEnd(null);
        }

        QueryWrapper<FdContract> queryWrapper = QueryGenerator.initQueryWrapper(fdContract, req.getParameterMap());
        queryWrapper.eq("fc.del_flag", "0");
        queryWrapper.orderByDesc("fc.create_time");
        // queryWrapper.eq("fcc.sort","1");
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("fc.code", code);
        }
        if (StringUtils.isNotBlank(projectName)) {
            queryWrapper.like("fc.project_name", projectName);
        }
        if (StringUtils.isNotBlank(bidParty)) {
            queryWrapper.like("fcb.id", bidParty);
        }
        if(StringUtils.isNotBlank(status)){
            queryWrapper.eq("fc.status",status);
        }
        if(StringUtils.isNotBlank(sourceQuotationCode)){
            queryWrapper.like("fc.source_quotation_code",sourceQuotationCode);
        }
        if(StringUtils.isNotBlank(relationCode)){
            queryWrapper.like("fpq.relation_code",relationCode);
        }
        if(createDate!=null){
            queryWrapper.eq("fc.create_time",createDate);
        }

        if(StringUtils.isNotBlank(contractParty)&&!contractParty.equals("null")){
            queryWrapper.eq("fc.contract_party",contractParty);
        }
        if(StringUtils.isNotBlank(pkCustomerId)&&!pkCustomerId.equals("null")){
            queryWrapper.eq("fc.pk_customer_id",pkCustomerId);
        }
        //签署日期范围查询
        if(StringUtils.isNotBlank(begin)&&StringUtils.isNotBlank(over)&&!begin.equals("null")&&!over.equals("null")){
            queryWrapper.between("fc.sign_date",begin,over);
        }
        //创建日期范围查询
        if(StringUtils.isNotBlank(createTimeStart)&&StringUtils.isNotBlank(createTimeEnd)&&!createTimeStart.equals("null")&&!createTimeEnd.equals("null")){
            queryWrapper.between("fc.create_time",createTimeStart,createTimeEnd);
        }
        //按时间排序
        queryWrapper.orderByDesc("fc.create_time");
        Page<FdContract> page = new Page<FdContract>(pageNo, pageSize);
        IPage<FdContract> pageList = fdContractService.findByPage(page, queryWrapper);
        List<String> contractIds=new ArrayList<>();
        if(pageList.getRecords()!=null&&pageList.getRecords().size()>0){
            for(FdContract fdContract1:pageList.getRecords()){
                contractIds.add(fdContract1.getId());
            }
        }
        FdContract fdContractSelect=new FdContract();
        fdContractSelect.setContractIdList(contractIds);
        List<FdContract> contractList=fdContractService.getContractExport(fdContractSelect);
        result.setResult(contractList);
        result.success("操作成功");

        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 单独修改付款方
    * @Date 2020/8/20 14:08
    * @Param [fdContract]
    * @return org.jeecg.common.api.vo.Result
    */
    @PutMapping(value = "/updatePayerName")
    public Result updatePayerName(@RequestBody FdContract fdContract){
        Result result=new Result();
        try {
            FdContract fdContract1=new FdContract();
            fdContract1.setId(fdContract.getId());
            fdContract1.setPayerName(fdContract.getPayerName());
            fdContractService.updateById(fdContract1);
            result.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

}
