<template>
  <section class="app-grid-block">
    <ai-list>
      <template slot="title">
        <ai-title title="网格区块" :isShowBottomBorder="true"></ai-title>
      </template>
      <template slot="left">
        <ai-tree-menu title="网格层级" @search="v=> $refs.tree.filter(v)">
          <el-tree
              :data="treeObj.treeList"
              :props="treeObj.defaultProps"
              @node-click="handleNodeClick"
              node-key="id"
              ref="tree"
              :expand-on-click-node="false"
              :defaultExpandedKeys="treeObj.defaultExpandedKeys"
              :filter-node-method="filterNode"
              highlight-current>
            <template slot-scope="{node,data}">
              <div v-text="node.label"/>
            </template>
          </el-tree>
        </ai-tree-menu>
      </template>
      <template slot="content">
        <ai-search-bar>
          <template slot="left">
            <el-date-picker
                v-model="searchObj.createTimeStr"
                type="date"
                @change="(page.current = 1), getList()"
                value-format="yyyy-MM-dd"
                size="small"
                placeholder="创建时间"
            >
            </el-date-picker>
          </template>
          <template slot="right">
            <el-input
                v-model="searchObj.girdName"
                size="small"
                placeholder="输入网格名称"
                @keyup.enter.native="(page.current = 1), getList()"
                clearable
                @clear="(searchObj.girdName = '', page.current = 1), getList()"
                suffix-icon="iconfont iconSearch"
            />
          </template>
        </ai-search-bar>
        <ai-search-bar bottomBorder>
          <template slot="left">
            <el-button
                type="primary"
                icon="iconfont iconAdd"
                @click="(isEdit = false), toAdd()"
            >新增
            </el-button>
            <el-button
                icon="iconfont iconDelete"
                @click="deleteById(ids.join(','))"
                :disabled="!Boolean(ids.length)"
            >
              删除
            </el-button>
            <ai-download
                :instance="instance"
                url="/app/appgirdinfo/exportGirdInfo"
                :params="{ ...searchObj, ids: ids.join(',') }"
                fileName="网格区块"
            >
              <el-button icon="iconfont iconExported" size="small"
              >导出全部
              </el-button
              >
            </ai-download>
            <ai-import
                ref="import"
                title="导入"
                name="网格区块"
                url="/app/appgirdinfo/downloadGirdInfo"
                importUrl="/app/appgirdinfo/importGirdInfo"
                suffixName="xlsx"
                :customCliker="true"
                :instance="instance"
            >
              <template slot="tips">
                <p>
                  如果表格中已经存在数据，则会被本次导入的数据覆盖；不存在数据，系统将生成新的标准记录；
                </p>
              </template>
              <el-button size="small" icon="iconfont iconImport"
              >导入
              </el-button
              >
            </ai-import>
          </template>
        </ai-search-bar>
        <ai-table
            class="mt10"
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="page.total"
            ref="aitableex"
            :current.sync="page.current"
            :size.sync="page.size"
            @selection-change="v=>ids=v.map((e) => e.id)"
            @getList="getList()"
            :dict="dict">
          <el-table-column label="网格成员" slot="user" align="center" width="160">
            <template slot-scope="{ row }">
              <el-button type="text" @click="showGridMembers(row)">{{ row.girdMemberNumber || 0 }}</el-button>
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              slot="options"
              align="center"
              fixed="right"
              width="160">
            <template slot-scope="{ row }">
              <el-button type="text" @click="showEdit(row.id)">编辑</el-button>
              <map-plotting :value="row.points" @change="v=>confirm(row,v)"/>
              <el-button type="text" @click="deleteById(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog :title="`${gridInfo.girdName}网格成员`" :visible.sync="dialog" customFooter @closed="gridInfo={}"
               width="700px">
      <ai-table :tableData="gridInfo.tableData" :colConfigs="gridMemberColConfigs" :dict="dict"
                :isShowPagination="false" :show-header="false"/>
      <template #footer>
        <el-button @click="dialog=false">关闭</el-button>
      </template>
    </ai-dialog>
  </section>
</template>

<script>
import MapPlotting from "./mapPlotting";

