package com.qmth.paper.library.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.paper.library.common.bean.dto.syssetting.SettingObject;
import com.qmth.paper.library.common.bean.dto.syssetting.SimpleObject;
import com.qmth.paper.library.common.contant.SysSettingConstant;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.SysSetting;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import com.qmth.paper.library.common.enums.RecognitionTypeEnum;
import com.qmth.paper.library.common.mapper.SysSettingMapper;
import com.qmth.paper.library.common.service.CommonCacheService;
import com.qmth.paper.library.common.service.SysSettingService;
import com.qmth.paper.library.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统设置 服务实现类
 * </p>
 */
@Service
public class SysSettingServiceImpl extends ServiceImpl<SysSettingMapper, SysSetting> implements SysSettingService {

    @Resource
    CommonCacheService commonCacheService;

    @Override
    public List<SettingObject> getData() {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        QueryWrapper<SysSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysSetting::getSchoolId, schoolId);
        List<SysSetting> sysSettingList = this.list(queryWrapper);

        SysSetting sysSetting = new SysSetting();
        // 第一次设置，初始化数据
        if (sysSettingList.isEmpty()) {
            sysSetting = SysSetting.init(schoolId);
            this.save(sysSetting);
        } else if (sysSettingList.size() > 1) {
            throw ExceptionResultEnum.ERROR.exception("系统设置有误，查出多条数据");
        }

        if (!sysSettingList.isEmpty()) {
            sysSetting = sysSettingList.get(0);
        }

        return JSON.parseArray(sysSetting.getParameterObject(), SettingObject.class);
    }

    @Override
    public boolean saveData(List<SettingObject> settingObjects) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        Long userId = Long.valueOf(ServletUtil.getRequestHeaderUserId().toString());

        QueryWrapper<SysSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysSetting::getSchoolId, schoolId);
        SysSetting sysSetting = this.getOne(queryWrapper);

        String parameterObject = JSON.toJSONString(settingObjects);
        // 新增
        if (sysSetting == null) {
            sysSetting = new SysSetting();
            sysSetting.setId(SystemConstant.getDbUuid());
            sysSetting.setParameterObject(parameterObject);
            sysSetting.setSchoolId(schoolId);
            sysSetting.setCreateId(userId);
            sysSetting.setCreateTime(System.currentTimeMillis());
        } else {
            sysSetting.setParameterObject(parameterObject);
            sysSetting.setUpdateId(userId);
            sysSetting.setUpdateTime(System.currentTimeMillis());

            String recognitionType = SysSetting.parseParameterObject(sysSetting, SysSettingConstant.RECOGNITION_TYPE);
            if (recognitionType != null && RecognitionTypeEnum.OCR.name().equals(recognitionType)) {
                Map<String, String> sysSettingGlobal = commonCacheService.getSysSettingGlobal();
                if (!sysSettingGlobal.containsKey(SysSettingConstant.OCR_APP_ID) || StringUtils.isBlank(sysSettingGlobal.get(SysSettingConstant.OCR_APP_ID))) {
                    throw ExceptionResultEnum.ERROR.exception("未设置OCR AppId，无法开启OCR识别");
                } else if (!sysSettingGlobal.containsKey(SysSettingConstant.OCR_APP_KEY) || StringUtils.isBlank(sysSettingGlobal.get(SysSettingConstant.OCR_APP_KEY))) {
                    throw ExceptionResultEnum.ERROR.exception("未设置OCR AppKey，无法开启OCR识别");
                } else if (!sysSettingGlobal.containsKey(SysSettingConstant.OCR_APP_SECRET) || StringUtils.isBlank(sysSettingGlobal.get(SysSettingConstant.OCR_APP_SECRET))) {
                    throw ExceptionResultEnum.ERROR.exception("未设置OCR AppSecret，无法开启OCR识别");
                }
            }

            commonCacheService.removeSysSetting(schoolId);
        }
        return this.saveOrUpdate(sysSetting);
    }

    @Override
    public SysSetting getBySchoolId(Long schoolId) {
        QueryWrapper<SysSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysSetting::getSchoolId, schoolId);
        return this.getOne(queryWrapper);
    }
}
