<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">                        
          </div>
          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>培训内容/计划名称：</span>
                <el-input
                  v-model="tableQuery.queryParam.contentName"
                  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 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"
                />
              </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 #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton text="查看" @click="handleView(scope.row.id)" />
                <ActionButton text="小结" v-if="scope.row.status===2" @click="handleSummary(scope.row)" />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
    <BatchImport
      v-if="batchImportVisible"
      :visible="batchImportVisible"
      :import-api-url="importApiUrl"
      :template-url="templateUrl"
      template-name="下载模板"
      :show-template="false"
      @close="batchImportVisible = false"
      @update="handleUpdate"
    />
    <el-dialog v-model="dialogVisible" title="填写培训小结">
        <el-form>
            <el-form-item label="材料上传" required>
                <el-upload
                    action=""
                    ref="courseContentUpload"
                    :auto-upload="false"
                    :on-change="handleFileChange"
                    accept=".rar, .zip, .doc, .docx, .pdf, .mp4"
                    :file-list="fileList"
                >
                    <el-button type="default">
                    <el-icon style="margin-right: 6px">
                        <UploadFilled />
                    </el-icon>
                    选择附件
                    </el-button>
                    <template #tip>
                    <div class="el-upload__tip"> 支持格式：.rar .zip .doc .docx .pdf .mp4，单个文件不能超过20MB </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="培训小结" required>
                <el-input type="textarea" v-model="form.trainingSummary"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="saveSummary" >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
  </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, TABLE_COLUMNS, STATUS_OPTIONS } from './configs/tables';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { getEducationAndTrainingProgramList, updateEducationTrainingPlanCourseSummary,exportTableData } from '@/api/production-education-training-plan-dept';
  import { downloadByData } from '@/utils/file/download';
  import BatchImport from '@/components/batch-import/BatchImport.vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { UploadFilled, Plus, Delete, Download, ZoomIn } from '@element-plus/icons-vue';
  import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';

  const router = useRouter();

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

  const { tableConfig, pagination } = useTableConfig(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: '岗位资质培训' },
    { label: '生产作业安全培训', value: '生产作业安全培训' },
    { label: '安全管理人员培训', value: '安全管理人员培训' },
  ]);
    // 验证文件类型
    const allowedTypes = [
      'application/rar',
      'application/zip',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/pdf',
      'video/mp4',
    ];

  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      // 培训内容/计划名称
      contentName: undefined,
      // 状态
      status: undefined,
      // 分类名称
      categoryName: undefined,
      // 开始时间
      datePlanStart: undefined,
      // 结束时间
      datePlanEnd: undefined,
    },
  });
  const fileList = ref([])
  const dialogVisible = ref(false)
  const handleCancel = ()=>{
    dialogVisible.value = false
  }
  const form = reactive({
    id:'',
    uploadAttach: '',
    trainingSummary: ''
  })
  const beforeUpload = (file) => {
    const isAllowedType = allowedTypes.includes(file.type);
    const isLt20M = file.size / 1024 / 1024 < 20;

    if (!isAllowedType) {
      ElMessage.error('上传文件格式不正确!');
    }
    if (!isLt20M) {
      ElMessage.error('上传文件大小不能超过20MB!');
    }

    return isAllowedType && isLt20M;
  };
     // 上传文件
 const formatAttachment = async (data: any) => {
    if (!data) return data;
    const uuid = Math.random().toString(36).substring(2, 9);
    const timestamp = Date.now().toString();
    const random = Math.random().toString(36).substring(2, 4);
    const fileName = data.name;
    const res = await uploadFileApi({
        bizType: UPLOAD_BIZ_TYPE.ATTACHMENT,
        fileName: `${uuid}-${timestamp}-${random}`,
        file: data,
    });
   
    return res
};
    // 文件选择更新
  const courseContentUpload = ref();
  const handleFileExceed = (files) => {
    courseContentUpload.value!.clearFiles(); // 清空文件列表
    const file = files[0];
    if (!beforeUpload(file)) {
      return;
    }
    courseContentUpload.value!.handleStart(file); // 手动触发上传
  };
    // 课程内容文件上传
  const handleFileChange = async (file, fileLists) => {

    if (!allowedTypes.includes(file.raw.type)) {
      ElMessage.error('不支持的文件格式');
      return;
    }

    if (file.raw.size > 20 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过20MB');
      return;
    }
    
    if(file.raw){
        try {
            const res = await formatAttachment(file.raw);
            
            const targetFile = fileLists.find(f => f.uid === file.uid);
            if (targetFile) {
                targetFile.url = res.url; 
                targetFile.contentType = res.contentType
            }
            fileList.value = fileLists; 
            form.uploadAttach = JSON.stringify(fileList.value); 
            ElMessage.success('上传成功');
        } catch (error) {
            ElMessage.error('上传失败，请重试');
            // 上传失败时，可以从 fileLists 中移除该文件
            fileList.value = fileLists.filter(f => f.uid !== file.uid);
        }
    }

  };
  const saveSummary = async()=>{
    if(!fileList.value.length){
      ElMessage.error('请先上传材料');
      return;
    }
    if(!form.trainingSummary){
      ElMessage.error('请输入小结内容');
      return;
    }
    try {
      await updateEducationTrainingPlanCourseSummary(form);
      ElMessage.success('更新小结成功');
      getTableData();
    } catch (e) {
      ElMessage.error('更新小结失败');
    }
    dialogVisible.value = false
  }
   const handleSummary = async (row) => {
    dialogVisible.value = true
    form.id = row.id
    form.trainingSummary = ''
    form.uploadAttach = ''
  };
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };

  async function getTableData() {
    tableConfig.loading = true;
    try {
      tableQuery.queryParam.datePlanStart = dateRange.value ? dateRange.value[0] : undefined;
      tableQuery.queryParam.datePlanEnd = dateRange.value ? dateRange.value[1] : undefined;
      const res = await getEducationAndTrainingProgramList(tableQuery);
      if (res) {
        // 映射返回数据字段到表格字段
        tableData.value = res.records;
        pagination.total = res.totalRow;
      }
    } catch (e) {
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

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

  const handleReset = () => {
    pagination.pageNumber = 1;
    pagination.pageSize = 20;
    Object.assign(tableQuery, {
      pageNumber: 1,
      pageSize: pagination.pageSize,
      queryParam: {
        // 培训内容/计划名称
        contentName: undefined,
        // 状态
        status: undefined,
        // 分类名称
        categoryName: undefined,
        // 开始时间
        datePlanStart: undefined,
        // 结束时间
        datePlanEnd: undefined,
      },
    });
    dateRange.value = null;
    handleSearch();
  };



  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/inventory/importInventory'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/import-inventory-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('导出教育培训计划管理（部门）失败，请重试');
    }
  };

  const handleView = (id: number) => {
    router.push({
      name: 'educationTrainingPlanManagementDeptItem',
      query: {
        id,
        operate: 'education-training-plan-management-dept-view',
      },
    });
  };

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