<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.hotelCode"
          placeholder="酒店id"
          clearable
        ></el-input>
      </el-form-item>
      <el-button @click="getDataList()">查询</el-button>
      <el-button
        type="primary"
        @click="
          visible = true;
          addHotels = [];
        "
      >
        导入
      </el-button>
      <el-button
        type="danger"
        @click="deleteHandle()"
        :disabled="dataListSelections.length <= 0"
      >
        批量删除
      </el-button>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
      height="575px"
    >
      <el-table-column type="selection" align="center" width="50">
      </el-table-column>
      <el-table-column align="center" width="80" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.hotelCode)"
            >删除</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="hotelCode"
        label="酒店id"
        align="center"
        width="120"
      >
      </el-table-column>
      <el-table-column prop="hotelName" label="酒店名称"> </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <el-dialog
      title="导入热销酒店"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="handleClose"
    >
      <el-form ref="dataForm" @keyup.enter.native="dataFormSubmit()">
        <el-form-item label="选择导入文件">
          <el-upload
            class="upload-demo"
            action=""
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="1"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :auto-upload="false"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataForm: {
        hotelCode: ""
      },
      me: 0,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addHotels: [],
      visible: false,
      fileList: []
    };
  },
  components: {},
  activated() {
    this.getDataList();
  },
  methods: {
    handleClose() {
      this.addHotels = [];
      this.fileList = [];
    },
    //上传文件时处理方法
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      this.importfxx(this.fileTemp);
    },
    //超出最大上传文件数量时的处理方法
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！"
      });
    },
    //移除文件的操作方法
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    importfxx(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据

      this.file = event.currentTarget.files[0];

      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;

      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        let binary = "";
        const rABS = false; //是否将文件读取为二进制字符串
        const pt = this;
        let wb; //读取完成的数据
        let outdata;
        const reader = new FileReader();
        reader.onload = function(e) {
          const bytes = new Uint8Array(reader.result);
          const length = bytes.byteLength;
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          //此处引入，用于解析excel
          const XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64"
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
          //此处可对数据进行处理
          let arr = [];
          outdata.map(v => {
            arr.push({ hotelCode: v["酒店id"], hotelName: v["酒店名称"] });
          });
          _this.addHotels = arr;
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    // 表单提交
    dataFormSubmit() {
      if (this.addHotels.length == 0) {
        this.$message.warning("请选择导入文件");
        return;
      }
      this.$http({
        url: this.$http.adornUrl("/ht/hotSaleHotel/addHotSaleHotel"),
        method: "post",
        data: this.$http.adornData({
          hotels: this.addHotels
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "导入成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.visible = false;
              this.sizeChangeHandle(1);
            }
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/ht/hotSaleHotel/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          hotelId: this.dataForm.hotelCode
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
          this.me = data.me;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },

    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.hotelCode;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/ht/hotSaleHotel/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    }
  }
};
</script>
<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  /* width: 50%; */
}
</style>
