package com.qmth.teachcloud.report.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.teachcloud.common.bean.result.SysConfigResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysConfig;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.CommonCacheService;
import com.qmth.teachcloud.common.service.SysConfigService;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.report.business.bean.params.SysAdminSetParam;
import com.qmth.teachcloud.report.business.bean.result.SysAdminSetResult;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description: 超管设置
 * @Author: CaoZixuan
 * @Date: 2022-12-22
 */
@Api(tags = "超管设置Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_REPORT_SET)
public class SysAdminSetController {
    @Resource
    CommonCacheService commonCacheService;
    @Resource
    SysConfigService sysConfigService;

    @ApiOperation(value = "同步配置查询")
    @ApiResponses({@ApiResponse(code = 200, message = "同步配置信息", response = SysAdminSetResult.class)})
    @RequestMapping(value = "/sync/select", method = RequestMethod.POST)
    public Result sysadminSyncSelect(@ApiParam(value = "学校id ", required = true) @RequestParam Long schoolId) {
        SysConfig sysConfigTeachCloudPrintHostUrl = commonCacheService.addSysConfigCache(schoolId, SystemConstant.TEACHCLOUD_PRINT_HOST_URL);
        SysConfig sysConfigTeachCloudReportLocationUrl = commonCacheService.addSysConfigCache(SystemConstant.TEACHCLOUD_REPORT_LOCATION_URL);

        List<SysConfigResult> sysConfigResultList = new ArrayList<>();
        if (Objects.nonNull(sysConfigTeachCloudPrintHostUrl)) {
            sysConfigResultList.add(new SysConfigResult(sysConfigTeachCloudPrintHostUrl));
        } else {
            SysConfig sysConfigTeachCloudPrintHostDefaultUrl = commonCacheService.addSysConfigCache(SystemConstant.TEACHCLOUD_PRINT_HOST_DEFAULT_URL);
            if (Objects.nonNull(sysConfigTeachCloudPrintHostDefaultUrl)) {
                sysConfigResultList.add(new SysConfigResult(sysConfigTeachCloudPrintHostDefaultUrl));
            } else {
                sysConfigResultList.add(new SysConfigResult(null, SystemConstant.TEACHCLOUD_PRINT_HOST_URL, "分布式印刷地址", "", 1));
            }
        }
        if (Objects.nonNull(sysConfigTeachCloudReportLocationUrl)) {
            sysConfigResultList.add(new SysConfigResult(sysConfigTeachCloudReportLocationUrl));
        } else {
            sysConfigResultList.add(new SysConfigResult(null, SystemConstant.TEACHCLOUD_REPORT_LOCATION_URL, "报告和登录地址", "", 2));
        }
        return ResultUtil.ok(new SysAdminSetResult(schoolId, sysConfigResultList));
    }

    @ApiOperation(value = "同步配置保存")
    @ApiResponses({@ApiResponse(code = 200, message = "同步配置信息", response = ResultUtil.class)})
    @RequestMapping(value = "/sync/save", method = RequestMethod.POST)
    @Transactional
    public Result sysadminSyncSave(@Valid @RequestBody SysAdminSetParam sysAdminSetParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        Optional.ofNullable(sysAdminSetParam.getParam()).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("同步配置地址不能为空"));

        List<SysConfigResult> sysConfigResultList = sysAdminSetParam.getParam();
        Long schoolId = sysAdminSetParam.getSchoolId();
        List<SysConfig> sysConfigList = new ArrayList<>();
        List<String> keys = new ArrayList<>();
        String value = null;
        for (SysConfigResult s : sysConfigResultList) {
            if (s.getCode().contains(SystemConstant.TEACHCLOUD_REPORT_LOCATION_URL)) {
                value = (String) s.getValue();
                sysConfigList.add(new SysConfig(s));
                if (Objects.nonNull(s.getEnable()) && !s.getEnable()){
                    throw ExceptionResultEnum.ERROR.exception("报告和登录地址不能关闭");
                }
            } else {
                s.setId(SystemConstant.getDbUuid());
                s.setCode(s.getCode().replace(".default", ""));
                keys.add(s.getCode());
                sysConfigList.add(new SysConfig(sysAdminSetParam.getSchoolId(), s));
            }
        }
        if (Objects.nonNull(value) && !Objects.equals(value.trim(), "")) {
            SysConfig sysConfigTeachCloudReportLocalUrl = commonCacheService.addSysConfigCache(SystemConstant.TEACHCLOUD_REPORT_LOGIN_URL);
            SysConfig sysConfigTeachCloudReportStudentUrl = commonCacheService.addSysConfigCache(SystemConstant.TEACHCLOUD_REPORT_STUDENT_URL);
            String[] localStrs = StringUtils.split(sysConfigTeachCloudReportLocalUrl.getConfigValue(), "#");
            String[] studentStrs = StringUtils.split(sysConfigTeachCloudReportStudentUrl.getConfigValue(), "#");
            String split = value.substring(value.length() - 1, value.length());
            if (split.contains(SystemConstant.ORG_SPLIT)) {
                sysConfigTeachCloudReportLocalUrl.setConfigValue(value + SystemConstant.DEFAULT_SIGN + localStrs[1]);
                sysConfigTeachCloudReportStudentUrl.setConfigValue(value + SystemConstant.DEFAULT_SIGN + studentStrs[1]);
            } else {
                sysConfigTeachCloudReportLocalUrl.setConfigValue(value + SystemConstant.ORG_SPLIT + SystemConstant.DEFAULT_SIGN + localStrs[1]);
                sysConfigTeachCloudReportStudentUrl.setConfigValue(value + SystemConstant.ORG_SPLIT + SystemConstant.DEFAULT_SIGN + studentStrs[1]);
            }
            sysConfigList.add(sysConfigTeachCloudReportLocalUrl);
            sysConfigList.add(sysConfigTeachCloudReportStudentUrl);
            commonCacheService.updateSysConfigCache(sysConfigTeachCloudReportLocalUrl.getConfigKey());
            commonCacheService.updateSysConfigCache(sysConfigTeachCloudReportStudentUrl.getConfigKey());
        } else {
            throw ExceptionResultEnum.ERROR.exception("报告和登录地址不能为空");
        }
        QueryWrapper<SysConfig> sysConfigQueryWrapper = new QueryWrapper<>();
        sysConfigQueryWrapper.lambda().eq(SysConfig::getSchoolId, schoolId)
                .in(SysConfig::getConfigKey, keys);
        sysConfigService.remove(sysConfigQueryWrapper);
        sysConfigService.saveOrUpdateBatch(sysConfigList);

        for (SysConfigResult s : sysConfigResultList) {
            if (s.getCode().contains(SystemConstant.TEACHCLOUD_REPORT_LOCATION_URL)) {
                commonCacheService.updateSysConfigCache(s.getCode());
            } else {
                commonCacheService.updateSysConfigCache(sysAdminSetParam.getSchoolId(), s.getCode());
            }
        }
        return ResultUtil.ok(true);
    }
}
