<template>
  <main class="safety-platform-container__main">
    <BasicForm
      ref="basicFormRef"
      :formData="ruleFormData"
      :formRules="isViewMode ? undefined : formRules"
      :formConfig="computedFormConfig"
    >
      <template #dangerId>
        <el-select
          v-model="ruleFormData.dangerId"
          placeholder="请选择隐患"
          clearable
          filterable
          :disabled="isViewMode"
          style="width: 100%"
          @change="onDangerChange"
        >
          <el-option
            v-for="item in hiddenDangerOptions"
            :key="item.id"
            :label="item.dangerProblem"
            :value="item.id"
          />
        </el-select>
      </template>
      <template #associationOtObligationDeptIds>
        <el-select
          v-model="associationOtObligationDeptIdsArray"
          placeholder="请选择责任部门，可多选"
          clearable
          filterable
          multiple
          collapse-tags
          collapse-tags-tooltip
          :disabled="isViewMode"
          style="width: 100%"
          @change="onAssociationDeptsChange"
        >
          <el-option
            v-for="d in deptOptions"
            :key="d.id"
            :label="d.deptName"
            :value="d.id"
          />
        </el-select>
      </template>
    </BasicForm>
    <div v-if="isViewMode && detailData?.issueRecords?.length" class="detail-section">
      <div class="section-title">下发记录</div>
      <el-table :data="detailData.issueRecords" border size="small">
        <el-table-column prop="associationOtObligationDeptName" label="责任部门" width="120" />
        <el-table-column prop="associationOtObligationDeptUserName" label="责任人" width="100" />
        <el-table-column prop="feedbackResult" label="反馈结果" min-width="200" show-overflow-tooltip />
        <el-table-column prop="feedbackTime" label="反馈时间" width="160" />
        <el-table-column prop="statusName" label="状态" width="100" />
      </el-table>
    </div>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <template v-if="!isViewMode">
      <el-button type="primary" @click="handleSubmit">
        {{ isCreateMode ? '提交' : '保存' }}
      </el-button>
    </template>
    <template v-else>
      <el-button v-if="canIssue" type="primary" @click="openIssueDialog">下发</el-button>
      <el-button v-if="canApprove" type="success" @click="openApproveDialog">审核</el-button>
    </template>
  </footer>

  <!-- 下发弹窗：简化版，单个部门下发 -->
    <el-dialog v-model="showIssueDialog" title="下发举一反三" width="520px" destroy-on-close @close="resetIssueForm">
      <el-form ref="issueFormRef" :model="issueForm" :rules="issueRules" label-width="140px">
        <el-form-item label="责任部门ID" prop="associationOtObligationDeptId">
          <el-input-number v-model="issueForm.associationOtObligationDeptId" :min="1" placeholder="部门ID" style="width: 100%" />
        </el-form-item>
        <el-form-item label="责任部门名称" prop="associationOtObligationDeptName">
          <el-input v-model="issueForm.associationOtObligationDeptName" placeholder="部门名称" />
        </el-form-item>
        <el-form-item label="部门责任人ID" prop="associationOtObligationDeptUserId">
          <el-input-number v-model="issueForm.associationOtObligationDeptUserId" :min="1" placeholder="责任人ID" style="width: 100%" />
        </el-form-item>
        <el-form-item label="部门责任人姓名" prop="associationOtObligationDeptUserName">
          <el-input v-model="issueForm.associationOtObligationDeptUserName" placeholder="责任人姓名" />
        </el-form-item>
        <el-form-item label="具体要求" prop="associationOneThree">
          <el-input v-model="issueForm.associationOneThree" type="textarea" :rows="2" placeholder="选填" />
        </el-form-item>
        <el-form-item label="完成时限" prop="associationOtTimeLimit">
          <el-date-picker
            v-model="issueForm.associationOtTimeLimit"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选填"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showIssueDialog = false">取消</el-button>
        <el-button type="primary" @click="handleIssueSubmit">确认下发</el-button>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog v-model="showApproveDialog" title="审核举一反三" width="400px" destroy-on-close @close="resetApproveForm">
      <el-form ref="approveFormRef" :model="approveForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="approveForm.statusId">
            <el-radio :value="5">通过（已完成）</el-radio>
            <el-radio :value="6">不通过（已作废）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态名称">
          <el-input v-model="approveForm.statusName" placeholder="如：已完成、已作废" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showApproveDialog = false">取消</el-button>
        <el-button type="primary" @click="handleApproveSubmit">确认审核</el-button>
      </template>
    </el-dialog>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import {
    DRAW_LESSONS_FORM_CONFIG,
    DRAW_LESSONS_FORM_DATA,
    DRAW_LESSONS_FORM_RULES,
  } from '../configs/form';
  import {
    getDrawLessonsAdminDetail,
    saveDrawLessons,
    updateDrawLessons,
    issueDrawLessons,
    approveDrawLessons,
    type SaveDrawLessonsRequest,
    type UpdateDrawLessonsRequest,
    type DrawLessonsDeptIssue,
  } from '@/api/drawLessons';
  import { queryHiddenDangerPage } from '@/api/hiddenDanger';
  import type { HiddenDangerItem } from '@/api/hiddenDanger';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { DeptTree } from '@/types/dept/type';

  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'one-by-one-create');
  const currentId = computed(() => Number(route.query.id));

  const isCreateMode = computed(() => operate.value === 'one-by-one-create');
  const isEditMode = computed(() => operate.value === 'one-by-one-edit');
  const isViewMode = computed(() => operate.value === 'one-by-one-view');

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData } =
    useFormConfigHook(DRAW_LESSONS_FORM_CONFIG, DRAW_LESSONS_FORM_DATA, DRAW_LESSONS_FORM_RULES);

  const viewFormConfig = ref(
    DRAW_LESSONS_FORM_CONFIG.map((item) => ({
      ...item,
      componentProps: {
        ...item.componentProps,
        disabled: true,
      },
    })),
  );

  const computedFormConfig = computed(() => {
    if (isViewMode.value) return viewFormConfig.value;
    return ruleFormConfig.value;
  });

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  /** 隐患台账列表，用于「隐患名称」下拉（value=id, label=dangerProblem） */
  const hiddenDangerOptions = ref<HiddenDangerItem[]>([]);

  const loadHiddenDangerOptions = async () => {
    try {
      const res = await queryHiddenDangerPage({
        pageNumber: 1,
        pageSize: 9999,
        queryParam: {},
      });
      const list = (res as any)?.records ?? (res as any)?.data?.records ?? [];
      hiddenDangerOptions.value = Array.isArray(list) ? list : [];
    } catch (e) {
      console.error('获取隐患台账列表失败:', e);
      hiddenDangerOptions.value = [];
    }
  };

  function onDangerChange() {
    const item = hiddenDangerOptions.value.find((d) => d.id === ruleFormData.dangerId);
    if (item?.dangerProblem) {
      ruleFormData.problem = item.dangerProblem;
    }
  }

  /** 责任部门：与新增隐患台账的举一反三责任部门同源（getAllDepartments 扁平化） */
  const deptTree = ref<DeptTree[]>([]);
  function flattenDeptTree(nodes: DeptTree[] | undefined): Array<{ id: number; deptName: string }> {
    if (!nodes?.length) return [];
    const list: Array<{ id: number; deptName: string }> = [];
    const walk = (items: DeptTree[]) => {
      items.forEach((n) => {
        if (n.id != null) list.push({ id: n.id, deptName: n.deptName });
        if (n.children?.length) walk(n.children);
      });
    };
    walk(nodes);
    return list;
  }
  const deptOptions = computed(() => flattenDeptTree(deptTree.value));
  const associationOtObligationDeptIdsArray = ref<number[]>([]);

  const loadDeptOptions = async () => {
    try {
      const deptRes = await getAllDepartments();
      const fullTree = (deptRes as DeptTree[]) ?? [];
      deptTree.value = Array.isArray(fullTree) && fullTree[0]?.children ? fullTree[0].children : [];
    } catch (e) {
      console.error('获取部门列表失败:', e);
      deptTree.value = [];
    }
  };

  function onAssociationDeptsChange() {
    ruleFormData.associationOtObligationDeptIds = associationOtObligationDeptIdsArray.value.join(',');
  }

  /** 详情接口返回的完整数据（含 issueRecords） */
  const detailData = ref<{
    issueRecords?: Array<{
      associationOtObligationDeptName?: string;
      associationOtObligationDeptUserName?: string;
      feedbackResult?: string;
      feedbackTime?: string;
      statusName?: string;
    }>;
    statusId?: number;
  } | null>(null);

  /** 状态 2-未下发 可下发；4-待审核 可审核 */
  const canIssue = computed(() => detailData.value?.statusId === 2);
  const canApprove = computed(() => detailData.value?.statusId === 4);

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await getDrawLessonsAdminDetail(currentId.value);
      const data = (res as any)?.data ?? res;
      if (data && typeof data === 'object') {
        detailData.value = data;
        ruleFormData.dangerId = data.dangerId;
        ruleFormData.problem = data.problem ?? '';
        ruleFormData.associationOneThree = data.associationOneThree ?? '';
        ruleFormData.associationOtObligationDeptIds = data.associationOtObligationDeptIds ?? '';
        associationOtObligationDeptIdsArray.value = ruleFormData.associationOtObligationDeptIds
          ? ruleFormData.associationOtObligationDeptIds.split(',').map((s) => Number(s.trim())).filter(Boolean)
          : [];
        ruleFormData.associationOtTimeLimit = data.associationOtTimeLimit ?? '';
      }
      cloneRuleFormData();
    } catch (e) {
      console.error('获取举一反三详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败');
    }
  };

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    return await basicFormRef.value.validateForm();
  };

  const handleSubmit = async () => {
    const ok = await handleValidate();
    if (!ok) return;
    try {
      const payload: SaveDrawLessonsRequest = {
        dangerId: ruleFormData.dangerId!,
        problem: ruleFormData.problem,
        associationOneThree: ruleFormData.associationOneThree,
        associationOtObligationDeptIds: ruleFormData.associationOtObligationDeptIds,
        associationOtTimeLimit: ruleFormData.associationOtTimeLimit || '',
      };
      if (isCreateMode.value) {
        await saveDrawLessons(payload);
        ElMessage.success('创建成功');
      } else if (currentId.value) {
        await updateDrawLessons({ id: currentId.value, ...payload } as UpdateDrawLessonsRequest);
        ElMessage.success('保存成功');
      }
      router.back();
    } catch (e) {
      console.error('保存举一反三失败:', e);
      ElMessage.error(e?.message || e?.data || '保存失败，请重试');
    }
  };

  // ---------- 下发 ----------
  const showIssueDialog = ref(false);
  const issueFormRef = ref<FormInstance>();
  const issueForm = ref<DrawLessonsDeptIssue & { associationOtTimeLimit?: string }>({
    associationOtObligationDeptId: 0,
    associationOtObligationDeptName: '',
    associationOtObligationDeptUserId: 0,
    associationOtObligationDeptUserName: '',
    associationOneThree: '',
    associationOtTimeLimit: '',
  });
  const issueRules: FormRules = {
    associationOtObligationDeptId: [{ required: true, message: '请输入责任部门ID', trigger: 'blur' }],
    associationOtObligationDeptName: [{ required: true, message: '请输入责任部门名称', trigger: 'blur' }],
    associationOtObligationDeptUserId: [{ required: true, message: '请输入部门责任人ID', trigger: 'blur' }],
    associationOtObligationDeptUserName: [{ required: true, message: '请输入部门责任人姓名', trigger: 'blur' }],
  };

  function resetIssueForm() {
    issueForm.value = {
      associationOtObligationDeptId: 0,
      associationOtObligationDeptName: '',
      associationOtObligationDeptUserId: 0,
      associationOtObligationDeptUserName: '',
      associationOneThree: '',
      associationOtTimeLimit: '',
    };
  }

  function openIssueDialog() {
    resetIssueForm();
    showIssueDialog.value = true;
  }

  async function handleIssueSubmit() {
    if (!currentId.value) return;
    await issueFormRef.value?.validate?.().catch(() => {});
    try {
      const deptIssue: DrawLessonsDeptIssue = {
        associationOtObligationDeptId: issueForm.value.associationOtObligationDeptId,
        associationOtObligationDeptName: issueForm.value.associationOtObligationDeptName,
        associationOtObligationDeptUserId: issueForm.value.associationOtObligationDeptUserId,
        associationOtObligationDeptUserName: issueForm.value.associationOtObligationDeptUserName,
        associationOneThree: issueForm.value.associationOneThree || undefined,
        associationOtTimeLimit: issueForm.value.associationOtTimeLimit || undefined,
      };
      await issueDrawLessons({ id: currentId.value, deptIssues: [deptIssue] });
      ElMessage.success('下发成功');
      showIssueDialog.value = false;
      getDetail();
    } catch (e) {
      console.error('下发失败:', e);
      ElMessage.error(e?.message || e?.data || '下发失败，请重试');
    }
  }

  // ---------- 审核 ----------
  const showApproveDialog = ref(false);
  const approveFormRef = ref<FormInstance>();
  const approveForm = ref({ id: 0, statusId: 5, statusName: '已完成' });

  function resetApproveForm() {
    approveForm.value = {
      id: currentId.value || 0,
      statusId: 5,
      statusName: '已完成',
    };
  }

  function openApproveDialog() {
    resetApproveForm();
    showApproveDialog.value = true;
  }

  async function handleApproveSubmit() {
    if (!currentId.value) return;
    try {
      await approveDrawLessons({
        id: currentId.value,
        statusId: approveForm.value.statusId,
        statusName: approveForm.value.statusName || (approveForm.value.statusId === 5 ? '已完成' : '已作废'),
      });
      ElMessage.success('审核成功');
      showApproveDialog.value = false;
      getDetail();
    } catch (e) {
      console.error('审核失败:', e);
      ElMessage.error(e?.message || e?.data || '审核失败，请重试');
    }
  }

  onMounted(() => {
    cloneRuleFormData();
    loadHiddenDangerOptions();
    loadDeptOptions();
    if (isEditMode.value || isViewMode.value) {
      getDetail();
    }
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;

  .detail-section {
    margin-top: 24px;
  }

  .section-title {
    margin: 0 0 8px;
    font-weight: 600;
    font-size: 14px;
  }
</style>
