
<template>
  <basic-container>
    <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" :visible.sync="manageVisible"
      title="管理" fullscreen="true" @close="closeManage">

      <residentialManage ref="resMang" :residentialId="selectedResidentialId" :residentialName="selectedResidentialName"
        :visible="manageVisible">

      </residentialManage>

    </el-dialog>
    <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" :visible.sync="detailVisible"
      title="详情" width="80%">
      <residential-detail :form="detailForm"></residential-detail>
    </el-dialog>
    <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="submitResidential">
        <template slot="mapSelect">
          <input class="el-input--small el-input__inner" placeholder="选择地址" @click="mapVisible = true">

        </template>
      </avue-form>
    </el-dialog>
    <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" :visible.sync="mapVisible"
    title="编辑地址" width="80%">
       <editPolygonMap v-if="mapVisible" :editForm.sync="editForm" :visible.sync="mapVisible"></editPolygonMap>
    </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.residential_delete" @click="handleDelete">删除
        </el-button>
        <cy-excel-import :flag="5" file-name="小区信息导入模板" v-if="permission.residential_add" @success="onLoad(page)"></cy-excel-import>
        <el-button type="success" size="small" icon="el-icon-refresh" v-if="permission.residential_add" plain @click="refreshNumber">计算统计</el-button>
        <el-button type="success" size="small" icon="el-icon-refresh" v-if="permission.residential_add" plain @click="syncHouseInfoAndUser(oldIds)">同步楼栋&住户</el-button>
      </template>
       <template slot-scope="scope" slot="regionForm">
        <avue-cascader v-model="scope.row.region" :dic="regionDic" key-value="value"></avue-cascader>
               <cy-area-select></cy-area-select>
      </template>
      <template slot="agencyId" slot-scope="scope">{{scope.row.agencyName}}</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="detail(scope.row)" icon="el-icon-office-building">详情</el-dropdown-item>
              <el-dropdown-item divided @click.native="edit(scope.row)" icon="el-icon-school">编辑</el-dropdown-item>
              <el-dropdown-item divided @click.native="manage(scope.row)" icon="el-icon-s-order">管理</el-dropdown-item>
              <el-dropdown-item divided @click.native="syncBuilding(scope.row)" v-if="permission.residential_syncBuilding">同步楼栋</el-dropdown-item>
              <el-dropdown-item divided @click.native="syncUnit(scope.row)" v-if="permission.residential_syncUnit">同步单元</el-dropdown-item>
              <el-dropdown-item divided @click.native="syncFloor(scope.row)" v-if="permission.residential_syncFloor">同步楼层</el-dropdown-item>
              <el-dropdown-item divided @click.native="syncRoom(scope.row)" v-if="permission.residential_syncRoom">同步房间</el-dropdown-item>
              <el-dropdown-item divided @click.native="syncUser(scope.row)" v-if="permission.residential_syncUser">同步住户</el-dropdown-item>
              <el-dropdown-item divided @click.native="syncDoorDevice(scope.row)" v-if="permission.residential_syncDoorDevice">同步门禁设备</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-button>
      </template>

      <template slot="mapSelectForm" slot-scope="scope">
        <div>
          <input class="el-input--small el-input__inner" placeholder="选择地址" @click="mapVisible2 = true">

          <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" :visible.sync="mapVisible2"
          title="编辑地址" width="80%">
             <editPolygonMap v-if="mapVisible2" :editForm.sync="scope.row" :visible.sync="mapVisible2"></editPolygonMap>
          </el-dialog>
        </div>
      </template>

    </avue-crud>
  </basic-container>
</template>

