package com.tourism.webadmin.back.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.github.pagehelper.page.PageMethod;
import com.tourism.webadmin.back.vo.*;
import com.tourism.webadmin.back.dto.*;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.service.*;
import com.tourism.common.core.object.*;
import com.tourism.common.core.util.*;
import com.tourism.common.core.constant.*;
import com.tourism.common.core.annotation.MyRequestBody;
import com.tourism.common.additional.config.ApplicationConfig;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 聊天敏感词白名单操作控制器类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Tag(name = "聊天敏感词白名单管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/tourImSensitiveWordAllow")
public class TourImSensitiveWordAllowController {

    @Autowired
    private ApplicationConfig appConfig;
    @Autowired
    private TourImSensitiveWordAllowService tourImSensitiveWordAllowService;

    private final SensitiveWordBs sensitiveWordBs;

    public TourImSensitiveWordAllowController(SensitiveWordBs sensitiveWordBs) {
        this.sensitiveWordBs = sensitiveWordBs;
    }

    public void refresh(){
        sensitiveWordBs.init();
    }


    /**
     * 新增聊天敏感词白名单数据。
     *
     * @param tourImSensitiveWordAllowDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"tourImSensitiveWordAllowDto.id", "tourImSensitiveWordAllowDto.searchString"})
    @SaCheckPermission("tourImSensitiveWordAllow.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody TourImSensitiveWordAllowDto tourImSensitiveWordAllowDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourImSensitiveWordAllowDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        TourImSensitiveWordAllow tourImSensitiveWordAllow = MyModelUtil.copyTo(tourImSensitiveWordAllowDto, TourImSensitiveWordAllow.class);
        tourImSensitiveWordAllow = tourImSensitiveWordAllowService.saveNew(tourImSensitiveWordAllow);
        ResponseResult<Long> success = ResponseResult.success(tourImSensitiveWordAllow.getId());
        refresh();
        return success;
    }

    /**
     * 更新聊天敏感词白名单数据。
     *
     * @param tourImSensitiveWordAllowDto 更新对象。
     * @return 应答结果对象。
     */
    @ApiOperationSupport(ignoreParameters = {"tourImSensitiveWordAllowDto.searchString"})
    @SaCheckPermission("tourImSensitiveWordAllow.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody TourImSensitiveWordAllowDto tourImSensitiveWordAllowDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourImSensitiveWordAllowDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        TourImSensitiveWordAllow tourImSensitiveWordAllow = MyModelUtil.copyTo(tourImSensitiveWordAllowDto, TourImSensitiveWordAllow.class);
        TourImSensitiveWordAllow originalTourImSensitiveWordAllow = tourImSensitiveWordAllowService.getById(tourImSensitiveWordAllow.getId());
        if (originalTourImSensitiveWordAllow == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!tourImSensitiveWordAllowService.update(tourImSensitiveWordAllow, originalTourImSensitiveWordAllow)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        refresh();
        return ResponseResult.success();
    }

    /**
     * 删除聊天敏感词白名单数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourImSensitiveWordAllow.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long id) {
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        ResponseResult<Void> voidResponseResult = this.doDelete(id);
        refresh();
        return voidResponseResult;
    }

    /**
     * 批量删除聊天敏感词白名单数据。
     *
     * @param idList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourImSensitiveWordAllow.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> idList) {
        if (MyCommonUtil.existBlankArgument(idList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long id : idList) {
            ResponseResult<Void> responseResult = this.doDelete(id);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        refresh();
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的聊天敏感词白名单列表。
     *
     * @param tourImSensitiveWordAllowDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("tourImSensitiveWordAllow.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<TourImSensitiveWordAllowVo>> list(
            @MyRequestBody TourImSensitiveWordAllowDto tourImSensitiveWordAllowDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        TourImSensitiveWordAllow tourImSensitiveWordAllowFilter = MyModelUtil.copyTo(tourImSensitiveWordAllowDtoFilter, TourImSensitiveWordAllow.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourImSensitiveWordAllow.class);
        List<TourImSensitiveWordAllow> tourImSensitiveWordAllowList =
                tourImSensitiveWordAllowService.getTourImSensitiveWordAllowListWithRelation(tourImSensitiveWordAllowFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tourImSensitiveWordAllowList, TourImSensitiveWordAllowVo.class));
    }

    /**
     * 导入主表数据列表。
     *
     * @param importFile 上传的文件，目前仅仅支持xlsx和xls两种格式。
     * @return 应答结果对象。
     */
    @SaCheckPermission("tourImSensitiveWordAllow.import")
    @OperationLog(type = SysOperationLogType.IMPORT)
    @PostMapping("/import")
    public ResponseResult<Void> importBatch(
            @RequestParam Boolean skipHeader,
            @RequestParam("importFile") MultipartFile importFile) throws IOException {
        String filename = ImportUtil.saveImportFile(appConfig.getUploadFileBaseDir(), null, importFile);
        List<ImportUtil.ImportHeaderInfo> headerInfoList = ImportUtil.makeHeaderInfoList(TourImSensitiveWordAllow.class, null);
        // 下面是导入时需要注意的地方，如果我们缺省生成的代码，与实际情况存在差异，请手动修改。
        // 1. 头信息数据字段，我们只是根据当前的主表实体对象生成了缺省数组，开发者可根据实际情况，对headerInfoList进行修改。
        ImportUtil.ImportHeaderInfo[] headerInfos = headerInfoList.toArray(new ImportUtil.ImportHeaderInfo[]{});
        // 2. 这里需要根据实际情况决定，导入文件中第一行是否为中文头信息，如果是可以跳过。这里我们默认为true。
        // 这里根据自己的实际需求，为doImport的最后一个参数，传递需要进行字典转换的字段集合。
        // 注意，集合中包含需要翻译的Java字段名，如: gradeId。
        Set<String> translatedDictFieldSet = new HashSet<>();
        List<TourImSensitiveWordAllow> dataList =
                ImportUtil.doImport(headerInfos, skipHeader, filename, TourImSensitiveWordAllow.class, translatedDictFieldSet);
        tourImSensitiveWordAllowService.saveNewBatch(dataList, -1);
        return ResponseResult.success();
    }

    /**
     * 导出符合过滤条件的聊天敏感词白名单列表。
     *
     * @param tourImSensitiveWordAllowDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @throws IOException 文件读写失败。
     */
    @SaCheckPermission("tourImSensitiveWordAllow.export")
    @OperationLog(type = SysOperationLogType.EXPORT, saveResponse = false)
    @PostMapping("/export")
    public void export(
            @MyRequestBody TourImSensitiveWordAllowDto tourImSensitiveWordAllowDtoFilter,
            @MyRequestBody MyOrderParam orderParam) throws IOException {
        TourImSensitiveWordAllow tourImSensitiveWordAllowFilter = MyModelUtil.copyTo(tourImSensitiveWordAllowDtoFilter, TourImSensitiveWordAllow.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TourImSensitiveWordAllow.class);
        List<TourImSensitiveWordAllow> resultList =
                tourImSensitiveWordAllowService.getTourImSensitiveWordAllowListWithRelation(tourImSensitiveWordAllowFilter, orderBy);
        // 导出文件的标题数组
        // NOTE: 下面的代码中仅仅导出了主表数据，主表聚合计算数据和主表关联字典的数据。
        // 一对一从表数据的导出，可根据需要自行添加。如：headerMap.put("slaveFieldName.xxxField", "标题名称")
        Map<String, String> headerMap = new LinkedHashMap<>(2);
        headerMap.put("id", "id");
        headerMap.put("word", "白名单词汇");
        ExportUtil.doExport(resultList, headerMap, "tourImSensitiveWordAllow.xlsx");
    }

    /**
     * 查看指定聊天敏感词白名单对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("tourImSensitiveWordAllow.view")
    @GetMapping("/view")
    public ResponseResult<TourImSensitiveWordAllowVo> view(@RequestParam Long id) {
        TourImSensitiveWordAllow tourImSensitiveWordAllow = tourImSensitiveWordAllowService.getByIdWithRelation(id, MyRelationParam.full());
        if (tourImSensitiveWordAllow == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TourImSensitiveWordAllowVo tourImSensitiveWordAllowVo = MyModelUtil.copyTo(tourImSensitiveWordAllow, TourImSensitiveWordAllowVo.class);
        return ResponseResult.success(tourImSensitiveWordAllowVo);
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        TourImSensitiveWordAllow originalTourImSensitiveWordAllow = tourImSensitiveWordAllowService.getById(id);
        if (originalTourImSensitiveWordAllow == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!tourImSensitiveWordAllowService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }
}
