<template>
  <div class="app-container">
    <addModal ref="addModel" @success="modalSuccess" :buyList="buyList" :applicationList="applicationList" :devicelList="devicelList"/>
    <div style="margin-bottom: 20px">
      <el-button
        class="filter-item m-r"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-input
          v-model="form.sn"
          placeholder="设备sn"
          class="filter-item input m-r"
        />
        <el-select
          v-model="form.purchaserId"
          class="filter-item m-r"
          placeholder="购买方公司"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in buyList"
            :key="index"
            :label="item.companyName"
            :value="item.purchaserId"
          />
        </el-select>
        <el-select
          v-model="form.applicationTypeId"
          class="filter-item m-r"
          placeholder="应用类型"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in applicationList"
            :key="index"
            :label="item.applicationType"
            :value="item.applicationTypeId"
          />
        </el-select>
        <el-select
          v-model="form.deviceModelId"
          class="filter-item m-r"
          placeholder="设备型号"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in devicelList"
            :key="index"
            :label="item.deviceModel"
            :value="item.deviceModelId"
          />
        </el-select>
        <el-select
          v-model="form.status"
          class="filter-item m-r"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="(item, index) in statusLists"
            :key="index"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="query"
      >
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="download"
        >下载模板</el-button
      >
      <UploadModal  @success="modalSuccess"/>
    </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.current - 1) * pagination.pageSize + (scope.$index + 1)
          }}
        </template>
      </el-table-column>
      <el-table-column label="购买方">
        <template slot-scope="scope">
          {{ scope.row.purchaserName }}
        </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.applicationType }}
        </template>
      </el-table-column>
      <el-table-column label="设备型号">
        <template slot-scope="scope">
          {{ scope.row.deviceModel }}
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        class-name="status-col"
        width="100"
      >
        <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="statusChange(row, false)"
              >停用</el-button
            >
            <el-button
              v-else
              size="mini"
              type="danger"
              @click="statusChange(row, true)"
              >授权</el-button
            >
          </template>
        </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"
    />
  </div>
</template>

<script>
import AddModal from "./modal/equipmentAddModal.vue";
import UploadModal from "./modal/UploadModal.vue";
import tableMixins from "@/mixins/tableMixins";
import { devicePage, deviceDisable,deviceEnable, deviceDel } from "@/api/tripartiteApi";
import { deviceModelList, applicationTypeList,purchaserList, } from "@/api/configuration";
import Pagination from "@/components/Pagination";

export default {
  components: { Pagination, AddModal,UploadModal },
  filters: {
    statusFilter(status) {
      return status ? "success" : "info";
    },
    statusFilterStr(status) {
      return status ? "已授权" : "已停用";
    },
  },
  mixins: [tableMixins],
  data() {
    return {
      form: {},
      devicelList: [],
      applicationList:[],
      buyList:[],
      statusLists: [
        {
          key: false,
          value: "未授权",
        },
        {
          key: true,
          value: "已授权",
        },
      ],
    };
  },
  methods: {
    initData() {
      this.getTableList();
      this.deviceModelList();
      this.applicationTypeList();
      this.purchaserList();
    },
    // 获取表格数据
    async getTableList() {
      this.tableLoading = true;
      try {
        const result = await devicePage(this.getFilterParams());
        this.setDataList(result.data);
      } catch (e) {
        console.log(e);
      } finally {
        this.tableLoading = false;
      }
    },
    // 获取筛选信息
    query() {
      this.clearPageParams();
      this.getTableList();
    },
    // 增加筛选条件
    transformFilterForm() {
      return {
        sn: this.form.sn || null,
        purchaserId: this.form.purchaserId || null,
        applicationTypeId: this.form.applicationTypeId || null,
        deviceModelId: this.form.deviceModelId || null,
        status: this.form.status,
      };
    },
    modalSuccess(isEdit) {
      if (!isEdit) {
        this.clearPageParams();
      }
      this.getTableList();
    },
    handleCreate() {
      this.$refs.addModel.open();
    },
    handleUpdate(row) {
      this.$refs.addModel.open(Object.assign({}, row));
    },
    statusChange(row, status) {
      const that = this;
      this.$confirm(
        `确定 ${status ? "启用授权" : "停用授权"} 操作吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showClose: false,
          type: "warning",
          beforeClose: async (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.cancelButtonLoading = true;
              instance.confirmButtonText = "提交中...";
              try {
                if (status) {
                  await deviceEnable(row.id);
                } else {
                  await deviceDisable(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 deviceDel(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(() => {});
    },
    // 下载模板
    download() {
      window.location.href =
        process.env.VUE_APP_BASE_API + "/static/三方API授权设备模板.xls";
    },
     // 设备型号列表
    deviceModelList() {
      deviceModelList().then((res) => {
        this.devicelList = res.data;
      });
    },
     // 获取应用类型列表
    applicationTypeList() {
      applicationTypeList().then((res) => {
        this.applicationList = res.data;
      });
    },
    // 购买方列表
    purchaserList() {
      purchaserList().then((res) => {
        this.buyList = res.data;
      });
    },
  },
};
</script>

<style scoped>
.filter-item{
  margin-bottom: 10px;
}
.m-r{
  margin-right: 10px;
}
.input{
  width: 200px;
}
</style>
