<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="infoData && infoData.projectRole !== 'personal'"  icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd" >新增设备</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="deviceList"
      :default-sort="{prop: 'createTime', order: 'descending'}"
      empty-text="分组下暂无设备"
      @sort-change="sortChange"
    >
<!--      <el-table-column :index="indexFormatter" align="center" label="序号" type="index" width="80px"></el-table-column>-->
      <el-table-column type="index" />
      <el-table-column align="left" label="设备key" prop="deviceKey" width="200px" />
      <el-table-column align="left" label="设备名称" prop="deviceName" width="200px" />
      <el-table-column align="left" label="设备类型" prop="deviceTypeName" width="120px" />
      <el-table-column align="center" label="创建时间" prop="createTime" sortable="custom"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="150">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.deviceType !== 'MINIATURE_BREAKER' && infoData && infoData.projectRole !== 'personal'"
            v-hasPermi="['iot:label:edit']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >解绑设备</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="selectTableShow"
      append-to-body
      class="select-table-dialog"
      title="选择设备"
      top="10vh"
      width="75%"
    >
      <select-table-wrap
        v-if="selectTableShow"
        :otherOption="tableSelectOption.otherOption"
        :queryOption="tableSelectOption.queryOpt"
        :tableList="tableSelectOption.tableList"
        :tableOption="tableSelectOption.tableOpt"
        @parentGetList="childGetList($event)"
        @returnEvent="returnEvent($event)"
      />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm(false)">确 定</el-button>
        <el-button size="mini" @click="() =>{selectTableShow = false}">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SelectTableWrap from "@/components/SelectTable/index";
import DialogTemplate from "@/components/DialogTemplate";

import {
  bindProjectGroupDeviceList,
  getProjectGroupDeviceList,
  unbindProjectGroupDeviceList
} from "@/api/tenant/project";

export default {
  name: "DeviceGroupDevice",
  props: [ "projectId", "groupId", "infoData"],
  components: {
    SelectTableWrap,
    DialogTemplate
  },
  data() {
    return {
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 空间设备表格数据
      deviceList: [],
      // 查询参数
      queryParams: {
        groupId: "",
        // 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: "",
            // pageSize: 10,
            // pageNum: 1,
            groupId:this.groupId,
            contains:false
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "请输入设备Key或者设备名称",
              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: "设备Key",
              type: "",
              prop: "deviceKey",
              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: "设备类型",
              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) {
      console.log("data.param",data)
      getProjectGroupDeviceList(data.param).then(response => {
        // this.tableSelectOption.tableList = response.data;
        this.tableSelectOption.tableList = response.rows;
        // this.tableSelectOption.queryOpt.page.total = Number(response.total);
      });
    },
    returnEvent(data) {
      console.log("data",data)
      if (data.type === "dblclick") {
        this.form.deviceKey = data.value.deviceKey;
        this.submitForm(false);
      } else if (data.type === "click") {
        this.form.deviceKey = data.value.deviceKey;
      }
    },

    /** 查询空间设备列表 */
    getList() {
      this.loading = true;
      this.queryParams.groupId = this.groupId;
      getProjectGroupDeviceList(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        groupId:this.groupId,
        deviceKey: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.handleDetails();
    },
    /** 提交按钮 */
    submitForm(flag=false) {
      this.form.force = flag;
      bindProjectGroupDeviceList(this.form).then(res => {
        if (res.code == 200) {
          this.msgSuccess("绑定成功");
          this.selectTableShow = false;
          this.getList();
        }else{
          this.msgError(`设备:${this.form.deviceKey}\n${res.msg}`)
        }
      }).catch(err=>{
        if(err == 'Error: 设备已绑定分组'){
          this.$confirm(`设备:${this.form.deviceKey}已被绑定设备组，是否强制移动到当前设备组`, "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(()=>{
            this.submitForm(true)
          })
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm("确认要解绑设备(" + row.deviceName + ")吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(()=>{
          return unbindProjectGroupDeviceList({ deviceKey: row.deviceKey,groupId:this.groupId});
        })
        .then(() => {
          this.getList();
          this.msgSuccess("解绑成功");
        });
    }
  }
};
</script>
