<template>
  <div>
    <!-- 表单查询项 -->
    <div class="headerbox">
      <el-form ref="queryForm" :model="queryParams" size="small" label-width="100px">
        <el-row>
          <el-col :span="5">
            <el-form-item label="文件名称" prop="name" style="width: 100%;">
              <el-input v-model="queryParams.name" placeholder="请输入文件名称" :fetch-suggestions="querySearchAsync"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="文件类型" prop="lx">
              <el-select v-model="queryParams.lx" placeholder="请选择文件类型">
                <el-option v-for="dict in dict.type.wjlx" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="medium" @click="handleQuery">查询</el-button>
              <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 表格内容区 -->
    <div class="tablebox">
      <!-- 导出行 -->
      <div class="tablebtntwo">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="medium" @click="handleAdd">新增</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-download" size="medium" @click="handleImport">导入</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
        <el-table-column label="文件名称" align="center" prop="name" />
        <el-table-column label="类型" align="center">
          <template slot-scope="scope">
            <a v-if="scope.row.lx === '3'" :href="scope.row.wz" target="_blank"
              style="color: #409EFF; text-decoration: underline;">
              <dict-tag :options="dict.type.wjlx" :value="scope.row.lx" />
            </a>
            <span v-else>
              <dict-tag :options="dict.type.wjlx" :value="scope.row.lx" />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="附件" align="center" prop="fj">
          <template slot-scope="scope">
            {{ getFileName(scope.row.fj) || "未上传" }}
          </template>
        </el-table-column>
        <el-table-column label="上传用户" align="center" prop="scyh" />
        <el-table-column label="上传时间" align="center" prop="scsj" :formatter="dateFormat" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="medium" type="text" @click="getInfo(scope.row)">详情</el-button>
            <el-button size="medium" type="text" @click="handleUpdate(scope.row)" style="color: #67c23a">编辑</el-button>
            <el-button size="medium" type="text" @click="handleDelete(scope.row)" style="color: red;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
        @pagination="getList" />
    </div>

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="45rem" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="7rem">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="类型" prop="lx">
          <el-select v-model="form.lx" placeholder="请选择文件类型" style="width: 100%;" @change="handleTypeChange">
            <el-option v-for="dict in dict.type.wjlx" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 文件类型是网络信息 -->
        <el-form-item v-if="form.lx === '3'" label="网址" prop="wz">
          <el-input v-model="form.wz" placeholder="请输入网址" class="input-with-select">
            <template slot="prepend">
              <el-select v-model="select" style="width: 5.7rem;" @change="handleProtocolChange">
                <el-option label="http" value="http"></el-option>
                <el-option label="https" value="https"></el-option>
              </el-select>
              <span class="wangzhispan">://</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="上传用户" prop="scyh">
          <el-input v-model="form.scyh" placeholder="请输入上传用户" />
        </el-form-item>
        <el-form-item label="上传时间" prop="scsj">
          <el-date-picker v-model="form.scsj" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item v-if="form.lx !== '3'" label="附件" prop="fj">
          <fileload v-model="form.fj"></fileload>
        </el-form-item>
        <el-form-item v-if="form.lx === '3'" label="附件" prop="fj">
          <fileload v-model="form.fj"></fileload>
        </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>

    <!-- 详情项目对话框 -->
    <el-dialog :title="title" :visible.sync="detailOpen" width="40rem" append-to-body>
      <el-form ref="detailForm" :model="detailForm" label-width="7rem" :disabled="true">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="detailForm.name" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="类型" prop="lx">
          <el-select v-model="detailForm.lx" placeholder="请选择文件类型" style="width: 100%;">
            <el-option v-for="dict in dict.type.wjlx" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="detailForm.lx === '3'" label="网址" prop="wz">
          <el-input v-model="detailForm.wz" placeholder="wz" readonly />
        </el-form-item>
        <el-form-item label="上传用户" prop="scyh">
          <el-input v-model="detailForm.scyh" placeholder="请输入上传用户" />
        </el-form-item>
        <el-form-item label="上传时间" prop="scsj">
          <el-date-picker v-model="detailForm.scsj" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="附件" prop="fj">
          <el-input v-model="detailForm.fj" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">取消</el-button>
        <el-button @click="detailOpen = false">确定</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getXmzskPage, addXmzsk, updateXmzsk, deleteXmzsk, getXmzskById } from "@/api/ManageApi/index";
import fileload from "@/components/FileUpload/index.vue"

