package com.microservices.pms.product.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.exception.NotFoundException;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.JSONUtils;
import com.microservices.common.core.utils.PageUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.pms.common.service.IPmsCommonService;
import com.microservices.pms.enterprise.domain.PmsEnterprise;
import com.microservices.pms.enterprise.service.IPmsEnterpriseService;
import com.microservices.pms.journals.service.IPmsJournalsService;
import com.microservices.pms.product.domain.PmsProduct;
import com.microservices.pms.product.domain.PmsProductModule;
import com.microservices.pms.product.domain.PmsProductPlan;
import com.microservices.pms.product.domain.PmsProductRequirement;
import com.microservices.pms.product.domain.vo.PmsProductRequirementBatchUpdateVo;
import com.microservices.pms.product.domain.vo.PmsProductRequirementDataVo;
import com.microservices.pms.product.domain.vo.PmsProductRequirementDetailVo;
import com.microservices.pms.product.mapper.PmsProductRequirementMapper;
import com.microservices.pms.product.service.*;
import com.microservices.pms.project.domain.PmsProject;
import com.microservices.pms.project.service.IPmsProjectService;
import com.microservices.pms.utils.PmsConstants;
import com.microservices.pms.utils.PmsUtils;
import com.microservices.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.microservices.common.core.utils.PageUtils.startPage;

/**
 * 产品需求Service业务层处理
 * 
 * @author otto
 * @date 2023-10-10
 */
@Service
public class PmsProductRequirementServiceImpl implements IPmsProductRequirementService 
{
    @Autowired
    private PmsProductRequirementMapper pmsProductRequirementMapper;
    @Autowired
    private IPmsEnterpriseService pmsEnterpriseService;
    @Autowired
    private IPmsProductPlanService pmsProductPlanService;
    @Autowired
    private IPmsProductService pmsProductService;
    @Autowired
    private IPmsProductModuleService pmsProductModuleService;
    @Autowired
    private IPmsProductRequirementTagService pmsProductRequirementTagService;
    @Autowired
    private IPmsProductPriorityService pmsProductPriorityService;
    @Autowired
    private IPmsProductStatusService pmsProductStatusService;
    @Autowired
    private IPmsCommonService pmsCommonService;
    @Autowired
    private IPmsProjectService pmsProjectService;
    @Autowired
    @Lazy
    private IPmsJournalsService pmsJournalsService;

    /**
     * 查询产品需求
     * 
     * @param id 产品需求主键
     * @return 产品需求
     */
    @Override
    public PmsProductRequirementDetailVo selectPmsProductRequirementDetailById(Long id)
    {
        PmsProductRequirement pmsProductRequirement = selectPmsProductRequirementById(id, false);
        return toPmsProductRequirementDetailVo(pmsProductRequirement);
    }

    private PmsProductRequirementDetailVo toPmsProductRequirementDetailVo(PmsProductRequirement pmsProductRequirement){
        PmsProductRequirementDataVo pmsProductRequirementDataVo = toPmsProductRequirementDataVo(pmsProductRequirement, null);
        PmsProductRequirementDetailVo pmsProductRequirementDetailVo=pmsProductRequirementDataVo.toPmsProductRequirementDetailVo();
        pmsProductRequirementDetailVo.setContent(pmsProductRequirement.getContent());
        // 设置文件列表
        pmsProductRequirementDetailVo.setFileList(pmsCommonService.getAllFileByFileIdentifiers(pmsProductRequirement.getFileIdentifiers())
        );
        // 设置产品计划
        if (pmsProductRequirement.getPmsProductPlanId() != null) {
            pmsProductRequirementDetailVo.setPmsProductPlan(pmsProductPlanService.selectPmsProductPlanById(pmsProductRequirement.getPmsProductPlanId(), false));
        }
        return pmsProductRequirementDetailVo;
    }

