<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">

      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-refresh" plain
                   v-if="permission.elevator_sync"
                   @click="handleSync">同 步
        </el-button>
      </template>

      <template slot="menu" slot-scope="scope">
        <el-button v-if="permission.elevator_bind" icon="el-icon-paperclip" :class="{changeBind: !!scope.row.residentialId}" type="text" @click="showDeviceBind(scope.row)">{{!scope.row.residentialId ? '小区绑定' : '小区改绑'}}</el-button>
      </template>

    </avue-crud>

    <!--    小区列表-->
    <el-dialog :modal-append-to-body="false" append-to-body :visible.sync="bindVisible" title="小区绑定" center width="20%">
      <div style="text-align: center;">
        <el-select v-model="selectValue" filterable placeholder="请选择">
          <el-option v-for="item in residentialList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <p style="margin-top: 20px;">
          <el-button type="primary" icon="el-icon-paperclip" @click="bindResidential">绑定</el-button>
        </p>
      </div>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, sync} from "@/api/device/elevatordevice";
  import {mapGetters} from "vuex";
  import {getAllList} from "@/api/community/residential";

  export default {
    data() {
      return {
        form: {},
        residentialList: [],
        loading: true,
        bindVisible: false,
        settingVisible: false,
        selectValue: '',
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 60,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          editBtn: false,
          delBtn: false,
          addBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "注册编码",
              prop: "registerCode",
              search: true,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "请输入电梯注册编码",
                trigger: "blur"
              }]
            },
            {
              label: "电梯名称",
              prop: "liftName",
              search: true,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "请输入电梯名称",
                trigger: "blur"
              }]
            },
            /*{
              label: "省编码",
              prop: "provinceCode",
              rules: [{
                required: true,
                message: "请输入省编码",
                trigger: "blur"
              }]
            },
            {
              label: "市编码",
              prop: "cityCode",
              rules: [{
                required: true,
                message: "请输入市编码",
                trigger: "blur"
              }]
            },
            {
              label: "区编码",
              prop: "townCode",
              rules: [{
                required: true,
                message: "请输入区编码",
                trigger: "blur"
              }]
            },
            {
              label: "街道编码",
              prop: "streetCode",
              rules: [{
                required: true,
                message: "请输入街道编码",
                trigger: "blur"
              }]
            },*/
            {
              label: "小区名称",
              prop: "nbhdName",
              search: true,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "请输入小区名称",
                trigger: "blur"
              }]
            },
            {
              label: "梯号",
              prop: "elevatorNo",
              rules: [{
                required: true,
                message: "请输入梯号",
                trigger: "blur"
              }]
            },
            {
              label: "楼层数",
              prop: "floorNum",
              rules: [{
                required: true,
                message: "请输入楼层数",
                trigger: "blur"
              }]
            },
            {
              label: "楼号",
              prop: "floorNo",
              hide: true,
              rules: [{
                required: true,
                message: "请输入楼号",
                trigger: "blur"
              }]
            },
            {
              label: "单元号",
              prop: "partNo",
              hide: true,
              rules: [{
                required: true,
                message: "请输入单元号",
                trigger: "blur"
              }]
            },
            {
              label: "云梯状态",
              prop: "ytStatus",
              type: "select",
              search: true,
              searchSpan: 4,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=yt_status",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              rules: [{
                required: true,
                message: "请输入云梯状态{10：云梯处于未上线，安装调试状态，20：云梯处于已上线，正常状态，30：云梯处于故障，维护状态}",
                trigger: "blur"
              }]
            },
            {
              label: "在线状态",
              prop: "onlineStatus",
              type: "select",
              search: true,
              searchSpan: 4,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=yt_online_status",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              rules: [{
                required: true,
                message: "请输入在离线状态{0：离线，1：在线}",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.elevatordevice_add, false),
          viewBtn: this.vaildData(this.permission.elevatordevice_view, false),
          delBtn: this.vaildData(this.permission.elevatordevice_delete, false),
          editBtn: this.vaildData(this.permission.elevatordevice_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleSync(){
        this.loading = true;
        sync().then(() => {
          this.loading = false;
          this.$message({
            type: "success",
            message: "同步成功!"
          });
          this.onLoad(this.page);
        });
      },
      showDeviceBind(row){
        this.selectValue = row.residentialId;
        if (this.residentialList.length == 0){
          //  请求获取小区列表
          getAllList().then(res => {
            this.residentialList = res.data.data;
            this.bindVisible = true;
          })
        }else{
          this.bindVisible = true;
        }
        this.form = row;
      },
      bindResidential(){
        this.form.residentialId = this.selectValue;
        //保存
        update(this.form).then(() => {
          this.onLoad(this.page);
          this.bindVisible = false;
          this.$message({
            type: "success",
            message: "绑定成功!"
          });
        }, error => {
          console.log(error);
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style scoped>
  >>> .changeBind {
    color: orange;
  }
</style>
