package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.sop.business.bean.params.SopQuickSearchParam;
import com.qmth.sop.business.cache.CommonCacheService;
import com.qmth.sop.business.entity.SysConfig;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBSopQuickSearch;
import com.qmth.sop.business.entity.TFCustomFlow;
import com.qmth.sop.business.mapper.TBSopQuickSearchMapper;
import com.qmth.sop.business.service.TBSopQuickSearchService;
import com.qmth.sop.business.service.TFCustomFlowService;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.FieldUniqueEnum;
import com.qmth.sop.common.enums.SopQuickSearchTypeEnum;
import com.qmth.sop.common.enums.TFCustomTypeEnum;
import com.qmth.sop.common.util.ResultUtil;
import com.qmth.sop.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * sop快捷搜索表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2024-05-21
 */
@Service
public class TBSopQuickSearchServiceImpl extends ServiceImpl<TBSopQuickSearchMapper, TBSopQuickSearch>
        implements TBSopQuickSearchService {

    @Resource
    CommonCacheService commonCacheService;

    @Resource
    TFCustomFlowService tfCustomFlowService;

    @Resource
    TBSopQuickSearchService tbSopQuickSearchService;

    /**
     * sop快捷搜索列表
     *
     * @param type
     * @param contentType
     * @return
     */
    @Override
    public List<TBSopQuickSearch> list(TFCustomTypeEnum type, SopQuickSearchTypeEnum contentType) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        QueryWrapper<TBSopQuickSearch> tbSopQuickSearchQueryWrapper = new QueryWrapper<>();
        tbSopQuickSearchQueryWrapper.lambda().eq(TBSopQuickSearch::getType, type)
                .eq(TBSopQuickSearch::getUserId, sysUser.getId());
        if (Objects.nonNull(contentType)) {
            tbSopQuickSearchQueryWrapper.lambda().eq(TBSopQuickSearch::getContentType, contentType);
        }
        tbSopQuickSearchQueryWrapper.lambda().orderByAsc(TBSopQuickSearch::getName);
        return this.list(tbSopQuickSearchQueryWrapper);
    }

    /**
     * sop快捷搜索保存
     *
     * @param sopQuickSearchParam
     * @return
     */
    @Override
    @Transactional
    public boolean save(SopQuickSearchParam sopQuickSearchParam) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        try {
            SysConfig sysConfig = commonCacheService.addSysConfigCache(SystemConstant.SOP_QUICK_COUNT);
            Objects.requireNonNull(sysConfig, "未设置sop快捷条数");
            Objects.requireNonNull(sysConfig.getConfigValue(), "未设置sop快捷条数值");
            Integer count = Integer.parseInt(sysConfig.getConfigValue());
            TBSopQuickSearch tbSopQuickSearch = null;
            if (Objects.isNull(sopQuickSearchParam.getId())) {//新增
                Integer countDb = this.count(new QueryWrapper<TBSopQuickSearch>().lambda()
                        .eq(TBSopQuickSearch::getType, sopQuickSearchParam.getType())
                        .eq(TBSopQuickSearch::getUserId, sysUser.getId())
                        .eq(TBSopQuickSearch::getContentType, sopQuickSearchParam.getContentType()));
                if (countDb.intValue() > count.intValue()) {
                    throw ExceptionResultEnum.ERROR.exception(
                            "超过[" + sopQuickSearchParam.getContentType().getTitle() + "]最大条数" + count);
                }
                TFCustomFlow maxTfCustomFlow = tfCustomFlowService.findMaxVersion(null, null,
                        sopQuickSearchParam.getType());
                Optional.ofNullable(maxTfCustomFlow)
                        .orElseThrow(() -> ExceptionResultEnum.FLOW_CUSTOM_NO_DATA.exception());
                tbSopQuickSearch = new TBSopQuickSearch(sopQuickSearchParam, maxTfCustomFlow.getFlowDeploymentId(),
                        maxTfCustomFlow.getVersion(), sysUser.getId());
            } else {//更新
                tbSopQuickSearch = this.getById(sopQuickSearchParam.getId());
                Objects.requireNonNull(tbSopQuickSearch, "未找到sop快捷数据");
                tbSopQuickSearch.updateInfo(sopQuickSearchParam);
            }
            return tbSopQuickSearchService.saveOrUpdate(tbSopQuickSearch);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String[] strs = StringUtils.split(errorColumn, "-");
                String[] columns = StringUtils.split(strs[strs.length - 1], "\\'");
                throw ExceptionResultEnum.SQL_ERROR.exception(
                        "[" + FieldUniqueEnum.convertToTitle(columns[columns.length - 1]) + "]数据不允许重复插入");
            } else if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return false;
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean delete(Long id) {
        return tbSopQuickSearchService.removeById(id);
    }
}