    @Override
    public PmsProductRequirement selectPmsProductRequirementById(Long id, boolean checkRole) {
        PmsProductRequirement pmsProductRequirement=pmsProductRequirementMapper.selectPmsProductRequirementById(id);
        if(pmsProductRequirement==null){
            throw new NotFoundException("该产品需求不存在(产品需求Id[%d])", id);
        }
        PmsProduct pmsProduct = pmsProductService.selectPmsProductByIdentifier(pmsProductRequirement.getPmsProductIdentifier());
        if (checkRole) {
            pmsProductService.checkManageRole(pmsProduct);
        }
        return pmsProductRequirement;
    }

    private PmsProductRequirementDataVo toPmsProductRequirementDataVo(PmsProductRequirement pmsProductRequirement, HashMap<String, Object> hashMap) {
        PmsProductRequirementDataVo pmsProductRequirementDataVo=pmsProductRequirement.toPmsProductRequirementDataVo();
        // 设置优先级
        pmsProductRequirementDataVo.setPriority(
                PmsUtils.getSelectObjectInCache(
                        hashMap
                        , pmsProductPriorityService::selectPmsProductPriorityById
                        , pmsProductRequirement.getPriorityId()));
        // 设置状态
        pmsProductRequirementDataVo.setStatus(
                PmsUtils.getSelectObjectInCache(
                        hashMap
                        , pmsProductStatusService::selectPmsProductStatusById
                        , pmsProductRequirement.getStatusId()));
        // 设置产品模块
        if (pmsProductRequirement.getPmsProductModuleId() != null) {
            pmsProductRequirementDataVo.setPmsProductModule(
                    PmsUtils.getSelectObjectInCache(
                            hashMap
                            , x -> pmsProductModuleService.selectPmsProductModuleById(x, false)
                            , pmsProductRequirement.getPmsProductModuleId())
            );
        }
        // 设置产品
        pmsProductRequirementDataVo.setPmsProduct(
                PmsUtils.getSelectObjectInCache(
                        hashMap
                        , pmsProductService::selectPmsProductByIdentifier
                        , pmsProductRequirement.getPmsProductIdentifier())
        );
        // 设置产品计划
        if (pmsProductRequirement.getPmsProductPlanId() != null) {
            pmsProductRequirementDataVo.setPmsProductPlan(
                    PmsUtils.getSelectObjectInCache(
                            hashMap
                            , x -> pmsProductPlanService.selectPmsProductPlanById(x, false)
                            , pmsProductRequirement.getPmsProductPlanId())
            );
        }

        // 设置标记Id列表
        pmsProductRequirementDataVo.setTags(pmsProductRequirement.getTagIds());
        // 设置需求负责人
        pmsProductRequirementDataVo.setRequirementAssigneeList(
                pmsCommonService.getSimpleSysUserListByGitlinkUserIdsAndCache(pmsProductRequirement.getRequirementAssigneeGitlinkIds(), hashMap));
        // 设置需求创建人
        pmsProductRequirementDataVo.setCreateByUser(
                PmsUtils.getSelectObjectInCache(
                        hashMap
                        , pmsCommonService::getSimpleSysUserByUsername
                        , pmsProductRequirement.getCreateBy())
        );
        // 设置需求更新人
        pmsProductRequirementDataVo.setUpdateByUser(
                PmsUtils.getSelectObjectInCache(
                        hashMap
                        , pmsCommonService::getSimpleSysUserByUsername
                        , pmsProductRequirement.getUpdateBy())
        );
        if (pmsProductRequirementDataVo.getCreateByUser() != null) {
            pmsProductRequirementDataVo.setCreateBy(pmsProductRequirementDataVo.getCreateByUser().getNickName());
        }
        if (pmsProductRequirementDataVo.getUpdateByUser() != null) {
            pmsProductRequirementDataVo.setUpdateBy(pmsProductRequirementDataVo.getUpdateByUser().getNickName());
        }

        return pmsProductRequirementDataVo;
    }

