<template>
  <main class="safety-platform-container__main">
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="150px"
      style="max-width: 600px"
      label-position="left"
    >
      <!-- 分类名称 -->
      <el-form-item label="教育培训计划名称：" prop="trainingPlanName">
        <el-input v-model="form.trainingPlanName" placeholder="输入教育培训计划名称" :disabled="isViewMode"></el-input>
      </el-form-item>

      <!-- 分类名称 -->
      <el-form-item label="分类名称：" prop="categoryName">
        <el-select v-model="form.categoryName" placeholder="请选择分类名称" filterable clearable :disabled="isViewMode">
          <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="trainingContent">
        <el-input v-model="form.trainingContent" placeholder="输入培训名称（内容）" :disabled="isViewMode" />
      </el-form-item>

      <!-- 培训对象 -->
      <el-form-item label="培训对象：" prop="trainingObject">
        <el-input v-model="form.trainingObject" placeholder="输入培训对象" :disabled="isViewMode" />
      </el-form-item>

      <!-- 培训人数 -->
      <el-form-item label="培训人数：" prop="trainingCount">
        <el-input v-model="form.trainingCount" placeholder="输入培训人数" :disabled="isViewMode" />
      </el-form-item>

      <!-- 培训时间 -->
      <el-form-item label="培训时间：" prop="trainingTime">
        <el-input v-model="form.trainingTime" placeholder="输入培训时间，如按需、12月等" :disabled="isViewMode" />
      </el-form-item>

      <!-- 培训方式 -->
      <el-form-item label="培训方式：" prop="trainingMethod">
        <el-input v-model="form.trainingMethod" placeholder="输入培训方式，如网络等" :disabled="isViewMode" />
      </el-form-item>

      <!-- 考核方式 -->
      <el-form-item label="考核方式：" prop="assessmentMethod">
        <el-input
          v-model="form.assessmentMethod"
          placeholder="输入考核方式，如网上学习/答题、发放材料等"
          :disabled="isViewMode"
        />
      </el-form-item>

      <!-- 培训责任部门 -->
      <el-form-item label="培训责任部门：" prop="responsibleDeptIds">
        <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="isViewMode"
        />
      </el-form-item>

      <!-- 学时 -->
      <el-form-item label="学时：" prop="studyHours">
        <el-input v-model.number="form.studyHours" placeholder="输入学时，如6、2、8等，单位时" :disabled="isViewMode" />
      </el-form-item>
    </el-form>

    <!-- 小结内容 -->
     <section v-if="form.status===2">
        <h5 class="border-b" v-if="form.dets.length!==0" >材料小结</h5>
        <div v-for="item in form.dets">
            <el-form  label-width="150px" style="max-width: 600px" label-position="left">
                <el-form-item label="材料上传" v-if="item.uploadAttach" required>
                    <ul>
                        <li  v-for="file in JSON.parse(item.uploadAttach)">
                            {{ file.name }} <el-button link @click="downloadFn(file)">下载</el-button>
                        </li>
                    </ul>
                </el-form-item>
                <el-form-item label="培训小结" v-if="item.trainingSummary" required>
                    <el-input v-model="item.trainingSummary" :disabled="isViewMode"></el-input>
                </el-form-item>
            </el-form>
        </div>
        
     </section>
    <!-- 提交按钮 -->
    <footer class="safety-platform-container__footer">
      <el-button @click="router.back()">返回</el-button>
      <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
        {{ isCreateMode ? '提交' : '保存' }}
      </el-button>
    </footer>
  </main>
</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 {
    queryEducationAndTrainingProgramDetail,
    saveEducationAndTrainingProgram,
    updateEducationAndTrainingProgram,
    type FormDataType,
  } from '@/api/production-education-training-plan';
  import { DeptTree } from '@/types/dept/type';
  import { getAllDepartments } from '@/api/auth/dept';
  import { debounce } from 'lodash-es';
import { downloadFile } from '@/views/disaster/utils';
  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'education-training-plan-management-create');
  const currentId = computed(() => Number(route.query.id));

  const isCreateMode = computed(() => operate.value === 'education-training-plan-management-create');
  const isEditMode = computed(() => operate.value === 'education-training-plan-management-edit');
  const isViewMode = computed(() => operate.value === 'education-training-plan-management-view');

  // 表单数据
  const form = reactive<FormDataType>({
    trainingPlanName: '',
    categoryName: '',
    trainingContent: '',
    trainingObject: '',
    trainingCount: '',
    trainingTime: '',
    trainingMethod: '',
    assessmentMethod: '',
    responsibleDeptIds: [],
    studyHours: '',
    status: 0,
    dets:[]
  });

  // 分类名称选项
  const classifyNameOptions = ref<Array<{ label: string; value: string }>>([
    { label: '全员安全培训', value: '全员安全培训' },
    { label: '新员工培训', value: '新员工培训' },
    { label: '岗位资质培训', value: '岗位资质培训' },
    { label: '生产作业安全培训', value: '生产作业安全培训' },
    { label: '安全管理人员培训', value: '安全管理人员培训' },
  ]);

  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 fileList = ref([])
  // 表单引用
  const formRef = ref<FormInstance>();

  // 表单验证规则
  const rules = reactive(FORM_RULES);

  const handleValidate = async () => {
    if (!formRef.value) return;
    const res = await formRef.value.validateField();
    return res;
  };
  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 getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryEducationAndTrainingProgramDetail(currentId.value);
      if (res) {
        Object.assign(form, {
          ...res,
          responsibleDeptIds: parseDeptIds(res.responsibleDeptIds),
        });
        fileList.value = res.uploadAttach ? JSON.parse(res.uploadAttach): []
      }
    } catch (e) {
      ElMessage.error('获取详情失败');
    }
  };
  const downloadFn = (item)=>{
    if(item.url){
        downloadFile(
            item.url,
            item.name,
        )
    }
  }
  const handleSubmit = debounce(async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      const basePayload = {
        ...form,
        responsibleDeptIds: form.responsibleDeptIds.toString(),
      };

      if (isCreateMode.value) {
        await saveEducationAndTrainingProgram(basePayload);
        ElMessage.success('创建成功');
      } else if (isEditMode.value && currentId.value) {
        await updateEducationAndTrainingProgram({
          id: currentId.value,
          ...basePayload,
        });
        ElMessage.success('保存成功');
      }

      router.back();
    } catch (e) {
      ElMessage.error('保存失败，请重试');
    }
  }, 1000);

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

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

  .el-form-item {
    margin-bottom: 25px;
  }
  li{
    list-style: none;
  }
  .border-b{
    border-bottom: 1px solid #efefef;
    padding-bottom:10px;
    margin-bottom:10px;
  }
</style>
