
package com.jeelowcode.module.biz.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.jeelowcode.core.framework.controller.BaseController;
import com.jeelowcode.core.framework.enums.ApproveStatusEnum;
import com.jeelowcode.core.framework.service.IFormService;
import com.jeelowcode.framework.exception.JeeLowCodeException;
import com.jeelowcode.framework.global.JeeLowCodeBaseConstant;
import com.jeelowcode.framework.tenant.annotation.JeeLowCodeTenantIgnore;
import com.jeelowcode.framework.utils.adapter.IJeeLowCodeAdapter;
import com.jeelowcode.framework.utils.model.JeeLowCodeUser;
import com.jeelowcode.framework.utils.model.ResultDataModel;
import com.jeelowcode.framework.utils.tool.CollectionUtil;
import com.jeelowcode.module.biz.service.IDrillPlanService;
import com.jeelowcode.tool.framework.common.pojo.CommonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import static com.jeelowcode.tool.framework.common.pojo.CommonResult.success;

/**
 * @author LIFY
 * @create 2025-09-13
 * @dedescription:
 */
@JeeLowCodeTenantIgnore
@Tag(name = "低代码框架 - 个性化接口")
@RestController
@AllArgsConstructor
@RequestMapping(JeeLowCodeBaseConstant.REQUEST_URL_START +"/planIssus")
public class PlanIssusController extends BaseController {

    @Autowired
    private IDrillPlanService iDrillPlanService;

    private final IJeeLowCodeAdapter jeeLowCodeAdapter;

    @Autowired
    private IFormService dbFormService;

    @GetMapping({"/addTask"})
    @ApiOperationSupport(order = 1)
    @Operation(summary = "分发任务数据")
    public CommonResult<String> savePlanIssus(String tableId, String ids, String userIds) {
        String[] idArr = ids.split(",");
        String[] userIdArr = userIds.split(",");
        if (Objects.isNull(idArr) || idArr.length == 0 || Objects.isNull(userIdArr) || userIdArr.length == 0) {
            throw new JeeLowCodeException("缺少必要参数");
        }

        String tableName="lc_drill_task";
        Long dbFormId = dbFormService.getDbFormIdByTableName(tableName);
        List<Long> userIdList = Arrays.stream(userIdArr).map(Long::parseLong).collect(Collectors.toList());
        IPage<JeeLowCodeUser> userPage = (IPage<JeeLowCodeUser>) jeeLowCodeAdapter.getUserPageByUserIds(1, 10000, userIdList);

        if (CollectionUtil.isNotEmpty(userPage.getRecords())) {
            for (int i = 0; i < idArr.length; i++) {
                ResultDataModel resultDataModel = super.getDataDetail(Long.parseLong(tableId), Long.valueOf(idArr[i]), new HashMap<String, Object>());
                if (CollectionUtil.isNotEmpty(resultDataModel.getRecords())) {
                    if (resultDataModel.getRecords().get(0).containsKey("jeelowcode_subtable_data")) {
                        HashMap<String, Object> details = (HashMap<String, Object>) resultDataModel.getRecords().get(0).get("jeelowcode_subtable_data");
                        if (details.containsKey("lc_drill_plan_issus")) {
                            List<HashMap<String, Object>> detail = (List<HashMap<String, Object>>) details.get("lc_drill_plan_issus");

                            List<JSONObject> tasks = new ArrayList<JSONObject>();
                            if(Objects.isNull(detail)) {
                                detail = new ArrayList<HashMap<String, Object>>();
                            }
                            for (JeeLowCodeUser dbuser : userPage.getRecords()) {
                                HashMap<String, Object> user = CollectionUtil.isEmpty(detail) ? null
                                        : detail.stream().filter(t ->
                                        t.containsKey("dept_id") && t.get("dept_id").toString().equals(dbuser.getDeptId())).
                                        findFirst().orElse(null);
                                if (Objects.isNull(user)) {
                                    HashMap<String, Object> newUser = new HashMap<>();
                                    newUser.put("charge_id", dbuser.getUserId());
                                    newUser.put("charge_name", dbuser.getNickName());
                                    newUser.put("dept_id", dbuser.getDeptId());
                                    newUser.put("dept_name", dbuser.getDeptName());
                                    newUser.put("drill_plan_id", Long.valueOf(idArr[i]));
                                    detail.add(newUser);

                                    // 组装任务
                                    //查询待分发单据 根据planId 从 lc_drill_plan 根据planId查询数据
                                    Map<String, Object>  drillPlan = iDrillPlanService.getDrillPlanById(Long.valueOf(idArr[i]));
                                    // 根据planId 从 lc_drill_plan_cycle 查询数据 list<LcDrillPlanCycle>

                                    List<Map<String, Object>> drillPlanCycles = iDrillPlanService.getDrillPlanCycles(Long.valueOf(idArr[i]));

                                    // 遍历lcDrillPlanCycles
                                    for (Map<String, Object> planCycle : drillPlanCycles) {
                                        HashMap<String, Object> newTask = new HashMap<>();

                                        newTask.put("charge_id", dbuser.getUserId());
                                        newTask.put("charge_name", dbuser.getNickName());
                                        newTask.put("dept_id", dbuser.getDeptId());
                                        newTask.put("dept_name", dbuser.getDeptName());

                                        newTask.put("emergency_plan_name", drillPlan.get("emergency_plan_name"));
                                        newTask.put("emergency_plan_id", drillPlan.get("emergency_plan_id"));

                                        newTask.put("drill_plan_name", drillPlan.get("drill_plan_name"));
                                        newTask.put("drill_plan_id", drillPlan.get("id"));
                                        newTask.put("sDate", planCycle.get("sdate"));
                                        newTask.put("eDate", planCycle.get("edate"));

                                        newTask.put("task_status", 1);

                                        newTask.put("billNo", "RW" + System.currentTimeMillis());

                                        tasks.add(JSONUtil.parseObj(newTask));
                                    }
                                }
                            }
                            resultDataModel.getRecords().get(0).put("lc_drill_plan_issus", detail);
                            resultDataModel.getRecords().get(0).put("drill_plan_status_type", 3);//跟新状态为执行中
                            super.editJsonData(Long.valueOf(tableId), JSONUtil.parseObj(resultDataModel.getRecords().get(0)));

                            super.addJsonData(dbFormId, tasks);
                        }
                    }
                }
            }
        }
        return success("下发成功");
    }

    @GetMapping({"/getEmergencyPlanDict"})
    @ApiOperationSupport(order = 2)
    @Operation(summary = "获取应急预案字典数据")
    public CommonResult<List<Map<String, Object>>> getEmergencyPlanDict()
    {
        String tableName="lc_emergency_plan";
        Long dbFormId = dbFormService.getDbFormIdByTableName(tableName);

        Map<String, Object> param = new HashMap<>();
        param.put(ApproveStatusEnum.codeField, ApproveStatusEnum.APPROVED.getCode());
        ResultDataModel resultDataModel = super.getDataPage(dbFormId, param);

        return success(resultDataModel.getRecords());
    }
}
