<template>
  <basic-container>
<!--    卡片-->
<!--    <el-container>-->
<!--      <el-main>-->
<!--        <template>-->
<!--          <el-carousel :interval="5000" height="200px">-->
<!--            <el-carousel-item>-->
<!--              <el-container>-->
<!--                <el-header style="background-color: rgb(29,67,58);height: 65px">-->
<!--                  <div class="titleLabel">-->
<!--                    <el-row :gutter="40">-->
<!--                      <div>-->
<!--                        <el-col :span="20"><div class="titleText">{{communityCount.agencyCount}}</div></el-col>-->
<!--                        <el-col :span="4"><div class="titleCount">{{communityCount.buildingCount}}</div></el-col>-->
<!--                      </div>-->
<!--                    </el-row>-->
<!--                  </div>-->
<!--                </el-header>-->
<!--                <el-main>-->
<!--                  <div style="margin-left: 100px">-->
<!--                    <avue-data-display :option="dataShow(item)"></avue-data-display>-->
<!--                  </div>-->
<!--                </el-main>-->
<!--              </el-container>-->
<!--            </el-carousel-item>-->
<!--          </el-carousel>-->
<!--        </template>-->
<!--      </el-main>-->
<!--    </el-container>-->

<!--卡片数据展示-->
    <el-card style="background: #f5f5f5;margin-bottom: 20px">
        <el-tabs type="border-card">
          <el-tab-pane label="社区数据统计">
            <div><avue-data-box :option="communityStatistics"></avue-data-box></div>
          </el-tab-pane>
        </el-tabs>
    </el-card>

    <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.agency_delete" @click="handleDelete">删
          除
        </el-button>
        <cy-excel-import :flag="1" file-name="社区信息导入模板" @success="onLoad(page)"></cy-excel-import>
      </template>
      <template slot="mapSelectForm" slot-scope="scope">
        <div>
          <!--          <input class="el-input&#45;&#45;small el-input__inner" placeholder="选择地址" @click="mapVisible = true">-->
          <el-button @click="mapVisible = true"> 选择地址</el-button>
          <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="scope.row" :region.sync="scope.row.address" :latitude.sync="scope.row.latitude" :longitude.sync="scope.row.longitude" :visible.sync="mapVisible"></editPolygonMap>
          </el-dialog>
        </div>
      </template>

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

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove
} from "@/api/community/agency.js";
import {getCommunityList} from "../../api/grid/index";
import {
  mapGetters
} from "vuex";
import {
  validatePhone
} from "@/util/validator"
import CyExcelImport from "../../components/excel/cy-excel-import"
import editPolygonMap from "../../components/residential/editPolygonMap.vue"
import {getDetail as getRegDetail} from "@/api/base/region"
export default {
  components: {CyExcelImport,editPolygonMap},
  data() {
    return {
      communityCount:{},
      mapVisible:false,
      areaData: [],
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      //数据展示
      communityStatistics:{
        span:6,
        data: [
          {
            title: '社区数量',
            count: 0,
            icon: 'el-icon-office-building',
            color: 'rgb(49, 180, 141)',
          },
          {
            title: '小区数量',
            count: 0,
            icon: 'el-icon-school',
            color: 'rgb(56, 161, 242)',
          },
          {
            title: '楼宇数量',
            count: 0,
            icon: 'el-icon-s-home',
            color: 'rgb(117, 56, 199)',
          },
          {
            title: '住户数量',
            count: 0,
            icon: 'el-icon-user-solid',
            color: 'rgb(143,119,0)',
          },
        ]
      },

      selectionList: [],
      option: {
        height: 'auto',
        // calcHeight: 60,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        menuWidth:350,
        column: [{
          label: "名称",
          prop: "name",
          search: true,
          width: 160,
          overHidden: true,
          rules: [{
            required: true,
            message: "请输入名称",
            trigger: "blur"
          }]
        },
          {
            label:'',
            prop:'mapSelect',
            viewDisplay: false,
            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: "regionProvince",
            type: "select",
            width: 150,
            dicUrl: "/api/blade-system/region/lazy-tree?parentCode=000000",
            cascaderItem:["regionCity"],
            props:{
              label:"title",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请选择所属省份",
              trigger: "blur"
            }]
          },
          {
            label: "所属市",
            prop: "regionCity",
            type: "select",
            width: 150,
            cascaderItem: ["regionArea"],
            dicUrl: `/api/blade-system/region/lazy-tree?parentCode={{key}}`,

            props:{
              label: "title",
              value: "id"
            },
            rules: [{
              required: false,
              message: "请选择所属市",
              trigger: "blur"
            }]
          },
          {
            label: "所属区",
            prop: "regionArea",
            type: "select",
            width: 150,
            cascaderItem: ["regionStreet"],
            dicUrl:  `/api/blade-system/region/lazy-tree?parentCode={{key}}`,
            props: {
              label: "title",
              value: "id"
            },
            rules: [{
              required: false,
              message: "请选择所属区",
              trigger: "blur"
            }]
          },
          {
            label: "所属街道",
            prop: "regionStreet",
            type:"select",

            width: 150,
            dicUrl: `/api/blade-system/region/lazy-tree?parentCode={{key}}`,
            props: {
              label: "title",
              value: "id"
            },

            rules: [{
              required: true,
              message: "请选择所属街道",
              trigger: "blur"
            }]
          },
          {
            label: "详细地址",
            search: true,
            prop: "address",
            type: "textarea",
            maxRows: 2,
            // width: 300,
            overHidden: true,
            rules: [{
              required: false,
              message: "请输入详细地址",
              trigger: "blur"
            }]
          },
          {
            label: "负责人名称",
            prop: "personName",
            width: 210,
            labelWidth: 100,
            rules: [{
              required: false,
              message: "请输入负责人名称",
              trigger: "blur"
            }]
          },
          {
            label: "联系方式",
            prop: "personPhone",
            width: 120,
            rules: [{
              required: false,
              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/put-file",
            display: true,
            tip:"上传图片不能超过500K",
            rules: [{
              required: false,
              message: "请上传封面图片",
              trigger: "blur"
            }]
          },
          {
            label: "小区数量",
            prop: "residentialCount",
            display: false,
            hide: true,
          },
          {
            label: "楼栋数量",
            prop: "buildingCount",
            hide: true,
            display: false,
          },
          {
            label: "单元数量",
            prop: "unitCount",
            hide: true,
            display: false,
          },
          {
            label: "楼层数量",
            prop: "floorCount",
            hide: true,
            display: false,
          },
          {
            label: "房间数量",
            prop: "roomCount",
            hide: true,
            display: false,
          },
          {
            label: "人员数量",
            prop: "personCount",
            hide: true,
            display: false,
          },

          {
            label: "备注",
            prop: "remark",
            hide: true,
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.agency_add, false),
        viewBtn: this.vaildData(this.permission.agency_view, false),
        delBtn: this.vaildData(this.permission.agency_delete, false),
        editBtn: this.vaildData(this.permission.agency_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch: {
    'form.address': {
      handler: function(value) {
        if (!value){
          return
        }else{
          var _this = this
          AMap.plugin('AMap.Geocoder', function() {
            var geocoder = new AMap.Geocoder({})
            let lnglat = [_this.form.longitude,_this.form.latitude]
            geocoder.getAddress(lnglat, function(status, result) {
              if (status === 'complete'&&result.regeocode&&result.regeocode.addressComponent.township) {
                let parentCode = result.regeocode.addressComponent.adcode
                let name = result.regeocode.addressComponent.township
                getRegDetail({"name":name,"regionLevel":"4","parentCode":parentCode}).then((res)=>{
                  let data = res.data.data
                  let obj = {}
                  obj['regionProvince'] = data.provinceCode
                  obj['regionCity']  = data.cityCode
                  obj['regionArea'] = data.districtCode
                  obj['regionStreet'] = data.code
                  _this.form = obj
                })
              }
            })
          })
        }
      },
    },
    '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;
        }
      },
    }
  },
  methods: {
    rowSave(row, done, loading) {
      row.residentialCount = 0;
      row.unitCount = 0;
      row.roomCount = 0;
      row.personCount = 0;
      row.carCount = 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) {
      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 = {}) {
      getCommunityList('/640000').then(res=>{
        this.communityCount = res.data.data;
        console.log(this.communityCount,"打印communityCount");
        this.communityStatistics.data[0].count = this.communityCount.agencyCount;
        this.communityStatistics.data[1].count = this.communityCount.residentialCount;
        this.communityStatistics.data[2].count = this.communityCount.buildingCount;
        this.communityStatistics.data[3].count = this.communityCount.userCount;
      });
      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>
</style>
