<template>
  <el-dialog
    :visible.sync="showDialog"
    title="查看设备"
    :modal-append-to-body="false"
    :modal="true"
    style="text-align:left;"
    @close="closeDialog"
    width="60%"
  >
    <div>
      <!--
      要resetFields起作用，必须配置:model和prop
      -->
      <el-divider></el-divider>
      <el-row class="button-group">
        <el-button
          type="primary"
          size="small"
          plain
          icon="el-icon-circle-plus"
          :disabled="multipleSelection.length==0"
          @click="handleBatchBound"
        >批量绑定</el-button>
      </el-row>
      <el-table
        :data="tableData"
        style="min-height:400px;"
        v-loading="loading"
        stripe
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="disableSelect" width="55"></el-table-column>
        <el-table-column prop="deviceNo" label="设备编号" width="220"></el-table-column>
        <el-table-column prop="aliasName" label="设备名称" width="180"></el-table-column>
        <el-table-column prop="typeN" label="类型" width="120"></el-table-column>
        <el-table-column prop="isBindPerson" label="绑定状态" width="120">
          <template slot-scope="{row}">{{row.isBindPerson ? "已绑定" : "未绑定"}}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <span v-if="!row.isBindPerson">
              <el-button size="mini" type="success" @click="handleBound(row)">绑定设备</el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="pageIndex"
        :total="totalElements"
        :page-sizes="pageSizeList"
        @current-change="changePage"
        @size-change="pageSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
      <personDeviceRelation-detail
        v-if="showModal"
        :businessKey="businessKey"
        :title="modalTitle"
        @close="onDetailModalClose"
      ></personDeviceRelation-detail>
    </div>
  </el-dialog>
</template>
<script>
import Constant from "@/constant";
import PersonDeviceRelationDetail from "./personDeviceRelation-detail";
import personDeviceRelationApi from "@/api/base/personDeviceRelation";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

export default {
  props: ["personId"],
  data() {
    var self = this;

    return {
      formModel: {},
      queryModel: {
        deviceId: "",
        personId: ""
      },
      loading: false,
      tableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalPages: 0,
      totalElements: 0,
      field: "",
      direction: "",
      pageSizeList: [10, 20, 30],
      multipleSelection: [],
      showModal: false,
      modalTitle: "",
      showDialog: true
    };
  },
  methods: {
    closeDialog() {
      this.$emit("close", false);
    },
    disableSelect(row, rowIndex) {
      //多选按钮是否禁用
      if (row.isBindPerson) {
        return false;
      } else {
        return true;
      }
    },
    changePage(pageIndex) {
      var self = this;

      self.loading = true;

      self.pageIndex = pageIndex;
      var formData = new FormData();

      formData.append("pageIndex", self.pageIndex);
      formData.append("pageSize", self.pageSize);

      formData.append("personId", self.personId);

      if (this.field != null) {
        formData.append("field", this.field);
      }

      if (this.direction != null) {
        formData.append("direction", this.direction);
      }

      personDeviceRelationApi
        .isUnbindDeviceList(formData)
        .then(function(response) {
          self.loading = false;
          
          var jsonData = response.data.data;

          self.tableData = jsonData.data;
          self.totalPages = jsonData.totalPages;
          self.totalElements = jsonData.recordsTotal;
        })
        .catch(error => {
          self.loading = false;
          // self.$message.error(error + "");
        });
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
    },
    sortChange(data) {
      this.field = data.column.field;
      this.direction = data.order;

      this.changePage(this.pageIndex);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    handleBound(record) {
      var self = this;
      // this.$confirm("是否绑定？", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      //   distinguishCancelAndClose: true
      // })
      //   .then(() => {
      if(confirm("是否绑定？")){
        self.formModel.personId = self.personId;
        self.formModel.deviceId = record.id;

        self.loading = true;

        return personDeviceRelationApi
          .add(self.formModel)
          .then(function(response) {
            self.loading = false;

            var jsonData = response.data;
            self.changePage(self.pageIndex);
            if (jsonData.result) {
              self.$message({
                message: "绑定成功!",
                type: "success"
              });
            } else {
              self.$message({
                message: jsonData.message + "",
                type: "warning"
              });
            }
          });
        }
        // })
        // .catch(error => {
        //   self.loading = false;
        //   // self.$message.error(error + "");
        // });
    },
    handleBatchBound() {
      var self = this;
      self.loading = true;
      var idList = this.multipleSelection.map(record => {
        return record.id;
      });

      this.$confirm("是否绑定选中项？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        distinguishCancelAndClose: true
      })
        .then(() => {
          var formData = new FormData();

          formData.append("personId", self.personId);
          formData.append("devices", idList);

          personDeviceRelationApi
            .batchBindDevice(formData)
            .then(function(response) {
              var jsonData = response.data;
              self.changePage(self.pageIndex);
              if (jsonData.result) {
                self.$message({
                  type: "success",
                  message: "绑定成功!"
                });
              } else {
                self.$message({
                  type: "error",
                  message: jsonData.message
                });
              }
            });
        })
        .catch(error => {
          self.loading = false;
          // self.$message.error(error + "");
        });
    },
    onDetailModalClose(refreshed) {
      //保存成功后回调
      this.showModal = false;

      if (refreshed) {
        this.changePage(this.pageIndex);
      }
    }
  },
  mounted: function() {
    this.changePage(1);
  },
  components: {
    "personDeviceRelation-detail": PersonDeviceRelationDetail
  }
};
</script>
<style lang="scss" scoped>
.el-breadcrumb {
  margin: 10px;
  line-height: 20px;
}

.el-divider {
  margin: 5px 0;
}

.demo-form-inline {
  margin-left: 10px;
  text-align: left;
}

.button-group {
  margin-left: 10px;
  text-align: left;
}
</style>