package com.cf.imes.module.system.service.systemconfig.factory.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.module.system.controller.admin.systemconfig.vo.*;
import com.cf.imes.module.system.dal.dataobject.systemconfig.SystemConfigDO;
import com.cf.imes.module.system.dal.dataobject.systemconfig.SystemConfigSealedgeDO;
import com.cf.imes.module.system.dal.mysql.systemconfig.SystemConfigSealedgeMapper;
import com.cf.imes.module.system.service.systemconfig.factory.service.AbstractSystemConfigServiceHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.*;


/**
 * @author 封边条对应
 */
@Service("sealedgeServiceHandler")
@Slf4j
public class SealedgeServiceHandler extends AbstractSystemConfigServiceHandler {

    @Resource
    private SystemConfigSealedgeMapper systemConfigSealedgeMapper;



    @Override
    public List<SystemConfigDO> selectList(ConfigPageReqVO pageReqVO) {

        List<SystemConfigSealedgeDO> systemConfigDOS = systemConfigSealedgeMapper.selectSystemConfigList(pageReqVO.getType(),null);

        if (systemConfigDOS.isEmpty()){
            return null;
        }

        return BeanUtils.toBean(systemConfigDOS,SystemConfigDO.class);
    }


    @Override
    public void checkValid(String setting) {

        try {

            JSONArray jsonArray = JSON.parseArray(setting);

            for (int i = 0; i < jsonArray.size(); i++) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);

                String widthMin = jsonObject.getString("widthMin");

                String widthMax = jsonObject.getString("widthMax");

                String widthValue = jsonObject.getString("widthValue");

                if(StringUtils.isEmpty(widthMin) || StringUtils.isEmpty(widthMax)  || StringUtils.isEmpty(widthValue) ){
                    throw exception(SEALEDGE_CONFIG_NOT_EXISTS,(i+1));
                }

                BigDecimal widthMin2 = BigDecimal.valueOf(Double.parseDouble(widthMin));

                BigDecimal widthMax2 = BigDecimal.valueOf(Double.parseDouble(widthMax));

                BigDecimal widthValue2 = BigDecimal.valueOf(Double.parseDouble(widthValue));


                if(widthMin2.scale() > 3 || widthMax2.scale() > 3 || widthValue2.scale() > 3 ){
                    throw exception(DECIMAL_PLACES_MAX_TWO,(i+1));
                }


                if( widthMin2.compareTo(BigDecimal.ZERO) != 1  ){
                    throw exception(SEALEDGE_CONFIG_MIN_VALUE_GREATER_THAN_ZERO,(i+1),widthMin2.stripTrailingZeros().toPlainString());
                }

                if( widthMax2.compareTo(BigDecimal.ZERO) != 1  ){
                    throw exception(SEALEDGE_CONFIG_MAX_VALUE_GREATER_THAN_ZERO,(i+1),widthMax2.stripTrailingZeros().toPlainString());
                }

                if( widthMax2.compareTo(widthMin2) == -1 ){
                    throw exception(SEALEDGE_CONFIG_VALUE_DATA_ERROR,(i+1));
                }

                if( widthValue2.compareTo(widthMax2) == -1 ){
                    throw exception(SEALEDGE_CONFIG_MAX_VALUE_DATA_ERROR,(i+1),widthValue2.stripTrailingZeros().toPlainString(),widthMax2.stripTrailingZeros().toPlainString());
                }

            }
        }

        catch (ServiceException e){
            throw e;
        }catch (Exception e){
            log.error("封边条配置有误："+e.getMessage());
            throw new ServiceException(SEALEDGE_CONFIG_DATA_ERROR);
        }
    }



    @Override
    public void beforeSaveConfig(ConfigSaveReqVO reqVO) {
        // todo beforeSaveConfig
    }



    @Override
    public void afterSaveConfig(SystemConfigDO systemConfigDO, ConfigSaveReqVO reqVO) {

        systemConfigSealedgeMapper.update(new LambdaUpdateWrapper<SystemConfigSealedgeDO>()
                .eq(SystemConfigSealedgeDO::getOrganId, OrganContextHolder.getOrganId())
                .eq(SystemConfigSealedgeDO::getDeleted,false)
                .ne(SystemConfigSealedgeDO::getId,systemConfigDO.getId())
                .set(SystemConfigDO::getDeleted,true));

    }


    @Override
    public void deleteConfig(ConfigDeleteReqVO reqVO) {
        // todo deleteConfig
    }


    @Override
    public void updateConfigStatus(ConfigUpdateStatusReqVO reqVO) {
        // TODO document why this method is empty
    }

    @Override
    public void updateConfigSort(List<ConfigUpdateSortReqVO> reqVO) {
        // TODO document why this method is empty
    }


    @Override
    public SystemConfigDO getSystemConfig(Long id) {

        SystemConfigSealedgeDO systemConfigDO = systemConfigSealedgeMapper.selectOne(new LambdaQueryWrapperX<SystemConfigSealedgeDO>()
                .eq(SystemConfigSealedgeDO::getId, id)
                .eq(SystemConfigSealedgeDO::getOrganId, OrganContextHolder.getOrganId()));

        if (ObjectUtil.isNull(systemConfigDO)) {
            throw exception(SYSTEM_CONFIG_NOT_EXISTS);
        }

        return systemConfigDO;

    }


    @Override
    public void modifySystemConfig(ConfigSaveReqVO reqVO) {

        // 校验规则
        checkValid(reqVO.getSetting());
        // 系统配置保存前操作
        beforeSaveConfig(reqVO);
        SystemConfigSealedgeDO systemConfigSealedgeDO;
        if (ObjectUtil.isNotNull(reqVO.getId())) {
            systemConfigSealedgeDO = validateSystemConfigExists(reqVO.getId());
            // 覆盖配置
            systemConfigSealedgeDO.setSetting(reqVO.getSetting());
            // 覆盖名称
            systemConfigSealedgeDO.setName(reqVO.getName());
            // 更新时间
            systemConfigSealedgeDO.setUpdateTime(LocalDateTime.now());
            // 更新
            systemConfigSealedgeMapper.updateById(systemConfigSealedgeDO);
        } else {
            systemConfigSealedgeDO = BeanUtils.toBean(reqVO, SystemConfigSealedgeDO.class);
            // 新增
            systemConfigSealedgeMapper.insert(systemConfigSealedgeDO);
        }
        // 系统配置保存后操作
        afterSaveConfig(systemConfigSealedgeDO, reqVO);

    }



    /**
     * 校验基础配置是否存在
     *
     * @param id
     * @return
     */
    private SystemConfigSealedgeDO validateSystemConfigExists(Long id) {

        SystemConfigSealedgeDO systemConfigSealedgeDO = systemConfigSealedgeMapper.selectOne(new LambdaQueryWrapperX<SystemConfigSealedgeDO>()
                .eq(SystemConfigSealedgeDO::getId, id)
                .eq(SystemConfigSealedgeDO::getOrganId, OrganContextHolder.getOrganId()));

        if (ObjectUtil.isNull(systemConfigSealedgeDO)) {
            throw exception(SYSTEM_CONFIG_NOT_EXISTS);
        }

        return systemConfigSealedgeDO;
    }





}