    /**
     * 查询产品需求列表
     * 
     * @param pmsProductRequirementSearch 产品需求
     * @return 产品需求
     */
    @Override
    public GenericsTableDataInfo<PmsProductRequirementDataVo> selectPmsProductRequirementPageList(PmsProductRequirement pmsProductRequirementSearch)
    {
        pmsProductService.selectPmsProductByIdentifier(pmsProductRequirementSearch.getPmsProductIdentifier());
        startPage();
        List<PmsProductRequirement> pmsProductRequirementList=pmsProductRequirementMapper.selectPmsProductRequirementList(pmsProductRequirementSearch);
        HashMap<String, Object> selectCache = new HashMap<>();
        return PageUtils.toPage(pmsProductRequirementList, x -> toPmsProductRequirementDataVo(x, selectCache));
    }

    /**
     * 新增产品需求
     * 
     * @param pmsProductRequirement 产品需求
     * @return 结果
     */
    @Override
    public Long insertPmsProductRequirement(PmsProductRequirement pmsProductRequirement)
    {
        // 校验产品是否存在
        PmsProduct pmsProduct = pmsProductService.selectPmsProductByIdentifier(pmsProductRequirement.getPmsProductIdentifier());
        pmsProductService.checkManageRole(pmsProduct);
        // 设置需求优先级，若未传入则设置为默认优先级
        Long priorityId=
                pmsProductPriorityService.selectPmsProductPriorityIdByInputId(pmsProductRequirement.getPriorityId(), PmsConstants.PRODUCT_STATUS_OR_PRIORITY_REQUIREMENT_TYPE);
        pmsProductRequirement.setPriorityId(priorityId);
        // 设置默认需求状态
        Long statusId=
                pmsProductStatusService.selectPmsProductDefaultStatusId(PmsConstants.PRODUCT_STATUS_OR_PRIORITY_REQUIREMENT_TYPE);
        pmsProductRequirement.setStatusId(statusId);
        checkPmsProductRequirement(pmsProductRequirement, pmsProduct, null);

        Date now=DateUtils.getNowDate();
        String username=SecurityUtils.getUsername();
        pmsProductRequirement.setCreateBy(username);
        pmsProductRequirement.setCreateTime(now);
        pmsProductRequirement.setUpdateBy(username);
        pmsProductRequirement.setUpdateTime(now);
        // 获取当前产品下需求的最大索引值
        Long maxIndex=pmsProductRequirementMapper.selectPmsProductRequirementMaxIndexByProductIdentifier(pmsProductRequirement.getPmsProductIdentifier());
        if (maxIndex == null) {
            maxIndex = 1L;
        }
        pmsProductRequirement.setIndex(++maxIndex);
        pmsProductService.updatePmsProductChange(pmsProductRequirement.getPmsProductIdentifier());
        pmsProductRequirementMapper.insertPmsProductRequirement(pmsProductRequirement);
        return pmsProductRequirement.getId();
    }