export default {
  name: "List",
  components: {MapPlotting},
  label: "网格区块",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
  },
  data() {
    return {
      treeObj: {
        treeList: [],
        defaultProps: {
          children: "children",
          label: "girdName",
        },
        defaultExpandedKeys: [],
      },
      filterText: "",
      page: {
        current: 1,
        size: 10,
        total: 0,
      },
      searchObj: {
        createTimeStr: "",
        girdName: "",
      },
      tableData: [],
      info: {},
      ids: [],
      showMap: false,
      map: "",
      polyEditor: "",
      editRow: {},
      searchAddress: "",
      mouseTool: "",
      placeSearch: "",
      path: [],
      overlays: [],
      isEdit: false,
      fileList: [],
      dialog: false,
      gridInfo: {},
      gridMemberColConfigs: [
        {prop: "name"},
        {prop: "checkType", formart: v => v === '1' ? '网格员' : '网格长'}
      ]
    };
  },
  created() {
    this.getTreeList();
    this.getList();
    this.dict.load("girdType", "isLastLevel", "plottingStatus", "girdMemberType");
  },
  computed: {
    colConfigs() {
      return [
        {type: 'selection'},
        {prop: "girdName", align: "left", label: "网格名称",},
        {slot: 'user'},
        {prop: "plottingStatus", align: "center", label: "标绘状态", dict: "plottingStatus"},
        {prop: "createTime", align: "center", label: "创建时间"},
        {slot: "options"}
      ];
    },
    isTopGrid() {
      return this.info.id == this.treeObj.treeList?.[0]?.id
    }
  },
  methods: {
    handleNodeClick(val) {
      this.info = this.$copy(val);
      this.getList();
    },
    getTreeList() {
      this.instance.post(`/app/appgirdinfo/listAll3`).then((res) => {
        if (res?.data) {

          this.treeObj.treeList = res.data.filter(e => !e.parentGirdId)
          const parentGirdId = this.treeObj.treeList[0].id

          this.treeObj.treeList.map(p => this.addChild(p, res.data.map(v => {
            if (v.id === parentGirdId) {
              this.treeObj.defaultExpandedKeys.push(v.id)
            }

            return {
              ...v
            }
          }), {
            parent: 'parentGirdId'
          }))
          this.$nextTick(() => {
            this.info = this.treeObj.treeList[0]
            this.$refs.tree.setCurrentKey(parentGirdId)
          })
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.girdName.indexOf(value) !== -1;
    },
    deleteById(ids) {
      ids && this.$confirm("删除网格后，会清除网格内网格员的责任家庭信息，如有下级网格，会同步删除下级网格所有数据!", {
        type: "error",
      }).then(() => {
        this.instance.post("/app/appgirdinfo/delete", null, {params: {ids}}).then((res) => {
          if (res?.code == 0) {
            this.$message.success("删除成功!");
            this.getList();
            this.getTreeList();
          }
        });
      }).catch(() => 0);
    },
    deleteTree(ids) {
      ids && this.$confirm("是否要删除该网格区块？", {
        type: "error",
      }).then(() => {
        this.instance.post("/app/appgirdinfo/delete", null, {
          params: {ids}
        }).then((res) => {
          if (res?.code == 0) {
            this.$message.success("删除成功!");
            this.getTreeList();
          }
        });
      }).catch(() => 0);
    },
    getList() {
      this.instance.post("/app/appgirdinfo/list", null, {
        params: {
          ...this.searchObj,
          ...this.page,
          parentGirdId: this.isTopGrid ? '' : this.info.id,
        },
      }).then((res) => {
        if (res?.data) {
          this.tableData = res.data.records;
          this.page.total = res.data.total;
        }
      });
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.map((e) => {
        this.ids.push(e.id);
      });
    },
    //添加二级网格
    addTwoLevel() {
      this.info = {...this.treeObj.treeList[0]};
      this.toAdd()
    },
    toAdd() {
      let {id: parentGirdId, girdName: parentGirdName} = this.info
      this.$router.push({
        hash: "#add", query: {parentGirdId, parentGirdName}
      })
    },
    goBack() {
      this.isAdd = false;
      this.$nextTick(() => {
        this.getList();
        this.getTreeList();
      });
    },
    showEdit(id) {
      this.$router.push({hash: "#add", query: {id}})
    },
    //map搜索
    confirm(row, points) {
      this.instance.post(`/app/appgirdinfo/updateCoordinate`, {...row, points}).then((res) => {
        if (res.code == 0) {
          this.$message.success("提交成功!")
          this.getList();
        }
      });
    },
    resetSearch() {
      Object.keys(this.searchObj).map((e) => {
        this.searchObj[e] = "";
      });
      this.getList();
    },
    showGridMembers(row) {
      if (row.girdMemberNumber > 0) {
        this.gridInfo = this.$copy(row)
        this.instance.post("/app/appgirdmemberinfo/listByGirdIdByThree", null, {
          params: {girdId: row.id}
        }).then(res => {
          if (res?.data) {
            this.gridInfo.tableData = res.data
            this.dialog = true
          }
        })
      } else this.$message.warning("当前网格无成员")
    }
  },
};
</script>

<style lang="scss" scoped>
.app-grid-block {
  width: 100%;
  height: 100%;

  ::v-deep .el-tree {
    background: transparent;

    .el-tree-node__expand-icon.is-leaf {
      color: transparent !important;
    }

    .el-tree-node__content > .el-tree-node__expand-icon {
      padding: 4px;
    }

    .el-tree-node__content {
      height: 32px;
    }

    .el-tree__empty-text {
      color: #222;
      font-size: 14px;
    }

    .el-tree-node__children .el-tree-node__content {
      height: 32px;
    }

    .el-tree-node__content:hover {
      background: #E8EFFF;
      color: #222222;
      border-radius: 2px;
    }

    .is-current > .el-tree-node__content {
      color: #fff !important;

      &:hover {
        background: #2266FF;
        color: #fff;
      }

      background: #2266FF;

      .el-tooltip {
        color: #fff;
      }
    }
  }

  .flex-box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;

    & > div {
      display: flex;
    }
  }

  .mt10 {
    padding: 8px 0;
  }

  ::v-deep.fullscreenMap {
    .el-dialog {
      display: flex;
      flex-direction: column;

      .el-dialog__body {
        padding: 0;
        flex: 1;
        min-height: 0;

        .ai-dialog__content {
          max-height: unset !important;
          padding-bottom: 0;
          height: 100%;

          .ai-dialog__content--wrapper {
            padding-right: 0 !important;
          }
        }
      }
    }
  }

  ::v-deep .treePanel {
    display: flex;
    flex-direction: column;

    .el-tree {
      min-height: 0;
      flex: 1;
    }

    footer {
      width: 100%;
      height: 32px;
      background-color: #fff;
      display: flex;
      align-items: center;

      span {
        width: 33.33%;
        text-align: center;
        cursor: pointer;
      }

      .el-button {
        width: 33.33%;
      }
    }
  }
}
</style>
