<template>
  <div>
    <div class="search_header">
      <div class="search_left">
        <Select
          v-model="searchForm.regionid"
          :transfer="true"
          @on-change="searchList()"
          style="margin-right: 16px; width: 150px"
        >
          <Option :value="0">所有区域</Option>
          <Option
            v-for="regionItem in searchForm.regionList"
            :value="regionItem.regionid"
            :key="regionItem.regionid"
            >{{ regionItem.regionName }}</Option
          >
        </Select>
        <DatePicker
          v-model="searchForm.dataRange"
          @on-change="searchList()"
          :transfer="true"
          type="daterange"
          placeholder="请选择年月日进行搜索"
          style="width: 220px"
        ></DatePicker>
      </div>
      <div class="search_right">
        <Button type="primary" class="primary_btn" @click="toImport()"
          >导入</Button
        >
      </div>
    </div>
    <div class="table_wrap">
      <Table :columns="columns" :data="searchForm.list">
        <template slot-scope="{ row }" slot="actionSlot">
          <div class="action_list">
            <div @click="toView(row)">查看</div>
            <div class="action_del" @click="toDel(row)">删除</div>
          </div>
        </template>
      </Table>
    </div>
    <div class="page_wrap">
      <Page
        :transfer="true"
        :total="searchForm.total"
        :current="searchForm.page"
        :page-size="searchForm.size"
        :page-size-opts="[10, 20, 40, 60]"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange"
        show-total
        show-sizer
      ></Page>
    </div>
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="importInfo.show"
      title="导入"
    >
      <Form
        v-if="importInfo.show"
        ref="importForm"
        :model="importInfo"
        :rules="rules"
        :label-width="100"
      >
        <FormItem label="所属区域" prop="regionid">
          <Select
            :transfer="true"
            v-model="importInfo.regionid"
            placeholder="请选择所属区域"
          >
            <Option
              v-for="regionItem in searchForm.regionList"
              :value="regionItem.regionid"
              :key="regionItem.regionid"
              >{{ regionItem.regionName }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="上传文件" class="require">
          <div style="display: flex">
            <Upload
              action
              :show-upload-list="false"
              :before-upload="
                (file) => {
                  upLoadExcel(file);
                  return false;
                }
              "
              accept=".xlsx,.xls"
            >
              <Button type="primary" class="primary_btn">上传excel</Button>
            </Upload>
            <div style="margin-left: 16px; color: #7c8db5">
              支持格式：xlsx/xls文件
              <span
                style="margin-left: 16px; color: #339dff; cursor: pointer"
                @click="toDownloadTemplate()"
                >下载设备导入模板</span
              >
            </div>
          </div>
          <div v-if="importInfo.file">{{ importInfo.file.name }}</div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="importInfo.show = false">取消</Button>
        <Button @click="saveFileInfo()" type="primary" class="primary_btn"
          >保存</Button
        >
      </div>
    </Modal>
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="viewInfo.show"
      title="查看"
    >
      <div class="view_title">{{ viewInfo.regionName }}</div>
      <div class="view_main">
        <div
          class="sn_item"
          v-for="(snItem, snIndex) in viewInfo.snList"
          :key="snIndex"
        >
          {{ snItem }}
        </div>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="viewInfo.show = false">关闭</Button>
      </div>
    </Modal>
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="importErrorInfo.show"
      title="提示"
    >
      <div
        style="margin-bottom: 16px; font-size: 18px"
        v-if="importErrorInfo.snDuplicate.length > 0"
      >
        以下设备号重复：
      </div>
      <div
        style="margin-bottom: 16px; font-size: 18px"
        v-if="
          importErrorInfo.snDuplicate.length === 0 &&
          importErrorInfo.snExisted.length > 0
        "
      >
        以下设备号已存在：
      </div>
      <div class="view_main" v-if="importErrorInfo.snDuplicate.length > 0">
        <div
          class="sn_item"
          v-for="(snItem, snIndex) in importErrorInfo.snDuplicate"
          :key="snIndex"
        >
          {{ snItem }}
        </div>
      </div>
      <div
        class="view_main"
        v-if="
          importErrorInfo.snDuplicate.length === 0 &&
          importErrorInfo.snExisted.length > 0
        "
      >
        <div
          class="sn_item"
          v-for="(snItem, snIndex) in importErrorInfo.snExisted"
          :key="snIndex"
        >
          {{ snItem }}
        </div>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="importErrorInfo.show = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { region_list_sel_pt } from "@/api/region";
import {
  deviceAuth_list_batch,
  deviceAuth_delete_db,
  deviceAuth_import,
  deviceAuth_list_sn
} from "@/api/device_manager";
import { dateFormat } from "@/utils";
export default {
  data() {
    return {
      dateFormat,
      rules: {
        regionid: [
          {
            required: true,
            type: "number",
            message: "请选择所属区域",
            trigger: "change"
          }
        ]
      },
      searchForm: {
        regionid: 0,
        regionList: [],
        dataRange: [],
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      viewInfo: {
        show: false,
        regionName: null,
        snList: []
      },
      importInfo: {
        show: false,
        regionid: null,
        file: null
      },
      importErrorInfo: {
        show: false,
        // 重复设备号列表
        snDuplicate: [],
        // 已存在设备号列表
        snExisted: []
      },
      columns: [
        {
          title: "序号",
          align: "center",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.searchForm.page - 1) * this.searchForm.size +
                1
            );
          }
        },
        {
          title: "所属区域",
          key: "regionName",
          align: "center"
        },
        {
          title: "导入时间",
          key: "createtime",
          width: 190,
          align: "center"
        },
        {
          title: "导入数量",
          key: "importNum",
          align: "center"
        },
        {
          title: "操作人",
          key: "updatename",
          align: "center"
        },
        {
          title: "操作时间",
          key: "updatetime",
          width: 190,
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 130,
          align: "center"
        }
      ]
    };
  },
  created() {
    this.getRegionList();
    this.searchList();
  },
  computed: {
    powerParams() {
      return this.$store.getters.powerParams;
    }
  },
  methods: {
    // 下载模板
    toDownloadTemplate() {
      let url = "/doc/设备导入.xlsx";
      let elementIftrame = document.createElement("iframe");
      elementIftrame.src = url;
      elementIftrame.style.display = "none";
      document.body.appendChild(elementIftrame);
    },
    // 获取搜索区域列表
    getRegionList() {
      region_list_sel_pt({}).then((data) => {
        if (data.code === 0) {
          this.searchForm.regionList = data.obj;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 搜索
    searchList() {
      this.searchForm.page = 1;
      this.getList();
    },
    // 页码改变
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },
    // 每页显示数量改变
    pageSizeChange(size) {
      this.searchForm.size = size;
      this.searchForm.page = 1;
      this.getList();
    },
    // 获取列表
    getList() {
      let _begindate = this.searchForm.dataRange[0];
      _begindate = _begindate ? dateFormat(_begindate, "yyyy-MM-dd") : null;
      let _enddate = this.searchForm.dataRange[1];
      _enddate = _enddate ? dateFormat(_enddate, "yyyy-MM-dd") : null;
      deviceAuth_list_batch({
        rtype: this.powerParams.rtype,
        regionid: this.searchForm.regionid,
        page: this.searchForm.page,
        size: this.searchForm.size,
        begindate: _begindate,
        enddate: _enddate
      }).then((data) => {
        if (data.code === 0) {
          this.searchForm.list = data.obj.data;
          this.searchForm.total = data.obj.total;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    toImport() {
      this.importInfo = {
        show: true,
        regionid: null,
        file: null
      };
    },
    upLoadExcel(file) {
      this.importInfo.file = null;
      let str = file.name.split(".");
      let suffix = str[str.length - 1];
      suffix = suffix.toLowerCase();
      if (suffix !== "xlsx" && suffix !== "xls") {
        this.$Message.warning("文件格式不正确");
        return;
      }
      this.importInfo.file = file;
    },
    saveFileInfo() {
      this.$refs.importForm.validate((valid) => {
        if (valid) {
          if (!this.importInfo.file) {
            this.$Message.error("请上传文件");
            return;
          }
          this.importInfo.show = false;
          let formData = new FormData();
          formData.append("file", this.importInfo.file);
          formData.append("regionid", this.importInfo.regionid);
          deviceAuth_import(formData).then((data) => {
            if (data.code === 0) {
              if (data.obj.code === 1) {
                this.importErrorInfo = {
                  show: true,
                  // 重复设备号列表
                  snDuplicate: data.obj.snDuplicate || [],
                  // 已存在设备号列表
                  snExisted: data.obj.snExisted || []
                };
              } else {
                this.searchList();
                this.$Message.success(data.msg);
              }
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    toView(row) {
      this.viewInfo = {
        show: true,
        regionName: row.regionName,
        snList: []
      };
      deviceAuth_list_sn({
        dbid: row.dbid
      }).then((data) => {
        if (data.code === 0) {
          this.viewInfo.snList = data.obj;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 删除
    toDel(row) {
      this.$Modal.confirm({
        title: "提示",
        content: `您确定要批量删除 ${row.importNum} 条数据吗？`,
        onOk: () => {
          deviceAuth_delete_db({
            rtype: this.powerParams.rtype,
            dbid: row.dbid
          }).then((data) => {
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        },
        onCancel: () => {}
      });
    }
  }
};
</script>

<style lang="less" scoped>
.search_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 16px;
  .search_left {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .search_right {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .primary_btn {
      margin-left: 16px;
    }
  }
}
.view_title {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}
.view_main {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  .sn_item {
    margin-top: -1px;
    margin-left: -1px;
    padding: 0 4px;
    width: 25%;
    font-size: 16px;
    line-height: 30px;
    text-align: center;
    word-break: break-all;
    border: 1px solid #ced9f2;
  }
}
</style>
