package com.cf.imes.module.system.service.setting;

import com.cf.imes.framework.common.util.json.JsonUtils;
import com.cf.imes.framework.security.core.LoginUser;
import com.cf.imes.module.system.controller.admin.setting.vo.PackageConfigReqVO;
import com.cf.imes.module.system.dal.dataobject.setting.PackageConfigDO;
import com.cf.imes.module.system.dal.mysql.setting.PackageConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;

import static com.cf.imes.framework.common.util.json.JsonUtils.unzipString;
import static com.cf.imes.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;


@Service
@Validated
public class SettingServiceImpl implements SettingService{


    @Resource
    private PackageConfigMapper packageConfigMapper;


    @Override
    public Long insertSetting(PackageConfigReqVO reqVO) {

        LoginUser loginUser = getLoginUser();

        packageConfigMapper.deleteSetting(reqVO.getType(),loginUser.getId(),loginUser.getOrganId());

        PackageConfigDO packageConfigDO = PackageConfigDO.builder()
                .userId(loginUser.getId())
                .organId(loginUser.getOrganId())
                .setting(JsonUtils.zipString(reqVO.getSetting().toJSONString()))
                .type(reqVO.getType())
                .build();

        packageConfigMapper.insert(packageConfigDO);


        return packageConfigDO.getId();

    }


    @Override
    public Long updateSetting(PackageConfigReqVO reqVO) {

        LoginUser loginUser = getLoginUser();
        // 更新
        PackageConfigDO packageConfigDO = packageConfigMapper.selectSetting(reqVO.getType(), loginUser.getId(), loginUser.getOrganId());
        if (packageConfigDO == null) {
            // 新增
            PackageConfigDO newPackageConfigDO = PackageConfigDO.builder()
                    .userId(loginUser.getId())
                    .organId(loginUser.getOrganId())
                    .setting(JsonUtils.zipString(reqVO.getSetting().toJSONString()))
                    .type(reqVO.getType())
                    .build();

            packageConfigMapper.insert(newPackageConfigDO);
            return newPackageConfigDO.getId();
        }
        if (reqVO.getSetting() != null) {
            packageConfigDO.setSetting(JsonUtils.zipString(reqVO.getSetting().toJSONString()));
        }
        packageConfigMapper.updateById(packageConfigDO);

        return packageConfigDO.getId();
    }



    @Override
    public PackageConfigDO selectSetting(Integer type) {

        LoginUser loginUser = getLoginUser();

        assert loginUser != null;
        PackageConfigDO packageConfigDO = packageConfigMapper.selectSetting(type, loginUser.getId(), loginUser.getOrganId());

        if (packageConfigDO == null) {
            return null;
        }

        packageConfigDO.setSetting(unzipString(packageConfigDO.getSetting()));

        return packageConfigDO;
    }

}
