<template>
  <div class="app-container">
    <div v-if="isShowUpdate">
      <div class="head">
        编辑设备
        <el-button
          type="primary"
          size="mini"
          style="margin-left: 20px"
          @click="back"
          >返回</el-button
        >
      </div>
      <edit-device
        :obj="updateData"
        style="margin-left: 40px"
        @finish="back"
        @back="back"
      />
    </div>
    <div v-show="!isShowUpdate">
      <!-- <addModal ref="addModel" @success="modalSuccess" /> -->
      <uploadModal ref="uploadModal" @finish="modalSuccess(false)" />
      <div class="search-layout" style="margin-bottom: 0px; margin-top: -10px">
        <el-input
          v-model="form.sn"
          placeholder="设备sn"
          style="width: 256px"
          class="filter-item"
        />
        <el-input
          v-model="form.company"
          placeholder="公司名"
          style="width: 256px"
          class="filter-item"
        />
        <el-select
          v-model="form.tenantId"
          class="filter-item"
          placeholder="请选择服务商平台名称"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in merchantLists"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-model="form.sceneId"
          class="filter-item"
          placeholder="请选择场景"
          clearable
        >
          <el-option
            v-for="(item, index) in sceneLists"
            :key="index"
            :label="item.sceneName"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-model="form.mode"
          class="filter-item"
          placeholder="请选择模式"
          clearable
        >
          <el-option
            v-for="(item, index) in modeLists"
            :key="index"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
        <el-select
          v-model="form.userLibId"
          class="filter-item"
          placeholder="请选择⽤户库"
          clearable
        >
          <el-option
            v-for="(item, index) in userlibLists"
            :key="index"
            :label="item.userLibName"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-model="form.status"
          class="filter-item"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="(item, index) in statusLists"
            :key="index"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </div>
      <div class="search-layout">
        <el-button
          class="filter-item"
          style="margin-right: 0"
          type="primary"
          icon="el-icon-search"
          @click="query(1)"
        >
          搜索
        </el-button>
        <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
        >
      </div>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        element-loading-text="加载中..."
        border
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{
              (pagination.page - 1) * pagination.pageSize +
              (scope.$index + 1)
            }}
          </template>
        </el-table-column>
        <el-table-column label="设备sn">
          <template slot-scope="scope">
            {{ scope.row.sn }}
          </template>
        </el-table-column>
        <el-table-column label="公司名称">
          <template slot-scope="scope">
            {{ scope.row.company }}
          </template>
        </el-table-column>
        <el-table-column label="服务商平台名称">
          <template slot-scope="scope">
            {{ scope.row.tenantName }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="设备appId">
        <template slot-scope="scope">
          {{ scope.row.tenantMachineAppId }}
        </template>
      </el-table-column> -->
        <!-- <el-table-column label="商户appId">
        <template slot-scope="scope">
          {{ scope.row.tenantServiceAppId }}
        </template>
      </el-table-column> -->
        <!-- <el-table-column label="商户平台地址">
        <template slot-scope="scope">
          {{ scope.row.tenantServiceAddress }}
        </template>
      </el-table-column> -->
        <el-table-column label="场景名称">
          <template slot-scope="scope">
            {{ scope.row.sceneName }}
          </template>
        </el-table-column>
        <el-table-column label="模式">
          <template slot-scope="scope">
            {{ scope.row.mode | modeFilter }}
          </template>
        </el-table-column>
        <el-table-column label="⽤⼾库名称">
          <template slot-scope="scope">
            {{ scope.row.userLibName }}
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          class-name="status-col"
          width="120"
        >
          <template slot-scope="{ row }">
            <el-tag :type="row.status | statusFilter">
              {{ row.status | statusFilterStr }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="250"
          class-name="small-padding fixed-width"
        >
          <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-button
                v-if="row.status"
                size="mini"
                type="danger"
                @click="handleAuth(row, false)"
                >取消授权</el-button
              >
              <el-button
                v-else
                size="mini"
                type="danger"
                @click="handleAuth(row, true)"
                >获取授权</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="pagination.total"
        :page.sync="pagination.page"
        :limit.sync="pagination.pageSize"
        :page-sizes="pagination.pageSizeOptions"
        :layout="pagination.layout"
        @pagination="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
import EditDevice from "./components/edit";
// import AddModal from './modal/AddModal.vue'
import UploadModal from "./modal/UploadModal.vue";
import tableMixins from "@/mixins/tableMixins";
import { getList, deleteById, autoById, autoCancelById } from "@/api/device";
import { getAllList as getMerchantList } from "@/api/merchant";
import { getList as getSceneList } from "@/api/scene";
import { getList as getUserlibList } from "@/api/userlib";
import Pagination from "@/components/Pagination";

export default {
  components: { Pagination, UploadModal, EditDevice },
  filters: {
    statusFilter(status) {
      return status ? "success" : "info";
    },
    statusFilterStr(status) {
      return status ? "已授权" : "未授权";
    },
    modeFilter(value) {
      if (value === "public") {
        return "开放";
      } else if (value === "close") {
        return "封闭";
      } else if (value === "elasticity") {
        return "弹性";
      } else {
        return "";
      }
    },
  },
  mixins: [tableMixins],
  data() {
    return {
      merchantLists: [],
      sceneLists: [],
      userlibLists: [],
      modeLists: [
        {
          key: "public",
          value: "开放",
        },
        {
          key: "close",
          value: "封闭",
        },
        {
          key: "elasticity",
          value: "弹性",
        },
      ],
      statusLists: [
        {
          key: false,
          value: "未授权",
        },
        {
          key: true,
          value: "已授权",
        },
      ],
      form: {},
      isShowUpdate: false,
      updateData: {},
      pagination:{
        page:1,
        current:1,
      }
    };
  },
  methods: {
    initData() {
      this.getTableList();
      this.getMerchantList();
      this.getSceneList();
      this.getUserlibList();
    },
    getMerchantList() {
      getMerchantList().then((res) => {
        this.merchantLists = res.data;
      });
    },
    getSceneList() {
      getSceneList({ pageNumber: 1, pageSize: 1000 }).then((res) => {
        this.sceneLists = res.data.records;
      });
    },
    getUserlibList() {
      getUserlibList({ pageNumber: 1, pageSize: 1000 }).then((res) => {
        this.userlibLists = res.data.records;
      });
    },
    // 获取表格数据
    async getTableList() {
      this.pagination.current=this.pagination.page
      this.tableLoading = true;
      try {
        const result = await getList(this.getFilterParams());
        this.setDataList(result.data);
      } catch (e) {
        console.log(e);
      } finally {
        this.tableLoading = false;
      }
    },
    // 获取筛选信息
    query(type) {
      if(type){
        this.pagination.page=1
        this.pagination.current=1
      }
      this.clearPageParams();
      this.getTableList();
    },
    // 增加筛选条件
    transformFilterForm() {
      return {
        sn: this.form.sn || null,
        company: this.form.company || null,
        tenantId: this.form.tenantId || null,
        sceneId: this.form.sceneId || null,
        mode: this.form.mode || null,
        userLibId: this.form.userLibId || null,
        status: this.form.status === "" ? null : this.form.status,
      };
    },
    // 下载模板
    download() {
      window.location.href =
        process.env.VUE_APP_BASE_API + "/static/deviceListExcel.xlsx";
    },
    addOrUpdate() {
      this.$refs.uploadModal.open();
    },
    modalSuccess(isEdit) {
      if (!isEdit) {
        this.clearPageParams();
      }
      this.getTableList();
    },
    handleCreate() {
      // this.$refs.addModel.open()
      this.$router.push({ path: "/device/add" });
    },
    handleUpdate(row) {
      this.isShowUpdate = true;
      this.updateData = JSON.parse(JSON.stringify(row));
      // this.$refs.addModel.open(Object.assign({}, row))
      // this.$router.push({
      //   path: "/device/change",
      //   query: { obj: encodeURIComponent(JSON.stringify(row)) },
      // });
    },
    back() {
      this.isShowUpdate=false
      this.query()
    },
    handleAuth(row, needAuth) {
      const that = this;
      this.$confirm(
        `确定 ${needAuth ? "获取授权" : "取消授权"} 操作吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showClose: false,
          type: "warning",
          beforeClose: async (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.cancelButtonLoading = true;
              instance.confirmButtonText = "提交中...";
              try {
                if (needAuth) {
                  await autoById(row.id);
                } else {
                  await autoCancelById(row.id);
                }
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                that.getTableList();
              } catch (e) {
                // this.$message({
                //   type: 'error',
                //   message: '删除失败!'
                // })
              } finally {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                  instance.cancelButtonLoading = false;
                }, 300);
              }
            } else {
              done();
            }
          },
        }
      )
        .then(() => {})
        .catch(() => {});
    },
    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 deleteById(row.id);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              that.getTableList();
            } catch (e) {
              // this.$message({
              //   type: 'error',
              //   message: '删除失败!'
              // })
            } finally {
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
                instance.cancelButtonLoading = false;
              }, 300);
            }
          } else {
            done();
          }
        },
      })
        .then(() => {})
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.search-layout {
  margin-bottom: 20px;
}
.search-layout .filter-item {
  margin-right: 20px;
  margin-top: 10px;
}
.search-layout .filter-item:last-of-type {
  margin-right: 0;
}
.head {
  margin-left: 16px;
  font-weight: 600;
  font-size: 18px;
  color: #333333;
}
</style>
