<template>
  <div id="equipmentData">
    <div v-if="isList">
      <el-card
        v-loading="loading"
        style="position: relative;"
      >
      <!-- <span>设备产品数据库</span> -->
      <el-form class="search_area" label-width="auto">
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-form-item label="通用名称">
                <el-input
                  v-model.trim="params.commonName"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="注册名">
                <el-input
                  v-model.trim="params.registrationName"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="厂家名称">
                <el-input
                  v-model.trim="params.factoryName"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="型号">
                <el-input
                  v-model.trim="params.model"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="参考价格">
                <el-input
                  v-model.trim="params.referencePrice"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="设备类别">
                <el-input
                  v-model.trim="params.deviceCategory"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="是否项目/厂家年度授权">
                <el-select clearable v-model="params.isProjectOrFactoryEmpower" size="mini" style="width: 200px">
                  <el-option v-for="dict in dict.type.sys_equipment_type" :key="dict.value" :label="dict.label" :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="参数">
                <el-input
                  v-model.trim="params.parameters"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="备注">
                <el-input
                  v-model.trim="params.remark"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>
        </el-row>

        <div style="position: absolute;top: 18px;right: 10px;">
          <el-button type="primary" size="mini" @click="searchList">搜索</el-button>
          <el-button size="mini" plain @click="resetList">重置</el-button>
        </div>
      </el-form>

      <div class="btn_grooup">
        <el-button type="primary" size="mini" @click="addDivision">新增</el-button>
        <el-button type="primary" size="mini" @click="delItems">删除</el-button>
        <el-button type="primary" size="mini" @click="downLoadMb">下载模板</el-button>
        <el-button type="primary" size="mini" @click="upload.open = true">导入数据</el-button>
        <el-button type="primary" size="mini" @click="exportData">导出数据</el-button>
      </div>
      <el-super-ux-table
        id="data-table"
        v-model="tableData"
        index
        checkbox
        :size="size"
        :dict="dict"
        :page="pageInfo"
        :height=500
        :columns="TableColumns"
        pagination
        convenitentOperation
        storage-key="equipmentDataSuperTable"
        @row-dblclick="useSee"
        @row-select="useSelect"
        @selection-change="handleSelectionChange"
        @row-click="rowSelect"
        @pagination="useQuery(params, pageInfo)"
        ref="tables"
      >
        <ux-table-column
          fixed="right"
          title="操作"
          align="center"
          width="100"
          >
          <template slot-scope="scope">
            <!-- <el-button type="text" size="mini" v-if="scope.row.status == '1' && scope.row.flowId" @click="reback(scope.row)">收回</el-button> -->
            <el-button type="text" size="mini" @click="check(scope.row)">查看</el-button>
            <el-button type="text" size="mini" @click="delItem(scope.row)">删除</el-button>
          </template>
        </ux-table-column>
      </el-super-ux-table>
      </el-card>
    </div>

    <Add v-model="isList" v-if="!isList" :pageStu="page" :disable="disable" :row="rowDetail" @refresh="searchList"/>

    <!-- 用户导入对话框 -->
    <el-dialog title="数据导入" :visible.sync="upload.open" width="400px">
      <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"
      :on-error="errorFile"
      :auto-upload="false"
      drag
      >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <!-- <div class="el-upload__tip" slot="tip">
        <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
      </div> -->
      <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer">
      <el-button size="mini" type="primary" @click="submitFileForm">确 定</el-button>
      <el-button size="mini" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入的token