    private void checkPmsProductRequirement(PmsProductRequirement pmsProductRequirement, PmsProduct pmsProduct, PmsProductRequirement oldPmsProductRequirement) {
        if (StringUtils.isNotBlank(pmsProductRequirement.getRequirementAssigneeGitlinkIds())) {
            String[] gitlinkUserIdStrList = pmsProductRequirement.getRequirementAssigneeGitlinkIds().split(",");
            checkGitlinkUserIds(gitlinkUserIdStrList, pmsProduct);
        }

        // 校验产品计划是否存在
        if(pmsProductRequirement.getPmsProductPlanId()!=null){
            PmsProductPlan pmsProductPlan = pmsProductPlanService.selectPmsProductPlanById(pmsProductRequirement.getPmsProductPlanId(), false);
            if(!pmsProductPlan.getPmsProductIdentifier().equals(pmsProduct.getProductIdentifier())){
                throw new ServiceException("该产品计划不属于当前产品(计划标题[%s],产品名称[%s])",pmsProductPlan.getPlanTitle(),pmsProduct.getProductName());
            }

            if (oldPmsProductRequirement == null || oldPmsProductRequirement.getPmsProductPlanId() == null) {
                // 当原需求没有计划时，此操作相当于将该需求移入该计划，需要更新计划的更新时间
                pmsProductPlanService.updatePmsProductPlanChange(pmsProductRequirement.getPmsProductPlanId());
            } else if (!oldPmsProductRequirement.getPmsProductPlanId().equals(pmsProductRequirement.getPmsProductPlanId())) {
                // 当原需求有计划且该计划id与原计划id不同时，此操作相当于从原计划移入新计划，需要更新原计划和新计划的更新时间
                pmsProductPlanService.updatePmsProductPlanChange(pmsProductRequirement.getPmsProductPlanId());
                pmsProductPlanService.updatePmsProductPlanChange(oldPmsProductRequirement.getPmsProductPlanId());
            }
        } else if (oldPmsProductRequirement != null && oldPmsProductRequirement.getPmsProductPlanId() != null) {
            // 当原需求有计划且当前设置计划为空时，此操作相当于将该需求从原计划中移除，需更新原计划的更新时间
            pmsProductPlanService.updatePmsProductPlanChange(oldPmsProductRequirement.getPmsProductPlanId());
        }
        // 校验项目是否存在
        if (pmsProductRequirement.getPmsProjectId() != null) {
            checkProjectId(pmsProductRequirement.getPmsProjectId(), pmsProduct);
        }


        // 校验模块是否存在
        if(pmsProductRequirement.getPmsProductModuleId()!=null){
            checkModuleId(pmsProductRequirement.getPmsProductModuleId(), pmsProduct);
        }

        // 校验标记是否存在
        pmsProductRequirementTagService.checkTags(pmsProductRequirement.getTags(), PmsConstants.PRODUCT_TAG_AND_MODULE_TYPE, pmsProduct.getPmsEnterpriseId());
        pmsProductRequirement.setTagIds(pmsProductRequirement.getTags());

        //校验结束时间需大于开始时间
        if(pmsProductRequirement.getStartTime()!=null&&pmsProductRequirement.getEndTime()!=null){
            if(pmsProductRequirement.getStartTime().after(pmsProductRequirement.getEndTime())){
                throw new ServiceException("结束时间不能早于开始时间");
            }
        }

        // 检查附件列表是否有异常数据
        pmsCommonService.getAllFileByFileIdentifiers(pmsProductRequirement.getFileIdentifiers());
    }

    /**
     * 修改产品需求
     * 
     * @param pmsProductRequirement 产品需求
     * @return 结果
     */
    @Override
    public int updatePmsProductRequirement(PmsProductRequirement pmsProductRequirement)
    {
        // 通过id检查需修改的产品需求是否存在
        PmsProductRequirement oldPmsProductRequirement = selectPmsProductRequirementById(pmsProductRequirement.getId(), true);
        pmsProductRequirement.setPmsProductIdentifier(oldPmsProductRequirement.getPmsProductIdentifier());
        if(pmsProductRequirement.getPriorityId()!=null){
            // 设置需求优先级
            Long priorityId=
                    pmsProductPriorityService.selectPmsProductPriorityIdByInputId(pmsProductRequirement.getPriorityId(), PmsConstants.PRODUCT_STATUS_OR_PRIORITY_REQUIREMENT_TYPE);
            pmsProductRequirement.setPriorityId(priorityId);
        }

        if(pmsProductRequirement.getStatusId()!=null){
            // 设置需求状态
            Long statusId=
                    pmsProductStatusService.selectPmsProductStatusIdByInputId(pmsProductRequirement.getStatusId(),PmsConstants.PRODUCT_STATUS_OR_PRIORITY_REQUIREMENT_TYPE);
            pmsProductRequirement.setStatusId(statusId);
        }
        PmsProduct pmsProduct=pmsProductService.selectPmsProductByIdentifier(oldPmsProductRequirement.getPmsProductIdentifier());
        checkPmsProductRequirement(pmsProductRequirement, pmsProduct, oldPmsProductRequirement);
        if (pmsProductRequirement.getStartTime() != null && pmsProductRequirement.getEndTime() == null) {
            if (oldPmsProductRequirement.getEndTime() != null && pmsProductRequirement.getStartTime().after(oldPmsProductRequirement.getEndTime())) {
                throw new ServiceException("开始时间不能晚于结束时间");
            }
        }
        if (pmsProductRequirement.getStartTime() == null && pmsProductRequirement.getEndTime() != null) {
            if (oldPmsProductRequirement.getStartTime() != null && oldPmsProductRequirement.getStartTime().after(pmsProductRequirement.getEndTime())) {
                throw new ServiceException("结束时间不能早于开始时间");
            }
        }
        pmsProductRequirement.setUpdateBy(SecurityUtils.getUsername());
        pmsProductRequirement.setUpdateTime(DateUtils.getNowDate());
        pmsProductService.updatePmsProductChange(oldPmsProductRequirement.getPmsProductIdentifier());
        return pmsProductRequirementMapper.updatePmsProductRequirement(pmsProductRequirement);
    }

