
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="常识名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入安全常识名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型"
               clearable
              @keyup.enter.native="handleQuery">
            <el-option
              v-for="(item, i) in dict.type.safety_type"
              :key="i"
              :label="item.label"
              :value="'' + item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gaoqu:knowledge:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gaoqu:knowledge:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gaoqu:knowledge:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gaoqu:knowledge:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="knowledgeList"
      @selection-change="handleSelectionChange"
      height="600px"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="安全常识名称" align="center" prop="name" />
      <el-table-column label="类型" align="center" prop="typeName" />
      <el-table-column label="上传时间" align="center" prop="uploadsDate" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gaoqu:knowledge:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gaoqu:knowledge:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改安全常识对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="安全常识名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入安全常识名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type" >
          <el-select v-model="form.type" placeholder=""  :disabled="form.type=='3' && form.id">
            <el-option
              v-for="(item, i) in typeDict"
              :key="i"
              :label="item.label"
              :value="'' + item.value"
           
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传的视频" prop="videoUrl" v-show="form.type!='3'">
          <el-upload
            ref="videoUpload"
            class="upload-demo"
            :action="upload.url"
            :on-success="handleVideoUploadSuccess"
            :before-upload="beforeVideoUpload"
            :headers="upload.headers"
            :limit="1"
            accept="video/mp4"
            :show-file-list="true"
            :auto-upload="true"
            v-model="form.videoUrl"
          >
            <el-button size="small" type="primary"
              >点击上传</el-button
            >
            <div slot="tip" class="el-upload__tip">
              仅支持mp4格式视频，最大支持100MB，只能上传1个
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="应知应会内容" prop="content"  v-show="form.type==='3'">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <!-- 新增附件上传表单项 -->
        <el-form-item label="附件" prop="file" v-show="form.type==='3'">
          <el-upload
            ref="fileUpload"
            class="upload-demo"
            :action="upload.url"
            :headers="upload.headers"
            :on-success="handleFileUploadSuccess"
            :before-upload="beforeFileUpload"
            :limit="1"
            accept="application/pdf"
            :show-file-list="true"
            :auto-upload="true"
            v-model="form.file"
          >
            <el-button size="small" type="primary">点击上传PDF</el-button>
            <div slot="tip" class="el-upload__tip">
              仅支持PDF格式，最大100MB
            </div>
          </el-upload>
          <!-- 预览链接（上传成功后显示） -->
          <el-link
            v-if="form.file"
            :href="form.file"
            target="_blank"
            type="primary"
            >点击预览附件</el-link
          >
        </el-form-item>
        <el-form-item label="上传日期" prop="uploadsDate">
          <el-date-picker
            v-model="form.uploadsDate"
            type="date"
            placeholder="选择上传日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :clearable="false"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listKnowledge,
  getKnowledge,
  delKnowledge,
  addKnowledge,
  updateKnowledge,
} from "@/api/gaoqu/knowledge";
import { getToken } from "@/utils/auth";

