<template>
  <main class="safety-platform-container__main">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="150px"
      style="max-width: 600px"
      label-position="left"
    >
      <el-form-item label="生产安全计划名称:" prop="trainingPlanName" required>
        <el-input v-model="form.trainingPlanName" placeholder="请输入生产安全计划名称" :disabled="true" />
      </el-form-item>

      <el-form-item label="分类名称：" prop="categoryName" required>
        <el-select v-model="form.categoryName" placeholder="请选择分类名称" :disabled="true">
          <el-option v-for="item in classifyNameOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="责任部门：" prop="responsibleDeptIds" required>
        <el-cascader
          v-model="form.responsibleDeptIds"
          :options="deptTree"
          :props="cascaderProp"
          clearable
          collapse-tags
          :show-all-levels="false"
          :max-collapse-tags="3"
          placeholder="请选择责任部门"
          style="width: 100%"
          :disabled="true"
        />
      </el-form-item>

      <el-form-item label="配合部门：" prop="cooperateDeptIds" required>
        <el-cascader
          v-model="form.cooperateDeptIds"
          :options="deptTree"
          :props="cascaderProp"
          clearable
          collapse-tags
          :show-all-levels="false"
          :max-collapse-tags="3"
          popper-class="cascader-popper--custom"
          placeholder="请选择配合部门"
          style="width: 100%"
          :disabled="true"
        />
      </el-form-item>

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

      <el-form-item label="工作内容：" prop="workContent" required>
        <el-input
          v-model="form.workContent"
          type="textarea"
          :rows="4"
          :maxlength="300"
          placeholder="请填写岗位职责"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item label="附件上传：" prop="fileUrl" :required="isViewMode">
        <UploadFiles
          label="上传附件"
          :file-list="attachmentFileList"
          :disabled="isViewMode"
          :maxCount="1"
          @uploadSuccess="handleAttachmentUploadSuccess"
          @preview="handlePreview"
        />
      </el-form-item>
    </el-form>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
      {{ isEditMode ? '提交' : '保存' }}
    </el-button>
  </footer>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, reactive } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import type { FormInstance } from 'element-plus';
  import { FORM_RULES } from '../configs/form';
  import {
    issueWorkPlanDept,
    queryWorkPlanDetail,
    type SaveWorkPlanRequest,
  } from '@/api/safety-system-construction-work-plan';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import type { FileItem } from '@/components/UploadFiles/types';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  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 currentPlanId = computed(() => Number(route.query.planId));

  const operate = computed(() => (route.query.operate as string) || 'work-plan-dept-view');
  const isEditMode = computed(() => operate.value === 'work-plan-dept-issue');
  const isViewMode = computed(() => operate.value === 'work-plan-dept-view');

  const form = reactive<SaveWorkPlanRequest>({
    workContent: '',
    categoryName: '',
    trainingPlanName: '',
    responsibleDeptIds: '',
    cooperateDeptIds: '',
    executGroupIds: '',
    plannedComplateTime: '',
    fileUrl: '',
  });

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

  /** 表单校验规则 */
  const rules = ref<Record<string, import('element-plus').FormItemRule[]>>(FORM_RULES);

  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;
  };

  /** 附件 JSON [{file_name, url}] 转 FileItem 列表，供 UploadFiles 使用（新增/编辑/查看/审核统一展示） */
  function convertAttachmentJsonToFileItems(attachmentStr: string): FileItem[] {
    if (!attachmentStr || !String(attachmentStr).trim()) return [];
    try {
      const arr = JSON.parse(attachmentStr);
      if (!Array.isArray(arr)) return [];
      return arr.map((item: any, index: number) => {
        const fileName = item.file_name || item.fileName || `附件${index + 1}`;
        const url = item.url || item.fileUrl || '';
        const ext = (fileName || '').split('.').pop()?.toLowerCase() || '';
        let fileType = 'pdf';
        if (['doc', 'docx'].includes(ext)) fileType = 'word';
        else if (['xls', 'xlsx'].includes(ext)) fileType = 'excel';
        else if (['ppt', 'pptx'].includes(ext)) fileType = 'ppt';
        return { fileId: index + 1, fileName, fileType, fileSize: '0', fileUrl: url };
      });
    } catch {
      return [];
    }
  }

  const attachmentFileList = computed(() => convertAttachmentJsonToFileItems(form.fileUrl || ''));

  async function handleAttachmentUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      form.fileUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || [])
        .map((r) => ({
          file_name: r.fileName,
          url: r.fileUrl || '',
        }))
        .filter((x) => x.url);
      form.fileUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('附件上传失败:', e);
      ElMessage.error('附件上传失败，请重试');
    }
  }
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const handlePreview = (url: string) => {
    if (url) {
      // 根据文件扩展名判断文件类型
      const extension = url.split('.').pop()?.toLowerCase() || '';
      let fileType: 'pdf' | 'word' | 'excel' | 'ppt' = 'pdf';
      if (extension === 'doc' || extension === 'docx') {
        fileType = 'word';
      } else if (extension === 'xls' || extension === 'xlsx') {
        fileType = 'excel';
      } else if (extension === 'ppt' || extension === 'pptx') {
        fileType = 'ppt';
      }
      previewOnlineRef.value?.open(url, fileType);
    }
  };
  //  时间格式化
  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}`; // 输出：****-**-**
  };
  //转部门格式 “2,3“ -> [2,3]
  const parseDeptIds = (ids: string | string[] | number[] | undefined | null): number[] => {
    if (!ids) {
      return [];
    }

    if (Array.isArray(ids)) {
      return ids.map((v: any) => Number(v)).filter((id) => !isNaN(id));
    }

    return String(ids)
      .split(',')
      .map(Number)
      .filter((id) => !isNaN(id));
  };

  const formRef = ref<FormInstance | null>(null);

  const handleValidate = async (): Promise<boolean> => {
    if (!formRef.value) return false;
    try {
      await formRef.value.validate();
      return true;
    } catch {
      return false;
    }
  };

  const getDetail = async () => {
    const id = currentPlanId.value;
    if (!id) return;
    try {
      const res = await queryWorkPlanDetail(id);
      if (res) {
        // 映射接口字段到表单字段
        const cooperateDeptIdsArray = parseDeptIds(res.cooperateDeptIds);
        const responsibleDeptIdsArray = parseDeptIds(res.responsibleDeptIds);
        Object.assign(form, {
          ...res,
          cooperateDeptIds: cooperateDeptIdsArray,
          responsibleDeptIds: responsibleDeptIdsArray,
        });
      }
      // cloneRuleFormData();
    } catch (e) {
      console.error('获取物品库存详情失败:', e);
      ElMessage.error('获取详情失败');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      if (isViewMode && form.fileUrl) {
        // 处理附件格式
        form.fileUrl = JSON.parse(form.fileUrl)[0].url;
      }
      if (isEditMode.value && currentId.value) {
        await issueWorkPlanDept({
          id: currentId.value,
          fileUrl: form.fileUrl,
        });
        ElMessage.success('保存成功');
      }

      router.back();
    } catch (e) {
      console.error('保存物品库存失败:', e);
      ElMessage.error('保存失败，请重试');
    }
  };

  onMounted(() => {
    loadDeptTreeData();
    console.log(isEditMode.value, isViewMode.value);
    if (isEditMode.value || isViewMode.value) {
      getDetail();
    }
  });
</script>

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