    @Override
    public int updatePmsProductRequirementChange(Long id) {
        PmsProductRequirement pmsProductRequirement = selectPmsProductRequirementById(id, false);
        pmsProductRequirement.setUpdateBy(SecurityUtils.getUsername());
        pmsProductRequirement.setUpdateTime(DateUtils.getNowDate());
        pmsProductService.updatePmsProductChange(pmsProductRequirement.getPmsProductIdentifier());
        return pmsProductRequirementMapper.updatePmsProductRequirement(pmsProductRequirement);
    }

    /**
     * 批量删除产品需求
     * 
     * @param ids 需要删除的产品需求主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePmsProductRequirementByIds(Long[] ids)
    {
        int success = 0;
        for (Long id : ids) {
            success += deletePmsProductRequirementById(id);
        }
        return success;
    }

    /**
     * 删除产品需求信息
     * 
     * @param id 产品需求主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePmsProductRequirementById(Long id)
    {
        PmsProductRequirement oldPmsProductRequirement = selectPmsProductRequirementById(id, true);
        if (oldPmsProductRequirement.getPmsProductPlanId() != null) {
            pmsProductPlanService.updatePmsProductPlanChange(oldPmsProductRequirement.getPmsProductPlanId());
        }
        pmsJournalsService.deletePmsJournalsByTypeAndJournalId(PmsConstants.JOURNAL_TYPE_PRODUCT_REQUIREMENT, id);
        pmsProductService.updatePmsProductChange(oldPmsProductRequirement.getPmsProductIdentifier());
        return pmsProductRequirementMapper.deletePmsProductRequirementById(id);
    }

    @Override
    public Integer selectPmsProductRequirementCount(PmsProductRequirement pmsProductRequirementSearch) {
        return pmsProductRequirementMapper.selectPmsProductRequirementCount(pmsProductRequirementSearch);
    }

    @Override
    public PmsProductRequirementDetailVo selectPmsProductRequirementDetailByProductIdentifierAndIndex(String productIdentifier, Long index) {
        PmsProductRequirement pmsProductRequirement=pmsProductRequirementMapper.selectPmsProductRequirementByProductIdentifierAndIndex(productIdentifier,index);
        if(pmsProductRequirement==null){
            throw new ServiceException("该产品需求不存在(产品标识[%s],产品需求索引[%d])",productIdentifier,index);
        }
        return toPmsProductRequirementDetailVo(pmsProductRequirement);
    }

    @Override
    public int batchUpdatePmsProductRequirement(JSONObject jsonObject) {
        List<Long> idList = JSONUtils.getLongListByJsonArray(jsonObject.getJSONArray("idList"));
        checkBatchUpdateInTheSameProduct(idList);
        return batchUpdatePmsProductRequirementByJsonObject(idList, jsonObject);
    }

    /**
     * 检查批量更新的产品需求是否属于同一个产品
     *
     * @param idList id列表
     */
    private void checkBatchUpdateInTheSameProduct(List<Long> idList) {
        List<String> productIdentifierList = pmsProductRequirementMapper.selectProductIdentifierListInRequirementIdList(idList);
        if (productIdentifierList != null && productIdentifierList.size() == 1) {
            // 校验数据权限
            PmsProduct pmsProduct = pmsProductService.selectPmsProductByIdentifier(productIdentifierList.get(0));
            pmsProductService.checkManageRole(pmsProduct);
            return;
        }
        throw new ServiceException("批量编辑需求时仅允许编辑同一产品下需求");

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePmsProductRequirementByProductIdentifier(String productIdentifier) {
        PmsProductRequirement pmsProductRequirementSearch = new PmsProductRequirement();
        pmsProductRequirementSearch.setPmsProductIdentifier(productIdentifier);
        List<PmsProductRequirement> pmsProductRequirementList = pmsProductRequirementMapper.selectPmsProductRequirementList(pmsProductRequirementSearch);
        for (PmsProductRequirement pmsProductRequirement : pmsProductRequirementList) {
            deletePmsProductRequirementById(pmsProductRequirement.getId());
        }
    }

    @Override
    public void updatePmsProductRequirementNoPlanByPlanId(Long planId) {
        PmsProductRequirement pmsProductRequirementSearch = new PmsProductRequirement();
        pmsProductRequirementSearch.setPmsProductPlanId(planId);
        List<PmsProductRequirement> pmsProductRequirementList = pmsProductRequirementMapper.selectPmsProductRequirementList(pmsProductRequirementSearch);
        for (PmsProductRequirement pmsProductRequirement : pmsProductRequirementList) {
            pmsProductRequirement.setPmsProductPlanId(null);
            updatePmsProductRequirement(pmsProductRequirement);
        }
    }

    @Override
    public void updatePmsProductRequirementToNoModule(Long moduleId) {
        PmsProductRequirement pmsProductRequirementSearch = new PmsProductRequirement();
        pmsProductRequirementSearch.setPmsProductModuleId(moduleId);
        List<PmsProductRequirement> pmsProductRequirementList = pmsProductRequirementMapper.selectPmsProductRequirementList(pmsProductRequirementSearch);
        for (PmsProductRequirement pmsProductRequirement : pmsProductRequirementList) {
            pmsProductRequirement.setPmsProductModuleId(null);
            updatePmsProductRequirement(pmsProductRequirement);
        }
    }

    @Override
    public List<PmsProductRequirement> selectPmsProductRequirementList(PmsProductRequirement pmsProductRequirementSearch) {
        return pmsProductRequirementMapper.selectPmsProductRequirementList(pmsProductRequirementSearch);
    }

    private int batchUpdatePmsProductRequirementByJsonObject(List<Long> idList, JSONObject jsonObject) {
        PmsProductRequirementBatchUpdateVo pmsProductRequirementBatchUpdateVo = new PmsProductRequirementBatchUpdateVo();
        pmsProductRequirementBatchUpdateVo.setIdList(idList);
        if(jsonObject.containsKey("priorityId")){
            pmsProductRequirementBatchUpdateVo.setPriorityId(jsonObject.getLong("priorityId"));
            pmsProductRequirementBatchUpdateVo.setPriorityIdIsChange(true);
        }
        if(jsonObject.containsKey("statusId")){
            pmsProductRequirementBatchUpdateVo.setStatusId(jsonObject.getLong("statusId"));
            pmsProductRequirementBatchUpdateVo.setStatusIdIsChange(true);
        }
        if(jsonObject.containsKey("pmsProductModuleId")){
            pmsProductRequirementBatchUpdateVo.setPmsProductModuleId(jsonObject.getLong("pmsProductModuleId"));
            pmsProductRequirementBatchUpdateVo.setPmsProductModuleIdIsChange(true);
        }
        if(jsonObject.containsKey("tags")){
            pmsProductRequirementBatchUpdateVo.setTagIds(jsonObject.getString("tags"));
            pmsProductRequirementBatchUpdateVo.setTagIdsIsChange(true);
        }
        if (jsonObject.containsKey("requirementAssigneeGitlinkIds")) {
            pmsProductRequirementBatchUpdateVo.setRequirementAssigneeGitlinkIds(jsonObject.getString("requirementAssigneeGitlinkIds"));
            pmsProductRequirementBatchUpdateVo.setRequirementAssigneeGitlinkIdsIsChange(true);
        }
        if(jsonObject.containsKey("pmsProjectId")){
            pmsProductRequirementBatchUpdateVo.setPmsProjectId(jsonObject.getLong("pmsProjectId"));
            pmsProductRequirementBatchUpdateVo.setPmsProjectIdIsChange(true);
        }
        if (jsonObject.containsKey("pmsProductPlanId")) {
            pmsProductRequirementBatchUpdateVo.setPmsProductPlanId(jsonObject.getLong("pmsProductPlanId"));
            pmsProductRequirementBatchUpdateVo.setPmsProductPlanIdIsChange(true);
        }
        if (pmsProductRequirementBatchUpdateVo.thisIsChange()) {
            checkPmsProductRequirementBatchUpdateVo(pmsProductRequirementBatchUpdateVo);
            pmsProductRequirementBatchUpdateVo.setUpdateBy(SecurityUtils.getUsername());
            pmsProductRequirementBatchUpdateVo.setUpdateTime(DateUtils.getNowDate());
            return pmsProductRequirementMapper.batchUpdatePmsProductRequirement(pmsProductRequirementBatchUpdateVo);
        }
        return 1;
    }


    private void checkPmsProductRequirementBatchUpdateVo(PmsProductRequirementBatchUpdateVo pmsProductRequirementBatchUpdateVo) {
        if (pmsProductRequirementBatchUpdateVo.getIdList() == null || pmsProductRequirementBatchUpdateVo.getIdList().isEmpty()) {
            return;
        }
        PmsProductRequirement oldPmsProductRequirement =
                pmsProductRequirementMapper.selectPmsProductRequirementById(pmsProductRequirementBatchUpdateVo.getIdList().get(0));
        PmsProduct pmsProduct = pmsProductService.selectPmsProductByIdentifier(oldPmsProductRequirement.getPmsProductIdentifier());
        if (pmsProductRequirementBatchUpdateVo.getRequirementAssigneeGitlinkIdsIsChange()
                && StringUtils.isNotBlank(pmsProductRequirementBatchUpdateVo.getRequirementAssigneeGitlinkIds())) {
            String[] gitlinkUserIdStrList = pmsProductRequirementBatchUpdateVo.getRequirementAssigneeGitlinkIds().split(",");
            checkGitlinkUserIds(gitlinkUserIdStrList, pmsProduct);
        }

        // 校验产品计划是否存在
        if (pmsProductRequirementBatchUpdateVo.getPmsProductPlanIdIsChange()
                && pmsProductRequirementBatchUpdateVo.getPmsProductPlanId() != null) {
            checkProductPlanId(pmsProductRequirementBatchUpdateVo.getPmsProductPlanId(), pmsProduct);
        }

        // 校验项目是否存在
        if (pmsProductRequirementBatchUpdateVo.getPmsProjectIdIsChange()
                && pmsProductRequirementBatchUpdateVo.getPmsProjectId() != null) {
            checkProjectId(pmsProductRequirementBatchUpdateVo.getPmsProjectId(), pmsProduct);
        }

        // 校验模块是否存在
        if (pmsProductRequirementBatchUpdateVo.getPmsProductModuleIdIsChange()
                && pmsProductRequirementBatchUpdateVo.getPmsProductModuleId() != null) {
            checkModuleId(pmsProductRequirementBatchUpdateVo.getPmsProductModuleId(), pmsProduct);
        }

        if (pmsProductRequirementBatchUpdateVo.getTagIdsIsChange()) {
            // 校验标记是否存在
            pmsProductRequirementTagService.checkTags(
                    pmsProductRequirementBatchUpdateVo.getTagIds(),
                    PmsConstants.PRODUCT_TAG_AND_MODULE_TYPE,
                    pmsProduct.getPmsEnterpriseId());
        }
        if (pmsProductRequirementBatchUpdateVo.getPriorityIdIsChange()) {
            pmsProductPriorityService.selectPmsProductPriorityIdByInputId(pmsProductRequirementBatchUpdateVo.getPriorityId(), PmsConstants.PRODUCT_STATUS_OR_PRIORITY_REQUIREMENT_TYPE);
        }
        if (pmsProductRequirementBatchUpdateVo.getStatusIdIsChange()) {
            pmsProductStatusService.selectPmsProductStatusIdByInputId(pmsProductRequirementBatchUpdateVo.getStatusId(), PmsConstants.PRODUCT_STATUS_OR_PRIORITY_REQUIREMENT_TYPE);
        }
    }

    private void checkProjectId(Long projectId, PmsProduct pmsProduct) {
        PmsProject pmsProject = pmsProjectService.selectAndCheckPmsProjectById(projectId);
        if (pmsProject.getPmsProductId() == null || !pmsProject.getPmsProductId().equals(pmsProduct.getId())) {
            throw new ServiceException("该项目不属于当前产品(项目名称[%s],产品名称[%s])", pmsProject.getProjectName(), pmsProduct.getProductName());
        }
    }

    private void checkGitlinkUserIds(String[] gitlinkUserIdStrList, PmsProduct pmsProduct) {
        for (String gitlinkUserIdStr : gitlinkUserIdStrList) {
            try {
                Long gitlinkUserId = Long.parseLong(gitlinkUserIdStr);
                SysUser productAssigneeUser = pmsCommonService.getSysUserByGitlinkId(gitlinkUserId);
                boolean isExist = pmsEnterpriseService.checkUserInEnterprise(pmsProduct.getPmsEnterpriseId(), productAssigneeUser.getUserId());
                if (!isExist) {
                    PmsEnterprise pmsEnterprise = pmsEnterpriseService.selectPmsEnterpriseById(pmsProduct.getPmsEnterpriseId());
                    throw new ServiceException("该产品需求的负责人不在当前企业中(企业名称[%s],用户名[%s])", pmsEnterprise.getEnterpriseName(), productAssigneeUser.getUserName());
                }
            } catch (NumberFormatException e) {
                throw new ServiceException("该Gitlink用户Id格式错误(Gitlink用户id[%s])", gitlinkUserIdStr);
            }
        }
    }

    private void checkProductPlanId(Long productPlanId, PmsProduct pmsProduct) {
        PmsProductPlan pmsProductPlan = pmsProductPlanService.selectPmsProductPlanById(productPlanId, false);
        if (!pmsProductPlan.getPmsProductIdentifier().equals(pmsProduct.getProductIdentifier())) {
            throw new ServiceException("该产品计划不属于当前产品(计划标题[%s],产品名称[%s])", pmsProductPlan.getPlanTitle(), pmsProduct.getProductName());
        }
    }

    private void checkModuleId(Long moduleId, PmsProduct pmsProduct) {
        PmsProductModule pmsProductModule = pmsProductModuleService.selectPmsProductModuleById(moduleId, false);
        if (!pmsProductModule.getPmsProductIdentifier().equals(pmsProduct.getProductIdentifier())) {
            throw new ServiceException("该模块不属于当前产品(模块名称[%s],产品名称[%s])", pmsProductModule.getModuleName(), pmsProduct.getProductName());
        }
    }
}
