<template>
  <div>
    <el-dialog :title="'党员中心户'"
               :visible="dlgShow"
               :close-on-click-modal="false"
               @close="handleDlgClose">
      <div>
        <el-button type="primary" @click="handleAddBtnClick">新增</el-button>
      </div>
      <el-table :data="bindingDatas"
                row-key="id"
                border
                style="width: 100%">
        <el-table-column label="党员中心户" align="center" prop="partyMemberName">
          <template slot-scope="scope">
            <el-select v-model="scope.row.partyMemberId"
                       v-if="scope.row.isEdit"
                       filterable>
              <el-option v-for="cm in centerMemberSelectorOptions"
                         :key="cm.id"
                         :value="cm.id"
                         :label="cm.name">
              </el-option>
            </el-select>
            <div v-else>{{ scope.row.partyMemberName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="联系家庭" align="center" prop="partyMemberName" :width="'500px'">
          <template slot-scope="scope">

            <!--v-model="scope.row.bindedHouses"-->
            <el-cascader :options="bindingHouseOptions"
                         clearable
                         ref="houseTreeRef"
                         style="width: 400px"
                         placeholder="请选择"
                         v-if="scope.row.isEdit"
                         @change=""
                         v-model="scope.row.bindedHouses"
                         :props="bindingProps">
            </el-cascader>
            <div v-else>{{ scope.row.bindedHousesStr }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" :width="'200px'">
          <template slot-scope="scope">
            <el-button type="primary" @click="handleSaveBtnClicked(scope.row)" v-if="scope.row.isEdit">保存</el-button>
            <el-button type="primary" @click="handleCancelBtnClicked(scope.row)" v-if="scope.row.isEdit">取消
            </el-button>
            <el-button type="primary" @click="handleDeleteBtnClicked(scope.row)" v-if="!scope.row.isEdit">删除
            </el-button>
            <el-button type="primary" @click="handleEditBtnClicked(scope.row)" v-if="!scope.row.isEdit">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>

import { requestGet, requestPost } from '@/js/dai/request'
import { EpmetResultResolver } from '@/js/epmet-result-resolver'

export default {
  mounted () {
    // 初始化结果解析器
    this.epmetResultResolver = new EpmetResultResolver(this)
  },
  data () {
    return {
      dlgShow: false,
      partyOrgId: null,
      epmetResultResolver: null,
      bindingDatas: [], // 党员中心户列表
      centerMemberSelectorOptions: [], // 中心户下拉框选择器
      bindingHouseOptions: [], // 联系家庭下拉框选择器
      bindingProps: {
        lazy: true,
        lazyLoad: ((node, resolve) => {
          this.handleTreeNodeClick(node, resolve)
        }),
        value: 'value',
        label: 'label',
        checkStrictly: false,
        multiple: true,
        children: "children",
        emitPath: true,
      },
      formData: {
        partyMemberId: null,
        bindingHouseIds: []
      }
    }
  },

  methods: {

    /**
     * 初始化
     */
    init (partyOrgId) {
      this.dlgShow = true
      this.partyOrgId = partyOrgId
      // 加载党员中心户列表
      this.$nextTick(async () => {
        await this.loadBindedDatas(partyOrgId)
      })
    },

    /**
     * "添加"按钮点击事件
     */
    handleAddBtnClick () {
      // 先检查是否已经有新增了但是没有填写的行
      let lastRow = this.bindingDatas[this.bindingDatas.length - 1]
      if (lastRow && lastRow.isEdit) {
        this.$message.warning('请逐行填写')
        return
      }

      // 添加新行上去
      let newRow = {
        partyMemberId: null,
        bindedHouses: [],
        isEdit: true
      }

      this.bindingDatas.push(newRow)

      this.$nextTick(async () => {
        // 加载下拉框
        await this.loadCenterMember4Selector(this.partyOrgId, 'create')
        await this.loadHousesTree4Select(this.partyOrgId)
      })

    },

    /**
     * 关联家庭级联下拉框选中事件
     * @returns {Promise<void>}
     */
    async handleTreeNodeClick (node, resolve) {
      console.log('发生了级联树的选中操作');
      if (node.root) {
        this.loadHousesTree4Select(this.partyOrgId)
      } else {
        node.children.length = 0
        let rstArr = await this.loadNextBindingHouseTreeLevel(node.data.nodeType, node.value)
        console.log('返回的下一级数据:', rstArr)
        resolve(rstArr)
      }
    },

    /**
     * 加载关联家庭的树
     * @param partyOrgId
     * @returns {Promise<void>}
     */
    async loadHousesTree4Select (partyOrgId) {
      let url = '/actual/base/party/org/centerMember/listQuarterOptionsByPartyOrgId'

      let rst = await requestGet(url, {
        partyOrgId: partyOrgId
      })

      this.epmetResultResolver.success((data) => {
        for (let e of data) {
          // 级别为小区
          e.nodeType = 'quarters'
        }
        this.bindingHouseOptions = data
      }).parse(rst)
      
      // let rootNodes = this.loadNextBindingHouseTreeLevel('root', null)
      // this.this.bindingHouseOptions = rootNodes;
    },

    /**
     * 加载关联家庭列表
     */
    async loadNextBindingHouseTreeLevel (currNodeType, nodeValue) {
      
      let url
      let param
      let nextNodeType

      // if (currNodeType === 'root') {
      //   // 根节点，加载小区
      //   let url = '/actual/base/party/org/centerMember/listQuarterOptionsByPartyOrgId'
      //
      //   let rst = await requestGet(url, {
      //     partyOrgId: partyOrgId
      //   })
      //
      //   let childrenNodes;
      //  
      //   this.epmetResultResolver.success((data) => {
      //     for (let e of data) {
      //       // 设置级别为小区
      //       e.nodeType = 'quarters'
      //     }
      //     childrenNodes = data;
      //   }).parse(rst)
      //  
      //   return childrenNodes;
      // } else 
      
      if (currNodeType === 'quarters') {
        url = '/actual/base/communityBuilding/buildingoption'
        nextNodeType = 'building'
        param = {
          quartersId: nodeValue
        }
      } else if (currNodeType === 'building') {
        url = '/actual/base/communityBuildingUnit/unitoption'
        nextNodeType = 'unit'
        param = {
          buildingId: nodeValue
        }
      } else if (currNodeType === 'unit') {
        url = '/actual/base/communityHouse/listHouses'
        nextNodeType = 'house'
        param = {
          buildingUnitId: nodeValue
        }
      } else {
        return []
      }

      let rst = await requestPost(url, param)

      let childrenNodes

      this.epmetResultResolver.success((data) => {
        if (nextNodeType === 'house') {
          data = data.list
        }

        for (let e of data) {
          // 级别
          e.nodeType = nextNodeType
          if (nextNodeType === 'house') {
            e.label = e.houseName
            e.value = e.houseId
            e.leaf = true
          }
        }
        // node.children.length = 0
        childrenNodes = data
      }).parse(rst)

      return childrenNodes
    },

    /**
     * 关联家庭下拉框选中变更事件
     */
    // handlebindingCascaderChange (selectedNodes) {
    //   this.formData.bindingHouseIds = selectedNodes.map(n => {
    //     return n[n.length - 1]
    //   })
    // },

    /**
     * 保存按钮点击事件
     */
    handleSaveBtnClicked (row) {
      let bindedHouseIds = row.bindedHouses.map(h => h[h.length - 1])
      this.saveCenterMemberbindingHome(row.persisted, row.partyMemberId, bindedHouseIds)
    },

    /**
     * 取消按钮点击事件
     */
    handleCancelBtnClicked (row) {
      console.log(row)
      if (row.isNew) {
        // 如果是新数据，就去掉
        this.bindingDatas.splice(row.$index, 1);
      } else {
        // 如果是旧数据，就切换编辑状态
        row.isEdit = false
      }
    },

    /**
     * 删除按钮点击事件
     */
    async handleDeleteBtnClicked (row) {
      this.$confirm('删除后无法恢复，是否确定?', '警告').then(async () => {
        let url = '/actual/base/party/member/centerMember/deleteByPartyMemberId/' + row.partyMemberId
        let rst = await requestPost(url, {})
        this.epmetResultResolver.success((data) => {
          this.$message.success('删除成功')
          this.loadBindedDatas(this.partyOrgId)
        }).parse(rst)
      })
    },

    /**
     * 编辑按钮点击事件
     */
    async handleEditBtnClicked (row) {

      // this.bindingHouseOptions = [
      //   {
      //     "label": "山东路第一小区",
      //     "code": null,
      //     "value": "1526844339424051202",
      //     "sysDictDataId": null,
      //     "children": [
      //       {
      //         "label": "1号楼",
      //         "code": null,
      //         "value": "1526844417257750530",
      //         "sysDictDataId": null,
      //         "children": [
      //           {
      //             "label": "1单元",
      //             "code": "1",
      //             "value": "1526844417278722049",
      //             "sysDictDataId": null,
      //             "children": [
      //               {
      //                 "customerId": "45687aa479955f9d06204d415238f7cc",
      //                 "houseId": "1526842714899566593",
      //                 "doorName": "101",
      //                 "buildingId": "1526844417257750530",
      //                 "houseName": "1号楼-1-101",
      //                 "rentFlag": "自住",
      //                 "neighborHoodId": "1526844339424051202",
      //                 "purposeKey": "1",
      //                 "unitNumKey": "1526844417278722049",
      //                 "agencyName": "山东路街道",
      //                 "agencyId": "d167076e825e75edda6540c5b9717c79",
      //                 "gridName": "山东路第一网格",
      //                 "gridId": "1489db92900a34838b371137087b36fd",
      //                 "neighborHoodName": "山东路第一小区",
      //                 "buildingName": "1号楼",
      //                 "unitNum": "1单元",
      //                 "houseType": "楼房",
      //                 "houseTypeKey": "1",
      //                 "purpose": "住宅",
      //                 "rentFlagKey": 0,
      //                 "ownerName": "因房主",
      //                 "ownerPhone": "157****9697",
      //                 "ownerIdCard": "3713251993******29",
      //                 "remark": "",
      //                 "sort": 0,
      //                 "houseCode": "3702030150000000200001",
      //                 "nodeType": "house",
      //                 "label": "1号楼-1-101",
      //                 "value": "1526842714899566593",
      //                 "leaf": true
      //               },
      //               {
      //                 "customerId": "45687aa479955f9d06204d415238f7cc",
      //                 "houseId": "1630738452589871106",
      //                 "doorName": "102",
      //                 "buildingId": "1526844417257750530",
      //                 "houseName": "1号楼-1-102",
      //                 "rentFlag": "自住",
      //                 "neighborHoodId": "1526844339424051202",
      //                 "purposeKey": "1",
      //                 "unitNumKey": "1526844417278722049",
      //                 "agencyName": "山东路街道",
      //                 "agencyId": "d167076e825e75edda6540c5b9717c79",
      //                 "gridName": "山东路第一网格",
      //                 "gridId": "1489db92900a34838b371137087b36fd",
      //                 "neighborHoodName": "山东路第一小区",
      //                 "buildingName": "1号楼",
      //                 "unitNum": "1单元",
      //                 "houseType": "楼房",
      //                 "houseTypeKey": "1",
      //                 "purpose": "住宅",
      //                 "rentFlagKey": 0,
      //                 "ownerName": "张三",
      //                 "ownerPhone": "",
      //                 "ownerIdCard": "",
      //                 "remark": "",
      //                 "sort": 0,
      //                 "houseCode": null,
      //                 "nodeType": "house",
      //                 "label": "1号楼-1-102",
      //                 "value": "1630738452589871106",
      //                 "leaf": true
      //               },
      //               {
      //                 "customerId": "45687aa479955f9d06204d415238f7cc",
      //                 "houseId": "1630745405168844801",
      //                 "doorName": "103",
      //                 "buildingId": "1526844417257750530",
      //                 "houseName": "1号楼-1-103",
      //                 "rentFlag": "自住",
      //                 "neighborHoodId": "1526844339424051202",
      //                 "purposeKey": "1",
      //                 "unitNumKey": "1526844417278722049",
      //                 "agencyName": "山东路街道",
      //                 "agencyId": "d167076e825e75edda6540c5b9717c79",
      //                 "gridName": "山东路第一网格",
      //                 "gridId": "1489db92900a34838b371137087b36fd",
      //                 "neighborHoodName": "山东路第一小区",
      //                 "buildingName": "1号楼",
      //                 "unitNum": "1单元",
      //                 "houseType": "楼房",
      //                 "houseTypeKey": "1",
      //                 "purpose": "住宅",
      //                 "rentFlagKey": 0,
      //                 "ownerName": "",
      //                 "ownerPhone": "",
      //                 "ownerIdCard": "",
      //                 "remark": "",
      //                 "sort": 0,
      //                 "houseCode": null,
      //                 "nodeType": "house",
      //                 "label": "1号楼-1-103",
      //                 "value": "1630745405168844801",
      //                 "leaf": true
      //               },
      //               {
      //                 "customerId": "45687aa479955f9d06204d415238f7cc",
      //                 "houseId": "1630506964648755202",
      //                 "doorName": "104",
      //                 "buildingId": "1526844417257750530",
      //                 "houseName": "1号楼-1-104",
      //                 "rentFlag": "自住",
      //                 "neighborHoodId": "1526844339424051202",
      //                 "purposeKey": "1",
      //                 "unitNumKey": "1526844417278722049",
      //                 "agencyName": "山东路街道",
      //                 "agencyId": "d167076e825e75edda6540c5b9717c79",
      //                 "gridName": "山东路第一网格",
      //                 "gridId": "1489db92900a34838b371137087b36fd",
      //                 "neighborHoodName": "山东路第一小区",
      //                 "buildingName": "1号楼",
      //                 "unitNum": "1单元",
      //                 "houseType": "楼房",
      //                 "houseTypeKey": "1",
      //                 "purpose": "住宅",
      //                 "rentFlagKey": 0,
      //                 "ownerName": "",
      //                 "ownerPhone": "",
      //                 "ownerIdCard": "",
      //                 "remark": "",
      //                 "sort": 0,
      //                 "houseCode": null,
      //                 "nodeType": "house",
      //                 "label": "1号楼-1-104",
      //                 "value": "1630506964648755202",
      //                 "leaf": true
      //               }
      //             ],
      //             "usableFlag": null,
      //             "type": null,
      //             "pid": null,
      //             "pvalue": null,
      //             "nodeType": "unit"
      //           }
      //         ],
      //         "usableFlag": null,
      //         "type": null,
      //         "pid": null,
      //         "pvalue": null,
      //         "nodeType": "building"
      //       },
      //       {
      //         "label": "2号楼",
      //         "code": null,
      //         "value": "1632674811918290945",
      //         "sysDictDataId": null,
      //         "children": null,
      //         "usableFlag": null,
      //         "type": null,
      //         "pid": null,
      //         "pvalue": null,
      //         "nodeType": "building"
      //       }
      //     ],
      //     "usableFlag": null,
      //     "type": null,
      //     "pid": null,
      //     "pvalue": null,
      //     "nodeType": "quarters"
      //   },
      //   {
      //     "label": "测试小区",
      //     "code": null,
      //     "value": "1541252207317544962",
      //     "sysDictDataId": null,
      //     "children": null,
      //     "usableFlag": null,
      //     "type": null,
      //     "pid": null,
      //     "pvalue": null,
      //     "nodeType": "quarters"
      //   },
      //   {
      //     "label": "山东路第二小区",
      //     "code": null,
      //     "value": "1630822418384191489",
      //     "sysDictDataId": null,
      //     "children": null,
      //     "usableFlag": null,
      //     "type": null,
      //     "pid": null,
      //     "pvalue": null,
      //     "nodeType": "quarters"
      //   }
      // ]

      // await this.loadHousesTree4Select(this.partyOrgId)
      await this.loadCenterMember4Selector(this.partyOrgId, 'edit')// 以编辑模式重新加载中心户下拉框
      row.isEdit = true

      // 加载出根节点（小区）
      await this.loadHousesTree4Select(this.partyOrgId);
      
      // 多选，所以是个二维数组
      let allPathIdsOfPartyMember = []
      for (let house of row.bindedHouses) {
        console.log(house)
        allPathIdsOfPartyMember.push(house.pathIds)
        
        // 递归加载数节点
        await this.rescureLoadTree(house.pathIds, 0, this.bindingHouseOptions);
      }

      row.bindedHouses = allPathIdsOfPartyMember;
    },

    /**
     * 递归加载
     */
    async rescureLoadTree(pathIds, currDepth, treeArr2Fill) {
      if (currDepth === 4) {
        // 超出最大深度，停止；
        return;
      }
      
      let objectId = pathIds[currDepth];
      let currNodeType;
      if (currDepth === 0) {
        currNodeType = 'quarters';
      } else if (currDepth === 1) {
        currNodeType = 'building';
      } else if (currDepth === 2) {
        currNodeType = 'unit';
      } else if (currDepth === 3) {
        currNodeType = 'house';
      }

      let childrenNodes = await this.loadNextBindingHouseTreeLevel(currNodeType, objectId);
      
      if (!childrenNodes || childrenNodes.length === 0) {
        // 没有更多子节点了，停止；
        return;
      }
      
      for (let node of treeArr2Fill) {
        if (node.value === objectId) {
          node.children = childrenNodes;
          break;
        }
      }

      await this.rescureLoadTree(pathIds, ++currDepth, childrenNodes);
      
      // for (let child of childrenNodes) {
      //   this.rescureLoadTree(pathIds, ++currDepth, childrenNodes);
      // }
    },

    /**
     * 打扫战场
     */
    handleDlgClose () {
      this.dlgShow = false
      this.bindingDatas.length = 0
      this.centerMemberSelectorOptions.length = 0
    },

    /**
     * 为中心户下拉框提供选项
     * bindingHomeOptions
     */
    async loadCenterMember4Selector (partyOrgId, purpose) {
      let url = '/actual/base/party/member/centerMember/centerMemberList4CreateSelect'

      let rst = await requestGet(url, {
        partyOrgId: partyOrgId,
        purpose: purpose
      })

      this.epmetResultResolver.success((data) => {
        this.centerMemberSelectorOptions = data
      }).parse(rst)
    },

    /**
     * 加载已经绑定的数据
     * @returns {Promise<void>}
     */
    async loadBindedDatas (partyOrgId) {
      let url = '/actual/base/party/member/centerMember/listCenterMemberBindingHouses'

      let rst = await requestGet(url, {
        partyOrgId: partyOrgId
      })

      this.epmetResultResolver.success((data) => {

        for (let row of data) {
          let bindedHouses = row.bindedHouses
          let houseNames = bindedHouses.map(e => e.houseName)
          row.bindedHousesStr = houseNames.join(',')
          row.isEdit = false
          row.isNew = false
          row.persisted = true // 已经持久化的数据，表示从后台去除的旧数据
        }

        this.bindingDatas = data
      }).parse(rst)
    },

    /**
     * 保存党员中心户-家庭绑定关系
     * @param partyMemberId
     * @param bindedHouseIds
     */
    async saveCenterMemberbindingHome (persisted, partyMemberId, bindedHouseIds) {
      let url
      if (!persisted) {
        url = '/actual/base/party/member/centerMember/createCenterMemberBindingHome'
      } else {
        url = '/actual/base/party/member/centerMember/updateCenterMemberBindingHome'
      }
      
      let rst = await requestPost(url, {
        partyMemberId: partyMemberId,
        partyOrgId: this.partyOrgId,
        bindedHouseIds: bindedHouseIds
      })

      this.epmetResultResolver.success(async (data) => {
        await this.loadBindedDatas(this.partyOrgId)
        // 重新加载中心户下拉框 + 房屋级联框
        await this.loadCenterMember4Selector(this.partyOrgId, 'create')
        await this.loadHousesTree4Select(this.partyOrgId)
      }).parse(rst)
    },
  }
}
</script>
