package com.ozs.web.controller.pm;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ozs.base.domain.BaseAgency;
import com.ozs.base.domain.BaseExpert;
import com.ozs.base.domain.BaseProfessional;
import com.ozs.base.domain.BaseUnitInformation;
import com.ozs.base.domain.vo.BaseExpertVo;
import com.ozs.base.domain.vo.BaseProfessionalVo;
import com.ozs.base.service.BaseAgencyService;
import com.ozs.base.service.BaseExpertService;
import com.ozs.base.service.BaseProfessionalService;
import com.ozs.common.annotation.Log;
import com.ozs.common.constant.ModularConstans;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysUser;
import com.ozs.common.enums.*;
import com.ozs.common.utils.RandomUtil;
import com.ozs.common.utils.StringUtils;
import com.ozs.pm.doman.*;
import com.ozs.pm.doman.vo.requestVo.*;
import com.ozs.pm.doman.vo.responseVo.PmDemandResVo;
import com.ozs.pm.service.*;
import com.ozs.system.domain.SysFileRef;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.*;

/**
 * 采购执行Controller
 *
 * @author ruoyi
 * @date 2023-01-16
 */
@Api(tags = "采购执行")
@RestController
@RequestMapping("/pm/purchaseExecution")
public class PmPurchaseExecutionController extends BaseController {
    @Autowired
    private IPmDemandService pmDemandService;
    @Autowired
    private PmDemandHisService pmDemandHisService;
    @Autowired
    private BaseAgencyService baseAgencyService;
    @Autowired
    private BaseExpertService baseExpertService;

    @Autowired
    private PmDemandExpertRefService pmDemandExpertRefService;
    @Autowired
    private PmDemandExpertRefHisService pmDemandExpertRefHisService;

    @Autowired
    private PmBidOpeningService pmBidOpeningService;
    @Autowired
    private PmBidOpeningHisService pmBidOpeningHisService;
    @Autowired
    private PmBidWinningOpeningRefService pmBidWinningOpeningRefService;
    @Autowired
    private PmBidWinningOpeningRefHisService pmBidWinningOpeningRefHisService;

    @Autowired
    private BaseProfessionalService baseProfessionalService;
    @Autowired
    private PmExpertFeedbackService pmExpertFeedbackService;
    @Autowired
    private PmProcurementDocumentsReviewService pmProcurementDocumentsReviewService;
    @Autowired
    private PmBidFailureService pmBidFailureService;
    @Autowired
    private PmCallQuestionService pmCallQuestionService;

