<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="space_deviceList"
      :default-sort="{prop: 'createTime', order: 'descending'}"
      @sort-change="sortChange"
    >
      <el-table-column type="index" label="序号" align="center" :index="indexFormatter" width="80px"></el-table-column>
      <el-table-column label="设备名称" align="left" width="200px" prop="deviceName" />
      <el-table-column label="所属型号" align="left" prop="modelName" />
      <el-table-column label="设备key" align="left" prop="deviceKey" />
      <el-table-column label="设备类型" align="left" width="120px" prop="deviceTypeName" />
      <el-table-column label="创建时间" sortable="custom" align="center" width="200" prop="createTime" />
      <el-table-column label="操作" width="150" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.deviceType !== 'MINIATURE_BREAKER'"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改空间设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px"></el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择设备"
      :visible.sync="selectTableShow"
      width="75%"
      top="10vh"
      class="select-table-dialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <select-table-wrap
        v-if="selectTableShow"
        :tableOption="tableSelectOption.tableOpt"
        :queryOption="tableSelectOption.queryOpt"
        :tableList="tableSelectOption.tableList"
        @parentGetList="childGetList($event)"
        :otherOption="tableSelectOption.otherOption"
        @returnEvent="returnEvent($event)"
      />

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="() =>{selectTableShow = false}">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSpace_device,
  getSpace_device,
  delSpace_device,
  addSpace_device,
  updateSpace_device,
  exportSpace_device,
  listProjectDevice
} from "@/api/iot/spaceDevice";
import { listSpaceDevice } from "@/api/iot/space";
import SelectTableWrap from "@/components/SelectTable/index";

export default {
  name: "SpaceDeviceWrap",
  props: ["sourceId", "projectId"],
  components: {
    SelectTableWrap
  },
  data() {
    return {
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 空间设备表格数据
      space_deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        spaceId: "",
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    // 打开厂商选择窗口 ——表格
    handleDetails() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "device"
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            deviceName: "",
            modelId: "",
            parentId: 0,
            deviceType: "GATEWAY_CONTROLLER"
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "设备名称",
              clearable: true,
              label: "设备名称",
              type: "input",
              key: "deviceName",
              size: "small",
              value: ""
            }
          ]
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "所属型号",
              type: "",
              prop: "modelName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "设备名称",
              type: "",
              prop: "deviceName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "设备Key",
              type: "",
              prop: "deviceKey",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "设备类型",
              type: "",
              prop: "deviceTypeName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "创建时间",
              type: "time",
              prop: "createTime",
              align: "center",
              width: "180",
              "show-overflow-tooltip": false,
              tempType: "span"
            }
          ],
          tableList: {
            type: Array
          }
        },
        tableList: []
      };
      this.selectTableShow = true;
    },
    childGetList(data) {
      listProjectDevice().then(response => {
        this.tableSelectOption.tableList = response.data;
        // this.tableSelectOption.queryOpt.page.total = Number(response.total);
      });
    },
    returnEvent(data) {
      if (data.type === "dblclick") {
        this.form.deviceId = data.value.deviceId;
        this.submitForm();
      } else if (data.type === "click") {
        this.form.deviceId = data.value.deviceId;
      }
    },

    /** 查询空间设备列表 */
    getList() {
      this.loading = true;
      this.queryParams.spaceId = this.sourceId;
      listSpace_device(this.queryParams).then(response => {
        this.space_deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        spaceId: this.sourceId,
        deviceId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.spaceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.handleDetails();
    },
    /** 提交按钮 */
    submitForm() {
      addSpace_device(this.form).then(response => {
        this.msgSuccess("新增成功");
        this.selectTableShow = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const spaceIds = row.deviceId;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delSpace_device(spaceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有空间设备数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportSpace_device(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
