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.enums.*;
import com.ozs.common.utils.RandomUtil;
import com.ozs.common.utils.StringUtils;
import com.ozs.pm.doman.PmBidOpening;
import com.ozs.pm.doman.PmBidWinning;
import com.ozs.pm.doman.PmDemand;
import com.ozs.pm.doman.PmDemandExpertRef;
import com.ozs.pm.doman.vo.requestVo.*;
import com.ozs.pm.doman.vo.responseVo.PmDemandResVo;
import com.ozs.pm.service.IPmDemandService;
import com.ozs.pm.service.PmBidOpeningService;
import com.ozs.pm.service.PmBidWinningService;
import com.ozs.pm.service.PmDemandExpertRefService;
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 BaseAgencyService baseAgencyService;
    @Autowired
    private BaseExpertService baseExpertService;
    @Autowired
    private PmDemandExpertRefService pmDemandExpertRefService;
    @Autowired
    private PmBidOpeningService pmBidOpeningService;
    @Autowired
    private BaseProfessionalService baseProfessionalService;


    /**
     * 采购执行查询列表
     */
    @ApiOperation(value = "采购执行查询列表", notes = "参数非必传")
    @PostMapping("/list")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:list')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.QUERY)
    public AjaxResult list(@RequestBody PmDemandReqVo pmDemandReqVo) {
        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,0);//白名单
        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) {

        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.WAIT_UPLOAD_BID_FILE.getCode());
        pmDemandUpdate.setAgencyId(agencyId);
        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) {

        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,0); //白名单
        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.WAIT_UPLOAD_BID_FILE.getCode());
        pmDemandUpdate.setAgencyId(any.getId());
        pmDemandUpdate.setExtractAgencyTime(new Date());
        pmDemandUpdate.setUpdateTime(pmDemandUpdate.getExtractAgencyTime());
        pmDemandUpdate.setUpdateBy(getUserId().toString());
        return success(pmDemandService.updateById(pmDemandUpdate));
    }

    @ApiOperation(value = "上传招标文件",notes = "采购需求ID和上传附件必传")
    @PostMapping("/uploadBidFile")
    @PreAuthorize("@ss.hasPermi('pm:purchaseExecution:uploadBidFile')")
    @Log(title = ModularConstans.purchaseExecution, businessType = BusinessType.IMPORT)
    public AjaxResult uploadBidFile(@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_FILE.getType(),sysFileRefs,getUserId().toString())) {
            PmDemand pmDemandUpdate = new PmDemand();
            pmDemandUpdate.setDemandId(demandId);
            pmDemandUpdate.setProjectStatus(PmProjectStatus.WAIT_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 = "获取专家身份证号列表")
    @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("/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("参数错误");
            }
            List<SysFileRef> sysFileRefs = pmCallQuestionReqVo.getSysFileRefs();
            pmDemandService.uploadFile(demandId, SysFileRefEnum.PM_BID_CALL_QEUSTION_FILE.getType(),sysFileRefs,getUserId().toString());
            pmDemand.setCallQuestion(pmCallQuestionReqVo.getCallQuestion());
            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.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 = "必传需求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);
    }

    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);
    }

}
