package com.yd.csf.api.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.common.constant.CodeGeneratorConstants;
import com.yd.common.enums.CommonEnum;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.common.utils.CodeGenerator;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.api.service.ApiRelObjectFormulaService;
import com.yd.csf.api.service.ApiRuleItemConfigService;
import com.yd.csf.feign.dto.formulaconfig.ApiFormulaConfigDto;
import com.yd.csf.feign.dto.formulaconfig.ApiRelObjectFormulaDto;
import com.yd.csf.feign.request.ruleItemconfig.ApiRuleItemConfigAddRequest;
import com.yd.csf.feign.request.ruleItemconfig.ApiRuleItemConfigEditRequest;
import com.yd.csf.feign.request.ruleItemconfig.ApiRuleItemConfigPageRequest;
import com.yd.csf.feign.response.ruleItemconfig.ApiRuleItemConfigDetailResponse;
import com.yd.csf.feign.response.ruleItemconfig.ApiRuleItemConfigPageResponse;
import com.yd.csf.service.dto.RuleItemConfigDto;
import com.yd.csf.service.model.RuleItemConfig;
import com.yd.csf.service.service.IRuleItemConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ApiRuleItemConfigServiceImpl implements ApiRuleItemConfigService {

    @Autowired
    private IRuleItemConfigService iRuleItemConfigService;

    @Autowired
    private ApiRelObjectFormulaService apiRelObjectFormulaService;

    /**
     * 分页查询-基本法项目配置信息
     * @param request
     * @return
     */
    @Override
    public Result<IPage<ApiRuleItemConfigPageResponse>> page(ApiRuleItemConfigPageRequest request) {
        Page<ApiRuleItemConfigPageResponse> page = new Page<>(request.getPageNo(), request.getPageSize());
        IPage<ApiRuleItemConfigPageResponse> iPage = iRuleItemConfigService.page(page, request);
        return Result.success(iPage);
    }

    /**
     * 详情-基本法项目配置信息
     * @param ruleItemBizId
     * @return
     */
    @Override
    public Result<ApiRuleItemConfigDetailResponse> detail(String ruleItemBizId) {
        //校验基本法项目配置信息是否存在
        Result<RuleItemConfig> result = checkRuleItemConfigIsExist(ruleItemBizId);
        RuleItemConfig ruleItemConfig = result.getData();
        ApiRuleItemConfigDetailResponse response = new ApiRuleItemConfigDetailResponse();
        BeanUtils.copyProperties(ruleItemConfig,response);
        //计算公式 - 查询对象公式配置关系表
        Result<List<ApiFormulaConfigDto>> listResult = apiRelObjectFormulaService.apiFormulaConfigDtoList(ApiRelObjectFormulaDto.builder()
                .objectBizId(ruleItemBizId)
                .build());
        if (!CollectionUtils.isEmpty(listResult.getData())) {
            ApiFormulaConfigDto configDto = listResult.getData().get(0);
            response.setApiFormulaConfigDto(configDto);
        }
        return Result.success(response);
    }

    /**
     * 添加-基本法项目配置信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(ApiRuleItemConfigAddRequest request) {
        //校验基本法项目名称的唯一性
        List<RuleItemConfig> list = iRuleItemConfigService.queryList(RuleItemConfigDto.builder()
                .itemName(request.getItemName())
                .build());
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("基本法项目名称已存在");
        }
        RuleItemConfig ruleItemConfig = new RuleItemConfig();
        BeanUtils.copyProperties(request,ruleItemConfig);
        //基本法项目配置表唯一业务ID
        ruleItemConfig.setRuleItemBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_RULE_ITEM_CONFIG.getCode()));
        //基本法项目编码
        ruleItemConfig.setItemCode(CodeGenerator.generate10Code(CodeGeneratorConstants.PREFIX_ITEM_CODE));
        iRuleItemConfigService.saveOrUpdate(ruleItemConfig);

        //保存对象和公式配置关系
        List<String> formulaBizIdList = new ArrayList<>();
        formulaBizIdList.add(request.getFormulaBizId());
        apiRelObjectFormulaService.saveRelList(ApiRelObjectFormulaDto.builder()
                .objectBizId(ruleItemConfig.getRuleItemBizId())
                .objectName(CommonEnum.UID_TYPE_RULE_ITEM_CONFIG.getName())
                .objectTableName(CommonEnum.UID_TYPE_RULE_ITEM_CONFIG.getCode())
                .objectType(CommonEnum.UID_TYPE_RULE_ITEM_CONFIG.getCode())
                .formulaBizIdList(formulaBizIdList)
                .build());

        return Result.success();
    }

    /**
     * 编辑-基本法项目配置信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result edit(ApiRuleItemConfigEditRequest request) {
        Result<RuleItemConfig>  result = checkRuleItemConfigIsExist(request.getRuleItemBizId());
        RuleItemConfig ruleItemConfig = result.getData();
        //校验基本法项目名称的唯一性
        List<RuleItemConfig> list = iRuleItemConfigService.queryList(RuleItemConfigDto.builder()
                .itemName(request.getItemName())
                .isExcludeMy(true)
                .ruleItemBizId(request.getRuleItemBizId())
                .build());
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("基本法项目名称已存在");
        }
        BeanUtils.copyProperties(request,ruleItemConfig);
        iRuleItemConfigService.saveOrUpdate(ruleItemConfig);

        //保存对象和公式配置关系
        List<String> formulaBizIdList = new ArrayList<>();
        formulaBizIdList.add(request.getFormulaBizId());
        apiRelObjectFormulaService.saveRelList(ApiRelObjectFormulaDto.builder()
                .objectBizId(ruleItemConfig.getRuleItemBizId())
                .objectName(CommonEnum.UID_TYPE_RULE_ITEM_CONFIG.getName())
                .objectTableName(CommonEnum.UID_TYPE_RULE_ITEM_CONFIG.getCode())
                .objectType(CommonEnum.UID_TYPE_RULE_ITEM_CONFIG.getCode())
                .formulaBizIdList(formulaBizIdList)
                .build());

        return Result.success();
    }

    /**
     * 删除-基本法项目配置信息 TODO
     * @param ruleItemBizId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result del(String ruleItemBizId) {
        return null;
    }

    /**
     * 校验基本法项目配置信息是否存在
     * @param ruleItemBizId
     * @return
     */
    public Result<RuleItemConfig> checkRuleItemConfigIsExist(String ruleItemBizId) {
        RuleItemConfig config = iRuleItemConfigService.queryOne(ruleItemBizId);
        if (Objects.isNull(config)) {
            //数据不存在
            throw new BusinessException(ResultCode.NULL_ERROR.getCode(),ResultCode.NULL_ERROR.getMessage());
        }
        return Result.success(config);
    }
}
