package org.dromara.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.system.utils.DifyUtil;
import org.springframework.beans.factory.annotation.Value;
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.system.domain.vo.TblEventVo;
import org.dromara.system.domain.bo.TblEventBo;
import org.dromara.system.service.ITblEventService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 事件
 *
 * @author Lion Li
 * @date 2025-06-13
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/event")
public class TblEventController extends BaseController {

    private final ITblEventService tblEventService;

    private final DifyUtil difyUtil;

    @Value("${user.fileUrl}")
    String FileBASE_URL = "http://192.168.39.17:9000/v1";


    /**
     * 查询事件列表
     */
//    @SaCheckPermission("system:event:list")
    @GetMapping("/list")
    public TableDataInfo<TblEventVo> list(TblEventBo bo, PageQuery pageQuery) {
        return tblEventService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出事件列表
     */
//    @SaCheckPermission("system:event:export")
    @Log(title = "事件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TblEventBo bo, HttpServletResponse response) {
        List<TblEventVo> list = tblEventService.queryList(bo);
        ExcelUtil.exportExcel(list, "事件", TblEventVo.class, response);
    }

    /**
     * 获取事件详细信息
     *
     * @param id 主键
     */
//    @SaCheckPermission("system:event:query")
    @GetMapping("/{id}")
    public R<TblEventVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(tblEventService.queryById(id));
    }

    /**
     * 新增事件
     */
//    @SaCheckPermission("system:event:add")
    @Log(title = "事件", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TblEventBo bo) {
        return toAjax(tblEventService.insertByBo(bo));
    }

    /**
     * 修改事件
     */
//    @SaCheckPermission("system:event:edit")
    @Log(title = "事件", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TblEventBo bo) {
        return toAjax(tblEventService.updateByBo(bo));
    }

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

    /**
     * 生成事件详情
     *
     * @param id 主键
     */
//    @SaCheckPermission("system:event:generate")
    @Log(title = "事件", businessType = BusinessType.UPDATE)
    @PostMapping("/generate/{id}")
    public R<Void> generate(@NotNull(message = "主键不能为空") @PathVariable Long id){
        TblEventVo tblEventVo = tblEventService.queryById(id);
        if(tblEventVo== null){
            return R.fail("事件不存在");
        }
        OssClient storage = OssFactory.instance();
        Map<String, Object> data = new HashMap<>();
        data.put("地点",tblEventVo.getAddr());
        data.put("事故时间",tblEventVo.getCreateTime());
        try{
            data.put("事故类型", JSONUtil.parseObj(tblEventVo.getExt2()).getStr("lx"));
        }catch (Exception e) {}
        try{
            data.put("事件来源", JSONUtil.parseObj(tblEventVo.getExt2()).getStr("from"));
        }catch (Exception e) {}


        //获取事件图片
        List fileInput = new ArrayList();
        try{
            JSONArray images = JSONUtil.parseArray(tblEventVo.getExt1());
            for(int i = 0; i < images.size(); i++){
                String  image = images.get(i).toString();
                if(image.toString().contains("mp4")) continue;
                try {
                    File file = storage.getLocalEnvFile(image);
                    String imageUrl = difyUtil.uploadFile(file.getAbsolutePath());
                    String imgid = JSONUtil.parseObj(imageUrl).getStr("id");
                    Map<String, Object> fileItem = new HashMap<>();
                    fileItem.put("transfer_method", "local_file");
                    fileItem.put("upload_file_id", imgid);
                    fileItem.put("type", image.toString().contains("mp4") ? "video" : "image");
                    fileInput.add(fileItem);
                }catch (Exception e){}
            }


        }catch(Exception e){}

        String  eventString = JSONUtil.toJsonStr( data);
        Map<String, Object> workflowInputs = new HashMap<>();

        workflowInputs.put("files", fileInput);
        workflowInputs.put("event",eventString);
        try {
            String workflowResult = difyUtil.runWorkflow(
                null,
                workflowInputs,
                "blocking",
                "user-12"
            );
            System.out.println("工作流结果: " + workflowResult);
            return R.ok(workflowResult);

        }catch (Exception e){}

       return R.fail("生成事件详情失败");
    }
}
