<template>
  <div class="safety-platform-container">
    <div class="back-header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">查看发送对象</span>
    </div>
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> {{ detail.workContent }}</div>
      <div class="breadcrumb-desc flex" style="margin-top: 20px">
        <span style="margin-right: 30px; font-size: 13px">创建人： {{ detail.createdByName }}</span>
        <span style="font-size: 13px">创建时间：{{ detail.createdAt }}</span>
      </div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header class="header-wrapper">
          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>状态：</span>
                <el-select v-model="tableQuery.queryParam.status" placeholder="请选择状态" clearable>
                  <el-option
                    v-for="item in VIEW_SENDER_WORK_PLAN_STATUS_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>部门名称：</span>
                <el-cascader
                  v-model="responsibleDept"
                  :options="deptTree"
                  :props="cascaderProp"
                  clearable
                  collapse-tags
                  :show-all-levels="false"
                  :max-collapse-tags="3"
                  placeholder="请选择责任部门"
                  style="width: 100%"
                />
              </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"
                  @change="onChangeDateRange"
                />
              </div>
              <div class="select-box--item">
                <span>关键词：</span>
                <el-input v-model="tableQuery.queryParam.keyword" placeholder="搜索关键词"></el-input>
              </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- 已作废 -->
                <!-- (2)待反馈-->
                <template v-if="Number(scope.row.status) === 2">
                  <ActionButton text="查看" @click="handleView(scope.row)" />
                  <ActionButton text="作废" @click="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)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Discount } from '@element-plus/icons-vue';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
import BreadcrumbBack from '@/components/BreadcrumbBack.vue';
  import {
    TABLE_OPTIONS,
    VIEW_SENDS_TABLE_COLUMNS,
    VIEW_SENDER_WORK_PLAN_STATUS_OPTIONS,
    WORK_PLAN_STATUS_LABEL,
  } from './configs/tables';
  import { useRouter, useRoute } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    queryViewSender,
    deleteWorkPlanDept,
    cancelWorkPlan,
    queryWorkPlanDetail,
    type SaveWorkPlanRequest,
  } from '@/api/safety-system-construction-work-plan';
  import { DeptTree } from '@/types/dept/type';
  import { getAllDepartments } from '@/api/auth/dept';

  const router = useRouter();
  const route = useRoute();
  const currentId = computed(() => Number(route.query.id));
  const detail = reactive({
    workContent: '',
    createdByName: '',
    createdAt: '',
  });

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(VIEW_SENDS_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 responsibleDept = ref([]);
  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      planId: currentId.value,
      keyword: '',
      status: '',
      responsibleDeptIds: '',
      categoryName: '',
      startDate: '',
      endDate: '',
      /** 排序 */
      // sortField: "created_at",
      // sortOrder: false,
    },
  });

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

  const cascaderProp = {
    multiple: true,
    expandTrigger: 'hover',
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'deptName',
  };

  // 获取级联部门数据
  const deptTree = ref<DeptTree[]>();
  const loadDeptTreeData = async () => {
    const result = await getAllDepartments();
    deptTree.value = result[0].children;
  };

  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 {
      let option = responsibleDept.value;
      if (tableQuery.queryParam.responsibleDeptIds) {
        tableQuery.queryParam.responsibleDeptIds = option.toString();
      }
      const res = await queryViewSender(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 fetchWorkPlanDetail = async () => {
    const res = await queryWorkPlanDetail(currentId.value);
    Object.assign(detail, res);
  };

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

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

  const handleDelete = async (id: number) => {
    try {
      await deleteWorkPlanDept(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e) {
      console.error('删除工作计划失败:', e);
      ElMessage.error('删除失败，请重试');
    }
  };
  // 查看
  const handleView = (row) => {
    router.push({
      name: 'SafetySystemConstructionWorkPlanManagementDeptItem',
      query: {
        id: currentId.value,
        planId: row.planId,
        operate: 'work-plan-dept-view',
      },
    });
  };

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

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

  .header-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .act-search {
      flex: 1;
      display: flex;
      justify-content: flex-end;

      .search-btn {
        margin-left: 40px;
      }
    }
  }
  .back-header {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px 22px;
    flex-shrink: 0;
    background-color: white;
  }
</style>