    /**
     * 采购执行查询列表
     */
    @ApiOperation(value = "采购执行查询列表", notes = "参数非必传")
    @PostMapping("/list")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:list')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult list(@RequestBody PmDemandReqVo pmDemandReqVo) {
        pmDemandReqVo.setIsAdmin(SysUser.isAdmin(getUserId()));
        pmDemandReqVo.setDeptId(getDeptId());
        pmDemandReqVo.setUserId(getUserId());
        IPage<PmDemandResVo> page = pmDemandService.selectPmDemandList(pmDemandReqVo, 3);
        return success(page);
    }

    /**
     * 查询代理机构列表
     */
    @ApiOperation(value = "查询代理机构列表", notes = "采购需求ID必传")
    @GetMapping("/getAgencyList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getAgencyList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getAgencyList(@NotEmpty(message = "采购需求ID不能为空")
                               @RequestParam(value = "demandId", required = true) Long demandId) {
        PmDemand pmDemand = pmDemandService.getById(demandId);
        if(ObjectUtils.isEmpty(pmDemand)){
            return error("参数错误");
        }
        LambdaQueryWrapper<BaseAgency> lw = new LambdaQueryWrapper<>();
        lw.eq(BaseAgency::getCompanyType,pmDemand.getProjectType());
        lw.eq(BaseAgency::getStatus,NameListType.WHITE.getCode());//白名单
        List<BaseAgency> agencyList = baseAgencyService.list(lw);
        return success(agencyList);
    }

    /**
     * 选取代理-选择填写招标代理机构信息
     */
    @ApiOperation(value = "选取代理-选择填写招标代理机构信息",notes = "采购需求ID和代理机构ID必传")
    @GetMapping("/selectAgency")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:selectAgency')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.UPDATE)
    public AjaxResult selectAgency(@NotEmpty(message = "采购需求ID不能为空")
                                   @RequestParam(value = "demandId", required = true) Long demandId,
                                   @NotEmpty(message = "代理机构ID不能为空")
                                   @RequestParam(value = "agencyId", required = true) Long agencyId,
                                   @RequestParam(value = "purchaseTaskDocumentNumber", required = false) String purchaseTaskDocumentNumber) {

        PmDemand pmDemand = pmDemandService.getById(demandId);
        if(ObjectUtils.isEmpty(pmDemand)){
            return error("参数错误");
        }
        BaseAgency baseAgency = baseAgencyService.getById(agencyId);
        if(ObjectUtils.isEmpty(baseAgency)){
            return error("参数错误");
        }
        PmDemand pmDemandUpdate = new PmDemand();
        pmDemandUpdate.setDemandId(demandId);
        pmDemandUpdate.setProjectStatus(PmProjectStatus.EXPERT_FEEDBACK.getCode());
        pmDemandUpdate.setAgencyId(agencyId);
        pmDemandUpdate.setPurchaseTaskDocumentNumber(purchaseTaskDocumentNumber);
        pmDemandUpdate.setExtractAgencyTime(new Date());
        pmDemandUpdate.setUpdateTime(pmDemandUpdate.getExtractAgencyTime());
        pmDemandUpdate.setUpdateBy(getUserId().toString());
        return success(pmDemandService.updateById(pmDemandUpdate));
    }

    /**
     * 选取代理-抽取招标代理机构信息
     */
    @ApiOperation(value = "选取代理-抽取招标代理机构信息",notes = "采购需求ID必传")
    @GetMapping("/extractAgency")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:extractAgency')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.UPDATE)
    public AjaxResult extractAgency(@NotEmpty(message = "采购需求id不能为空")
                                     @RequestParam(value = "demandId", required = true) Long demandId,
                                    @RequestParam(value = "purchaseTaskDocumentNumber", required = false) String purchaseTaskDocumentNumber) {

        PmDemand pmDemand = pmDemandService.getById(demandId);
        if(ObjectUtils.isEmpty(pmDemand)){
            return error("参数错误");
        }
        LambdaQueryWrapper<BaseAgency> lw = new LambdaQueryWrapper<>();
        lw.eq(BaseAgency::getCompanyType,pmDemand.getProjectType());
        lw.eq(BaseAgency::getStatus,NameListType.WHITE.getCode()); //白名单
        List<BaseAgency> baseAgencyList = baseAgencyService.list(lw);
        if (ObjectUtils.isEmpty(baseAgencyList)){
            return error("没有符合的招标代理机构，抽取失败！");
        }

        BaseAgency any = (BaseAgency)(RandomUtil.getRandomList(baseAgencyList,1).get(0));

        PmDemand pmDemandUpdate = new PmDemand();
        pmDemandUpdate.setDemandId(demandId);
        pmDemandUpdate.setProjectStatus(PmProjectStatus.EXPERT_FEEDBACK.getCode());
        pmDemandUpdate.setAgencyId(any.getId());
        pmDemandUpdate.setPurchaseTaskDocumentNumber(purchaseTaskDocumentNumber);
        pmDemandUpdate.setExtractAgencyTime(new Date());
        pmDemandUpdate.setUpdateTime(pmDemandUpdate.getExtractAgencyTime());
        pmDemandUpdate.setUpdateBy(getUserId().toString());
        return success(pmDemandService.updateById(pmDemandUpdate));
    }

    @ApiOperation(value = "1-2专家意见反馈",notes = "采购需求ID和上传附件必传")
    @PostMapping("/expertFeedback")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:expertFeedback')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.IMPORT)
    public AjaxResult expertFeedback(@NotEmpty(message = "数据为空") @RequestBody PmExpertFeedbackReqVo pmExpertFeedbackReqVo) {
        Long demandId = pmExpertFeedbackReqVo.getDemandId();
        if(ObjectUtils.isEmpty(demandId)){
            return error("参数错误");
        }

        PmDemand pmDemand = pmDemandService.getById(demandId);
        if(ObjectUtils.isEmpty(pmDemand)){
            return error("参数错误");
        }

        List<SysFileRef> sysFileRefs = pmExpertFeedbackReqVo.getSysFileRefs();
        if(ObjectUtils.isEmpty(sysFileRefs)){
            return error("上传附件不能为空");
        }
        PmExpertFeedback pmExpertFeedback = new PmExpertFeedback();
        BeanUtils.copyProperties(pmExpertFeedbackReqVo,pmExpertFeedback);
        if(pmExpertFeedbackService.save(pmExpertFeedback)){
            pmDemandService.uploadFile(pmExpertFeedback.getId(), SysFileRefEnum.PM_EXPERT_FEEDBACK.getType(),sysFileRefs,getUserId().toString());
            PmDemand pmDemandUpdate = new PmDemand();
            pmDemandUpdate.setDemandId(demandId);
            pmDemandUpdate.setProjectStatus(PmProjectStatus.PROCUREMENT_DOCUMENTS_REVIEW.getCode());
            pmDemandUpdate.setUpdateTime(new Date());
            pmDemandUpdate.setUpdateBy(getUserId().toString());
            return success(pmDemandService.updateById(pmDemandUpdate));
        } else {
            return error("保存失败");
        }
    }


    @ApiOperation(value = "1-3采购文件编制审核",notes = "采购需求ID和上传附件必传")
    @PostMapping("/uploadBidFile")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:uploadBidFile')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.IMPORT)
    public AjaxResult uploadBidFile(@NotEmpty(message = "数据为空") @RequestBody PmProcurementDocumentsReviewReqVo pmProcurementDocumentsReviewReqVo) {
        Long demandId = pmProcurementDocumentsReviewReqVo.getDemandId();
        if(ObjectUtils.isEmpty(demandId)){
            return error("参数错误");
        }

        PmDemand pmDemand = pmDemandService.getById(demandId);
        if(ObjectUtils.isEmpty(pmDemand)){
            return error("参数错误");
        }

        List<SysFileRef> sysFileRefs = pmProcurementDocumentsReviewReqVo.getSysFileRefs();
        if(ObjectUtils.isEmpty(sysFileRefs)){
            return error("上传附件不能为空");
        }
        PmProcurementDocumentsReview pmProcurementDocumentsReview = new PmProcurementDocumentsReview();
        BeanUtils.copyProperties(pmProcurementDocumentsReviewReqVo,pmProcurementDocumentsReview);
        if(this.pmProcurementDocumentsReviewService.save(pmProcurementDocumentsReview)){
            pmDemandService.uploadFile(pmProcurementDocumentsReview.getId(), SysFileRefEnum.PM_BID_FILE.getType(),sysFileRefs,getUserId().toString());
            PmDemand pmDemandUpdate = new PmDemand();
            pmDemandUpdate.setDemandId(demandId);
            pmDemandUpdate.setProjectStatus(PmProjectStatus.PROCUREMENT_ANNOUNCEMENT.getCode());
            pmDemandUpdate.setUpdateTime(new Date());
            pmDemandUpdate.setUpdateBy(getUserId().toString());
            return success(pmDemandService.updateById(pmDemandUpdate));
        } else {
            return error("保存失败");
        }
    }


    @ApiOperation(value = "发布公告")
    @PostMapping("/insertPmReleaseAnnouncement")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:insertPmReleaseAnnouncement')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.INSERT)
    public AjaxResult insertPmReleaseAnnouncement(@NotEmpty(message = "数据为空")
                                       @RequestBody PmReleaseAnnouncementReqVo pmReleaseAnnouncementReqVo) {
        try {
            Long demandId = pmReleaseAnnouncementReqVo.getDemandId();
            if(ObjectUtils.isEmpty(demandId)){
                return error("参数错误");
            }
            pmReleaseAnnouncementReqVo.setCreateBy(getUserId().toString());
            pmReleaseAnnouncementReqVo.setCreateTime(new Date());
            pmReleaseAnnouncementReqVo.setUpdateBy(pmReleaseAnnouncementReqVo.getCreateBy());
            pmReleaseAnnouncementReqVo.setUpdateTime(pmReleaseAnnouncementReqVo.getCreateTime());
            return toAjax(pmDemandService.insertPmReleaseAnnouncement(pmReleaseAnnouncementReqVo));
        }  catch (Exception e) {
            return error(e.getMessage());
        }

    }

    @ApiOperation(value = "1-5标前质疑投诉",notes = "采购需求ID必传")
    @PostMapping("/handlePreCallQuestion")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:handlePreCallQuestion')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.UPDATE)
    public AjaxResult handlePreCallQuestion(@NotEmpty(message = "数据为空")
                                         @RequestBody PmCallQuestionReqVo pmCallQuestionReqVo) {
        try {
            Long demandId = pmCallQuestionReqVo.getDemandId();
            if(ObjectUtils.isEmpty(demandId)){
                return error("参数错误");
            }
            PmDemand pmDemand = pmDemandService.getById(demandId);
            if(ObjectUtils.isEmpty(pmDemand)){
                return error("参数错误");
            }
            if("1".equals(pmCallQuestionReqVo.getCallQuestion())) { //有质疑
                if (ObjectUtils.isEmpty(pmCallQuestionReqVo.getCallQuestionTime())) {
                    return error("质疑时间不能为空");
                }
            }
            PmCallQuestion pmCallQuestion = new PmCallQuestion();
            BeanUtils.copyProperties(pmCallQuestionReqVo,pmCallQuestion);
            pmCallQuestion.setType("0");

           if(pmCallQuestionService.save(pmCallQuestion)) {
               if("1".equals(pmCallQuestion.getCallQuestion())) { //有质疑
                   List<SysFileRef> sysFileRefs = pmCallQuestionReqVo.getSysFileRefs();
                   pmDemandService.uploadFile(pmCallQuestion.getId(), SysFileRefEnum.PM_PRE_BID_CALL_QUESTION.getType(),sysFileRefs,getUserId().toString());
               }
           }

            pmDemand.setProjectStatus(PmProjectStatus.WAIT_OPEN_BID.getCode());
            pmDemand.setUpdateBy(getUserId().toString());
            pmDemand.setUpdateTime(new Date());
            return toAjax(pmDemandService.updateById(pmDemand));

        }  catch (Exception e) {
            return error(e.getMessage());
        }
    }


    @ApiOperation(value = "获取专家身份证号列表")
    @GetMapping("/getExpertIdNumberList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getExpertIdNumberList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getExpertIdNumberList(@NotEmpty(message = "采购需求id不能为空")
                                                @RequestParam(value = "demandId", required = true) Long demandId) {
        PmDemand pmDemand = pmDemandService.getById(demandId);
        if(ObjectUtils.isEmpty(pmDemand)){
            return error("参数错误");
        }

        LambdaQueryWrapper<BaseExpert> lw = new LambdaQueryWrapper<BaseExpert>();
        lw.eq(BaseExpert::getVarietyPurchase,pmDemand.getProjectType())
                .eq(BaseExpert::getStatus,NameListType.WHITE.getCode());
        List<BaseExpert> baseExpertList = baseExpertService.list(lw);
        List<String> idNumberList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(baseExpertList)) {
            for(BaseExpert baseExpert :baseExpertList ){
                idNumberList.add(baseExpert.getIdNumber());
            }
        }
        return success(idNumberList);
    }

    @ApiOperation(value = "根据身份证号查询专家", notes = "必传 查询条件：身份证号")
    @GetMapping("/findExpertWithIdNumber")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:findExpertWithIdNumber')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult findExpertWithIdNumber(@NotEmpty(message = "采购需求id不能为空")
                                                 @RequestParam(value = "demandId", required = true) Long demandId,
                                             @NotEmpty(message = "身份证号不能为空")
                                       @RequestParam(value = "idNumber", required = true) String idNumber) {
        PmDemand pmDemand = pmDemandService.getById(demandId);
        if(ObjectUtils.isEmpty(pmDemand)){
            return error("参数错误");
        }
        LambdaQueryWrapper<BaseExpert> lw = new LambdaQueryWrapper<>();
        lw.eq(BaseExpert::getIdNumber,idNumber);
        BaseExpert baseExpert = baseExpertService.getOne(lw);
        if(baseExpert != null){
            if(NameListType.BLACK.getCode().equals(baseExpert.getStatus())){
                return error("该专家属于黑名单");
            }
            if(!ObjectUtils.isEmpty(pmDemand.getProjectType()) && !pmDemand.getProjectType().equals(baseExpert.getVarietyPurchase())){
                return error("该专家所属采购品种和项目类型不匹配");
            }
        }

        return success(baseExpert);
    }

    @ApiOperation(value = "查询专业库树结构", notes = "非必传 查询条件：品目名称")
    @PostMapping("/selectBaseProfessional")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:selectBaseProfessional')")
    @Log(title = ModularConstans.professional, businessType = BusinessType.QUERY)
    public AjaxResult selectBaseProfessional(@RequestBody BaseProfessionalVo baseProfessionalVo) {
        List<BaseProfessionalVo> baseSupplierList = baseProfessionalService.selectBaseProfessionalVo(baseProfessionalVo);
        return success(baseSupplierList);
    }


    @ApiOperation(value = "填写专家信息批量提交", notes = "必传 采购需求ID和专家信息列表,注意：若该专家已经在库里存在，需要传专家对象BaseExpert的ID")
    @PostMapping("/insertExpertBatch")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:insertExpertBatch')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.INSERT)
    public AjaxResult insertExpertBatch(@NotEmpty(message = "参数不能为空") @RequestBody PmBaseExpertFillReqVo pmBaseExpertFillReqVo) {

        try {
            if (ObjectUtils.isEmpty(pmBaseExpertFillReqVo)
                    || ObjectUtils.isEmpty(pmBaseExpertFillReqVo.getDemandId())
                    || ObjectUtils.isEmpty(pmBaseExpertFillReqVo.getAccessTime())
                    || ObjectUtils.isEmpty(pmBaseExpertFillReqVo.getBaseExpertList())) {
                return error("参数错误");
            }
            pmBaseExpertFillReqVo.setCreateBy(getUserId().toString());
            pmBaseExpertFillReqVo.setUpdateBy(pmBaseExpertFillReqVo.getCreateBy());

            return toAjax(pmDemandService.insertExpertBatch(pmBaseExpertFillReqVo));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @ApiOperation(value = "获取回避单位下拉列表")
    @GetMapping("/getExpertUnitList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getExpertUnitList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getExpertUnitList() {
        List<BaseUnitInformation> baseUnitInformationList = baseExpertService.getBaseUnitInformationList();
        if(ObjectUtils.isEmpty(baseUnitInformationList)){
            return error("专家单位列表是空的");
        }
        Set<String> set = new HashSet<>();
        for(BaseUnitInformation baseUnitInformation : baseUnitInformationList) {
            set.add(baseUnitInformation.getUnitName());
        }
        return success(set);
    }

    /**
     * 抽取专家
     */
    @ApiOperation(value = "抽取专家",notes = "采购需求ID必传")
    @PostMapping("/extractExpertBatch")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:extractExpertBatch')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.UPDATE)
    public AjaxResult extractExpertBatch(@NotEmpty(message = "参数不能为空")
                                             @RequestBody PmBaseExpertExtractReqVo pmBaseExpertExtractReqVo) {

        try {
            if (ObjectUtils.isEmpty(pmBaseExpertExtractReqVo)
                    || ObjectUtils.isEmpty(pmBaseExpertExtractReqVo.getDemandId())
                    || ObjectUtils.isEmpty(pmBaseExpertExtractReqVo.getAccessTime())) {
                return error("参数错误");
            }
            return toAjax(pmDemandService.extractExpertBatch(pmBaseExpertExtractReqVo));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @ApiOperation(value = "填写开标信息",notes = "采购需求ID必传")
    @PostMapping("/insertBidOpeningBatch")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:insertBidOpeningBatch')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.INSERT)
    public AjaxResult insertBidOpeningBatch(@NotEmpty(message = "数据为空")
                                                  @RequestBody PmBidOpeningFillReqVo pmBidOpeningFillReqVo) {

        try {
            if (ObjectUtils.isEmpty(pmBidOpeningFillReqVo)
                    || ObjectUtils.isEmpty(pmBidOpeningFillReqVo.getDemandId())
                    || ObjectUtils.isEmpty(pmBidOpeningFillReqVo.getPmBidOpeningList())) {
                return error("参数错误");
            }
            pmBidOpeningFillReqVo.setCreateBy(getUserId().toString());
            pmBidOpeningFillReqVo.setUpdateBy(getUserId().toString());
            return toAjax(pmDemandService.insertBidOpeningBatch(pmBidOpeningFillReqVo));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 中标基本情况填制-开标信息下拉列表
     */
    @ApiOperation(value = "中标基本情况填制-开标信息下拉列表", notes = "必传选需求ID")
    @GetMapping("/getPullDownBidOpeningList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getPullDownBidOpeningList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getPullDownBidOpeningList(@NotEmpty(message = "需求ID不能为空")
                                        @RequestParam(value = "demandId", required = true) Long demandId) {
        LambdaQueryWrapper<PmBidOpening> pmBidOpeningLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pmBidOpeningLambdaQueryWrapper.eq(PmBidOpening::getDemandId,demandId)
                .orderByDesc(PmBidOpening::getScore)
        ;
        List<PmBidOpening> pmBidOpeningList = pmBidOpeningService.list(pmBidOpeningLambdaQueryWrapper);
        return success(pmBidOpeningList);
    }

    @ApiOperation(value = "中标基本情况填制-中标情况填制提交(评标结果公告)",notes = "采购需求ID必传")
    @PostMapping("/insertPmBidWinning")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:insertPmBidWinning')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.INSERT)
    public AjaxResult insertPmBidWinning(@NotEmpty(message = "数据为空")
                                                  @RequestBody PmBidWinningReqVo pmBidWinningReqVo) {
      try {
          Long demandId = pmBidWinningReqVo.getDemandId();
          if(ObjectUtils.isEmpty(demandId)){
              return error("采购需求ID不能为空");
          }
          pmBidWinningReqVo.setCreateBy(getUserId().toString());
          pmBidWinningReqVo.setCreateTime(new Date());
          pmBidWinningReqVo.setUpdateBy(pmBidWinningReqVo.getCreateBy());
          pmBidWinningReqVo.setUpdateTime(pmBidWinningReqVo.getCreateTime());
          return toAjax(pmDemandService.insertPmBidWinning(pmBidWinningReqVo));
      }  catch (Exception e) {
          return error(e.getMessage());
      }
    }

    @ApiOperation(value = "中标基本情况填制-更换中标人提交",notes = "采购需求ID必传")
    @PostMapping("/updatePmBidWinning")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:updatePmBidWinning')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.UPDATE)
    public AjaxResult updatePmBidWinning(@NotEmpty(message = "数据为空")
                                         @RequestBody PmBidWinningReqVo pmBidWinningReqVo) {
        try {
            Long demandId = pmBidWinningReqVo.getDemandId();
            if(ObjectUtils.isEmpty(demandId)){
                return error("采购需求ID不能为空");
            }
            pmBidWinningReqVo.setUpdateBy(getUserId().toString());
            pmBidWinningReqVo.setUpdateTime(new Date());
            return toAjax(pmDemandService.updatePmBidWinning(pmBidWinningReqVo));
        }  catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @ApiOperation(value = "流标情况填制",notes = "采购需求ID必传")
    @PostMapping("/insertPmBidFailure")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:insertPmBidFailure')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.INSERT)
    public AjaxResult insertPmBidFailure(@NotEmpty(message = "数据为空")
                                         @RequestBody PmBidFailureReqVo pmBidFailureReqVo) {
        try {
            Long demandId = pmBidFailureReqVo.getDemandId();
            if(ObjectUtils.isEmpty(demandId)){
                return error("参数错误");
            }
            pmBidFailureReqVo.setCreateBy(getUserId().toString());
            pmBidFailureReqVo.setCreateTime(new Date());
            pmBidFailureReqVo.setUpdateBy(pmBidFailureReqVo.getCreateBy());
            pmBidFailureReqVo.setUpdateTime(pmBidFailureReqVo.getCreateTime());
            return toAjax(pmDemandService.insertPmBidFailure(pmBidFailureReqVo));
        }  catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @ApiOperation(value = "流废标处置-质疑处理",notes = "采购需求ID必传")
    @PostMapping("/handleBidFailureCallQuestion")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:handleBidFailureCallQuestion')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.UPDATE)
    public AjaxResult handleBidFailureCallQuestion(@NotEmpty(message = "数据为空")
                                         @RequestBody PmCallQuestionReqVo pmCallQuestionReqVo) {
        try {
            Long demandId = pmCallQuestionReqVo.getDemandId();
            if(ObjectUtils.isEmpty(demandId)){
                return error("参数错误");
            }
            PmDemand pmDemand = pmDemandService.getById(demandId);
            if(ObjectUtils.isEmpty(pmDemand)){
                return error("参数错误");
            }
            if("1".equals(pmCallQuestionReqVo.getCallQuestion())) { //有质疑
                if (ObjectUtils.isEmpty(pmCallQuestionReqVo.getCallQuestionTime())) {
                    return error("质疑时间不能为空");
                }
            }
            LambdaQueryWrapper<PmBidFailure> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PmBidFailure::getDemandId,pmDemand.getDemandId())
                    .orderByDesc(PmBidFailure::getBidFailureTime)
                    .last(" limit 1");
            PmBidFailure bidFailure = this.pmBidFailureService.getOne(lambdaQueryWrapper);
            if (ObjectUtils.isEmpty(bidFailure)) {
                return error("没有流标信息");
            }
            PmBidFailure bidFailureUpdate = new PmBidFailure();
            bidFailureUpdate.setId(bidFailure.getId());
            bidFailureUpdate.setCallQuestion(pmCallQuestionReqVo.getCallQuestion());
            bidFailureUpdate.setCallQuestionTime(pmCallQuestionReqVo.getCallQuestionTime());

            if("1".equals(bidFailureUpdate.getCallQuestion())){ //有质疑
                List<SysFileRef> sysFileRefs = pmCallQuestionReqVo.getSysFileRefs();
                pmDemandService.uploadFile(bidFailureUpdate.getId(), SysFileRefEnum.PM_BID_FAILURE_CALL_QUESTION.getType(),sysFileRefs,getUserId().toString());
            }

            bidFailureUpdate.setUpdateBy(getUserId().toString());
            bidFailureUpdate.setUpdateTime(new Date());
            return toAjax(pmBidFailureService.updateById(bidFailureUpdate));

        }  catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @ApiOperation(value = "流废标退回",notes = "采购需求ID必传")
    @GetMapping("/returnBidFailure")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:returnBidFailure')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.UPDATE)
    public AjaxResult returnBidFailure(@NotEmpty(message = "采购需求id不能为空")
                                           @RequestParam(value = "demandId", required = true) Long demandId) {
        try {
            return toAjax(pmDemandHisService.returnBidFailure(demandId, getUserId().toString()));
        }  catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @ApiOperation(value = "标后质疑",notes = "采购需求ID必传")
    @PostMapping("/handleCallQuestion")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:handleCallQuestion')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.UPDATE)
    public AjaxResult handleCallQuestion(@NotEmpty(message = "数据为空")
                                         @RequestBody PmCallQuestionReqVo pmCallQuestionReqVo) {
        try {
            Long demandId = pmCallQuestionReqVo.getDemandId();
            if(ObjectUtils.isEmpty(demandId)){
                return error("参数错误");
            }
            PmDemand pmDemand = pmDemandService.getById(demandId);
            if(ObjectUtils.isEmpty(pmDemand)){
                return error("参数错误");
            }
            if("1".equals(pmCallQuestionReqVo.getCallQuestion())) { //有质疑
                if (ObjectUtils.isEmpty(pmCallQuestionReqVo.getCallQuestionTime())) {
                    return error("质疑时间不能为空");
                }
            }
            PmCallQuestion pmCallQuestion = new PmCallQuestion();
            BeanUtils.copyProperties(pmCallQuestionReqVo,pmCallQuestion);
            pmCallQuestion.setType("1");
            if(pmCallQuestionService.save(pmCallQuestion)) {
                if("1".equals(pmCallQuestion.getCallQuestion())) { //有质疑
                    List<SysFileRef> sysFileRefs = pmCallQuestionReqVo.getSysFileRefs();
                    pmDemandService.uploadFile(pmCallQuestion.getId(), SysFileRefEnum.PM_BID_CALL_QEUSTION_FILE.getType(), sysFileRefs, getUserId().toString());
                }
            }

            pmDemand.setUpdateBy(getUserId().toString());
            pmDemand.setUpdateTime(new Date());
            return toAjax(pmDemandService.updateById(pmDemand));

        }  catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @ApiOperation(value = "上传中标通知书",notes = "采购需求ID和上传附件必传")
    @PostMapping("/uploadBidWinningNotification")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:uploadBidWinningNotification')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.IMPORT)
    public AjaxResult uploadBidWinningNotification(@NotEmpty(message = "数据为空") @RequestBody PmPurchaseExecutionReqVo pmPurchaseExecutionReqVo) {
        Long demandId = pmPurchaseExecutionReqVo.getDemandId();
        if(ObjectUtils.isEmpty(demandId)){
            return error("参数错误");
        }

        PmDemand pmDemand = pmDemandService.getById(demandId);
        if(ObjectUtils.isEmpty(pmDemand)){
            return error("参数错误");
        }

        List<SysFileRef> sysFileRefs = pmPurchaseExecutionReqVo.getSysFileRefs();
        if(ObjectUtils.isEmpty(sysFileRefs)){
            return error("上传附件不能为空");
        }
        if (pmDemandService.uploadFile(demandId, SysFileRefEnum.PM_BID_WINNING_NOTIFICATION.getType(),sysFileRefs,getUserId().toString())) {
            PmDemand pmDemandUpdate = new PmDemand();
            pmDemandUpdate.setDemandId(demandId);
            pmDemandUpdate.setProjectStatus(PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
            pmDemandUpdate.setRealPurchaseFinishTime(new Date());
            pmDemandUpdate.setWarnStatus(WarnStatus.NORMAL.getCode());
            pmDemandUpdate.setUpdateTime(new Date());
            pmDemandUpdate.setUpdateBy(getUserId().toString());
            return success(pmDemandService.updateById(pmDemandUpdate));
        } else {
            return error("保存上传附件失败");
        }
    }

    /**
     * 查看详情
     */
    @ApiOperation(value = "查看详情", notes = "必传demandId和详情类型(1项目计划，2需求建档，3任务下达,4中标信息，5合同信息，6建设情况),其他字段不传")
    @PostMapping("/view")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:view')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult view(@RequestBody PmDemandReqVo pmDemandReqVo) {
        if(pmDemandReqVo.getDemandId() == null){
            return AjaxResult.error("demandId不能为空");
        }
        if(StringUtils.isEmpty(pmDemandReqVo.getDetailType())){
            return AjaxResult.error("详情的类型不能为空");
        }
        return success(pmDemandService.selectPmDemandByDemandId(pmDemandReqVo.getDemandId(),pmDemandReqVo.getDetailType()));
    }
    /**
     * 获取回退下拉列表
     */
    @ApiOperation(value = "获取回退下拉列表", notes = "必传demandId")
    @GetMapping("/getReturnList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getReturnList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getReturnList(@NotEmpty(message = "需求ID不能为空")
                                    @RequestParam(value = "demandId", required = true) Long demandId) {
        List< Map<String,Integer>> list = new ArrayList<>();
        LambdaQueryWrapper<PmDemandHis> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmDemandHis::getDemandId,demandId).orderByAsc(PmDemandHis::getReturnOrderNumber);
        List<PmDemandHis> pmDemandHisList = this.pmDemandHisService.list(lambdaQueryWrapper);
        if(!ObjectUtils.isEmpty(pmDemandHisList)){
            Map<String,Integer> map = new HashMap<>();
            map.put("当前信息",0);
            list.add(map);
            for (PmDemandHis pmDemandHis : pmDemandHisList) {
                Map<String,Integer> map2 = new HashMap<>();
                map2.put("第" + pmDemandHis.getReturnOrderNumber() + "回退",pmDemandHis.getReturnOrderNumber());
                list.add(map2);
            }
        }

        return success(list);
    }
    /**
     * 查看历史详情
     */
    @ApiOperation(value = "查看历史详情", notes = "必传demandId和详情类型(1项目计划，2需求建档，3任务下达,4中标信息，5合同信息，6建设情况),必传returnOrderNumber(回退序号,0当前/1第一次回退/2第二次回退...),其他字段不传")
    @PostMapping("/viewHis")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:viewHis')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult viewHis(@RequestBody PmDemandReqVo pmDemandReqVo) {
        if(pmDemandReqVo.getDemandId() == null){
            return AjaxResult.error("demandId不能为空");
        }
        if(ObjectUtils.isEmpty(pmDemandReqVo.getDetailType())){
            return AjaxResult.error("详情的类型不能为空");
        }
        if(ObjectUtils.isEmpty(pmDemandReqVo.getReturnOrderNumber())){
            return AjaxResult.error("回退序号不能为空");
        }
        if(0 == pmDemandReqVo.getReturnOrderNumber()){
            return success(pmDemandService.selectPmDemandByDemandId(pmDemandReqVo.getDemandId(),pmDemandReqVo.getDetailType()));
        } else {
            return success(pmDemandHisService.selectPmDemandHisByDemandId(pmDemandReqVo.getDemandId(),pmDemandReqVo.getDetailType(),pmDemandReqVo.getReturnOrderNumber()));
        }

    }

    /**
     * 专家信息查看详情列表
     */
    @ApiOperation(value = "专家信息查看详情列表", notes = "必传需求ID和选取时间(yyyy-MM-dd)")
    @GetMapping("/getBaseExpertList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getBaseExpertList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getBaseExpertList(@NotEmpty(message = "需求ID不能为空")
                                            @RequestParam(value = "demandId", required = true) Long demandId,
                                         @NotEmpty(message = "选取时间不能为空")
                                            @RequestParam(value = "accessTime", required = true) String accessTime) {
        LambdaQueryWrapper<PmDemandExpertRef> pmDemandExpertRefLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pmDemandExpertRefLambdaQueryWrapper.eq(PmDemandExpertRef::getDemandId,demandId);
        pmDemandExpertRefLambdaQueryWrapper.eq(PmDemandExpertRef::getAccessTime,accessTime);
        List<PmDemandExpertRef> pmDemandExpertRefList = pmDemandExpertRefService.list(pmDemandExpertRefLambdaQueryWrapper);
        List<BaseExpertVo> baseExpertVoList = new ArrayList<>();
        if(!ObjectUtils.isEmpty(pmDemandExpertRefList)) {
            for(PmDemandExpertRef pmDemandExpertRef : pmDemandExpertRefList) {
                BaseExpert baseExpert = baseExpertService.getById(pmDemandExpertRef.getExpertId());
                if(baseExpert != null){
                    BaseExpertVo baseExpertVo = new BaseExpertVo();
                    BeanUtils.copyProperties(baseExpert,baseExpertVo);
                    baseExpertVo.setMajorTypeName(getMajorTypeName(baseExpertVo.getMajorType()));
                    baseExpertVo.setExpertTypeName(ExpertType.getCodeToInfo(baseExpertVo.getExpertType()));
                    baseExpertVo.setVarietyPurchaseName(PurchaseType.getCodeToInfo(baseExpertVo.getVarietyPurchase()));
                    baseExpertVoList.add(baseExpertVo);
                }
            }
        }

        return success(baseExpertVoList);
    }

    /**
     * 专家信息查看历史详情列表
     */
    @ApiOperation(value = "专家信息查看历史详情列表", notes = "必传需求ID、回退序号和选取时间(yyyy-MM-dd)")
    @GetMapping("/getBaseExpertHisList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getBaseExpertHisList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getBaseExpertHisList(@NotEmpty(message = "需求ID不能为空")
                                        @RequestParam(value = "demandId", required = true) Long demandId,
                                           @NotEmpty(message = "回退序号不能为空")
                                           @RequestParam(value = "returnOrderNumber", required = true) Integer returnOrderNumber,
                                        @NotEmpty(message = "选取时间不能为空")
                                        @RequestParam(value = "accessTime", required = true) String accessTime) {
        if( 0 == returnOrderNumber){
            return getBaseExpertList(demandId,accessTime);
        }
        LambdaQueryWrapper<PmDemandExpertRefHis> pmDemandExpertRefLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pmDemandExpertRefLambdaQueryWrapper.eq(PmDemandExpertRefHis::getDemandId,demandId);
        pmDemandExpertRefLambdaQueryWrapper.eq(PmDemandExpertRefHis::getReturnOrderNumber,returnOrderNumber);
        pmDemandExpertRefLambdaQueryWrapper.eq(PmDemandExpertRefHis::getAccessTime,accessTime);
        List<PmDemandExpertRefHis> pmDemandExpertRefHisList = pmDemandExpertRefHisService.list(pmDemandExpertRefLambdaQueryWrapper);
        List<BaseExpertVo> baseExpertVoList = new ArrayList<>();
        if(!ObjectUtils.isEmpty(pmDemandExpertRefHisList)) {
            for(PmDemandExpertRefHis pmDemandExpertRefHis : pmDemandExpertRefHisList) {
                BaseExpert baseExpert = baseExpertService.getById(pmDemandExpertRefHis.getExpertId());
                if(baseExpert != null){
                    BaseExpertVo baseExpertVo = new BaseExpertVo();
                    BeanUtils.copyProperties(baseExpert,baseExpertVo);
                    baseExpertVo.setMajorTypeName(getMajorTypeName(baseExpertVo.getMajorType()));
                    baseExpertVo.setExpertTypeName(ExpertType.getCodeToInfo(baseExpertVo.getExpertType()));
                    baseExpertVo.setVarietyPurchaseName(PurchaseType.getCodeToInfo(baseExpertVo.getVarietyPurchase()));
                    baseExpertVoList.add(baseExpertVo);
                }
            }
        }

        return success(baseExpertVoList);
    }

    private String getMajorTypeName(String majorType){
        if(ObjectUtils.isEmpty(majorType)) {
            return null;
        }
        LambdaQueryWrapper<BaseProfessional> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(BaseProfessional::getProfessionalCode,majorType.split(","));
        List<BaseProfessional> list = this.baseProfessionalService.list(lambdaQueryWrapper);
        if(ObjectUtils.isEmpty(list)){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for(BaseProfessional baseProfessional : list){
            sb.append(baseProfessional.getProfessionalName()).append(",");
        }
        String majorTypeName = sb.toString();
        if(majorTypeName.endsWith(",")){
            majorTypeName = majorTypeName.substring(0, majorTypeName.length() - 1);
        }
        return majorTypeName;
    }

  /**
     * 开标信息查看详情列表
     */
    @ApiOperation(value = "开标信息查看详情列表", notes = "必传选需求ID和开标时间(yyyy-MM-dd)")
    @GetMapping("/getBidOpeningList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getBidOpeningList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getBidOpeningList(@NotEmpty(message = "需求ID不能为空")
                                        @RequestParam(value = "demandId", required = true) Long demandId,
                                        @NotEmpty(message = "开标时间不能为空")
                                        @RequestParam(value = "openBidTime", required = true) String openBidTime) {
        LambdaQueryWrapper<PmBidOpening> pmBidOpeningLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pmBidOpeningLambdaQueryWrapper.eq(PmBidOpening::getDemandId,demandId)
        .eq(PmBidOpening::getOpenBidTime,openBidTime).orderByDesc(PmBidOpening::getScore);
        List<PmBidOpening> pmBidOpeningList = pmBidOpeningService.list(pmBidOpeningLambdaQueryWrapper);
        return success(pmBidOpeningList);
    }

    /**
     * 开标信息查看历史详情列表
     */
    @ApiOperation(value = "开标信息查看历史详情列表", notes = "必传选需求ID、回退序号和开标时间(yyyy-MM-dd)")
    @GetMapping("/getBidOpeningHisList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getBidOpeningHisList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getBidOpeningHisList(@NotEmpty(message = "需求ID不能为空")
                                        @RequestParam(value = "demandId", required = true) Long demandId,
                                           @NotEmpty(message = "回退序号不能为空")
                                           @RequestParam(value = "returnOrderNumber", required = true) Integer returnOrderNumber,
                                        @NotEmpty(message = "开标时间不能为空")
                                        @RequestParam(value = "openBidTime", required = true) String openBidTime) {
        if( 0 == returnOrderNumber){
            return getBidOpeningList(demandId,openBidTime);
        }
        LambdaQueryWrapper<PmBidOpeningHis> pmBidOpeningLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pmBidOpeningLambdaQueryWrapper.eq(PmBidOpeningHis::getDemandId,demandId).eq(PmBidOpeningHis::getReturnOrderNumber,returnOrderNumber)
                .eq(PmBidOpeningHis::getOpenBidTime,openBidTime).orderByDesc(PmBidOpeningHis::getScore);
        List<PmBidOpeningHis> pmBidOpeningList = pmBidOpeningHisService.list(pmBidOpeningLambdaQueryWrapper);
        return success(pmBidOpeningList);
    }

    /**
     * 评标结果公告详情查看中标单位列表
     */
    @ApiOperation(value = "评标结果公告详情查看中标单位列表", notes = "必传选需求ID和中标ID")
    @GetMapping("/getBidWinningUnitList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getBidWinningUnitList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getBidWinningUnitList(@NotEmpty(message = "需求ID不能为空")
                                        @RequestParam(value = "demandId", required = true) Long demandId,
                                        @NotEmpty(message = "开中标ID不能为空")
                                        @RequestParam(value = "winningId", required = true) Long winningId) {

        LambdaQueryWrapper<PmBidWinningOpeningRef> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmBidWinningOpeningRef::getDemandId,demandId).eq(PmBidWinningOpeningRef::getWinningId,winningId);
        List<PmBidWinningOpeningRef> pmBidWinningOpeningRefList = pmBidWinningOpeningRefService.list(lambdaQueryWrapper);
        if(ObjectUtils.isEmpty(pmBidWinningOpeningRefList)){
            return AjaxResult.error("中标单位列表为空");
        }

        List<Long> idList = new ArrayList<>();
        for (PmBidWinningOpeningRef pmBidWinningOpeningRef : pmBidWinningOpeningRefList) {
            idList.add(pmBidWinningOpeningRef.getOpeningId());
        }

        LambdaQueryWrapper<PmBidOpening> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.in(PmBidOpening::getId,idList).orderByDesc(PmBidOpening::getScore);
        List<PmBidOpening> pmBidOpeningList = this.pmBidOpeningService.list(lambdaQueryWrapper1);

        return success(pmBidOpeningList);
    }

    /**
     * 历史评标结果公告详情查看中标单位列表
     */
    @ApiOperation(value = "历史评标结果公告详情查看中标单位列表", notes = "必传选需求ID、回退序号和中标ID")
    @GetMapping("/getBidWinningUnitHisList")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:getBidWinningUnitHisList')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult getBidWinningUnitHisList(@NotEmpty(message = "需求ID不能为空")
                                            @RequestParam(value = "demandId", required = true) Long demandId,
                                               @NotEmpty(message = "回退序号不能为空")
                                               @RequestParam(value = "returnOrderNumber", required = true) Integer returnOrderNumber,
                                            @NotEmpty(message = "开中标ID不能为空")
                                            @RequestParam(value = "winningId", required = true) Long winningId) {
        if( 0 == returnOrderNumber){
            return getBidWinningUnitList(demandId,winningId);
        }
        LambdaQueryWrapper<PmBidWinningOpeningRefHis> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmBidWinningOpeningRefHis::getDemandId,demandId).eq(PmBidWinningOpeningRefHis::getReturnOrderNumber,returnOrderNumber)
                .eq(PmBidWinningOpeningRefHis::getWinningId,winningId);
        List<PmBidWinningOpeningRefHis> pmBidWinningOpeningRefHisList = pmBidWinningOpeningRefHisService.list(lambdaQueryWrapper);
        if(ObjectUtils.isEmpty(pmBidWinningOpeningRefHisList)){
            return AjaxResult.error("中标单位列表为空");
        }

        List<Long> idList = new ArrayList<>();
        for (PmBidWinningOpeningRefHis pmBidWinningOpeningRefHis : pmBidWinningOpeningRefHisList) {
            idList.add(pmBidWinningOpeningRefHis.getOpeningId());
        }

        LambdaQueryWrapper<PmBidOpeningHis> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.in(PmBidOpeningHis::getId,idList).eq(PmBidOpeningHis::getReturnOrderNumber,returnOrderNumber)
                .orderByDesc(PmBidOpeningHis::getScore);
        List<PmBidOpeningHis> pmBidOpeningHisList = this.pmBidOpeningHisService.list(lambdaQueryWrapper1);

        return success(pmBidOpeningHisList);
    }
}
