package org.dromara.zhishu.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.oss.entity.UploadResult;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.web.core.BaseController;
import org.dromara.zhishu.domain.bo.ExcelTaskBo;
import org.dromara.zhishu.domain.vo.BookVo;
import org.dromara.zhishu.domain.vo.ExcelTaskVo;
import org.dromara.zhishu.domain.vo.TDepotVo;
import org.dromara.zhishu.service.IExcelTaskService;
import org.dromara.zhishu.service.ITDepotService;
import org.dromara.zhishu.threads.ExcelTaskRunnable;
import org.dromara.zhishu.util.EasyExcelUtil;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * execel任务列表
 *
 * @author yxy
 * @date 2025-03-21
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/excelTask")
public class ExcelTaskController extends BaseController {

    private final IExcelTaskService taskService;
//
//    private final IShopDetailService shopDetailService;

//    private final PddServiceImpl pddService;

    private final ITDepotService tdepotService;


    /**
     * 查询任务列表列表
     */
    @SaCheckPermission("zhishu:excelTask:list")
    @GetMapping("/list")
    public TableDataInfo<ExcelTaskVo> list(ExcelTaskBo bo, PageQuery pageQuery) {
        return taskService.queryPageList(bo, pageQuery);
    }


    @GetMapping("/logsList")
    public List<Map<String,Object>> logsList(String id){
        String fileName = id+".txt";
        List<Map<String,Object>> logsMapList = EasyExcelUtil.readFileContent(UrlUtil.getUrl() +fileName);
        return logsMapList;
    }

    @GetMapping("/logsMsg")
    public String logsMsg(String id){
        String msg = EasyExcelUtil.readFileContentString(UrlUtil.getUrl()+id+"-msg.txt");
        return msg;
    }

    @GetMapping("/logsDetailList/{taskId}/{shopId}")
    public List<Map<String,Object>> logsDetailList(@PathVariable("taskId") String taskId,
                                                   @PathVariable("shopId") String shopId){
        String fileName = taskId+shopId+".txt";
        List<Map<String,Object>> logsDetailList = EasyExcelUtil.readFileContent(UrlUtil.getUrl()+fileName);
        return logsDetailList;
    }

    @SaIgnore
    @GetMapping("/downloadLogs/{fileName}")
    public ResponseEntity<Resource> downloadLogs(HttpServletResponse response,@PathVariable String fileName) {
        String filePath = UrlUtil.getUrl() + fileName;
        File file = new File(filePath);
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        Resource resource = new FileSystemResource(file);
        try {
            // 编码文件名以处理 Unicode 字符
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 导出任务列表列表
     */
    @SaCheckPermission("zhishu:excelTask:export")
    @Log(title = "任务列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ExcelTaskBo bo, HttpServletResponse response) {
//        List<ExcelTaskVo> list = taskService.queryList(bo);
//        ExcelUtil.exportExcel(list, "任务列表", ExcelTaskVo.class, response);
    }

    /**
     * 获取任务列表详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zhishu:excelTask:query")
    @GetMapping("/{id}")
    public R<ExcelTaskVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(taskService.queryById(id));
//        return null;
    }

    /**
     * 新增任务列表
     */
//    @SaCheckPermission("zhishu:excelTask:add")
    @Log(title = "任务列表", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody Map map) {

        //任务类型
        String taskType = map.get("taskType").toString();
//
        //仓库ids
        String[] depotIdsArr  = map.get("depotIds").toString().split(",");
        //仓库名称
        String depotNames = "";
        for(String depotIds:depotIdsArr){
             String depotId="";
            if(depotIds.contains(String.valueOf("["))){
               depotId= depotIds.replace("[","").trim();
            }else if(depotIds.contains(String.valueOf("]"))){
                depotId= depotIds.replace("]","").trim();
            }
            TDepotVo TDepotVo = tdepotService.queryById(Long.parseLong(depotId));

            if(depotNames.equals("")){
                depotNames= TDepotVo.getName();
            }else{
                depotNames = depotNames + "," + TDepotVo.getName();
            }
        }

        //图书列表
//        List<BookVo> list = RedisUtils.getCacheList("bookVoList");
//        RedisUtils.deleteObject("bookVoList");
        //文件名称
        String taskExcelName = RedisUtils.getCacheObject("taskExcelName");
        RedisUtils.deleteObject("taskExcelName");

        //存储任务信息
        ExcelTaskBo taskBo = new ExcelTaskBo();
        taskBo.setTaskType(taskType);
        taskBo.setFileName(taskExcelName);
        taskBo.setDepotIds(depotNames);
//        taskBo.setDataNum(Long.parseLong(list.size()+""));
        taskBo.setTaskStatus("1");
        taskService.insertByBo(taskBo);
//
        // 创建并启动线程
        ExcelTaskRunnable taskRunnable = new ExcelTaskRunnable(map,taskBo);
        Thread thread = new Thread(taskRunnable);
        thread.start();
//
//
//        taskBo.setThreadId(thread.getId());
//        taskService.updateByBo(taskBo);
        return toAjax(1);
    }

    /**
     * 暂停线程
     * @param threadId
     */
    @GetMapping("/pauseThread/{threadId}/{taskId}")
    public void pauseThread(@PathVariable("threadId") Long threadId,@PathVariable("taskId") Long taskId){
//        pddService.zanTing(String.valueOf(threadId));
//        ExcelTaskBo taskBo = new ExcelTaskBo();
//        taskBo.setId(taskId);
//        taskBo.setTaskStatus("2");
//        taskService.updateByBo(taskBo);
    }

    /**
     * 继续执行线程
     * @param threadId
     */
    @GetMapping("/continueThread/{threadId}/{taskId}")
    public void continueThread(@PathVariable("threadId") Long threadId,@PathVariable("taskId") Long taskId){
//        pddService.huanXing(String.valueOf(threadId));
//        ExcelTaskBo taskBo = new ExcelTaskBo();
//        taskBo.setId(taskId);
//        taskBo.setTaskStatus("1");
//        taskService.updateByBo(taskBo);
    }


    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "发布任务数据", BookVo.class, response);
    }


    /**
     * 修改任务列表
     */
    @SaCheckPermission("zhishu:task:edit")
    @Log(title = "任务列表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ExcelTaskBo bo) {
        return toAjax(taskService.updateByBo(bo));
//        return null;
    }


    /**
     * 删除任务列表
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zhishu:excelTask:remove")
    @Log(title = "任务列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(taskService.deleteWithValidByIds(List.of(ids), true));
//        return null;
    }

    @PostMapping(value = "/upload")
    public R<UploadResult> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        /**
         * 存储书号到radis
         */
        RedisUtils.deleteObject("bookVoList");
        RedisUtils.deleteObject("taskExcelName");
        try {
            ExcelResult<BookVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), BookVo.class, true);
            List<BookVo> list = MapstructUtils.convert(excelResult.getList(), BookVo.class);
            RedisUtils.setCacheList("bookVoList", list);
            RedisUtils.setCacheObject("taskExcelName",file.getOriginalFilename());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        UploadResult uploadResult = shopDetailService.upload(file);
//        return R.ok(uploadResult);
        return null;
    }
}
