package com.zjsgfa.project.zjsgfa.controller;

import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.zjsgfa.common.utils.SecurityUtils;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.task.Task;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zjsgfa.framework.aspectj.lang.annotation.Log;
import com.zjsgfa.framework.aspectj.lang.enums.BusinessType;
import com.zjsgfa.project.zjsgfa.domain.BizTodoItem;
import com.zjsgfa.project.zjsgfa.service.IBizTodoItemService;
import com.zjsgfa.framework.web.controller.BaseController;
import com.zjsgfa.framework.web.domain.AjaxResult;
import com.zjsgfa.common.utils.poi.ExcelUtil;
import com.zjsgfa.framework.web.page.TableDataInfo;

/**
 * 待办事项Controller
 *
 * @author ruoyi
 * @date 2026-02-11
 */
@RestController
@RequestMapping("/system/bizTodoItem")
public class BizTodoItemController extends BaseController {
    @Autowired
    private IBizTodoItemService bizTodoItemService;

    @Autowired
    private TaskService taskService;

    /**
     * 查询待办事项列表
     */
    //@PreAuthorize("@ss.hasPermi('system:bizTodoItem:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizTodoItem bizTodoItem) {
        startPage();
        bizTodoItem.setIsHandle("0");
        bizTodoItem.setTodoUserId(SecurityUtils.getUsername());
        bizTodoItem.setOrderBy("todo_time");
        List<BizTodoItem> list = bizTodoItemService.selectBizTodoItemList(bizTodoItem);
        return getDataTable(list);
    }

    //已办任务
    @GetMapping("/doneList")
    public TableDataInfo getdolist(BizTodoItem bizTodoItem) {
        startPage();
        bizTodoItem.setIsHandle("1");
        bizTodoItem.setTodoUserId(SecurityUtils.getUsername());
        bizTodoItem.setOrderBy("handle_time");
        List<BizTodoItem> list = bizTodoItemService.selectBizTodoItemList(bizTodoItem);
        List<Task> taskList_all = taskService.createTaskQuery().list();

        for (BizTodoItem item : list) {
            item.setCxbs("0");  // 初始化撤销状态
//            if(item.getNodeName().equals("开始节点")){
            List<Task> taskList = taskList_all.stream().filter(d -> item.getInstanceId().equals(d.getProcessInstanceId()))
                    .collect(Collectors.toList());

            // 根据当前流程ID、当前人员、以及任务名称分组，查询最大的处理时间
            BizTodoItem lastTodoItem = bizTodoItemService.listMaxHandleTimeGroup(BizTodoItem.builder()
                    .taskName(item.getTaskName())
                    .instanceId(item.getInstanceId())
                    .todoUserId(item.getTodoUserId()).build());

            if (!CollectionUtils.isEmpty(taskList)) {
                TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
//                    item.setTaskId(task.getId());
                if (task.getSuspensionState() == 2) {
                    item.setDqtaskName("已挂起");
                } else {
                    item.setDqtaskName(task.getName());
                }
                if ("安全审批".equals(item.getDqtaskName()) && "开始节点".equals(item.getNodeName()) && item.getHandleTime().getTime() == lastTodoItem.getMaxHandleTime().getTime()) {
                    item.setCxbs("1");  // 初始化撤销状态
                }
            } else {
                // 已办结或者已撤销
                item.setDqtaskName("已结束");
            }
//            }
        }


        return getDataTable(list);
    }

    /**
     * 导出待办事项列表
     */
    //@PreAuthorize("@ss.hasPermi('system:bizTodoItem:export')")
    @Log(title = "待办事项", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizTodoItem bizTodoItem) {
        List<BizTodoItem> list = bizTodoItemService.selectBizTodoItemList(bizTodoItem);
        ExcelUtil<BizTodoItem> util = new ExcelUtil<BizTodoItem>(BizTodoItem.class);
        util.exportExcel(response, list, "待办事项数据");
    }

    /**
     * 获取待办事项详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:bizTodoItem:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizTodoItemService.selectBizTodoItemById(id));
    }

    /**
     * 新增待办事项
     */
    //@PreAuthorize("@ss.hasPermi('system:bizTodoItem:add')")
    @Log(title = "待办事项", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizTodoItem bizTodoItem) {
        return toAjax(bizTodoItemService.insertBizTodoItem(bizTodoItem));
    }

    /**
     * 修改待办事项
     */
    //@PreAuthorize("@ss.hasPermi('system:bizTodoItem:edit')")
    @Log(title = "待办事项", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizTodoItem bizTodoItem) {
        return toAjax(bizTodoItemService.updateBizTodoItem(bizTodoItem));
    }

    /**
     * 删除待办事项
     */
    //@PreAuthorize("@ss.hasPermi('system:bizTodoItem:remove')")
    @Log(title = "待办事项", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bizTodoItemService.deleteBizTodoItemByIds(ids));
    }
}
