<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="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.room_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="residentialId" slot-scope="scope">
        <div>{{scope.row.residentialName}}</div>
      </template>
      <template slot="unitId" slot-scope="scope">
        {{scope.row.unitName}}
      </template>
      <template slot="buildingId" slot-scope="scope">
        {{scope.row.buildingName}}
      </template>
      <template slot="floorId" slot-scope="scope">
        {{scope.row.floorName}}
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, getRoomList, getRoomDetail} from "@/api/community/room";
  import {mapGetters} from "vuex";


  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        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,
          // delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            // {
            //   label: "房间名称",
            //   prop: "name",
            //   search: true,
            //   rules: [{
            //     required: true,
            //     message: "请输入房间名称",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "门牌号 ",
              prop: "name",
              search: true,
              rules: [{
                required: true,
                message: "请输入门牌号-限制数字，单元楼下唯一  ",
                trigger: "blur"
              }]
            },{
              label: "所属社区",
              prop: "agencyId",
              slot: true,
              hide: true,
              display:false,
              type: "select",
              // search: true,
              dicUrl: "/api/cyzh-community/agency/list",
              // cascaderItem: ['residentialId','unitId'],
              props: {
                label: "agencyName",
                value: "id"
              },
              dicFormatter: (res)=>{
                return res.data.records;
              },
              rules: [{
                required: true,
                message: "请选择所属社区",
                trigger: "blur"
              }]
            },{
              label: "所属小区",
              prop: "residentialId",
              slot: true,
              type: "select",
              search: true,
              cascaderItem: ["buildingId"],
              // dicUrl: "/grid/estate/getResidentialList",
              remote: true,
              //回显的时候有问题，如果所选不在前十条内，下拉框只会显示id
              dicUrl: "/api/cyzh-community/residential/list?name={{key}}",
              // dicFlag: false,
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请输入所属小区",
                trigger: "blur"
              }]
            },
            {
              label: "所属楼栋",
              prop: "buildingId",
              cascaderItem: ["unitId"],
              slot: true,
              type: "select",
              search: true,
              dicFlag: false,
              filterable: true,
              dicUrl: "/api/cyzh-community/building/list?residentialId={{key}}",
              dicFormatter: (res)=>{
                return res.data.records;
              },
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请输入所属单元名称",
                trigger: "blur"
              }]
            },
            {
              label: "所属单元",
              prop: "unitId",
              slot: true,
              type: "select",
              search: true,
              dicFlag: false,
              cascaderItem: ["floorId"],
              filterable: true,
              dicUrl: "/api/cyzh-community/unit/list?buildingId={{key}}",
              dicFormatter: (res)=>{
                return res.data.records;
              },
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请输入所属单元名称",
                trigger: "blur"
              }]
            },
            {
              label: "所属楼层",
              prop: "floorId",
              slot: true,
              type: "select",
              search: true,
              dicFlag: false,
              // cascaderIndex:1,
              // dicUrl: "/grid/estate/getUnitList",
              dicUrl: "/api/cyzh-community/floor/list?unitId={{key}}&size=900000",
              dicFormatter: (res)=>{
                return res.data.records;
              },
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请输入所属单元名称",
                trigger: "blur"
              }]
            },
            {
              label: "房屋面积",
              prop: "area",
              hide: true,
            },{
              label: "入住用户数量",
              prop: "userNumber",
              hide: true,
              display: false,
            },
            {
              label: "户型",
              prop: "houseType",
              hide: true,
              type: "select",
              // search: true,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=house_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: "楼层",
              prop: "floor",
              hide: true,
            },
            {
              label: "装饰",
              prop: "ornament",
              hide: true,
            },
            {
              label: "房屋朝向",
              prop: "orientation",
              hide: true,
            },{
              label: "序号",
              prop: "serial",
              value: 1,
              hide: true,
              display: false,
            }, {
              label: "备注",
              prop: "remark",
              hide: true,
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              type: "datetime",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              display: false,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.room_add, false),
          viewBtn: this.vaildData(this.permission.room_view, false),
          delBtn: this.vaildData(this.permission.room_delete, false),
          editBtn: this.vaildData(this.permission.room_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      let tenantType = localStorage.getItem("tenantType");
      const agencyColumn = this.findObject(this.option.column, "agencyId");
      const residentialColumn = this.findObject(this.option.column, "residentialId");
      if (tenantType == 1) { //园区
        agencyColumn.label = "所属园区";
        residentialColumn.label = "所属区域";
      } else { //社区
        agencyColumn.label = "所属社区";
        residentialColumn.label = "所属小区";
      }
    },
    methods: {
      rowSave(row, done, loading) {
        row.userNumber = 0;
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        // done()
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        if (row.userNumber > 0){
          this.$message.error("请先删除该房间的住户和其他数据")
        }
        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;
        if (this.$route.query){
          Object.assign(this.query,this.$route.query)
        }
        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>
</style>
