<template>
  <section class="AiPeopleMember party-member">
    <a v-if="customCliker" class="custom-clicker" @click="visible = true">
      <slot></slot>
    </a>
    <el-button v-else size="small" @click="visible = true">{{ btnText }}</el-button>
    <ai-dialog
        :title="dialogTitle"
        :visible.sync="visible"
        :modal="true"
        :append-to-body="true"
        @onConfirm="$emit('change', selectPeople), (visible = false)"
        @close=";(selectPeople = []), $refs.peopleTable.clearSelection()"
        :width="dialogWidth">
      <div>
        <el-row type="flex" class="AiPeopleMember-dialog">
          <el-row class="search-panel" type="flex" justify="space-between">
            <div class="add-item" v-if="!meta.length && !action">
              <p class="add_top">
                <span>党组织</span>
                <el-input
                    class="search-input"
                    placeholder="党组织名称"
                    size="small"
                    v-model="filterText"
                    suffix-icon="iconfont iconSearch"
                    clearable>
                </el-input>
              </p>
              <div class="tree_list">
                <el-tree
                    :data="orgList"
                    class="dialog-tree"
                    :props="orgTreeProp"
                    ref="orgTree"
                    node-key="id"
                    :highlight-current="true"
                    :current-node-key="currNodeKey"
                    @node-click="treeNodeClick"
                    :filter-node-method="filterNode">
                </el-tree>
              </div>
            </div>
            <div class="add-item add-item__middel"
                 :style="{ 'border-left' : (hasMeta || action) ? '1px solid #d0d4dc' : 'none' }">
              <p class="add_top">
                <span>党员</span>
                <el-input
                    placeholder="姓名/手机号"
                    size="small"
                    clearable
                    v-model="searchObj.con"
                    @clear="onClear"
                    suffix-icon="iconfont iconSearch"
                    v-throttle="onPartyMemberChange">
                </el-input>
              </p>
              <el-table
                  ref="peopleTable"
                  :data="getTableData"
                  size="mini"
                  class="people-list"
                  :border="false"
                  header-cell-class-name="table-header"
                  :header-cell-style="{ lineHeight: '26px' }"
                  :cell-style="{ padding: 0, lineHeight: '26px', cursor: 'pointer' }"
                  tooltip-effect="light"
                  cell-class-name="table-cell-add"
                  @row-click="onRowClick"
                  @select="onSelect"
                  @select-all="onSelectAll"
                  @selection-change="onSelectionChange">
                <el-table-column type="selection" width="30px"/>
                <el-table-column
                    prop="con"
                    align="left"
                    label="全选"
                    show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div class="user-wrapper">
                      <i class="iconfont iconProlife"></i>
                      <span>{{ scope.row.name }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="phone" align="right" label="" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span style="color: #999999;padding-right: 6px">{{ scope.row.phone }}</span>
                  </template>
                </el-table-column>
                <div slot="empty" style="font-size: 14px;margin-top: -20px;height: 20px;line-height: 20px">
                  当前党组织暂无党员
                </div>
              </el-table>
              <div class="pagination">
                <el-pagination
                    background
                    :pager-count="5"
                    small
                    :current-page.sync="searchObj.current"
                    :total="total || 0"
                    :page-size.sync="searchObj.size"
                    layout="prev, slot, next, sizes, total"
                    @select="onSelect"
                    @size-change="onSizeChange"
                    @current-change="getPartyMemberByOrg">
                  <div class="pagination-slot">
                    <em>第</em>
                    <i>{{ searchObj.current }}</i>
                    <em>页</em>
                  </div>
                </el-pagination>
              </div>
            </div>
          </el-row>
          <div class="selected-people add-item">
            <p class="add_top">
              <span>已选择</span>
              <el-button
                  class="clear-btn"
                  icon="iconfont iconDelete"
                  size="mini"
                  @click=";(selectPeople = []), $refs.peopleTable.clearSelection()">
                清空
              </el-button>
            </p>
            <div class="add_tag" v-if="selectPeople.length">
              <div
                  class="tag-item"
                  v-for="(item, i) in selectPeople"
                  :key="i">
                <span>{{ item.name }}</span>
                <i @click="cancelSelect(item, i)" class="iconfont iconOverrule"></i>
              </div>
            </div>
            <div class="add_tag add_tag-nomore" v-else>
              <span>暂无数据</span>
            </div>
          </div>
        </el-row>
      </div>
    </ai-dialog>
  </section>
</template>

<script>
export default {
  name: 'AiPartyMember',
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: Array,
    instance: Function,
    btnText: {type: String, default: '选择党员'},
    dialogTitle: {type: String, default: '选择党员'},
    meta: {type: Array, default: () => []},
    action: String,
    partyList: {
      type: Array,
      default: () => []
    },
    partyOrgList: {
      type: Array,
      default: () => []
    },
    organizationId: {
      type: String
    },
    customOrg: {
      type: Boolean,
      default: false
    },
    customCliker: {type: Boolean, default: false},
    isSingle: {type: Boolean, default: false},
    disable: {type: Array, default: () => []}
  },
  data() {
    return {
      aid: '',
      currNodeKey: '',
      visible: false,
      total: '',
      filterText: '',
      searchObj: {
        partyOrgId: '',
        con: '',
        current: 1,
        size: 10
      },
      orgTreeProp: {
        children: 'children',
        label: 'name',
      },
      orgList: [],
      peopleList: [],
      selecteds: [],
      selectPeople: [],
      isChangeData: false,
      isResetData: false,
      copyMeta: [],
      chooseOrgNum: 0
    }
  },

  computed: {
    hasMeta() {
      return Boolean(this.meta.length)
    },

    dialogWidth() {
      if (this.hasMeta || this.action) {
        return '640px'
      }

      return '912px'
    },

    partyOrgIdList() {
      return this.partyOrgList.map(item => {
        return item.id
      })
    },

    getTableData() {
      if (this.hasMeta) {
        const current = this.searchObj.current

        return this.copyMeta.slice((current - 1) * 10, current * 10)
      } else {
        return this.peopleList
      }
    }
  },

  watch: {
    visible(v) {
      if (this.value) {
        this.selectPeople = JSON.parse(JSON.stringify(this.value))
        if (v && this.selectPeople) {
          setTimeout(() => {
            this.toggleSelection()
          }, 200)
        }
        setTimeout(() => {
          if (this.$refs.orgTree && this.filterText) {
            this.$refs.orgTree.filter(this.filterText)
          }
        }, 200)
      }
    },

    filterText(val) {
      if (this.$refs.orgTree) {
        this.$refs.orgTree.filter(val)
      }
    },

    partyOrgList: {
      handler(v, value) {
        if (v.length && value) {
          this.getOrgList()
        }
      }
    },

    disable: {
      handler(v, value) {
        if (v.length && value) {
          this.getOrgList()
        }
      },
      immediate: true,
      deep: true
    }
  },

  mounted() {
    if (this.hasMeta || this.action) {
      let list = this.meta
      if (this.disable.length) {
        list = this.meta.filter(item => {
          let index = this.disable.findIndex(d => {
            return d.id == item.id
          })

          return index === -1
        })
      }
      this.copyMeta = [...list]

      this.getPartyMemberByOrg()
    } else {
      this.getOrgList()
    }
  },

  methods: {
    onSelect(params, row) {
      if (this.isSingle) {
        let index = params.findIndex((d) => d.id == row.id)
        this.getTableData.forEach(item => {
          this.$refs.peopleTable.toggleRowSelection(item, false)
        })

        this.$refs.peopleTable.toggleRowSelection(row, index > -1 ? true : false)
        this.selectPeople = params.length ? [row] : []
      } else {
        let index = this.selectPeople.findIndex((d) => d.id == row.id)
        if (index > -1) {
          this.selectPeople.splice(index, 1)
        }
      }
    },

    onSelectAll(e) {
      if (this.isSingle) {
        if (this.getTableData.length) {
          this.getTableData.forEach(item => {
            this.$refs.peopleTable.toggleRowSelection(item, false)
          })

          this.selecteds = []
        }
      }

      if (!e.length) {
        this.selectPeople = []
      }
    },

    filter() {
      if (this.disable.length) {
        this.peopleList = this.peopleList.filter(item => {
          let index = this.disable.findIndex((d) => d.id == item.id)

          return index === -1
        })
      }
    },

    onSelectionChange(params) {
      if (this.isSingle) return

      if (this.selectPeople.length && (this.isChangeData || this.isResetData)) return
      params.forEach(item => {
        let index = this.selectPeople.findIndex((d) => d.id == item.id)
        if (index === -1) this.selectPeople.push(item)
      })

      this.isChangeData = false
      this.isResetData = false
    },

    onRowClick(row) {
      if (this.isSingle) return
      this.$refs.peopleTable.toggleRowSelection(row)
    },

    toggleSelection() {
      if (this.selectPeople.length) {
        this.isChangeData = true
        this.peopleList.forEach(item => {
          let index = this.selectPeople.findIndex((d) => d.id == item.id)

          if (index > -1) {
            this.$refs.peopleTable && this.$refs.peopleTable.toggleRowSelection(item, true)
          }
        })

        this.isChangeData = false
        this.isResetData = false
      }
    },

    getOrgList() {
      if (this.hasMeta) {
        this.getPartyMemberByOrg()
        let partys = this.meta.map((e) => {
          return {id: e.partyOrgId, name: e.partyOrgName}
        })

        if (partys.length) {
          let pending = [],
              partyList = []
          partys.map((u) => {
            if (partys.some((e) => e.id == u.partyOrgId)) {
              pending.push(u)
            } else {
              let index = partyList.findIndex(item => u.id == item.id)
              index === -1 && (partyList.push(u))
            }
          })
          partyList.map((t) => this.addChild(t, pending))
          this.orgList = [
            {
              name: '全部',
              children: partyList,
            },
          ]
        }
      } else {
        this.instance.post(`/app/partyOrganization/queryPartyOrganizationServiceList`).then((res) => {
          res.data = res.data.map((a) => {
            return {...a, label: a.name}
          })
          this.orgList = res.data.filter((e) => {
            if (this.customOrg && this.partyOrgIdList.length) {
              return this.partyOrgIdList.indexOf(e.id) > -1
            }

            if (this.customOrg && !this.partyOrgIdList.length) {
              return false
            }

            return !e.parentId
          })


          if (this.partyList.length) {
            this.orgList = this.partyList.map((a) => {
              return {...a, label: a.name}
            }).filter(v => {
              return !v.parentId
            })
            this.orgList = this.orgList.length ? this.orgList : this.partyList
            this.orgList.map((t) => this.addChild(t, this.partyList))
          } else {
            !this.partyOrgIdList.length && this.orgList.map((t) => this.addChild(t, res.data))
          }

          if (this.orgList.length) {
            this.currNodeKey = this.orgList[0].id
            this.searchObj.partyOrgId = this.orgList[0]
            this.getPartyMemberByOrg(this.orgList[0])
          }
        })
      }
    },
    addChild(parent, pending) {
      let doBeforeCount = pending.length
      parent['children'] = parent['children'] || []
      pending.map((e, index, arr) => {
        if (e.parentId == parent.id) {
          parent.children.push(e)
          arr.splice(index, 1)
          this.addChild(parent, arr)
        }
      })
      if (pending.length > 0 && doBeforeCount > pending.length) {
        parent.children.map((c) => this.addChild(c, pending))
      }
    },

    onClear() {
      this.searchObj.con = ''

      this.$nextTick(() => {
        this.onPartyMemberChange()
      })
    },

    onSizeChange() {
      this.searchObj.current = 1
      this.getPartyMemberByOrg()
    },

    onPartyMemberChange() {
      this.searchObj.current = 1
      if (!this.meta.length) {
        this.isResetData = true

        this.$nextTick(() => {
          this.getPartyMemberByOrg()
        })
      } else {
        if (!this.searchObj.con) {
          this.meta = this.copyMeta

          return false
        }

        this.p = this.meta.filter(item => {
          return item.name.indexOf(this.searchObj.con) > -1 || item.phone.indexOf(this.searchObj.con) > -1
        })
      }
    },

    getPartyMemberByOrg(partyOrg) {
      if (partyOrg) this.searchObj.partyOrgId = partyOrg.id
      if (this.hasMeta) {
        return new Promise((resolve) => {
          this.peopleList = this.meta.filter((f) => {
            if (this.searchObj.partyOrgId) {
              return f.partyOrgId == this.searchObj.partyOrgId
            } else if (this.searchObj.con) {
              return (
                  [f.name, f.phone]
                  .join('|')
                  .indexOf(this.searchObj.con) > -1
              )
            } else return true
          })
          this.peopleList = this.peopleList.map((p) => {
            return p
          })

          this.filter()

          this.$nextTick(() => {
            this.toggleSelection()
          })
          this.total = this.meta.length
          resolve()
        })
      } else {
        let search = {...this.searchObj}

        if (this.action) {
          delete search.partyOrgId
        }

        return this.instance.post(this.action || '/app/appparty/list', null, {
          params: {
            ...search
          },
        }).then((res) => {
          this.total = res.data.total ? res.data.total : 0
          this.peopleList = res.data.records.map(item => {
            return item
          })
          this.filter()

          this.$nextTick(() => {
            this.toggleSelection()
          })
        })
      }
    },
    treeNodeClick(partyOrg) {
      this.isResetData = true
      this.getPartyMemberByOrg(partyOrg)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    cancelSelect(row, index) {
      let tableItem = this.peopleList.find((s) => s.id == row.id)
      if (tableItem) {
        this.$refs.peopleTable.toggleRowSelection(tableItem)
      }
      this.selectPeople.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.clear-btn {
  width: 64px;
  height: 28px;
  padding: 0 8px;
  font-size: 12px;
}

.pagination-slot {
  display: inline-block;
  align-items: center;
  width: 56px;
  height: 22px;
  line-height: 22px;
  background: #fff;
  border: 1px solid #d0d4dc;
  border-radius: 4px;
  font-size: 12px;
  color: #999;
  box-sizing: border-box;

  em {
    font-style: normal;
    font-weight: normal;
  }

  i {
    padding: 0 3px;
    color: #333;
    font-style: normal;
  }
}

.AiPeopleMember-dialog {
  ::v-deep .el-input__validateIcon {
    display: none;
  }

  ::v-deep.el-pagination__sizes {
    width: 72px !important;

    .el-select, .el-input, input {
      width: 72px !important;
      height: 22px;
    }

    .el-input--mini .el-input__icon {
      line-height: 22px !important;
    }

    .el-select .el-input .el-input__inner {
      padding-right: 18px;
    }
  }
}

.AiPeopleMember .iconfont {
  margin: 0;
}

.add_tag-nomore {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;

  span {
    font-size: 12px;
  }
}

.add-item__middel {
  overflow: hidden !important;

  .people-list {
    height: calc(100% - 72px);
    overflow-y: auto;
  }
}

.AiPeopleMember-dialog {
  .search-panel {
    width: auto;
    margin-right: 16px;
  }

  .user-wrapper {
    display: flex;
    align-items: center;

    i {
      font-size: 16px;
      color: #8899BB;
    }

    span {
      position: relative;
      top: 2px;
      color: #333;
      font-size: 12px;
    }
  }

  ::v-deep.pagination {
    padding: 0 !important;


  }

  ::v-deep.pagination .el-pager li {
    line-height: 22px !important;
  }

  ::v-deep.el-table__header {
    margin-bottom: 4px;
    border-bottom: 1px solid rgba(208, 212, 220, 1);

    thead {
      height: 32px;
      background: #fff;
    }

    .table-header {
      margin-bottom: 4px;
      border-right: none !important;
      background: #fff !important;
    }
  }

  .add-item {
    position: relative;
    width: 300px;
    height: 360px;
    background: rgba(252, 252, 252, 1);
    border-radius: 2px;
    border: 1px solid rgba(208, 212, 220, 1);
    position: relative;
    overflow: auto;
    box-sizing: border-box;

    ::v-deep.el-table td, .el-table th.is-leaf {
      border-bottom: none;
    }

    ::v-deep.el-table::before {
      display: none;
    }

    .pagination {
      display: flex;
      position: absolute;
      align-items: center;
      justify-content: center;
      bottom: 0 !important;
      height: 32px;
      line-height: 1;
      background: rgba(245, 246, 247, 1);
    }

    &:nth-of-type(2) {
      width: 273px;
      overflow: hidden;
    }

    &:nth-of-type(3) {
      width: 360px;
      overflow: hidden;
    }

    .pagination {
      position: absolute;
      bottom: 20px;
      padding: 0;
    }

    .add_top {
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 40px;
      background: rgba(245, 245, 245, 1);
      border-bottom: 1px solid rgba(208, 212, 220, 1);
      padding: 0 8px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .el-input {
        width: 166px;
      }

      ::v-deep.el-input--small .el-input__icon {
        line-height: 28px;
      }

      ::v-deep.el-input--small .el-input__inner {
        width: 166px;
        height: 28px;
      }
    }

    .tree_list {
      width: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      height: calc(100% - 40px);
      padding: 12px 0;
      box-sizing: border-box;;

      .el-tree {
        height: 100%;
      }
    }

    .add_buttom {
      position: absolute;
      left: 0;
      bottom: 0;
      font-size: 12px;
      width: 310px;
      height: 32px;
      line-height: 32px;
      z-index: 10000;
      background: rgba(245, 246, 247, 1);
      color: rgba(51, 51, 51, 1);
      box-shadow: 0 1px 0 0 rgba(216, 220, 227, 1);
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }

    .add_tag {
      width: 100%;
      height: calc(100% - 40px);
      padding: 8px 8px 0 8px;
      font-size: 0;
      line-height: 1;
      overflow-y: auto;
      overflow-x: hidden;
      box-sizing: border-box;

      .tag-item {
        display: inline-block;
        height: 24px;
        line-height: 24px;
        margin: 0 8px 8px 0;
        padding: 0 2px 0 8px;
        font-size: 12px;
        color: #666666;
        border-radius: 2px;
        border: 1px solid rgba(208, 212, 220, 1);

        i {
          margin-right: 0;
          padding-left: 6px;
          font-size: 12px;
          color: #8899BB;
          cursor: pointer;
          font-weight: normal;
        }
      }
    }
  }
}

.el-input--mini {
  height: 22px;
  line-height: 22px;
}

.table-cell-add {
  padding: 0 !important;
}
</style>
