<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"
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select v-model="tableQuery.queryParam.status" placeholder="请选择状态" clearable>
                  <el-option
                    v-for="item in WORK_PLAN_STATUS_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>分类名称：</span>
                <el-select
                  v-model="tableQuery.queryParam.categoryName"
                  placeholder="请选择分类名称"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in classifyNameOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div>
                <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"
                  @change="onChangeDateRange"
                />
              </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 #action="scope">
              <div class="action-container--div" style="justify-content: left">

                <!-- 1-未下发、2-待反馈、3-已完成 4- 已作废 -->
                <!-- 未下发(1)：编辑、删除、下发 -->
                <template v-if="Number(scope.row.status) === 1">
                  <ActionButton text="编辑" @click="handleEdit(scope.row.id)" />
                  <ActionButton
                    text="删除"
                    :popconfirm="{
                      title: '确定要删除?', 
                    }"
                    @confirm="handleDelete(scope.row.id)"
                  />
                  <ActionButton text="下发" @click="handleIssue(scope.row.id)" />
                </template>

                <!-- (2)待反馈-->
                <template v-else-if="Number(scope.row.status) === 2">
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                  <ActionButton text="查看发送对象" @click="handleViewRecipients(scope.row.id)" />
                  <ActionButton
                    text="作废"
                    :popconfirm="{
                      title: '确定要作废?',
                    }"
                    @confirm="handleViewInvalid(scope.row.id)"
                  />
                </template>

                <!-- 已完成(3)/已作废（4）-->
                <template v-else>
                  <ActionButton
                    text="删除"
                    :popconfirm="{
                      title: '确定要删除?',
                    }"
                    @confirm="handleDelete(scope.row.id)"
                  />
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                  <ActionButton text="发送查看对象" @click="handleViewRecipients(scope.row.id)" />
                </template>
              </div>
            </template>
            <template #feedbackCount="scope">
              {{ (scope.row.feedbackCount === 0 && scope.row.status === 1) ? '-' : scope.row.feedbackCount }}
            </template>
            <template #issuedCount="scope">
              {{ (scope.row.issuedCount === 0 && scope.row.status === 1) ? '-' : scope.row.issuedCount }}
            </template>
            <template #feedbackRatio="scope">
              {{ (scope.row.feedbackRatio === 0 && scope.row.status === 1) ? '-' : scope.row.feedbackRatio }}
            </template>
          </BasicTable>
        </div>
      </div>
      <el-dialog
        v-model="issueWorkPlanDialogVisible"
        title="生产安全计划下发"
        width="500"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <div>
          <el-form ref="formRef" :model="issueWorkPlanForm" :rules="issueWorkPlanFormRules" label-width="150px">
            <el-form-item label="计划执行部门分组：" prop="executGroupIds">
              <el-select
                v-model="issueWorkPlanForm.executGroupIds"
                multiple
                size="large"
                placeholder="分组名称"
                style="width: 100%"
              >
                <el-option v-for="group in groupList" :key="group.id" :label="group.name" :value="group.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="计划开始时间：" prop="plannedStartTime" required>
              <el-date-picker
                v-model="issueWorkPlanForm.plannedStartTime"
                type="date"
                placeholder="请选择完成时间"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="计划完成时间：" prop="plannedEndTime" required>
              <el-date-picker
                v-model="issueWorkPlanForm.plannedEndTime"
                type="date"
                placeholder="请选择完成时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="issueWorkPlanDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmIssue"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </main>
  </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,
    WORK_PLAN_TABLE_COLUMNS,
    WORK_PLAN_STATUS_OPTIONS,
    WORK_PLAN_STATUS_LABEL,
  } from './configs/tables';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    queryWorkPlanPage,
    cancelWorkPlan,
    issueWorkPlan,
    deleteWorkPlan,
    type IssueWorkPlanParams,
  } from '@/api/safety-system-construction-work-plan';

  import { queryUserGroupPage } from '@/api/system/person-group';
  import { IssueWorkPlanFormRules } from './configs/form';

  const router = useRouter();
  const groupList = ref<any>([]);
  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(WORK_PLAN_TABLE_COLUMNS, TABLE_OPTIONS);

  const tableData = ref<any[]>([]);

  // 日期范围
  const dateRange = ref<[string, string] | null>(null);

  // 分类名称选项
  const classifyNameOptions = ref<Array<{ label: string; value: string }>>([
    { label: '全部', value: '全部' },
    { label: '安全综合工作', value: '安全综合工作' },
    { label: '生产安全工作', value: '生产安全工作' },
  ]);

  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      keyword: '',
      status: '',
      categoryName: '',
      startDate: '',
      endDate: '',
      /** 排序 */
      // sortField: "created_at",
      // sortOrder: false,
    },
  });
  /**
   * @description: 下发
   * @return {*}
   */
  const issueWorkPlanDialogVisible = ref(false);

  /**
   * @description: 下发参数
   * @return {*}
   */
  const issueWorkPlanForm = reactive<IssueWorkPlanParams>({
    id: 0,
    executGroupIds: '',
    plannedStartTime: '',
    plannedEndTime: '',
  });
  /**
   * @description: 下发rules验证
   * @param {*} value
   * @return {*}
   */
  const issueWorkPlanFormRules = ref(IssueWorkPlanFormRules);

  /**
   * @description: 部门接口
   * @return {*}
   */

  const cascaderProp = {
    multiple: true,
    expandTrigger: 'hover',
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'deptName',
  };
  // 格式化时间
  const formatDate = (date) => {
    if (!date) return '';
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`; // 输出：2026/02/11
  };
  // 获取级联部门数据
  const loadGroupTreeData = async () => {
    queryUserGroupPage({
      pageNumber: 1,
      pageSize: 500,
    }).then((res) => {
      groupList.value = res.records;
    });
  };

  /**
   * @description: 下发
   * @param {*} id
   * @return {*}
   */
  const handleIssue = async (id: number) => {
    issueWorkPlanDialogVisible.value = true;
    issueWorkPlanForm.id = id;
    Object.assign(issueWorkPlanForm, {
      executGroupIds: '',
      plannedStartTime: '',
      plannedEndTime: '',
    });
  };
  const handleConfirmIssue = async () => {
    try {
      await issueWorkPlan({
        ...issueWorkPlanForm,
        executGroupIds: issueWorkPlanForm.executGroupIds.toString(),
        plannedStartTime: formatDate(issueWorkPlanForm.plannedStartTime),
        plannedEndTime: formatDate(issueWorkPlanForm.plannedEndTime),
      });
      ElMessage.success('下发成功');
      getTableData();
    } catch (e) {
      console.error('下发工作计划失败:', e);
      ElMessage.error('下发失败，请重试');
    }
    issueWorkPlanDialogVisible.value = false;
  };

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

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };
  const onChangeDateRange = (value) => {
    tableQuery.queryParam.startDate = value[0];
    tableQuery.queryParam.endDate = value[1];
    getTableData();
  };

  async function getTableData() {
    tableConfig.loading = true;
    try {
      const res = await queryWorkPlanPage(tableQuery);
      if (res) {
        tableData.value = res.records;
        pagination.total = res.totalRow;
      }
    } catch (e) {
      console.error('获取工作计划列表失败:', e);
      ElMessage.error('获取工作计划列表失败');
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.pageNumber = 1;
    tableQuery.queryParam = {
      keyword: '',
      status: '',
      categoryName: '',
      startDate: '',
      endDate: '',
      /** 排序 */
      // sortField: "created_at",
      // sortOrder: false,
    };
    dateRange.value = null;
    handleSearch();
  };

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

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

  const handleDelete = async (id: number) => {
    try {
      await deleteWorkPlan(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e) {
      console.error('删除工作计划失败:', e);
      ElMessage.error('删除失败，请重试');
    }
  };

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

  const handleViewInvalid = async (id: number) => {
    try {
      await cancelWorkPlan(id);
      ElMessage.success('作废成功');
      getTableData();
    } catch (e) {
      console.error('作废工作计划失败:', e);
      ElMessage.error('作废失败，请重试');
    }
  };

  const handleViewRecipients = (id: number) => {
    router.push({
      name: 'SafetySystemConstructionWorkPlanManagementViewSender',
      query: {
        id,
      },
    });
  };

  onMounted(() => {
    getTableData();
    loadGroupTreeData();
  });
</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>
