package org.dromara.zhishu.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.oss.entity.UploadResult;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.vo.BookVo;
import org.dromara.zhishu.domain.vo.FilterSetTxtVo;
import org.dromara.zhishu.util.EasyExcelUtil;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.zhishu.domain.vo.FilterSetVo;
import org.dromara.zhishu.domain.bo.FilterSetBo;
import org.dromara.zhishu.service.IFilterSetService;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 过滤设置
 *
 * @author yxy
 * @date 2025-04-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/filterSet")
public class FilterSetController extends BaseController {

    private final IFilterSetService filterSetService;

    /**
     * 查询过滤设置列表
     */
    @SaCheckPermission("zhishu:filterSet:list")
    @GetMapping("/list")
    public TableDataInfo<FilterSetVo> list(FilterSetBo bo, PageQuery pageQuery) {
        return filterSetService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出过滤设置列表
     */
    @SaCheckPermission("zhishu:filterSet:export")
    @Log(title = "过滤设置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(FilterSetBo bo, HttpServletResponse response) {
        List<FilterSetVo> list = filterSetService.queryList(bo);
        ExcelUtil.exportExcel(list, "过滤设置", FilterSetVo.class, response);
    }

    /**
     * 获取过滤设置详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zhishu:filterSet:query")
    @GetMapping("/{id}")
    public R<FilterSetVo> getInfo(@NotNull(message = "主键不能为空")
                                  @PathVariable Long id) {
        return R.ok(filterSetService.queryById(id));
    }

    /**
     * 新增过滤设置
     */
    @SaCheckPermission("zhishu:filterSet:add")
    @Log(title = "过滤设置", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @SaIgnore
    public R<Void> add(@Validated(AddGroup.class) @RequestBody FilterSetBo bo) {
        String sort = bo.getSort();
        String[] addTxts = bo.getAddTxt().split("\n");
        Boolean bool = false;
        for(String addTxt : addTxts){
            if (StringUtils.isEmpty(addTxt)){
                continue;
            }

            bo.setId(null);
            bo.setSort(sort);
            //去掉前后空格
            addTxt = addTxt.trim();
            bo.setAddTxt(addTxt);
            //查询是否有相同的违规词，如果有，则合并
            List<FilterSetVo> list = filterSetService.selectVoListByBo(bo);
            if(list.isEmpty()){
                //没有则直接新增
                bo.setAddTxt(addTxt);
                bool = filterSetService.insertByBo(bo);
            }else{
                //如果存在则合并平台字段,并将多余的数据删除
                //两个数组合并
                Set<String> sortSet = new HashSet();
                FilterSetVo vo = list.get(0);
                String[] newSortArr = bo.getSort().split( ",");
                for (int j=0;j<newSortArr.length;j++){
                    sortSet.add(newSortArr[j]);
                }
                for (int i=0;i<list.size();i++){
                    String[] oldSortArr = list.get(i).getSort().split( ",");
                    for (int j=0;j<oldSortArr.length;j++){
                        sortSet.add(oldSortArr[j]);
                    }
                    if(i != 0){
                        //执行delete语句
                        filterSetService.deleteTrueById(list.get(i).getId());
                    }
                }
                bo.setId(vo.getId());
                bo.setSort(StringUtils.join(sortSet, ","));
                bool = filterSetService.updateByBo(bo);
            }
        }
        return toAjax(bool);
    }

    /**
     * 修改过滤设置
     */
    @SaCheckPermission("zhishu:filterSet:edit")
    @Log(title = "过滤设置", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody FilterSetBo bo) {
        return toAjax(filterSetService.updateByBo(bo));
    }

    /**
     * 删除过滤设置
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zhishu:filterSet:remove")
    @Log(title = "过滤设置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(filterSetService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "过滤设置数据", FilterSetTxtVo.class, response);
    }

    @PostMapping(value = "/upload")
    public R<List<FilterSetTxtVo>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        try {
            ExcelResult<FilterSetTxtVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), FilterSetTxtVo.class, true);
            List<FilterSetTxtVo> list = MapstructUtils.convert(excelResult.getList(), FilterSetTxtVo.class);
            return R.ok(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
