<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" :icon="Plus" class="search-table-container--button" @click="handleCreate"> 添加 </el-button>
            <el-button plain  class="search-table-container--button" @click="handleImport">导入</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>
              <el-button plain  @click="handleDownload">导出</el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <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>
            <template #plannedEndTime="scope">
                {{ scope.row.status === 1 ? '-' : scope.row.plannedEndTime }}
            </template>
            <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="handleView(scope.row.id)" />
                  <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="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="handleViewRecipients(scope.row.id)" />
                </template>
                <ActionButton text="复制" @click="handleCopyData(scope.row.id)" />
              </div>
            </template>
            
          </BasicTable>
        </div>
      </div>
      <!-- 生产安全计划时间设置（复制） -->
       <el-dialog
        v-model="copyDialogVisible"
        title="生产安全计划时间设置"
        width="500"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <div>
          <el-form ref="copyFormRef" :model="copyParams" :rules="copyParamsRules" label-width="150px">
            <el-form-item label="计划结束时间：" prop="plannedEndTime">
              <el-date-picker
                v-model="copyParams.plannedEndTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择完成时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="copyDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmCopy"> 保存 </el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 生产安全计划下发 -->
      <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>
    <BatchImport
      v-if="batchImportVisible"
      :visible="batchImportVisible"
      :import-api-url="importApiUrl"
      :template-url="templateUrl"
      template-name="安全体系建设工作计划导入模版"
      :show-template="true"
      @close="batchImportVisible = false"
      @update="handleUpdate"
    />
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  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,
    exportTableData,
    copyWorkPlan,
    type IssueWorkPlanParams,
  } from '@/api/safety-system-construction-work-plan';

  import { queryUserGroupPage } from '@/api/system/person-group';
  import { IssueWorkPlanFormRules } from './configs/form';
  import { downloadByData } from '@/utils/file/download';
  import BatchImport from '@/components/batch-import/BatchImport.vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';

  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: '生产安全工作' },
    { 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 () => {

    if (!issueWorkPlanForm.executGroupIds || issueWorkPlanForm.executGroupIds.length === 0) {
      ElMessage.error('请选择执行部门');
      return;
    }
    if (!issueWorkPlanForm.plannedStartTime || !issueWorkPlanForm.plannedEndTime) {
      ElMessage.error('请选择计划时间');
      return;
    }
    if (issueWorkPlanForm.plannedStartTime >= issueWorkPlanForm.plannedEndTime) {
      ElMessage.error('计划开始时间不能晚于计划结束时间');
      return;
    }

    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,
      },
    });
  };
  // 复制
  const copyDialogVisible = ref(false)
  const copyFormRef = ref()
  const copyParams = reactive({
    id: 0,
    plannedEndTime: ''
  })
  const copyParamsRules = ref({
    plannedEndTime: [{ required: true, message: '请选择计划结束日期', trigger: 'change' }]
  })
  const handleCopyData = (id:number)=>{
    copyDialogVisible.value = true
    copyParams.id = id
  }
 const handleValidate = async () => {
  if (!copyFormRef.value) return false;
  try {
    await copyFormRef.value.validate();
    return true;

  } catch (error) {

    return false;
  }
};
  // 保存复制
  const handleConfirmCopy = async ()=>{
    const res = await handleValidate();
    if (!res) return;
    try {
        await copyWorkPlan(copyParams)
        ElMessage.success('复制成功')
        copyDialogVisible.value = false
        getTableData();
        copyFormRef.value.resetFields()
    } catch (error:any) {
        ElMessage.error('复制失败', error.message)
        copyDialogVisible.value = false
        copyFormRef.value.resetFields()
    }
  }
    // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/safetyWorkPlan/workPlan/import'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/安全体系建设工作计划导入模版.xlsx');
  // 导入
  const handleImport = () => {
    batchImportVisible.value = true;
  };
  
  const handleUpdate = () => {
    batchImportVisible.value = false;
    getTableData();
  };
  // 导出
  const handleDownload = async () => {
    try {
      const response = await exportTableData(tableQuery.queryParam);
      if (response) {
        const fileName = `教育培训计划管理（管理员）_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出教育培训计划管理（管理员）失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  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>
