<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="芯片ID" prop="uId">
        <el-input
          v-model="queryParams.uId"
          placeholder="请输入芯片ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次编码" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入流水号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="硬件条码" prop="devId">
        <el-input
          v-model="queryParams.devId"
          placeholder="请输入硬件条码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="['iot:library: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="['iot:library: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="['iot:library: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="['iot:library:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportCSV"
          v-hasPermi="['iot:library:export']"
          >导出CSV</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="libraryList"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
      @sort-change="sortChange"
    >
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <el-table-column
        type="index"
        label="序号"
        align="center"
        :index="indexFormatter"
        width="80px"
      ></el-table-column>
      <el-table-column label="芯片ID" align="left" prop="uId" />
      <el-table-column label="批次编码" align="left" prop="batchCode" />
      <el-table-column label="硬件条码" align="left" prop="devId" />
      <el-table-column
        label=" 创建时间"
        align="center"
        prop="createTime"
        sortable="custom"
        width="150px"
      />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        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="['iot:library:edit']"
            >修改</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:library: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"
    />

    <!-- 添加或修改硬件数据库对话框 -->
    <div>
      <dialog-template :title="title" :visible="open">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          slot="dialog-center"
          label-width="80px"
        >
          <el-form-item label="芯片ID" prop="uId">
            <el-input v-model="form.uId" placeholder="请输入芯片ID" />
          </el-form-item>
          <el-form-item label="批次" prop="batchId">
            <el-input
              v-model="batchNumber"
              placeholder="点击选择批次"
              @focus="openTableSelectDialog()"
            />
          </el-form-item>
        </el-form>
        <div slot="dialog-footer">
          <el-button type="primary" size="mini" @click="submitForm"
            >确 定</el-button
          >
          <el-button size="mini" @click="cancel">取 消</el-button>
        </div>
      </dialog-template>

      <el-dialog
        title="选择"
        :visible.sync="selectTableShow"
        width="75%"
        top="10vh"
        class="select-table-dialog"
        :close-on-click-modal="false"
      >
        <select-table-wrap
          v-if="selectTableShow"
          :tableOption="tableSelectOption.tableOpt"
          :queryOption="tableSelectOption.queryOpt"
          :tableList="tableSelectOption.tableList"
          @parentGetList="childGetList($event)"
          :otherOption="tableSelectOption.otherOption"
          @returnEvent="returnEvent($event)"
        />

        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="resuleClick"
            >确 定</el-button
          >
          <el-button
            size="mini"
            @click="
              () => {
                selectTableShow = false;
              }
            "
            >取 消</el-button
          >
        </div>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog
        :title="upload.title"
        :visible.sync="upload.open"
        width="400px"
        append-to-body
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="批次" prop="batchId">
            <el-input
              v-model="batchNumber"
              placeholder="点击选择批次"
              @focus="openTableSelectDialog()"
            />
          </el-form-item>
        </el-form>

        <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"
          :data="form"
          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" />是否更新已经存在的硬件数据 -->
            <el-link type="info" style="font-size: 12px" @click="importTemplate"
              >下载模板</el-link
            >
          </div>
          <div class="el-upload__tip" style="color: red" slot="tip">
            提示：仅允许导入“xls”或“xlsx”格式文件！
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="submitFileForm"
            >确 定</el-button
          >
          <el-button size="mini" @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listLibrary,
  getLibrary,
  delLibrary,
  addLibrary,
  updateLibrary,
  exportLibrary,
  exportLibraryCsv,
  importTemplate,
} from "@/api/iot/library";
import { listBatch } from "@/api/iot/batch";
import DialogTemplate from "@/components/DialogTemplate";
import SelectTableWrap from "@/components/SelectTable/index";
import { getToken } from "@/utils/auth";
import { downloadFile } from '@/utils/hciot'

export default {
  name: "Library",
  components: {
    DialogTemplate,
    SelectTableWrap,
  },
  data() {
    return {
      importForm: {
        batchId: "",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/iot/library/importData",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 硬件数据库表格数据
      libraryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uId: null,
        serialNumber: null,
        devId: null,
      },
      batchNumber: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        uId: [
          { required: true, message: "芯片ID不能为空", trigger: "blur" },
          {
            type: "string",
            pattern: /^[A-z 0-9]{16,30}$/,
            message: "格式不正确：[A-z 0-9] 16-30字符",
            trigger: "blur",
          },
        ],
        batchId: [
          { required: true, message: "批次主键不能为空", trigger: "change" },
        ],
      },
      selectResult: {},
      tableSelectOption: {},
      selectTableShow: false,
      differentCodeDicts: null,
      queryVendorList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    // 文件上传中处理
    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(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$refs.upload.submit();
        }
      });
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "批量导入硬件";
      this.form = {
        batchId: ''
      }
      this.batchNumber = ''
      this.upload.open = true;
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    // 菜单状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.differentCodeDicts, row.differentCode);
    },
    // 打开厂商选择窗口 ——表格
    openTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "batch",
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            batchNumber: "",
            batchCode: "",
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0,
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "批次号",
              clearable: true,
              label: "批次号",
              type: "input",
              key: "batchNumber",
              size: "small",
              value: "",
            },
            {
              style: "",
              placeholder: "批次编码",
              clearable: true,
              label: "批次编码",
              type: "input",
              key: "batchCode",
              size: "small",
              value: "",
            },
          ],
        },
        tableOpt: {
          loading: false,
          rowKey: "batchId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "批次号",
              type: "",
              prop: "batchNumber",
              align: "center",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: " 区别编码",
              type: "",
              prop: "differentCode",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: "厂商",
              type: "",
              prop: "batchNumber",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: "批次编码",
              type: "",
              prop: "batchCode",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
          ],
          tableList: {
            type: Array,
          },
        },
        tableList: [],
      };
      this.selectTableShow = true;
    },
    // 查询回调
    childGetList(data) {
      if (data.otherOption.tableType === "batch") {
        this.vendorChildList(data);
      }
    },
    vendorChildList(data) {
      listBatch(Object.assign(data.page, data.param, { selected: 1 })).then(
        (response) => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      this.selectResult = {};
      if (data.type === "dblclick") {
        if (data.otherOption.tableType === "batch") {
          this.form.batchId = data.value.batchId;
          this.batchNumber = data.value.batchNumber;
        }
        this.selectTableShow = false;
      } else if (data.type === "click") {
        if (data.otherOption.tableType === "batch") {
          this.selectResult.batchId = data.value.batchId;
          this.selectResult.batchNumber = data.value.batchNumber;
        }
        this.selectResult.tableType = data.otherOption.tableType;
      }
    },
    // 点击确定按钮
    resuleClick() {
      if (this.selectResult.tableType === "batch") {
        this.form.batchId = this.selectResult.batchId;
        this.batchNumber = this.selectResult.batchNumber;
      }
      this.selectTableShow = false;
    },
    /** 查询硬件数据库列表 */
    getList() {
      this.loading = true;
      listLibrary(this.queryParams).then((response) => {
        this.libraryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        hardwareId: null,
        uId: null,
        batchId: null,
      };
      this.batchNumber = ''
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.hardwareId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加硬件数据库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const hardwareId = row.hardwareId || this.ids;
      getLibrary(hardwareId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改硬件数据库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.hardwareId != null) {
            updateLibrary(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLibrary(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const hardwareIds = row.hardwareId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delLibrary(hardwareIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExportCSV() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有硬件数据库数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportLibraryCsv(queryParams);
        })
        .then((response) => {
          downloadFile(response, '硬件设备数据.csv');
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有硬件数据库数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportLibrary(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
