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.ApiRelObjectConditionService;
import com.yd.csf.api.service.ApiRelObjectSqlService;
import com.yd.csf.api.service.ApiVariableService;
import com.yd.csf.feign.dto.conditionconfig.ApiConditionTypeDto;
import com.yd.csf.feign.dto.conditionconfig.ApiRelObjectConditionDto;
import com.yd.csf.feign.dto.formulaconfig.ApiRelObjectFormulaDto;
import com.yd.csf.feign.dto.sqltemplate.ApiCommissionSqlTemplateDto;
import com.yd.csf.feign.dto.sqltemplate.ApiRelObjectSqlDto;
import com.yd.csf.feign.request.variable.ApiVariableAddRequest;
import com.yd.csf.feign.request.variable.ApiVariableEditRequest;
import com.yd.csf.feign.request.variable.ApiVariablePageRequest;
import com.yd.csf.feign.response.variable.ApiVariableDetailResponse;
import com.yd.csf.feign.response.variable.ApiVariablePageResponse;
import com.yd.csf.service.dto.VariableDto;
import com.yd.csf.service.model.Variable;
import com.yd.csf.service.service.IRelObjectConditionService;
import com.yd.csf.service.service.IVariableService;
import org.apache.commons.lang3.StringUtils;
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 ApiVariableServiceImpl implements ApiVariableService {

    @Autowired
    private IVariableService iVariableService;

    @Autowired
    private ApiRelObjectConditionService apiRelObjectConditionService;

    @Autowired
    private ApiRelObjectSqlService apiRelObjectSqlService;

    /**
     * 分页查询-变量信息
     * @param request
     * @return
     */
    @Override
    public Result<IPage<ApiVariablePageResponse>> page(ApiVariablePageRequest request) {
        Page<ApiVariablePageResponse> page = new Page<>(request.getPageNo(), request.getPageSize());
        IPage<ApiVariablePageResponse> iPage = iVariableService.page(page, request);
        return Result.success(iPage);
    }

    /**
     * 详情-变量信息
     * @param variableBizId
     * @return
     */
    @Override
    public Result<ApiVariableDetailResponse> detail(String variableBizId) {
        //校验变量信息是否存在
        Result<Variable> result = checkVariableIsExist(variableBizId);
        Variable variable = result.getData();
        ApiVariableDetailResponse response = new ApiVariableDetailResponse();
        BeanUtils.copyProperties(variable,response);
        //绑定的条件类型对象 - 查询对象条件关系表
        Result<List<ApiConditionTypeDto>> listResult = apiRelObjectConditionService.apiConditionTypeDtoList(ApiRelObjectConditionDto.builder().objectBizId(variableBizId).build());
        if (!CollectionUtils.isEmpty(listResult.getData())) {
            ApiConditionTypeDto typeDto = listResult.getData().get(0);
            response.setApiConditionTypeDto(typeDto);
        }
        //绑定的SQL模板对象
        Result<List<ApiCommissionSqlTemplateDto>> listResult1 = apiRelObjectSqlService.apiCommissionSqlTemplateDtoList(ApiRelObjectSqlDto.builder().objectBizId(variableBizId).build());
        if (!CollectionUtils.isEmpty(listResult1.getData())) {
            ApiCommissionSqlTemplateDto sqlTemplateDto = listResult1.getData().get(0);
            response.setApiCommissionSqlTemplateDto(sqlTemplateDto);
        }
        return Result.success(response);
    }

    /**
     * 添加-变量信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(ApiVariableAddRequest request) {
        //校验变量中文名唯一性
        List<Variable> variableList = iVariableService.queryList(VariableDto.builder()
                .nameCn(request.getNameCn())
                .build());
        if (!CollectionUtils.isEmpty(variableList)) {
            throw new BusinessException("变量中文名已存在");
        }
        //校验变量英文名唯一性
        List<Variable> variableList1 = iVariableService.queryList(VariableDto.builder()
                .nameEn(request.getNameEn())
                .build());
        if (!CollectionUtils.isEmpty(variableList1)) {
            throw new BusinessException("变量英文名已存在");
        }
        Variable variable = new Variable();
        BeanUtils.copyProperties(request,variable);
        variable.setVariableBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_VARIABLE.getCode()));
        //变量编码
        variable.setVariableCode(CodeGenerator.generate10Code(CodeGeneratorConstants.PREFIX_VARIABLE_CODE));
        iVariableService.saveOrUpdate(variable);

        //绑定的条件类型业务ID - 保存对象条件关系表数据
        if (StringUtils.isNotBlank(request.getConditionTypeBizId())) {
            List<String> conditionTypeBizIdList = new ArrayList<>();
            conditionTypeBizIdList.add(request.getConditionTypeBizId());
            apiRelObjectConditionService.saveRelList(ApiRelObjectConditionDto.builder()
                    .objectBizId(variable.getVariableBizId())
                    .objectName(CommonEnum.UID_TYPE_VARIABLE.getName())
                    .objectTableName(CommonEnum.UID_TYPE_VARIABLE.getCode())
                    .objectType(CommonEnum.UID_TYPE_VARIABLE.getCode())
                    .conditionTypeBizIdList(conditionTypeBizIdList)
                    .build());
        }

        //绑定的sql模板业务ID - 保存对象sql模板关系表数据
        if (StringUtils.isNotBlank(request.getSqlTemplateBizId())) {
            List<String> sqlTemplateBizIdList = new ArrayList<>();
            sqlTemplateBizIdList.add(request.getSqlTemplateBizId());
            apiRelObjectSqlService.saveRelList(ApiRelObjectSqlDto.builder()
                    .objectBizId(variable.getVariableBizId())
                    .objectName(CommonEnum.UID_TYPE_VARIABLE.getName())
                    .objectTableName(CommonEnum.UID_TYPE_VARIABLE.getCode())
                    .objectType(CommonEnum.UID_TYPE_VARIABLE.getCode())
                    .sqlTemplateBizIdList(sqlTemplateBizIdList)
                    .build());
        }

        return Result.success();
    }

    /**
     * 编辑-变量信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result edit(ApiVariableEditRequest request) {
        //校验变量信息是否存在
        Result<Variable> result = checkVariableIsExist(request.getVariableBizId());
        Variable variable = result.getData();
        //校验变量中文名唯一性
        List<Variable> variableList = iVariableService.queryList(VariableDto.builder()
                .nameCn(request.getNameCn())
                .isExcludeMy(true)
                .variableBizId(request.getVariableBizId())
                .build());
        if (!CollectionUtils.isEmpty(variableList)) {
            throw new BusinessException("变量中文名已存在");
        }
        //校验变量英文名唯一性
        List<Variable> variableList1 = iVariableService.queryList(VariableDto.builder()
                .nameEn(request.getNameEn())
                .isExcludeMy(true)
                .variableBizId(request.getVariableBizId())
                .build());
        if (!CollectionUtils.isEmpty(variableList1)) {
            throw new BusinessException("变量英文名已存在");
        }
        BeanUtils.copyProperties(request,variable);
        iVariableService.saveOrUpdate(variable);

        //绑定的条件类型业务ID - 保存对象条件关系表数据
        if (StringUtils.isNotBlank(request.getConditionTypeBizId())) {
            List<String> conditionTypeBizIdList = new ArrayList<>();
            conditionTypeBizIdList.add(request.getConditionTypeBizId());
            apiRelObjectConditionService.saveRelList(ApiRelObjectConditionDto.builder()
                    .objectBizId(variable.getVariableBizId())
                    .objectName(CommonEnum.UID_TYPE_VARIABLE.getName())
                    .objectTableName(CommonEnum.UID_TYPE_VARIABLE.getCode())
                    .objectType(CommonEnum.UID_TYPE_VARIABLE.getCode())
                    .conditionTypeBizIdList(conditionTypeBizIdList)
                    .build());
        }

        //绑定的sql模板业务ID - 保存对象sql模板关系表数据
        if (StringUtils.isNotBlank(request.getSqlTemplateBizId())) {
            List<String> sqlTemplateBizIdList = new ArrayList<>();
            sqlTemplateBizIdList.add(request.getSqlTemplateBizId());
            apiRelObjectSqlService.saveRelList(ApiRelObjectSqlDto.builder()
                    .objectBizId(variable.getVariableBizId())
                    .objectName(CommonEnum.UID_TYPE_VARIABLE.getName())
                    .objectTableName(CommonEnum.UID_TYPE_VARIABLE.getCode())
                    .objectType(CommonEnum.UID_TYPE_VARIABLE.getCode())
                    .sqlTemplateBizIdList(sqlTemplateBizIdList)
                    .build());
        }
        return Result.success();
    }

    /**
     * 删除-变量信息 TODO
     * @param variableBizId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result del(String variableBizId) {
        return null;
    }

    /**
     * 校验变量信息是否存在
     * @param variableBizId
     * @return
     */
    public Result<Variable> checkVariableIsExist(String variableBizId) {
        Variable variable = iVariableService.queryOne(variableBizId);
        if (Objects.isNull(variable)) {
            //数据不存在
            throw new BusinessException(ResultCode.NULL_ERROR.getCode(),ResultCode.NULL_ERROR.getMessage());
        }
        return Result.success(variable);
    }
}
