<template>
  <div class="app-container">
    <addModal ref="addModel" @success="modalSuccess" />
    <div class="search-layout">
      <el-button
        class="filter-item"
        style="margin-right: 0"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加配置
      </el-button>
      <el-button type="primary" icon="el-icon-download" @click="download"
        >下载模板</el-button
      >
      <!-- <el-button type="primary" plain @click="addOrUpdate">批量导入</el-button> -->
      <a href="javascript:;" class="file"
        >批量导入
        <input type="file" name="file" ref="file" @change="uploadFun($event)"
      /></a>
      <el-input
        clearable
        v-model="form.address"
        placeholder="请输入设备地点"
        class="input"
      />
      <el-input
        clearable
        v-model="form.sn"
        placeholder="请输入设备sn"
        class="input"
      />
      <el-select
        v-model="form.handleProveId"
        class="input"
        placeholder="请选择标题"
        clearable
        filterable
      >
        <el-option
          v-for="(item, index) in option"
          :key="index"
          :label="item.handleProveTitle"
          :value="item.id"
        />
      </el-select>
      <el-date-picker
        v-model="form.startTime"
        type="datetime"
        placeholder="选择起始时间"
        value-format="yyyy-MM-dd HH:mm:ss"
        class="filter-item input"
      >
      </el-date-picker>
      <el-date-picker
        v-model="form.endTime"
        type="datetime"
        placeholder="选择结束时间"
        value-format="yyyy-MM-dd HH:mm:ss"
        class="filter-item wid"
      >
      </el-date-picker>
      <!-- <el-date-picker
        v-model="form.date"
        value-format="yyyy-MM-dd"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item wid picker-left"
      >
      </el-date-picker> -->
      <el-button
        class="filter-item"
        type="primary"
        style="margin-left: 10px"
        icon="el-icon-search"
        @click="query"
      >
        搜索
      </el-button>
    </div>
    <!-- 主体表格 -->
    <el-table
      :data="tableData"
      border
      fit
      highlight-current-row
      class="table"
      v-loading="loading"
    >
      <el-table-column align="center" width="80" label="序号">
        <template v-slot="scope">
          {{
            (pagination.current - 1) * pagination.pageSize + (scope.$index + 1)
          }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="address" label="winds终端地点">
      </el-table-column>
      <el-table-column align="center" prop="sn" label="设备sn">
      </el-table-column>
      <el-table-column align="center" prop="handleProveTitle" label="标题">
      </el-table-column>
      <el-table-column align="center" prop="handleProveNotice" label="须知">
        <template v-slot="{ row }">
          <el-popover width="500" trigger="click">
            <div v-html="row.handleProveNotice"></div>
            <div
              slot="reference"
              class="handle-prove-notice"
              v-html="row.handleProveNotice"
            ></div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="zhang" label="公章">
        <template v-slot="{ row }">
          <el-image
            style="width: 70px; height: 70px"
            :src="row.zhang"
            :preview-src-list="[row.zhang]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="createTime"
        label="创建时间"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column align="center" label="操作区" width="150">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="pagination.total"
      :page.sync="pagination.current"
      :limit.sync="pagination.pageSize"
      :page-sizes="pagination.pageSizeOptions"
      :layout="pagination.layout"
      @pagination="handleSizeChange"
    />
    <el-drawer
      :title="hasCompleted ? '导入已完成' : '正在处理中..'"
      :visible.sync="drawerVisible"
      :wrapperClosable="false"
      size="50%"
      direction="rtl"
    >
      <div style="padding: 50px">
        <div>
          已处理条数；{{ hasDealNumber }}; 待处理条数：{{ waitDealNumber }};
          总共文件数：{{ allNumber }}
        </div>
        <el-progress
          style="margin-top: 10px"
          :percentage="makePercent"
          :format="formatProgress"
        ></el-progress>
        <el-table
          class="table"
          ref="batch_upload_result"
          v-loading="false"
          :data="batchUploadResultList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          height="500"
        >
          <el-table-column label="错误序号" align="center" width="100px">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="文件名" align="center">
            <template slot-scope="scope">
              {{ scope.row.name | matchNull }}
            </template>
          </el-table-column>
          <el-table-column label="错误描述" align="center">
            <template slot-scope="scope">
              {{ scope.row.err | matchNull }}
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center; margin: 20px 0" v-show="hasCompleted">
          <el-button type="primary" @click="drawerVisible = false">
            我已知晓
          </el-button>
          <el-button
            type="warning"
            @click="downloadBatchUploadErrorList"
            v-show="batchUploadResultList.length > 0"
          >
            下载错误列表文件
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import AddModal from "./modal/AddModal.vue";
import tableMixins from "@/mixins/tableMixins";
import { getList, deleteTitleList, setTitleList } from "@/api/devicelib";
import { getSelectData } from "@/api/titlelib";
import Pagination from "@/components/Pagination";
import { readExcel } from "@/utils/getExcelList";
export default {
  components: { Pagination, AddModal },
  filters: {
    matchNull(str) {
      if (!str) {
        return "未填写";
      } else {
        return str;
      }
    },
  },
  mixins: [tableMixins],
  data() {
    return {
      form: {},
      option: [],
      loading: false,
      // 批量导入结果返回
      resultVisible: false,
      result_list: [],
      //批量人员注册-处理提示值
      hasDealNumber: 0,
      waitDealNumber: 0,
      allNumber: 0,
      hasCompleted: false,
      //批量注册人员-抽屉控制值
      drawerVisible: false,
      batchUploadResultList: [],
      batchVisible: false, //批量注册人员-弹框
    };
  },
  methods: {
    initData() {
      this.getTableList();
      this.getSelect();
    },
    getSelect() {
      getSelectData().then((res) => {
        // console.log(res, "数据");
        this.option = res.data;
      });
    },
    // 获取表格数据
    async getTableList() {
      this.loading = true;
      const result = await getList(this.getFilterParams());
      await this.setDataList(result.data);
      // console.log(result);
      this.loading = false;
    },
    // 获取筛选信息
    query() {
      this.clearPageParams();
      this.getTableList();
    },
    transformFilterForm() {
      return {
        address: this.form.address || undefined,
        sn: this.form.sn || undefined,
        handleProveId: this.form.handleProveId || undefined,
        // startTime: this.form?.date[0] || undefined,
        // endTime: this.form?.date[1] || undefined,
        startTime: this.form.startTime || undefined,
        endTime: this.form.endTime || undefined,
      };
    },
    modalSuccess() {
      this.getTableList();
    },
    // 添加配置
    handleCreate() {
      this.$refs.addModel.open();
    },
    // 编辑配置
    handleUpdate(row) {
      console.log(row);
      this.$refs.addModel.open(row);
    },
    // 删除
    handleDelete(row, index) {
      const that = this;
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showClose: false,
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.cancelButtonLoading = true;
            instance.confirmButtonText = "提交中...";
            try {
              await deleteTitleList(row.id);
              that.getTableList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } catch (e) {
            } finally {
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
                instance.cancelButtonLoading = false;
              }, 300);
            }
          } else {
            done();
          }
        },
      })
        .then(() => {})
        .catch(() => {});
    },
    // 下载模版
    download() {
      window.location.href =
        // process.env.VUE_APP_BASE_API + "/static/deviceListExcel.xlsx";
        process.env.VUE_APP_BASE_API + "/static/设备配置列表.xlsx";
    },
    // 批量导入
    // addOrUpdate() {},
    // 批量导入
    async uploadFun(e) {
      console.log(111);
      this.loading = true;
      var files = e.currentTarget.files;
      if (!files.length) {
        return;
      }
      let data = await readExcel(files[0]); //file指的是获取的excel文件对象，如e.file
      let newData = [];
      data.forEach((i) => {
        for (let key in i) {
          if (i[key]) {
            newData.push(i);
            return;
          }
        }
      });
      data = newData;
      this.loading = false;
      this.allNumber = data.length;
      this.drawerVisible = true;
      this.doUploadAddUserInfo(0, data);
      this.$refs.file.value = "";
    },
    // 递归调用校验数据并请求
    async doUploadAddUserInfo(i, data) {
      if (i > data.length - 1) {
        this.hasCompleted = true;
        this.getTableList();
        this.$message.success("导入已完成！");
        return;
      }
      let form = {};
      form.address = data[i]["winds终端地点"];
      form.sn = data[i]["设备sn"];
      form.handleProveTitle = data[i]["标题"];
      form.zhang = data[i]["公章"];
      // console.log(this.form.option);
      // this.option.forEach((item) => {
      //   if (item.handleProveTitle == form.handleProveTitle) {
      //     form.handleProveId = item.id;
      //   }
      // });
      form.handleProveId = this.option.find(
        (item) => item.handleProveTitle == form.handleProveTitle
      ).id ??= null;

      await this.isPassFun(form, i).then(async (res) => {
        let timeout = 0;
        if (res.isOk) {
          await this.addUserInfo(data, form, i);
        } else {
          this.getFileList1(data, i, res, form);
          timeout = 0;
        }
        this.hasDealNumber = i + 1;
        this.waitDealNumber = data.length - (i + 1);
        setTimeout(() => {
          this.doUploadAddUserInfo(++i, data);
        }, timeout);
      });
    },
    // 校验模板数据内容
    async isPassFun(form, i) {
      let isPass = {
        isOk: true,
        incorrect: {
          name: `第${i + 1}行`,
          err: "",
        },
      };
      if (!form.address) {
        isPass.incorrect.err = "winds终端地点为必填项";
        isPass.isOk = false;
        return isPass;
      }
      if (!form.sn) {
        isPass.incorrect.err = "设备sn为必填项";
        isPass.isOk = false;
        return isPass;
      }
      return new Promise((resolve) => {
        resolve(isPass);
      });
    },
    // 批量注册人员-保持滚动条在最底部
    makeScrollDown() {
      this.$nextTick(() => {
        this.$refs.batch_upload_result.$refs.bodyWrapper.scrollTop =
          this.$refs.batch_upload_result.$refs.bodyWrapper.scrollHeight;
      });
    },
    //批量注册人员-返回进度条尾部显示值
    formatProgress(percent) {
      return percent == 100 ? "已完成" : "";
    },
    //批量注册人员-导出错误名单
    downloadBatchUploadErrorList() {
      let list = this.batchUploadResultList;
      let string = "序号\t文件名\t错误原因\n";
      for (let i = 0; i < this.batchUploadResultList.length; i++) {
        string +=
          (i + 1).toString() +
          "\t" +
          list[i].name +
          "\t" +
          list[i].err +
          "\t" +
          "\n";
      }
      let blob = new Blob([string], { type: "text/plain;charset=utf-8" });
      let excel_url = window.URL.createObjectURL(blob);
      let link = document.createElement("a");
      link.href = excel_url;
      link.download = "结果错误名单.xls";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 批量导入-调用添加员工接口
    async addUserInfo(data, form, i) {
      // console.log(form);
      await setTitleList(form)
        .then((res) => {})
        .catch((err) => {
          this.batchUploadResultList.push({ name: `第${i + 1}行`, err: err });
          this.makeScrollDown();
        });
    },
    // 批量导入-推入错误信息
    getFileList1(data, i, isPass) {
      // this.initAddress(this.user_form.contents);
      this.batchUploadResultList.push(isPass.incorrect);
      this.makeScrollDown();
    },
    // 批量编辑
    // batchEditor(e) {
    //   console.log(990128);
    //   var files = e.currentTarget.files;
    //   if (!files.length) {
    //     return;
    //   }
    //   const loading = this.$loading({
    //     lock: true,
    //     text: "拼命导入中...",
    //     spinner: "el-icon-loading",
    //     background: "rgba(0, 0, 0, 0.7)",
    //   });
    //   var formData = new FormData(); // 必需声明一个FormData对象
    //   formData.append("file", files[0]);
    //   editUserWhitelistExcel(formData)
    //     .then((res) => {
    //       loading.close();
    //       this.getTableList();
    //       if (res.data.length > 0) {
    //         this.resultVisible = true;
    //         this.result_list = res.data;
    //       } else {
    //         this.$message({
    //           type: "success",
    //           message: "导入成功!",
    //         });
    //       }
    //     })
    //     .catch((err) => {
    //       loading.close();
    //       this.getTableList();
    //     });
    // },
  },
  watch: {
    drawerVisible(n) {
      if (n) {
        this.batchVisible = false;
      }
    },
  },
  computed: {
    //批量注册人员-返回向下取整，减少渲染次数
    makePercent() {
      console.log(this.hasDealNumber);
      return Math.floor((this.hasDealNumber / this.allNumber) * 100);
    },
  },
};
</script>

<style lang="scss" scoped>
.search-layout {
  margin-bottom: 20px;
  margin-top: -10px;
  .filter-item {
    margin-right: 20px;
    margin-top: 10px;
  }
  .input {
    width: 200px;
    margin-left: 10px;
  }
  .picker-left {
    margin-left: 10px;
  }
}
.search-layout .filter-item:last-of-type {
  margin-right: 0;
}
/*批量导入按钮*/
.file {
  margin: 10px 0 0 10px;
  position: relative;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 10px 20px;
  box-sizing: border-box;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
}
.file input {
  position: absolute;
  font-size: 14px;
  width: 106px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
// .file:hover {
//   background: #aadffd;
//   border-color: #78c3f3;
//   color: #004974;
//   text-decoration: none;
// }
.table {
  margin-top: 15px;
}
.handle-prove-notice {
  width: 100%;
  overflow: hidden;
  max-height: 70px;
  text-overflow: ellipsis;
  /* 弹性伸缩盒子模型显示 */
  display: -webkit-box;
  /* 限制在一个块元素显示的文本的行数 */
  -webkit-line-clamp: 3;
  /* 设置或检索伸缩盒对象的子元素的排列方式 */
  -webkit-box-orient: vertical;
  cursor: pointer;
}
</style>