import { getToken } from "@/utils/auth";
import { getEquipmentDataList, downLoadMb, deleteEquipments, exportEquipments} from '@/api/purchase/equipmentData.js'
export default {
  name: "equipmentData",
  dicts: ['sys_equipment_type'],
  components: {
    Add: () => import("./add.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
  },
  data() {
    return {
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "数据导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 1,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/device/origin/importData"
      },
      // 页面配置
      isList: true,
      // 页面状态
      page: '',
      disable: false,
      rowDetail: {},
      size: "mini",
      loading: false,
      params: {
        commonName: '',
        registrationName: '',
        deviceCategory: '',
        factoryName: '',
        model: '',
        referencePrice: '',
        parameters: '',
        isDeleteFile: '',
        isProjectOrFactoryEmpower: '',
        remark: ''
      },
      pageInfo: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      tableData: [],
      selectData: [],
      // SearchColumns: SearchColumns,
      TableColumns: [
        { item: { key: "commonName", title: "通用名称" }, attr: {} },
        { item: { key: "registrationName", title: "注册名" }, attr: {} },
        { item: { key: "deviceCategory", title: "设备类别" }, attr: {} },
        { item: { key: "factoryName", title: "厂家名称" }, attr: {} },
        { item: { key: "model", title: "型号"}, attr: {} },
        { item: { key: "referencePrice", title: "参考价格" }, attr: {} },
        { item: { key: "isProjectOrFactoryEmpower", title: "是否项目/厂家年度授权" }, attr: {is: "el-dict-tag", dictName: "sys_equipment_type"} },
        { item: { key: "parameters", title: "参数" }, attr: {} },
        { item: { key: "remark", title: "备注"}, attr: {} },
      ].map(({ item, attr }) => ({
      attr,
      item: {
        ...item,
        sortabled: true,
        fixedabled: true,
        filterabled: true,
        hiddenabled: true,
      },
      })),
      ids: []
    }
  },
  created() {
    this.useQuery(this.params, this.pageInfo)
  },
  methods: {
    useSee() {},
    useSelect() {},
    handleSelectionChange(selection) {
      console.log('选中', selection)
      this.ids = selection.map(item => item.id)
      console.log('选中数组', this.ids)
    },
    rowSelect(row) {
      this.$refs.tables.toggleRowSelection([{row: row}]);
    },
    // 加载列表
    async useQuery(prop, page) {
      let params = {...prop, ...page}
      await getEquipmentDataList(params).then(res => {
        if( res.code === 200 ) {
          this.tableData = res.rows
          this.pageInfo.total = res.total
        }
      })
      // 获取搜索框和表格元素
      const searchInput = this.params.parameters;
      const table = document.querySelector('#data-table'); 
      // 监听搜索框输入事件
      // searchInput.addEventListener('input', () => {
      // 获取搜索关键字
      const keyword = searchInput; 
      // 如果搜索关键字为空，移除所有高亮样式
      if (!keyword) {
        table.querySelectorAll('.highlight').forEach(el => {
          el.classList.remove('highlight');
        });
        return;
      } 
      // 遍历表格中的每个单元格
      table.querySelectorAll('td').forEach(td => {
        console.log('td',td)
        // 获取单元格文本内容
        const cellText = td.innerHTML.trim().toLowerCase();

        // 如果单元格内容包含搜索关键字，添加高亮样式
        if (cellText.includes(keyword)) {
          // 将匹配到的关键字替换为带有高亮样式的文本
          const highlightedText = cellText.replace(new RegExp(keyword, 'gi'), match => `<span class="highlight">${match}</span>`);
          td.innerHTML = highlightedText;
        } else {
          // 移除高亮样式
          td.innerHTML = cellText;
        }
      });
      // });
    },
    // 新增
    addDivision() {
      this.isList = false
      this.page = 'add'
      this.disable = false
    },
    delItems() {
      if (this.ids.length <= 0) {
        this.$modal.notifyWarning("至少勾选一条数据");
      } else {
        deleteEquipments(this.ids).then(res => {
          if(res.code === 200) {
            this.$modal.notifySuccess("删除成功");
            this.useQuery(this.params, this.pageInfo)
          }
       })
      }
    },
    // 下载模板
    async downLoadMb() {
      this.$modal.loading("正在下载模板，请稍后...");
      downLoadMb().then(res => {
        this.$modal.closeLoading();
        const blob = new Blob([res], {
          type: "application/vnd.ms-excel;charset=UTF-8",
        });// 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
        const downloadElement = document.createElement("a"); //创建a标签
        const href = window.URL.createObjectURL(blob); // 创建下载的链接
        // var temp = res.headers["content-disposition"]; 
        // var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码）
        // var name = fileName.split(";")[0]; //切割成文件名
        downloadElement.href = href;  //下载地址
        downloadElement.download = '设备产品数据库模板'+ this.parseTime(new Date().getTime()) + ".xlsx"; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放blob对象
        this.download.open = false
      }).catch(err => {
        this.$modal.closeLoading();
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.$modal.loading("正在导入数据，请稍后...");
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.$modal.closeLoading();
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.useQuery(this.params, this.pageInfo)
    },
    errorFile(err) {
      this.$modal.closeLoading();
      this.$modal.notifyError("文件已变动，请重新上传");
    },
        // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    searchList() {
      this.useQuery(this.params, this.pageInfo)
    },
    resetList() {
      this.params = {
        commonName: '',
        registrationName: '',
        deviceCategory: '',
        factoryName: '',
        model: '',
        referencePrice: '',
        parameters: '',
        isDeleteFile: '',
        isProjectOrFactoryEmpower: '',
        remark: ''
      }
      this.useQuery(this.params, this.pageInfo)
    },
    check(row) {
      this.isList = false
      this.page = 'check'
      this.rowDetail = row
      this.disable = true
    },
    delItem(row) {
      console.log(row)
      const param = [row.id]
      deleteEquipments(param).then(res => {
        if(res.code === 200) {
          this.$modal.notifySuccess("删除成功");
          this.useQuery(this.params, this.pageInfo)
        }
      })
    },
    // 导出
    exportData() {
      this.$modal.loading("正在导出数据，请稍后...");
      exportEquipments(this.params).then(res => {
        this.$modal.closeLoading();
        const blob = new Blob([res], {
          type: "application/vnd.ms-excel;charset=UTF-8",
        });// 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
        const downloadElement = document.createElement("a"); //创建a标签
        const href = window.URL.createObjectURL(blob); // 创建下载的链接
        // var temp = res.headers["content-disposition"]; 
        // var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码）
        // var name = fileName.split(";")[0]; //切割成文件名
        downloadElement.href = href;  //下载地址
        downloadElement.download = '设备产品数据导出' + this.parseTime(new Date().getTime()) + ".xlsx"; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放blob对象
      }).catch(err => {
        this.$modal.closeLoading();
      })
    },
  }
}
</script>

<style lang="scss" scoped>
#equipmentData {
  padding: 12px;
  box-sizing: border-box;
  overflow-y: scroll;
}
.btn_grooup {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}
::v-deep .highlight {
  background: yellow !important;
}
</style>