<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-input
                  v-model.trim="params.departmentCode"
                  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-col :span="1.5">
            <el-form-item label-width="80px">
              <el-button type="primary" size="mini" icon="el-icon-search" @click="searchList">搜 索</el-button>
              <el-button size="mini" plain icon="el-icon-refresh" @click="resetList">重 置</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <div style="position: absolute;top: 18px;right: 10px;">
          <el-button type="primary" size="mini" icon="el-icon-search" @click="searchList">搜 索</el-button>
          <el-button size="mini" plain icon="el-icon-refresh" @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
          field="parameters"
          title="参数"
        >
          <template slot-scope="scope">
            <span v-html="showData(scope.row.parameters, params.parameters)"></span>
          </template>
        </ux-table-column>
        <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: '',
        departmentCode: '',
        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: "departmentCode", 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: {
    showData(val, searchData) {
        // 不区分大小写  const Reg = new RegExp(searchData, 'i');
        // 全局替换  const Reg = new RegExp(searchData, 'g');
        const Reg = new RegExp(searchData, 'ig');
        if (val) {
            // 注意 这里推荐使用正则占位符$& 不使用${searchData}  因为当这里使用正则表达式（i）不区分大小写时，如果你的文本是大写，搜索的关键字是小写，匹配结果会替换掉大写的文本
            // const res = val.replace(Reg, `<span style="background-color: yellow;">${searchData}</span>`);
            const res = val.replace(Reg, `<span style="background-color: yellow;">$&</span>`);
            return res;
        }
    },
    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
        }
      })
    },
    // 新增
    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: '',
        departmentCode: '',
        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;
}
</style>