<template>
  <basic-container>
    <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" :visible.sync="editVisible"
               title="单元编辑" width="80%">
      <avue-form v-model="editForm" :option="option" @submit="submitUnit"></avue-form>
    </el-dialog>
    <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.unit_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menu" slot-scope="scope">
        <el-button type="text" size="small" icon="el-icon-setting">
          <el-dropdown @command="tip">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"> </i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item divided @click.native="edit(scope.row)" icon="el-icon-school">编辑</el-dropdown-item>
              <el-dropdown-item divided @click.native="unitManage(scope.row.id,2)" icon="el-icon-s-home">楼层管理</el-dropdown-item>
              <el-dropdown-item divided @click.native="unitManage(scope.row.id,3)" icon="el-icon-s-home">房间管理</el-dropdown-item>
              <el-dropdown-item divided @click.native="unitManage(scope.row.id,4)" icon="el-icon-user-solid" v-if="permission.permanent_people_view">住户管理</el-dropdown-item>
              <!-- <el-dropdown-item divided @click.native="tip(2,scope.row)">审核通过</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </el-button>
        <!-- <el-button type="text" icon="el-icon-setting" size="mini" @click="manageResidential(scope.row.oldId)">管理</el-button> -->
      </template>
      <template slot="agencyId" slot-scope="scope">
        {{scope.row.agencyName}}
      </template>
      <template slot="residentialId" slot-scope="scope">
        <div>{{scope.row.residentialName}}</div>
      </template>
      <template slot="buildingId" slot-scope="scope">
        <div>{{scope.row.buildingName}}</div>
      </template>
    </avue-crud>
  </basic-container>
</template>

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

import {communityManage} from "@/views/community/util/communityManage";
import {validatePhone} from "../../util/validator";


export default {
  data() {
    return {
      editForm: {},
      editVisible: false,
      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: false,
        delBtn: true,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        column: [{
          label: "单元名称",
          prop: "name",
          search: true,
          width: 100,
          // hide: true,
          rules: [{
            required: true,
            message: "请输入单元名称",
            trigger: "blur"
          }]
        },
          {
            label: "单元编号",
            prop: "unitNumber",
            display: false,
            hide: true,
            // search: true,
          },
          {
            label: "单元楼类型",
            prop: "type",
            hide: true,
            type: "select",
            // search: true,
            dataType: "number",
            searchLabelWidth: 110,
            labelWidth: 110,
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=unit_type",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            rules: [{
              required: false,
              message: "请选择单元楼类型",
              trigger: "blur"
            }]
          },
          // {
          //   label: "所属社区",
          //   prop: "agencyId",
          //   slot: true,
          //   search: true,
          //   cascaderItem: ['residentialId'],
          //   type: "select",
          //   // remote: true,
          //   searchFilterable:true,
          //   dicUrl: "/api/cyzh-community/agency/list?size=9999&name={{key}}",
          //   dicFormatter:(res)=>{
          //     return res.data.records;//返回字典的层级结构
          //   },
          //   props: {
          //     label: "name",
          //     value: "id"
          //   },
          //   rules: [{
          //     required: true,
          //     message: "请选择所属社区",
          //     trigger: "blur"
          //   }]
          // },
          {
            label: "所属小区",
            prop: "residentialId",
            slot: true,
            type: "select",
            search: true,
            cascaderItem: ['buildingId'],
            // remote: true,
            //回显的时候有问题，如果所选不在前十条内，下拉框只会显示id
            dicUrl: "/api/cyzh-community/residential/list?size=999",
            dicFormatter:(res)=>{
              return res.data.records;//返回字典的层级结构
            },
            // dicFlag: false,
            searchFilterable: true,
            props: {
              label: "name",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请选择所属小区",
              trigger: "blur"
            }]
          },
          {
            label: "所属楼栋",
            prop: "buildingId",
            // width: 100,
            slot: true,
            type: "select",
            search: true,
            dicUrl: `/api/cyzh-community/building/list?residentialId={{key}}`,
            dicFormatter:(res)=>{
              return res.data.records;//返回字典的层级结构
            },
            dicFlag: false,
            searchFilterable: true,
            props: {
              label: "name",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请选择所属楼栋",
              trigger: "blur"
            }]
          },
          {
            label: "负责人姓名",
            prop: "personName",
            // labelWidth: 110,
            hide: true,

            rules: [{
              required: false,
              message: "请输入负责人姓名",
              trigger: "blur"
            }]
          }, {
            label: "负责人电话",
            prop: "personTel",
            labelWidth: 110,
            hide: true,
            rules: [{
              required: false,
              message: "请输入负责人电话",
            },{
              validator: validatePhone,
              trigger: "blur"
            }]
          }, {
            label: "建筑年代",
            prop: "builtYear",
            hide: true,
          }, {
            label: "产权性质",
            prop: "propertyNature",
            hide: true,
          }, {
            label: "有无电梯",
            prop: "includingElevator",
            hide: true,
            // type: "select",
            // search: true,
            // dicUrl: "/api/blade-system/dict-biz/dictionary?code=including_elevator",
            // props: {
            //   label: "dictValue",
            //   value: "dictKey"
            // },
          },
         {
           label: "图片",
           prop: "pic",
           type: 'upload',
           dataType: 'string',
           hide: true,
           propsHttp: {
             res: "data",
             url: 'link'
           },
           listType: 'picture-img',
           span: 24,
           row: true,
           // value: "/img/default/building.png",
           action: "/api/blade-resource/oss/endpoint/put-file",
           rules: [{
             required: false,
             message: "请上传封面图片",
             trigger: "blur"
           }]
         },
          {
            label: "楼层数量",
            prop: "floorCount",
            // width: 100,
            display: false
          },
          {
            label: "房间数量",
            prop: "roomCount",
            // width: 100,
            display: false
          },
          {
            label: "住户数量",
            prop: "userNumber",
            display: false,
            hide: true,
          },
          {
            label: "序号",
            prop: "serial",
            hide: true,
            display: false,
            value: 1
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "datetime",
            hide: true,
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            display: false
          },
          {
            label: "备注",
            prop: "remark",
            hide: true,
            type: "textarea"
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.unit_add, false),
        viewBtn: this.vaildData(this.permission.unit_view, false),
        delBtn: this.vaildData(this.permission.unit_delete, false),
        editBtn: this.vaildData(this.permission.unit_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: {
    submitUnit(row,done,loading) {
      update(this.editForm).then(() => {
        this.onLoad(this.page);
        this.editVisible = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    edit(row) {
      this.editForm = row;
      this.editVisible = true;
    },
    unitManage(id,type){
      let query = {unitId: id};
      communityManage(this,type,query)
    },
    rowSave(row, done, loading) {
      row.roomNumber = 0;
      row.floorNumber = 0;
      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.roomNumber > 0) {
        this.$message.error("请先删除该单元的房间和其他数据")
        return
      }
      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>
