
package com.jeelowcode.module.biz.controller;

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.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.IExamPlanService;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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 +"/examIssus")
public class ExamIssusController extends BaseController {

    @Autowired
    private IExamPlanService iExamPlanService;

    private final IJeeLowCodeAdapter jeeLowCodeAdapter;

    @Autowired
    private IFormService dbFormService;

    @GetMapping({"/addRecord"})
    @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_exam_record";
        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_exam_plan_issus")) {
                            List<HashMap<String, Object>> detail = (List<HashMap<String, Object>>) details.get("lc_exam_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("userId") && t.get("userId").toString().equals(dbuser.getUserId())).findFirst().orElse(null);
                                if (Objects.isNull(user)) {
                                    HashMap<String, Object> newUser = new HashMap<>();
                                    newUser.put("chargeId", dbuser.getUserId());
                                    newUser.put("chargeName", dbuser.getNickName());
                                    newUser.put("deptId", dbuser.getDeptId());
                                    newUser.put("deptName", dbuser.getDeptName());
                                    newUser.put("examId", Long.valueOf(idArr[i]));
                                    detail.add(newUser);

                                    // 组装任务
                                    //查询待分发单据 examId 从 lc_exam_plan 根据Id查询数据
                                    Map<String, Object>  examPlan = iExamPlanService.getExamPlanById(Long.valueOf(idArr[i]));

                                    HashMap<String, Object> newRecord = new HashMap<>();

                                    newRecord.put("chargeId", dbuser.getUserId());
                                    newRecord.put("chargeName", dbuser.getNickName());
                                    newRecord.put("IssusDeptName", dbuser.getDeptName());
                                    newRecord.put("IssueDeptId", dbuser.getDeptId());

                                    newRecord.put("examName", examPlan.get("examname"));
                                    newRecord.put("examId", examPlan.get("id"));
                                    newRecord.put("examRecordStatus", 1);

                                    newRecord.put("billNo", "KSJL" + System.currentTimeMillis());
                                    tasks.add(JSONUtil.parseObj(newRecord));
                                }
                            }
                            resultDataModel.getRecords().get(0).put("lc_exam_plan_issus", detail);
                            resultDataModel.getRecords().get(0).put("examStatus", 2);//跟新状态为待执行
                            super.editJsonData(Long.valueOf(tableId), JSONUtil.parseObj(resultDataModel.getRecords().get(0)));

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

}