export default {
  dicts: ['wjlx'],
  name: "Xmzsk",
  components: {
    fileload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 目录表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示添加或修改弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        lx: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        lx: undefined,
        fj: undefined,
        scsj: undefined,
        scyh: undefined,
        wz: undefined,
        createBy: undefined,
        createId: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateId: undefined,
        updateTime: undefined
      },
      // 详情表单参数
      detailForm: {
        id: undefined,
        name: undefined,
        lx: undefined,
        fj: undefined,
        scsj: undefined,
        scyh: undefined,
        wz: undefined,
        createBy: undefined,
        createId: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateId: undefined,
        updateTime: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
        lx: [
          { required: true, message: "文件类型不能为空", trigger: "change" }
        ],
        wz: [
          { required: true, message: "网址不能为空", trigger: "change" }
        ],
        scyh: [
          { required: true, message: "上传用户不能为空", trigger: "blur" }
        ],
        scsj: [
          { required: true, message: "上传时间不能为空", trigger: "change" }
        ],
        fj: [
          { required: true, message: "附件不能为空", trigger: "blur" }
        ]
      },
      // 文件类型映射
      // fileTypeMap: {
      //   1: "政策文件",
      //   2: "研究报告",
      //   3: "网络信息",
      //   4: "其他",
      // },
      select: 'http', // 默认协议类型
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "目录导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/gysl/xmzsk/import",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 日期格式化函数
    dateFormat(row, column, cellValue) {
      if (cellValue) {
        const date = new Date(cellValue);
        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}`;
      }
      return '';
    },
    // 获取文件名字
    getFileName(filePath) {
      if (filePath) {
        return filePath.split('/').pop();
      }
      return '';
    },

    querySearchAsync(queryString, cb) {
      let results = [];
      getXmzskPage({ name: queryString }).then(res => {
        res.data.records.forEach(item => {
          results.push({
            value: item.name,
            id: item.id,
          });
        });
      });
      cb(results);
    },
    // 查询目录列表
    getList() {
      this.loading = true;
      getXmzskPage(this.queryParams).then(response => {
        this.postList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(error => {
        console.error('API Request Error:', error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        lx: undefined,
        fj: undefined,
        scsj: undefined,
        scyh: undefined,
        wz: undefined,
        createBy: undefined,
        createId: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateId: undefined,
        updateTime: undefined
      };
      this.select = 'https'; // 重置协议类型
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 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 catalogId = row.id;
      this.form = { ...row };
      this.setProtocolType(this.form.wz); 
      this.$nextTick(() => {
        this.handleTypeChange(); // 确保在 DOM 更新后调用
      });
      this.open = true;
      this.title = "编辑项目知识库";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateXmzsk(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch();
          } else {
            addXmzsk(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => { });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const catalogIds = row.id || this.ids;
      const getFileName = row.name; // 获取 pjys 字段的内容
      this.$modal.confirm(`是否确认删除"${getFileName}"的数据项？`).then(() => {
        return deleteXmzsk([catalogIds]);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 详情按钮操作 */
    getInfo(row) {
      const catalogId = row.id;
      getXmzskById(catalogId).then(response => {
        this.detailForm = { ...response.data };
        this.detailOpen = true;
        this.title = "项目知识库详情";
      }).catch(error => {
        console.error('API Request Error:', error);
      });
    },
    // 设置协议类型
    setProtocolType(url) {
      if (url) {
        if (url.startsWith('https://')) {
          this.select = 'https';
        } else if (url.startsWith('http://')) {
          this.select = 'http';
        } else {
          this.select = 'http';
          this.form.wz = 'http://' + url;
        }
      } else {
        this.select = 'http';
      }
    },
    // 协议类型改变时更新网址
    handleProtocolChange() {
      if (this.form.wz && !this.form.wz.startsWith(this.select + '://')) {
        this.form.wz = this.select + '://' + this.form.wz.replace(/(http|https):\/\//, '');
      }
    },
    // 文件类型改变时重置网址
    handleTypeChange() {
      if (this.form.lx !== '3') {
        this.form.wz = undefined;
        this.select = 'http';
        // 更新 fj 的校验规则
        this.rules.fj[0].required = true;
      } else {
        this.setProtocolType(this.form.wz);
        // 更新 fj 的校验规则
        this.rules.fj[0].required = false;
      }
      // 手动触发表单校验
      this.$refs.form.clearValidate('fj');
    },

    /**导出 */
    //     handleExport() {
    //   this.download(
    //     "/gysl/ml/exportMl",
    //     {
    //       ...this.form,
    //     },
    //     `管理${new Date().getTime()}.xlsx`
    //   );
    // },
    // 导入操作
    handleImport() {
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "/gysl/xmzsk/importTemplate",
        {},
        `知识库导入模板${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>

<style scoped>
.headerbox {
  background-color: #fff;
  border-radius: .5rem;
  padding: 1rem;
  margin: .5rem;
  border: 1px solid #eee;
}

.tablebox {
  background-color: #fff;
  border-radius: .5rem;
  padding: 1rem;
  margin: .5rem;
  border: 1px solid #eee;
}

.tablehead {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.headbtn {
  display: flex;
}

.tablebtntwo {
  margin-top: 1rem;
  margin-bottom: 1rem;
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>