<script>
  import {
    getList,
    updateNumber,
    add,
    update,
    remove,
    updateResidential,
    syncHouseInfoAndUser,
    syncBuilding,
    syncUnit,
    syncFloor,
    syncRoom,
    syncUser,
    syncDoorDevice
  } from "@/api/community/residential";
  import {
    mapGetters
  } from "vuex";

  import CyAreaSelect from "../../components/cy-area-select/cy-area-select";


  import residentialManage from "./residentialManage.vue";
  import residentialDetail from "../../components/residential/residentialDetail.vue";
  import CyExcelImport from "../../components/excel/cy-excel-import.vue"
  import editPolygonMap from "../../components/residential/editPolygonMap.vue";
  export default {
    components: {
      CyAreaSelect,
      residentialManage,
      residentialDetail,
      CyExcelImport,
      editPolygonMap
    },
    data() {
      return {
        mapVisible2:false,
        mapVisible:false,
        selectedResidentialId: "",
        selectedResidentialName: "",
        manageVisible: false,
        form: {},
        detailForm: {},
        detailVisible: false,
        editForm: {},
        editVisible: false,
        regionDic: [],
        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,
          addBtn: true,
          editBtn: false,
          delBtn: true,
          selection: true,
          dialogClickModal: false,
          menuWidth: 200,
          column: [{
              label: "名称",
              overHidden: true,
              width: 150,
              prop: "name",
              // row: true,
              overHidden: true,
              search: true,
              rules: [{
                required: true,
                message: "请输入名称",
                trigger: "blur"
              }]
            },
            {
              label:'',
              prop:'mapSelect',
              // row: true,
              // span: 20,
              formslot: true,
              hide: true,
            },
            {
              label: "经度",
              prop: "longitude",
              width: 120,
              hide: true,
              rules: [{
                required: false,
                message: "请输入经度",
                trigger: "blur"
              }]
            },
            {
              label: "纬度",
              prop: "latitude",
              width: 120,
              hide: true,
              rules: [{
                required: false,
                message: "请输入纬度",
                trigger: "blur"
              }]
            },
            {
              label: "所属社区",
              prop: "agencyId",
              // slot: true,
              search: true,
              width: 150,
              overHidden: true,
              type: "select",
              remote: true,
              dicUrl: "/api/cyzh-community/agency/list?size=1000&name={{key}}",
              props: {
                label: "name",
                value: "id"
              },
              dicFormatter:(res)=>{
                return res.data.records;
              },
              rules: [{
                required: true,
                message: "请输入所属机构名称",
                trigger: "blur"
              }]

            },

            {
              label: "详细地址",
              prop: "address",
              overHidden: true,
            },
            {
              label: "楼栋数量",
              prop: "buildingNumber",
              width: 100,
              display: false,
            },
            {
              label: "单元数量",
              prop: "unitNumber",
              width: 100,
              display: false,
            },
            {
              label: "楼层数量",
              prop: "floorNumber",
              width: 100,
              display: false,
            },
            {
              label: "房间数量",
              prop: "roomNumber",
              width: 100,
              display: false,
            },
            {
              label: "住户数量",
              prop: "userNumber",
              width: 100,
              display: false,
              hide: true,
            },
            {
              label: "已录入人脸住户数",
              prop: "userFaceNumber",
              hide: true,
              width: 120,
              display: false,
            },
            {
              label: "物业名称",
              prop: "estatePidName",
              labelWidth: 110,
              hide: true,
              rules: [{
                required: true,
                message: "请输入物业名称",
                trigger: "blur"
              }]
            },
            {
              label: "物业电话",
              prop: "estatePidPhone",
              labelWidth: 110,
              hide: true,
              rules: [{
                required: true,
                message: "请输入物业电话",
                trigger: "blur"
              }, {
                // validator: validatePhone,
                trigger: "blur"
              }]
            },
            {
              label: "负责人姓名",
              prop: "personName",
              labelWidth: 110,
              hide: true,
              rules: [{
                required: true,
                message: "请输入负责人姓名",
                trigger: "blur"
              }]
            },
            {
              label: "负责人电话",
              prop: "personTel",
              labelWidth: 110,
              hide: true,
              rules: [{
                required: true,
                message: "请输入负责人电话",
                trigger: "blur"
              }, {
                // validator: validatePhone,
                trigger: "blur"
              }]
            },
            {
              label: "图片",
              prop: "pic",
              type: 'upload',
              hide: true,
              propsHttp: {
                res: "data",
                url: 'link'
              },
              listType: 'picture-img',
              span: 24,
              row: true,

              action: "/api/blade-resource/oss/endpoint/putfile",
              display: true,
              rules: [{
                required: false,
                message: "请输入封面图片",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              hide: true,
              prop: "remark",
              type: "textarea"
            },
            {
              label: "创建时间",
              hide: true,
              width: 85,
              prop: "createTime",
              type: "datetime",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              display: false,
            },
            {
              label: "旧平台id",
              prop: "oldId",
              hide: true,
              display: false
            }
          ]
        },
        menuData: {
          list: [],
          form: {
            parentId: 0
          },
          option: {
            column: [{
              label: "父级编码",
              prop: "parentId",
              value: 0,
              disabled: true,
              span: 24
            }, {
              label: "权限名称",
              prop: "name",
              span: 24,
              rules: [{
                required: true,
                message: "请输入权限名称",
                trigger: "blur"
              }]
            }, {
              label: "权限标识",
              prop: "code",
              span: 24,
              rules: [{
                required: true,
                message: "请输入权限标识",
                trigger: "blur"
              }]
            }, {
              label: "类型",
              prop: "state",
              span: 24,
              type: "radio",
              dicData: [{
                label: '系统',
                value: 0
              }, {
                label: '菜单',
                value: 1
              }, {
                label: '按钮',
                value: 2
              }],
              rules: [{
                required: true,
                message: "请输入类型",
                trigger: "blur"
              }]
            }, {
              label: "组件地址",
              prop: "component",
              span: 24
            }, {
              label: "图标",
              prop: "icon",
              span: 24
            }, {
              label: "请求地址",
              prop: "path",
              span: 24
            }, {
              label: "权限描述",
              prop: "des",
              span: 24
            }, {
              label: "排序",
              prop: "order",
              span: 24
            }]
          }
        },
        menuOption: {
          column: [{
            label: "父级编码",
            prop: "parentId",
            disabled: true,
            span: 24
          }, {
            label: "权限名称",
            prop: "name",
            span: 24,
            rules: [{
              required: true,
              message: "请输入权限名称",
              trigger: "blur"
            }]
          }, {
            label: "权限标识",
            prop: "code",
            span: 24,
            rules: [{
              required: true,
              message: "请输入权限标识",
              trigger: "blur"
            }]
          }, {
            label: "类型",
            prop: "state",
            span: 24,
            type: "radio",
            dicData: [{
              label: '系统',
              value: 0
            }, {
              label: '菜单',
              value: 1
            }, {
              label: '按钮',
              value: 2
            }],
            rules: [{
              required: true,
              message: "请输入类型",
              trigger: "blur"
            }]
          }, {
            label: "组件地址",
            prop: "component",
            span: 24
          }, {
            label: "图标",
            prop: "icon",
            span: 24


          }, {
            label: "请求地址",
            prop: "path",
            span: 24
          }, {
            label: "权限描述",
            prop: "des",
            span: 24
          }, {
            label: "排序",
            prop: "order",
            span: 24
          }]
        },
        data: [],
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.residential_add, false),
          viewBtn: this.vaildData(this.permission.residential_view, false),
          delBtn: this.vaildData(this.permission.residential_delete, false),
          editBtn: this.vaildData(this.permission.residential_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      oldIds() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.oldId);
        });
        return ids.join(",");
      }
    },
    mounted() {

    },
    watch: {
      'form.mapSelect': {
        handler: function(value) {
          if (!value){
            return
          }else{
            this.form.longitude = this.form.mapSelect.longitude;
            this.form.latitude = this.form.mapSelect.latitude;
            this.form.address = this.form.mapSelect.formattedAddress;
          }
        },
        immediate: false
      },
      'editForm.mapSelect': {
        handler: function(value) {
          if (!value){
            return
          }else{
            this.editForm.longitude = this.editForm.mapSelect.longitude;
            this.editForm.latitude = this.editForm.mapSelect.latitude;
            // this.editForm.address = this.editForm.mapSelect.formattedAddress;
          }
        },
        immediate: false
      },
    },
    methods: {
      syncHouseInfoAndUser(){
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        syncHouseInfoAndUser(this.oldIds).then(() => {
          this.onLoad(this.page)
        });
      },
       refreshNumber(){
        updateNumber(this.ids).then(() => {
          this.onLoad(this.page)
        });
      },
      syncUser(row){
        syncUser(row.oldId).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
      },
      syncBuilding(row){
        syncBuilding(row.oldId).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
      },
      syncUnit(row){
        syncUnit(row.oldId).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
      },
      syncFloor(row){
        syncFloor(row.oldId).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
      },
      syncRoom(row){

        syncRoom(row.oldId).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },

      syncDoorDevice(row){
syncDoorDevice(row.oldId).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      closeManage() {
        this.manageVisible = false;
      },
      manage(row) {
        this.selectedResidentialId = row.id;
        this.selectedResidentialName = row.name;
        console.log("id:" + this.selectedResidentialId + "  name" + this.selectedResidentialName)
        this.manageVisible = true;
        this.$nextTick(() => {
          this.$refs.resMang.init();
        })
      },
      edit(row) {
        this.editForm = row;
        this.editVisible = true;
      },
      detail(row) {
        this.detailForm = row;
        this.detailVisible = true;
      },

      rowSave(row, done, loading) {
        debugger
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      submitResidential(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);
        });
      },
      rowUpdate(row, index, done, loading) {
        row.isUpdateOrg = false;
        updateResidential(row).then(() => {
          // update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        if (row.unitNumber > 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) {
        let _this = this;
        if (["edit", "view"].includes(type)) {
          // getResidentialDetail(this.form.id).then(res => {
          //   _this.form = res.data.data;
          //   let region = [];
          //   region.push(_this.form.regionProvince);
          //   region.push(_this.form.regionCity);
          //   region.push(_this.form.regionArea);
          //
          //   _this.form.region = region;
          // });
        }
        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();
        });
        // getResidentialList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        //   const data = res.data.data;
        //   this.page.total = Number.parseInt(data.total);
        //   this.data = data.records;
        //   this.loading = false;
        //   this.selectionClear();
        // });


      },

    }
  };
</script>

<style scoped>
  >>>.el-cascader-menu__wrap {
    height: 300px !important;
  }
</style>
