<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">区域检查计划管理(管理员)</div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header>
          <div style="position: relative">
            <el-button type="primary" class="search-table-container--button" @click="handleCreate">
              添加
            </el-button>
          </div>

          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>检查场所/计划名称：</span>
                <el-input
                  v-model="tableQuery.queryParam.keyword"
                  placeholder="搜索检查场所或计划名称"
                  class="act-search-input"
                  clearable
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select
                  v-model="tableQuery.queryParam.status"
                  placeholder="请选择状态"
                  clearable
                >
                  <el-option
                    v-for="item in AREA_CHECK_PLAN_STATUS_OPTIONS"
                    :key="String(item.value)"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>场所所属类别：</span>
                <el-select
                  v-model="tableQuery.queryParam.venueCategory"
                  placeholder="请选择场所所属类别"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in venueCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>日期范围：</span>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #status="scope">
              <span>{{ AREA_CHECK_PLAN_STATUS_LABEL[String(scope.row.status)] ?? '-' }}</span>
            </template>
            <template #needOverallDesc="scope">
              <span>{{ scope.row.needOverallDesc === true ? '是' : scope.row.needOverallDesc === false ? '否' : '-' }}</span>
            </template>
            <template #needInspectedSign="scope">
              <span>{{ scope.row.needInspectedSign === true ? '是' : scope.row.needInspectedSign === false ? '否' : '-' }}</span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <!-- 未下发(0)：编辑、删除、查看、下发 -->
                <template v-if="Number(scope.row.status) === 0">
                  <ActionButton text="编辑" @click="handleEdit(scope.row.id)" />
                  <ActionButton
                    text="删除"
                    :popconfirm="{ title: '确定要删除?' }"
                    @confirm="handleDelete(scope.row.id)"
                  />
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                  <ActionButton text="下发" @click="handleIssue(scope.row.id)" />
                </template>
                <!-- 进行中(1)：查看、作废 -->
                <template v-else-if="Number(scope.row.status) === 1">
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                  <ActionButton
                    text="作废"
                    :popconfirm="{ title: '确定要作废该计划?' }"
                    @confirm="handleCancel(scope.row.id)"
                  />
                </template>
                <!-- 已完成(2)：查看 -->
                <template v-else-if="Number(scope.row.status) === 2">
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                </template>
                <!-- 已作废(3)：删除、查看 -->
                <template v-else-if="Number(scope.row.status) === 3">
                  <ActionButton
                    text="删除"
                    :popconfirm="{ title: '确定要删除?' }"
                    @confirm="handleDelete(scope.row.id)"
                  />
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>

    <!-- 下发区域检查计划任务弹窗 -->
    <el-dialog
      v-model="showIssueDialog"
      title="下发区域检查计划任务"
      width="560px"
      destroy-on-close
      @open="onIssueDialogOpen"
      @close="currentIssuePlanId = null"
    >
      <el-form ref="issueFormRef" :model="issueForm" :rules="issueRules" label-width="160px">
        <el-form-item label="责任部门：" prop="responsibleDeptIds">
          <el-cascader
            ref="issueResponsibleDeptCascaderRef"
            v-model="issueForm.responsibleDeptIds"
            :options="issueDeptTree"
            :props="cascaderDeptPropMultiple"
            :show-all-levels="false"
            placeholder="请选择责任部门名称,支持多选"
            filterable
            clearable
            collapse-tags
            collapse-tags-tooltip
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="责任部门人员分组：" prop="mainDeptGroupId">
          <el-select
            v-model="issueForm.mainDeptGroupId"
            placeholder="请选择责任部门执行人所在分组名称,单选"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in userGroupOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="安全应急部门：" prop="safetyEmergencyDeptId">
          <el-cascader
            v-model="issueForm.safetyEmergencyDeptId"
            :options="issueDeptTree"
            :props="cascaderDeptProp"
            :show-all-levels="false"
            placeholder="请选择安全应急部门"
            filterable
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="安全应急部人员分组：" prop="safetyEmergencyGroupId">
          <el-select
            v-model="issueForm.safetyEmergencyGroupId"
            placeholder="请选择安全应急部执行人所在分组名称,单选"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in userGroupOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="院领导部门：" prop="hospitalLeaderDeptId">
          <el-cascader
            v-model="issueForm.hospitalLeaderDeptId"
            :options="issueDeptTree"
            :props="cascaderDeptProp"
            :show-all-levels="false"
            placeholder="请选择院领导部门"
            filterable
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="院领导人员分组：" prop="hospitalLeaderGroupId">
          <el-select
            v-model="issueForm.hospitalLeaderGroupId"
            placeholder="请选择院领导部门执行人所在分组名称,单选"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in userGroupOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始日期：" prop="planStartTime">
          <el-date-picker
            v-model="issueForm.planStartTime"
            type="date"
            placeholder="选择计划开始日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            style="width: 100%"
            :disabled-date="(date: Date) => (issueForm.planEndTime ? date > new Date(issueForm.planEndTime) : false)"
          />
        </el-form-item>
        <el-form-item label="计划结束时间：" prop="planEndTime">
          <el-date-picker
            v-model="issueForm.planEndTime"
            type="date"
            placeholder="选择计划结束日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            style="width: 100%"
            :disabled-date="(date: Date) => (issueForm.planStartTime ? date < new Date(issueForm.planStartTime) : false)"
          />
        </el-form-item>
        <el-form-item label="是否需要整体检查情况描述：" prop="needOverallDesc">
          <el-radio-group v-model="issueForm.needOverallDesc">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否需要被检查人签字：" prop="needInspectedSign">
          <el-radio-group v-model="issueForm.needInspectedSign">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showIssueDialog = false">取消</el-button>
        <el-button type="primary" @click="handleIssueSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, AREA_CHECK_PLAN_TABLE_COLUMNS, AREA_CHECK_PLAN_STATUS_OPTIONS, AREA_CHECK_PLAN_STATUS_LABEL } from './configs/tables';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import type { AreaCheckPlanQuery, AreaCheckPlanRecord } from './configs/types';

  const router = useRouter();

  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const { tableConfig, pagination } = useTableConfig(AREA_CHECK_PLAN_TABLE_COLUMNS, TABLE_OPTIONS);
  const allData = ref<AreaCheckPlanRecord[]>([]);
  const tableData = ref<AreaCheckPlanRecord[]>([]);
  const dateRange = ref<[string, string] | null>(null);

  // 场所所属类别选项（示例数据，本页面不调用接口）
  const venueCategoryOptions = ref<Array<{ label: string; value: string }>>([]);

  // 下发弹窗
  const showIssueDialog = ref(false);
  const currentIssuePlanId = ref<number | null>(null);
  const issueFormRef = ref();
  const issueResponsibleDeptCascaderRef = ref();
  const issueForm = reactive({
    responsibleDeptIds: [] as number[],
    mainDeptGroupId: undefined as number | undefined,
    safetyEmergencyDeptId: undefined as number | undefined,
    safetyEmergencyGroupId: undefined as number | undefined,
    hospitalLeaderDeptId: undefined as number | undefined,
    hospitalLeaderGroupId: undefined as number | undefined,
    planStartTime: '',
    planEndTime: '',
    needOverallDesc: false,
    needInspectedSign: false,
  });
  const issueRules = {
    responsibleDeptIds: [{ required: true, message: '请选择责任部门', trigger: 'change', type: 'array', min: 1 }],
    mainDeptGroupId: [{ required: true, message: '请选择责任部门人员分组', trigger: 'change' }],
    safetyEmergencyDeptId: [{ required: true, message: '请选择安全应急部门', trigger: 'change' }],
    safetyEmergencyGroupId: [{ required: true, message: '请选择安全应急部人员分组', trigger: 'change' }],
    hospitalLeaderDeptId: [{ required: true, message: '请选择院领导部门', trigger: 'change' }],
    hospitalLeaderGroupId: [{ required: true, message: '请选择院领导人员分组', trigger: 'change' }],
    planStartTime: [{ required: true, message: '请选择计划开始日期', trigger: 'change' }],
    planEndTime: [{ required: true, message: '请选择计划结束时间', trigger: 'change' }],
    needOverallDesc: [{ required: true, message: '请选择是否需要整体检查情况描述', trigger: 'change' }],
    needInspectedSign: [{ required: true, message: '请选择是否需要被检查人签字', trigger: 'change' }],
  };
  // 下发弹窗：示例部门树与分组（不调用接口）
  const issueDeptTree = ref<any[]>([]);
  const cascaderDeptProp = {
    checkStrictly: true,
    expandTrigger: 'hover' as const,
    value: 'id',
    label: 'deptName',
    emitPath: false,
  };
  const cascaderDeptPropMultiple = {
    ...cascaderDeptProp,
    multiple: true,
  };
  const userGroupOptions = ref<Array<{ id: number; name: string }>>([]);

  const initIssueMockData = () => {
    issueDeptTree.value = [
      { id: 1, deptName: '试验验证中心' },
      { id: 2, deptName: '质量管理部' },
      { id: 3, deptName: '安全应急部' },
      { id: 4, deptName: '院领导' },
    ];
    userGroupOptions.value = [
      { id: 1, name: '自查小分队分组' },
      { id: 2, name: '安全应急部小分队分组' },
      { id: 3, name: '领导小分队执行组' },
    ];
  };

  const onIssueDialogOpen = () => {
    initIssueMockData();
  };

  const resetIssueForm = () => {
    issueForm.responsibleDeptIds = [];
    issueForm.mainDeptGroupId = undefined;
    issueForm.safetyEmergencyDeptId = undefined;
    issueForm.safetyEmergencyGroupId = undefined;
    issueForm.hospitalLeaderDeptId = undefined;
    issueForm.hospitalLeaderGroupId = undefined;
    issueForm.planStartTime = '';
    issueForm.planEndTime = '';
    issueForm.needOverallDesc = false;
    issueForm.needInspectedSign = false;
    issueFormRef.value?.resetFields?.();
  };

  const tableQuery = reactive<QueryPageRequest<AreaCheckPlanQuery>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      keyword: '',
      status: '' as AreaCheckPlanQuery['status'],
      venueCategory: '',
      planStartTime: '',
      planEndTime: '',
    },
  });

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };

  /** 主列表假数据（本页面不调用接口，全部使用示例数据） */
  const MOCK_LIST: AreaCheckPlanRecord[] = [
    {
      id: 1,
      checkVenue: '18号楼、油库、液氮罐',
      status: 1,
      venueCategoryName: '各级风险点',
      planName: '2025年度生产安全检查计划',
      mainDeptName: '试验验证中心、质量管理部',
      selfCheckFrequency: '每日',
      mainDeptExecutorGroupName: '自查小分队分组',
      mainDeptResponsiblePerson: '孙菲、周萍',
      safetyEmergencyDeptName: '安全应急部',
      safetyEmergencyCheckFrequency: '每周',
      safetyEmergencyExecutorGroupName: '安全应急部小分队分组',
      safetyEmergencyResponsiblePerson: '李雪峰',
      hospitalLeaderDeptName: '院领导',
      hospitalLeaderCheckFrequency: '每季度',
      hospitalLeaderExecutorGroupName: '领导小分队执行组',
      hospitalLeaderResponsiblePerson: '孙菲亚',
      checklistCategoryName: '安全管理检查单',
      checklistTemplateName: '上飞院安全检查表',
      needOverallDesc: true,
      needInspectedSign: true,
      planStartTime: '2019-03-28',
      planEndTime: '2019-03-28',
    },
    {
      id: 2,
      checkVenue: '试验车间、配电间',
      status: 0,
      venueCategoryName: '关键业务活动',
      planName: '2025年一季度专项检查计划',
      mainDeptName: '生产保障部',
      selfCheckFrequency: '每周',
      mainDeptExecutorGroupName: '安全员分组',
      mainDeptResponsiblePerson: '张三',
      safetyEmergencyDeptName: '安全应急部',
      safetyEmergencyCheckFrequency: '每月',
      safetyEmergencyExecutorGroupName: '应急值班组',
      safetyEmergencyResponsiblePerson: '李四',
      hospitalLeaderDeptName: '院领导',
      hospitalLeaderCheckFrequency: '每半年',
      hospitalLeaderExecutorGroupName: '领导检查组',
      hospitalLeaderResponsiblePerson: '王五',
      checklistCategoryName: '关键业务活动专项检查单',
      checklistTemplateName: '关键业务活动专项检查单',
      needOverallDesc: false,
      needInspectedSign: true,
      planStartTime: '2025-01-01',
      planEndTime: '2025-03-31',
    },
    {
      id: 3,
      checkVenue: '办公区、食堂',
      status: 2,
      venueCategoryName: '日常安全',
      planName: '日常安全检查计划',
      mainDeptName: '综合管理部',
      selfCheckFrequency: '每日',
      mainDeptExecutorGroupName: '日常检查组',
      mainDeptResponsiblePerson: '赵六',
      safetyEmergencyDeptName: '安全应急部',
      safetyEmergencyCheckFrequency: '每周',
      safetyEmergencyExecutorGroupName: '安全应急部小分队分组',
      safetyEmergencyResponsiblePerson: '李雪峰',
      hospitalLeaderDeptName: '院领导',
      hospitalLeaderCheckFrequency: '每年',
      hospitalLeaderExecutorGroupName: '领导小分队执行组',
      hospitalLeaderResponsiblePerson: '孙菲亚',
      checklistCategoryName: '日常安全检查单',
      checklistTemplateName: '日常安全检查单',
      needOverallDesc: true,
      needInspectedSign: false,
      planStartTime: '2025-01-06',
      planEndTime: '2025-12-31',
    },
  ];

  function getTableData() {
    tableConfig.loading = true;
    try {
      let list = allData.value.slice();
      const { keyword, status, venueCategory, planStartTime, planEndTime } = tableQuery.queryParam;

      if (keyword && keyword.trim()) {
        const kw = keyword.trim().toLowerCase();
        list = list.filter(
          (row) =>
            (row.checkVenue || '').toLowerCase().includes(kw) ||
            (row.planName || '').toLowerCase().includes(kw),
        );
      }
      if (status !== '' && status !== undefined && status !== null) {
        list = list.filter((row) => String(row.status) === String(status));
      }
      if (venueCategory && venueCategory.trim()) {
        const vc = venueCategory.trim().toLowerCase();
        list = list.filter((row) => (row.venueCategoryName || '').toLowerCase().includes(vc));
      }
      if (planStartTime) {
        list = list.filter((row) => !row.planStartTime || row.planStartTime >= planStartTime);
      }
      if (planEndTime) {
        list = list.filter((row) => !row.planEndTime || row.planEndTime <= planEndTime);
      }

      pagination.total = list.length;
      const start = (tableQuery.pageNumber - 1) * tableQuery.pageSize;
      tableData.value = list.slice(start, start + tableQuery.pageSize);
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    if (dateRange.value && dateRange.value.length === 2) {
      tableQuery.queryParam.planStartTime = dateRange.value[0];
      tableQuery.queryParam.planEndTime = dateRange.value[1];
    } else {
      tableQuery.queryParam.planStartTime = '';
      tableQuery.queryParam.planEndTime = '';
    }
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.queryParam.keyword = '';
    tableQuery.queryParam.status = '';
    tableQuery.queryParam.venueCategory = '';
    tableQuery.queryParam.planStartTime = '';
    tableQuery.queryParam.planEndTime = '';
    dateRange.value = null;
    handleSearch();
  };

  const handleCreate = () => {
    router.push({
      name: 'areaCheckPlanManagementItem',
      query: { operate: 'area-check-plan-create' },
    });
  };

  const handleEdit = (id: number) => {
    router.push({
      name: 'areaCheckPlanManagementItem',
      query: { id, operate: 'area-check-plan-edit' },
    });
  };

  const handleView = (id: number) => {
    router.push({
      name: 'areaCheckPlanManagementItem',
      query: { id, operate: 'area-check-plan-view' },
    });
  };

  const handleDelete = async (id: number) => {
    allData.value = allData.value.filter((item) => item.id !== id);
    ElMessage.success('删除成功（本地示例数据，未调用接口）');
    getTableData();
  };

  const handleIssue = (id: number) => {
    currentIssuePlanId.value = id;
    resetIssueForm();
    showIssueDialog.value = true;
  };

  const handleIssueSave = async () => {
    if (!issueFormRef.value || !currentIssuePlanId.value) return;
    const valid = await issueFormRef.value.validate().catch(() => false);
    if (!valid) return;
    if (issueForm.planStartTime && issueForm.planEndTime && new Date(issueForm.planStartTime) > new Date(issueForm.planEndTime)) {
      ElMessage.error('计划开始日期不能大于计划结束日期');
      return;
    }
    const record = allData.value.find((item) => item.id === currentIssuePlanId.value);
    if (record) {
      record.status = 1; // 标记为进行中
      record.planStartTime = issueForm.planStartTime || record.planStartTime;
      record.planEndTime = issueForm.planEndTime || record.planEndTime;
      record.needOverallDesc = issueForm.needOverallDesc;
      record.needInspectedSign = issueForm.needInspectedSign;
    }
    ElMessage.success('下发成功（本地示例数据，未调用接口）');
    showIssueDialog.value = false;
    getTableData();
  };

  const handleCancel = async (id: number) => {
    const record = allData.value.find((item) => item.id === id);
    if (record) {
      record.status = 3; // 已作废
    }
    ElMessage.success('作废成功（本地示例数据，未调用接口）');
    getTableData();
  };

  onMounted(() => {
    // 初始化本地数据与筛选项
    allData.value = [...MOCK_LIST];
    venueCategoryOptions.value = [
      { label: '各级风险点', value: '各级风险点' },
      { label: '关键业务活动', value: '关键业务活动' },
      { label: '日常安全', value: '日常安全' },
    ];
    getTableData();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '@/views/traffic/violation/style/act-search-table.scss' as *;
</style>
