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


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.util.Assert.AssertUtils;
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.SystemConfigFilterDO;
import com.cf.imes.module.system.dal.mysql.systemconfig.SystemConfigFilterMapper;
import com.cf.imes.module.system.service.systemconfig.factory.service.AbstractSystemConfigServiceHandler;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.framework.security.core.util.SecurityFrameworkUtils.getUserOrganId;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.SYSTEM_CONFIG_NOT_EXISTS;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.THIS_CONFIG_NAME_IS_EXISTS;


/**
 * @author 板件分线生成服务
 */
@Service("intellectBranchingService")
public class IntellectBranchingService extends AbstractSystemConfigServiceHandler {


    @Resource
    private SystemConfigFilterMapper systemConfigFilterMapper;

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

        List<SystemConfigFilterDO> systemConfigDOS = systemConfigFilterMapper.selectSystemConfigList(pageReqVO.getType(),null);

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

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

    @Override
    public void checkValid(String setting) {

        // todo checkValid
    }


    @Override
    public void beforeSaveConfig(ConfigSaveReqVO reqVO) {

        List<SystemConfigFilterDO> systemConfigFilterDOS = systemConfigFilterMapper.selectList(new LambdaQueryWrapperX<SystemConfigFilterDO>()
                .eq(SystemConfigFilterDO::getOrganId,getUserOrganId())
                .eq(SystemConfigFilterDO::getName, reqVO.getName())
                .neIfPresent(SystemConfigFilterDO::getId,reqVO.getId()));

        AssertUtils.empty(systemConfigFilterDOS,THIS_CONFIG_NAME_IS_EXISTS);
    }


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

        List<SystemConfigFilterDO> systemConfigDOS = systemConfigFilterMapper.selectSystemConfigList(reqVO.getType(), CommonStatusEnum.ENABLE.getStatus());

        if(systemConfigDOS.size() > 1){
            systemConfigFilterMapper.update(new LambdaUpdateWrapper<SystemConfigFilterDO>()
                    .eq(SystemConfigFilterDO::getOrganId, OrganContextHolder.getOrganId())
                    .eq(SystemConfigFilterDO::getId,systemConfigDO.getId())
                    .set(SystemConfigFilterDO::getStatus, CommonStatusEnum.DISABLE.getStatus()));
        }

    }


    @Override
    public void deleteConfig(ConfigDeleteReqVO reqVO) {

        validateSystemConfigExists(reqVO.getId());

        systemConfigFilterMapper.deleteConfig(reqVO.getId(),getUserOrganId());

    }

    @Override
    public void updateConfigStatus(ConfigUpdateStatusReqVO reqVO) {

        Long id = reqVO.getId();

        // 校验存在
        SystemConfigFilterDO systemConfigFilterDO = systemConfigFilterMapper.selectOne(new LambdaQueryWrapperX<SystemConfigFilterDO>()
                .eq(SystemConfigFilterDO::getId, id)
                .eq(SystemConfigFilterDO::getOrganId, OrganContextHolder.getOrganId()));
        if (ObjectUtil.isNull(systemConfigFilterDO)) {
            throw exception(SYSTEM_CONFIG_NOT_EXISTS);
        }

        // 更新状态
        systemConfigFilterMapper.update(new LambdaUpdateWrapper<SystemConfigFilterDO>()
                .eq(SystemConfigFilterDO::getId, id)
                .set(SystemConfigFilterDO::getStatus, reqVO.getStatus()));

        systemConfigFilterMapper.update(new LambdaUpdateWrapper<SystemConfigFilterDO>()
                .eq(SystemConfigFilterDO::getOrganId, OrganContextHolder.getOrganId())
                .eq(SystemConfigFilterDO::getDeleted,false)
                .notIn(SystemConfigFilterDO::getId,reqVO.getId())
                .eq(SystemConfigFilterDO::getType, systemConfigFilterDO.getType())
                .set(SystemConfigFilterDO::getStatus, CommonStatusEnum.DISABLE.getStatus()));

    }



    @Override
    public void updateConfigSort(List<ConfigUpdateSortReqVO> reqVO) {

        ArrayList<SystemConfigFilterDO> systemConfigFilterDOS = new ArrayList<>();

        reqVO.forEach(f->
                systemConfigFilterDOS.add(BeanUtils.toBean(SystemConfigDO
                        .builder()
                        .id(f.getId())
                        .type(f.getType())
                        .status(f.getStatus())
                        .sort(f.getSort())
                        .build(),SystemConfigFilterDO.class)));

        systemConfigFilterMapper.updateBatch(systemConfigFilterDOS);

    }


    @Override
    public SystemConfigDO getSystemConfig(Long id) {

        SystemConfigFilterDO systemConfigFilterDO = validateSystemConfigExists(id);

        return BeanUtils.toBean(systemConfigFilterDO,SystemConfigDO.class);

    }

    @Override
    public void modifySystemConfig(ConfigSaveReqVO reqVO) {

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

    }


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

        SystemConfigFilterDO systemConfigFilterDO = systemConfigFilterMapper.selectOne(new LambdaQueryWrapperX<SystemConfigFilterDO>()
                .eq(SystemConfigFilterDO::getId, id)
                .eq(SystemConfigFilterDO::getOrganId, OrganContextHolder.getOrganId()));

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

        return systemConfigFilterDO;
    }




}

