package com.testor.module.train.database.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.file.model.domain.SysFile;
import com.testor.biz.file.service.SysFileService;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.constant.DefaultRule;
import com.testor.module.train.database.dao.TTrainDatabaseDao;
import com.testor.module.train.database.model.domain.TTrainDatabase;
import com.testor.module.train.database.model.dto.TTrainDatabaseDelParam;
import com.testor.module.train.database.model.dto.TTrainDatabaseParam;
import com.testor.module.train.database.service.TTrainDatabaseService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 培训资料管理——安全培训教育Service业务层处理
 *
 * @author testor-framework
 * @date 2022-07-12 10:01:27
 */
@Service
public class TTrainDatabaseServiceImpl extends SuperServiceImpl<TTrainDatabaseDao, TTrainDatabase> implements TTrainDatabaseService {
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private SysRuleService sysRuleService;

    @Override
    public BaseResponse<TTrainDatabase> addEntity(TTrainDatabase addRequest) throws Exception {

        if (ObjectHelper.isEmpty(addRequest)) {
            throw new BusinessException("请求参数有误");
        }
        BaseResponse<TTrainDatabase> baseResponse = new BaseResponse<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_ALL.name());
        if (ObjectHelper.isNotEmpty(addRequest)) {
            List<TTrainDatabase> list = this.list(new QueryWrapper<TTrainDatabase>()
                    .eq(TTrainDatabase.DATA_NAME, addRequest.getDataName())
                    .apply(rule)
                    .ne(TTrainDatabase.STATUS, BizConstants.STATUS_DELETE)
            );
            if (ObjectHelper.isNotEmpty(list)) {
                throw new BusinessException("资料名称已存在");
            }
            String id = IdHelper.getId32bit();
            TTrainDatabase data = BeanHelper.beanToBean(addRequest, TTrainDatabase.class);
            data.setOrgId(loginUser.getOrgId());
            data.setDataSource(sysOrg.getOrgName());
            data.setProcessStatus("3");
            data.setLevel(sysOrg.getTreeLevel().toString());
            data.setId(id);
            boolean result = false;
            try {
                result = this.save(data);
            } catch (org.springframework.dao.DataIntegrityViolationException e) {
                throw new BusinessException("名称过长");
            }
            if (result) {
                TTrainDatabase newEntity = new TTrainDatabase();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<TTrainDatabaseParam> getByIds(String id) throws Exception {
        BaseResponse<TTrainDatabaseParam> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TTrainDatabase data = this.getById(id);
            TTrainDatabaseParam tTrainDatabaseParam = BeanHelper.beanToBean(data, TTrainDatabaseParam.class);
            String attachmentId = tTrainDatabaseParam.getAttachmentId();
            if (StringHelper.isNotEmpty(attachmentId)) {
                SysFile sysFile = sysFileService.getById(attachmentId);
                tTrainDatabaseParam.setFileName(sysFile.getFileName());
                tTrainDatabaseParam.setFilePath(sysFile.getFilePath());
            }
            baseResponse.setData(tTrainDatabaseParam);
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> updateEntity(TTrainDatabase updateRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_ALL.name());
            TTrainDatabase database = this.getById(updateRequest.getId());
            if (!updateRequest.getDataName().equals(database.getDataName())) {
                List<TTrainDatabase> list = this.list(new QueryWrapper<TTrainDatabase>()
                        .eq(TTrainDatabase.DATA_NAME, updateRequest.getDataName())
                        .apply(rule)
                        .ne(TTrainDatabase.STATUS, BizConstants.STATUS_DELETE)
                );
                if (ObjectHelper.isNotEmpty(list)) {
                    throw new BusinessException("资料名称已存在");
                }
            }
            TTrainDatabase data = BeanHelper.beanToBean(updateRequest, TTrainDatabase.class);
            boolean result = false;
            try {
                result = this.updateById(data);
            } catch (org.springframework.dao.DataIntegrityViolationException e) {
                throw new BusinessException("名称过长");
            }
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> deleteEntity(TTrainDatabaseDelParam deleteRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            TTrainDatabase data = new TTrainDatabase();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = this.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }
}