export default {
  name: "Knowledge",
  dicts: ["safety_type"],
  data() {
    return {
      typeDict:[],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 安全常识表格数据
      knowledgeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        videoUrl: null,
        content: null,
        file: null,
      },
      // 表单参数
      form: { id: null,
        name: null,
        type: null,
        videoUrl: null,
        content: null,
        file: null,
        uploadsDate: new Date().toISOString().split('T')[0] // 初始化时设置当前日期（格式：YYYY-MM-DD）
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "安全常识名称不能为空", trigger: "blur" },
        ],
        type: [ // 新增类型必填校验
          { required: true, message: "请选择类型", trigger: "change" }
        ],
        // videoUrl: [ // 新增视频必填校验
        //   { required: true, message: "请上传视频", trigger: "change" }
        // ],
        // content: [ // 新增内容必填校验
        //   { required: true, message: "请输入应知应会内容", trigger: "blur" }
        // ],
        // file: [ // 新增附件必填校验
        //   { required: true, message: "请上传附件", trigger: "change" }
        // ],
        uploadsDate: [ // 新增日期必填校验
          { required: true, message: "请选择上传日期", trigger: "change" }
        ]
      },
    };
  },
  created() {
    this.getList();
    this.typeDict = this.dict.type.safety_type
  },
  methods: {
    /** 附件上传前校验 */
    beforeFileUpload(file) {
      const isPdf = file.type === "application/pdf";
      const isLt100M = file.size / 1024 / 1024 < 100; // 100MB限制

      if (!isPdf) {
        this.$message.error("仅支持PDF格式文件上传");
        return false;
      }
      if (!isLt100M) {
        this.$message.error("文件大小不能超过100MB");
        return false;
      }
      return true;
    },

    /** 附件上传成功处理 */
    handleFileUploadSuccess(response, file) {
      if (response.code === 200) {
        this.form.file = response.url; // 假设接口返回文件路径
        this.$message.success("附件上传成功");
      } else {
        this.$message.error("附件上传失败");
      }
    },
    /** 视频上传前校验 */
    beforeVideoUpload(file) {
      const isVideo = file.type.startsWith("video/mp4");
      const isLt100M = file.size / 1024 / 1024 < 100; // 限制100MB

      if (!isVideo) {
        this.$message.error("仅支持MP4视频格式文件上传");
        return false;
      }
      if (!isLt100M) {
        this.$message.error("视频大小不能超过100MB");
        return false;
      }
      return true;
    },

    /** 视频上传成功处理 */
    handleVideoUploadSuccess(response, file) {
      if (response.code === 200) {
        this.form.videoUrl = response.url; // 假设接口返回视频路径
        this.$message.success("视频上传成功");
      } else {
        this.$message.error("视频上传失败");
      }
    },
    /** 查询安全常识列表 */
    getList() {
      this.loading = true;
      listKnowledge(this.queryParams).then((response) => {
        this.knowledgeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        videoUrl: null,
        content: null,
        file: null,
        uploadsDate: new Date().toISOString().split('T')[0] // 重置时设置当前日期
      };
      this.typeDict = this.dict.type.safety_type

      // 清空上传组件的文件列表（关键新增逻辑）
      if (this.$refs.videoUpload) {
        this.$refs.videoUpload.clearFiles(); // 清空视频上传组件的文件列表
      }
      if (this.$refs.fileUpload) {
        this.$refs.fileUpload.clearFiles(); // 清空附件上传组件的文件列表
      }

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加安全常识";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      //   const id = row.id || this.ids
      //   getKnowledge(id).then(response => {
        this.typeDict = this.dict.type.safety_type.filter((item)=>{
          if(row.id&&row.type!=='3'){
            return item.value+'' !== '3'
          }
          return true
        })
        

      this.form = JSON.parse(JSON.stringify(row));
      this.open = true;
      this.title = "修改安全常识";
      // 回显视频上传组件的历史文件
      if (this.form.videoUrl) {
        // 从URL中提取文件名（例如："test.mp4"）
        const fileName = this.form.videoUrl.split('/').pop();
        // 构造符合el-upload格式的文件对象（需包含name/url/status）
        this.$refs.videoUpload.fileList = [{
          name: fileName,
          url: this.form.videoUrl,
          status: 'success' // 标记为已上传状态
        }];
      }

      // 回显附件上传组件的历史文件（可选，根据业务需求）
      if (this.form.file) {
        const fileFileName = this.form.file.split('/').pop();
        this.$refs.fileUpload.fileList = [{
          name: fileFileName,
          url: this.form.file,
          status: 'success'
        }];
      }
      //   });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.$modal)
   
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if(this.form.type === '3'){ // 应知应会内容
          if(!this.form.content){
            this.$modal.alertWarning('请输入应知应会内容');
              return;
          }
          if(!this.form.file){
              this.$modal.alertWarning('请上传附件');
              return;
          }
        }
        if(this.form.type !== '3'){ // 警示、常识视频等内容
          if(!this.form.videoUrl){
            this.$modal.alertWarning('请上传视频');
            return;
          }
        }
          if (this.form.id != null) {
            updateKnowledge(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addKnowledge(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除该数据？')
        .then(function () {
          return delKnowledge(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "gaoqu/knowledge/export",
        {
          ...this.queryParams,
        },
        `knowledge_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
