<template>
  <van-popup
    v-model="dialogVisible"
    class="user-mobile__selector"
    position="right"
    :style="{ width: '100%', height: '100%' }"
    get-container="body"
    @cancel="handleDialogClose"
    @close="handleDialogClose"
    @click-overlay="handleDialogClose"
  >
    <van-nav-bar :title="title" left-arrow @click-left="handleDialogClose" />

    <van-search
      v-model="searchWord"
      shape="round"
      :placeholder="searchPlaceholder"
      @input="onSearchInput"
      @clear="reset"
    >
      <template #left-icon>
        <ht-icon name="search1" width="22" height="22" fill="#8C8C8C" />
      </template>
    </van-search>
    <template v-if="!isRangeFilter">
      <userSelectorMobileDropDown
        v-show="mode !== 'search'"
        ref="userSelectorMobileDropDown"
        :filter-type="filterType"
        @contact-group-change="(group) => $emit('contact-group-change', group)"
      />
    </template>

    <div class="space"></div>

    <template v-if="vanLoading">
      <van-loading class="van-Loading" />
    </template>
    <template v-else>
      <div v-if="loadCount > 0" class="pullRefresh">
        <van-loading v-if="showLoading" class="vanLoading" />
        <van-pull-refresh
          v-model="isLoading"
          pull-distance="80"
          @refresh="onRefresh"
        >
          <template v-if="data && data.length > 0">
            <van-cell
              v-if="!single && data && data.length > 0"
              clickable
              @click="handleCheckAll"
            >
              <van-checkbox :class="getCheckedAllState" shape="square">
                全选
              </van-checkbox>
            </van-cell>

            <van-list
              v-model="isLoading"
              class="user-data__list"
              :finished="finished"
              finished-text="没有更多了"
              @load="loadMore"
            >
              <template v-for="item in data">
                <div
                  :key="item['id']"
                  class="user-data__div"
                  :class="!checkBoxShow(item) ? 'user-data__div_padding' : ''"
                >
                  <van-checkbox
                    v-if="checkBoxShow(item)"
                    :name="item[primaryFieldProp]"
                    :shape="single ? 'round' : 'square'"
                    :class="getCheckedItemState(item)"
                    :bind-group="false"
                    @click="rowClick(item, null, $event)"
                  ></van-checkbox>
                  <div class="user-list__container">
                    <div class="user-list__container_border">
                      <template v-if="item.dataType == 'org'">
                        <div
                          class="org-icon"
                          @click="rowClick(item, null, $event)"
                        >
                          <ht-icon name="org-tree" color="#409eff" />
                        </div>
                        <div
                          class="selector-item__detail selector-item__detail--org"
                          @click.stop="loadLeaf(item)"
                        >
                          <div class="selector-detail__name">
                            <label
                              v-html="brightenKeyword(item['name'], searchWord)"
                            ></label>

                            <span
                              v-if="
                                orgListChildCache[item[primaryFieldProp]] &&
                                orgListChildCache[item[primaryFieldProp]]
                                  .selectCount &&
                                orgListChildCache[item[primaryFieldProp]]
                                  .selectCount > 0
                              "
                              style="color: #409eff"
                            >
                              ({{
                                orgListChildCache[item[primaryFieldProp]]
                                  .selectCount
                              }}/{{ item.userNumber }})
                            </span>

                            <span v-else>({{ item.userNumber }}人)</span>
                          </div>

                          <div class="arrow">
                            <ht-icon name="select" scale="1.1" :rotate="270" />
                          </div>
                        </div>
                      </template>

                      <template v-else>
                        <ht-avatar-image
                          class="follow-theme-background-color"
                          :username="item[selectLabel]"
                          background-color="#409EFF"
                          color="#fff"
                          :size="36"
                          @click="rowClick(item, null, $event)"
                        />
                        <div
                          class="selector-item__detail"
                          @click="rowClick(item, null, $event)"
                        >
                          <div class="selector-detail__name">
                            <!-- <label>{{ item[selectLabel] }}</label> -->
                            <label
                              v-html="
                                brightenKeyword(item[selectLabel], searchWord)
                              "
                            ></label>
                            <span>
                              (
                              <span
                                class="spaceSpan"
                                v-html="
                                  brightenKeyword(item.account, searchWord)
                                "
                              ></span>
                              )
                            </span>
                          </div>
                          <div class="selector-detail__desc">
                            <span :title="item.orgname">
                              <ht-icon name="org-tree" />
                              {{ item.orgname || '暂无组织' }}
                            </span>
                            <span :title="item.postname">
                              <ht-icon name="users" />
                              {{ item.postname || '暂无岗位' }}
                            </span>
                          </div>
                        </div>
                      </template>
                    </div>
                  </div>
                </div>
              </template>
            </van-list>
          </template>
          <template v-else>
            <div class="list-selector__nodata">
              <el-image :src="noDataImg"></el-image>
              <span>暂无数据</span>
            </div>
          </template>
        </van-pull-refresh>
      </div>

      <!-- 已选人员 s-->
      <div class="dialog-footer">
        <div class="txt">
          <div class="center" @click="selectDialogVisible = true">
            已选用户
            <span>{{ selectItemsMap.size }}/{{ maxLimit }}</span>
            <ht-icon name="select" scale="1.1" :rotate="180" />
          </div>
        </div>
        <van-button
          class="mobile-btn"
          block
          round
          size="normal"
          type="info"
          @click="handleDialogSure"
        >
          确 定
        </van-button>
      </div>
      <!-- 已选人员 s-->
      <!-- 已选人员popup s-->
      <van-popup
        v-model="selectDialogVisible"
        round
        position="bottom"
        class="selectDialog"
        :style="{ height: '78vh', width: '100vw' }"
      >
        <div class="head">
          <div class="close" @click="selectDialogVisible = false">关闭</div>
          <div class="title">
            已选人员
            <span>{{ selectItemsMap.size }}/{{ maxLimit }}</span>
          </div>
          <div class="empty" @click="emptySelect">清空</div>
        </div>
        <van-search
          v-model="selectSearchWord"
          shape="round"
          placeholder="搜索"
          @input="onSearchInput"
          @clear="selectSearchWord = ''"
          @cancel="selectSearchWord = ''"
        >
          <template #left-icon>
            <ht-icon name="search1" width="22" height="22" fill="#8C8C8C" />
          </template>
        </van-search>
        <div
          v-if="popupSelectList.length"
          id="popupSelectListUserSelectorMobileDialog"
          class="user-data__list"
        >
          <div
            v-for="item in popupSelectList"
            :key="item['id']"
            class="user-list__container user-select__item"
          >
            <ht-avatar-image
              class="follow-theme-background-color"
              :username="item[selectLabel]"
              background-color="#409EFF"
              color="#fff"
              :size="36"
            />
            <div class="selector-item__detail">
              <div class="selector-detail__name">
                <label
                  v-html="brightenKeyword(item[selectLabel], selectSearchWord)"
                ></label>
                <span v-if="item.account">
                  (
                  <span
                    v-html="brightenKeyword(item.account, selectSearchWord)"
                  ></span>
                  )
                </span>
              </div>
              <div
                v-if="item.orgname || item.postname"
                class="selector-detail__desc"
              >
                <span v-if="item.orgname" :title="item.orgname">
                  <ht-icon name="org-tree" />
                  {{ item.orgname || '暂无岗位' }}
                </span>
                <span v-if="item.postname" :title="item.postname">
                  <ht-icon name="users" />
                  {{ item.postname || '暂无组织' }}
                </span>
              </div>
            </div>
            <van-icon
              name="clear"
              color="#bfbfbf"
              class="cell-close"
              @click="removeSelectUser(item)"
            />
          </div>
        </div>
        <div v-else class="list-selector__nodata">
          <el-image :src="noDataImg"></el-image>
          <span>暂未选择人员</span>
        </div>
      </van-popup>
      <!-- 已选人员popup e-->
    </template>
  </van-popup>
</template>

<script>
  import { debounce } from 'lodash'
  import styles from '@/styles/index.scss'
  import Locale from '@/mixins/locale'
  import UserSelectorMobileDropDown from './UserSelectorMobileDropDown.vue'
  import popupMode from '@/mixins/popupMode.js'

  export default {
    name: 'UserSelectorMobileDialog',
    components: {
      UserSelectorMobileDropDown,
    },
    mixins: [Locale, popupMode('dialogVisible', 'selectDialogVisible')],
    props: {
      range: Object,
      value: {
        type: Array,
        default: () => {
          return []
        },
      },
      selectorsCache: {
        type: Array,
        default: () => {
          return []
        },
      },
      title: {
        type: String,
        default: '选择用户',
      },
      appendToBody: {
        type: Boolean,
        default: true,
      },
      mode: {
        type: String,
      },
      data: {
        type: Array,
        default: () => {
          return []
        },
      },
      pagination: {
        type: Object,
        default: () => {
          return {
            page: 1,
            pageSize: 50,
            total: 0,
          }
        },
      },
      selectLabel: {
        type: String,
        default: 'fullname',
      },
      single: {
        type: Boolean,
        default: false,
      },
      searchPlaceholder: {
        type: String,
        default: '用户名称、账号',
      },
      primaryField: {
        type: String,
        default: '',
      },
      currentPolicyId: {
        type: String,
        default: '',
      },
      filterType: {
        type: String,
        default: '',
      },
      currentRoleId: {
        type: String,
        default: '',
      },
      maxLength: {
        // 最大选中长度
        type: Number,
        default: 0,
      },
      minLength: {
        // 最小选中长度
        type: Number,
        default: 0,
      },
    },
    inject: ['dialogInstance'],
    data() {
      return {
        noDataImg: require('@/assets/no-data.png'),
        dialogVisible: false,
        isLoading: false,

        vanLoading: false,
        showLoading: false,
        searchWord: null,
        selectIds: [],
        selectedData: [],
        finished: false,
        currentUserOrgs: [],
        masterOrgInfo: null,
        loadCount: 0,
        selectDialogVisible: false,
        selectSearchWord: '',
        selectItemsMap: new Map(), // 所有已选择的用户
        orgListChildCache: {
          //id:{item,selectCount,rows}
        },
        popupSelectList: [],
      }
    },
    computed: {
      // 是否是过滤范围
      isRangeFilter() {
        return this.range && this.range.type
      },
      maxLimit() {
        return this.single ? 1 : 100 //100
      },
      primaryColor() {
        return styles.primary_color
      },

      sureButtonText() {
        const selectedText =
          this.selectIds.length > 0 ? `(${this.selectIds.length})` : ''
        return `${this.$t('ht.common.confirm')}${selectedText}`
      },
      primaryFieldProp: function () {
        return this.primaryField ? this.primaryField : 'id'
        // return this.filterType == 'org'
        //   ? 'id'
        //   : this.primaryField
        //   ? this.primaryField
        //   : 'id'
      },

      getCheckedAllState() {
        if (this.selectItemsMap.size == 0) {
          return ''
        }
        let noCheck = 0
        let checked = 0
        //
        this.data.forEach((item) => {
          if (
            this.getCheckedItemState(item) == 'van-checkbox__icon--checked' ||
            (item.dataType == 'org' && item.userNumber == 0)
          ) {
            checked++
          } else if (this.getCheckedItemState(item) == '') {
            noCheck++
          } else {
            checked++
            noCheck++
          }
        })

        if (checked === 0) {
          return ''
        }
        if (noCheck === 0) {
          return 'van-checkbox__icon--checked'
        }
        return ''
        // return 'van-checkbox__icon--indeterminate'
      },
      // 获取当前节点的选中状态
      getCheckedItemState() {
        return function (node) {
          //
          //
          //非组织节点
          if (node.dataType != 'org') {
            if (!this.selectItemsMap.has(node[this.primaryFieldProp])) {
              return ''
            }

            if (
              this.selectItemsMap.get(node[this.primaryFieldProp]).selectFlag
            ) {
              return 'van-checkbox__icon--checked'
            }
            return ''
          }
          // 判断当前组织是否被选中时

          //组织节点
          if (!this.orgListChildCache[node[this.primaryFieldProp]]) {
            return ''
          }
          const { item, selectCount } =
            this.orgListChildCache[node[this.primaryFieldProp]]

          if (
            item.userNumber > 0 &&
            selectCount &&
            selectCount === item.userNumber
          ) {
            return 'van-checkbox__icon--checked'
          }

          // //半选中
          // if (
          //   item.userNumber > 0 &&
          //   selectCount > 0 &&
          //   selectCount < item.userNumber
          // ) {
          //   // return 'van-checkbox__icon--indeterminate'
          //   return ''
          // }

          return ''
        }
      },
    },
    watch: {
      data: {
        handler(val) {
          val.forEach((it) => {
            if (it.dataType == 'org') {
              it[this.primaryFieldProp] = it.id
            }
          })
          if (this.filterType == 'org') {
            val.forEach((it) => {
              if (!this.orgListChildCache[it[this.primaryFieldProp]]) {
                this.$set(this.orgListChildCache, it[this.primaryFieldProp], {
                  item: it,
                  selectCount: 0,
                  rows: [],
                })
              }
            })
          }
          this.handleSelectCount()
          this.$forceUpdate()
        },
        immediate: true,
        deep: true,
      },

      pagination: function (newVal, oldVal) {
        this.isLoading = false
        if (newVal !== oldVal) {
          const { page, pageSize, total } = newVal
          if (page > 0 && pageSize > 0 && total > 0) {
            this.finished = page * pageSize >= total
          } else {
            this.finished = true
          }
        }
      },
      currentPolicyId: {
        handler(val) {
          if (val) {
            this.loadUserWithPolicy(val)
          }
        },
        immediate: true,
        deep: true,
      },

      selectSearchWord: {
        handler() {
          this.handlePopupSelectList()
        },
      },
      selectDialogVisible: {
        handler(val) {
          val && this.handlePopupSelectList()
          if (val && this.popupSelectList.length > 0) {
            this.$nextTick(() => {
              document
                .getElementById('popupSelectListUserSelectorMobileDialog')
                .scrollTo({
                  top: 0,
                })
            })
          }
        },
      },
      currentRoleId: {
        handler(newVal, oldVal) {
          this.isLoading = false

          if (newVal) {
            this.$emit('load-role-user', newVal)
          }
        },
        immediate: true,
      },
    },
    methods: {
      checkBoxShow(item) {
        return !this.single || (item.dataType != 'org' && this.single)
      },
      // 打开弹窗时，初始化空数据
      initEmptyData() {
        this.selectItemsMap = new Map()
        // this.orgListChildCache = {}
      },
      // 清空已选择人员
      emptySelect() {
        this.$nextTick(() => {
          // this.handleCheckAll()
          // 改为全部不选中（无论当前是否全选状态）
          this.unselectAll()

          this.popupSelectList = []
          this.selectItemsMap = new Map()
          this.selectDialogVisible = false
        })
        this.$forceUpdate()
      },
      // 全部不选中（无论当前是否全选状态）
      unselectAll() {
        this.data.forEach((item) => {
          if (item.dataType != 'org') {
            this.selectItemsMap.has(item[this.primaryFieldProp]) &&
              this.unSelectItem(item)
          } else {
            item.userNumber > 0 &&
              this.orgListChildCache[item[this.primaryFieldProp]] &&
              this.orgListChildCache[item[this.primaryFieldProp]].rows &&
              this.orgListChildCache[item[this.primaryFieldProp]].rows.forEach(
                (it) => {
                  this.selectItemsMap.has(it[this.primaryFieldProp]) &&
                    this.unSelectItem(it)
                }
              )
          }
        })
      },
      // 已选择列表中删除已选择人员
      removeSelectUser(item) {
        let index = null
        this.popupSelectList.forEach((k, i) => {
          if (k.id == item.id) {
            index = i
          }
        })

        this.popupSelectList.splice(index, 1)

        this.unSelectItem(item)
      },
      onSearchInput: debounce(function () {
        this.onRefresh()
      }, 500),
      onRefresh() {
        this.isloading = true
        this.$emit('search', this.searchWord)
        this.loadCount == 0 &&
          setTimeout(() => {
            this.loadCount++
          }, 100)
      },
      reset() {
        this.$emit('reset')
      },
      loadMore() {
        if (this.data && this.data.length > 0) {
          this.$emit('page-change', ++this.pagination.page)
        } else {
          this.isLoading = false
        }
      },

      //点击下级
      loadLeaf(item) {
        this.dialogInstance.$emit(
          'load-org',
          {
            demId: item.demId,
            parentId: item.id,
          },
          1,
          () => {
            this.$refs.userSelectorMobileDropDown &&
              this.$refs.userSelectorMobileDropDown.addMiniNavList({
                demId: item.demId,
                parentId: item.id,
                name: item.name,
              })
          }
        )
      },

      //初始化选中数据
      initSelectItemsMap(value = this.selectorsCache, type) {
        this.selectItem(value, type)
      },

      showDialog() {
        this.vanLoading = true
        this.$nextTick(() => {
          if (this.value && this.value.length > 0) {
            this.selectIds = this.value.map(
              (item) => item[this.primaryFieldProp]
            )
            this.selectedData = this.value

            this.initSelectItemsMap(this.selectedData, 'replace')
          } else {
            this.initEmptyData()
          }

          this.dialogVisible = true
          setTimeout(() => {
            this.vanLoading = false
          }, 300)
          if (this.mode !== 'search' && !this.isRangeFilter) {
            this.$nextTick(() => {
              this.$refs.userSelectorMobileDropDown.handleTabToggle(
                'contact',
                'recently'
              )
            })
          }
        })
      },
      handleDialogSure() {
        var data = this.getSelectedData()
        if (this.maxLength && data.length > this.maxLength) {
          try {
            this.$message.warning('超出最大选择数量,请重新选择')
          } catch (error) {
            this.$notify({
              type: 'warning',
              message: '超出最大选择数量,请重新选择',
            })
          }
          return
        }
        if (this.minLength && data.length < this.minLength) {
          try {
            this.$message.warning(`至少选择${this.minLength}个`)
          } catch (error) {
            this.$notify({
              type: 'warning',
              message: `至少选择${this.minLength}个`,
            })
          }
          return
        }
        this.$emit('input', data)
        this.$emit('select-data', data)

        if (data && data.length > 0) {
          // 记录为最近联系人
          var userAccountList = data.map((user) => user.account)
          this.$requestConfig
            .addLogUserSelector(userAccountList)
            .finally(() => {
              this.selectIds = []
              this.selectedData = []
              this.dialogVisible = false
            })
        } else {
          this.selectIds = []
          this.selectedData = []
          this.dialogVisible = false
        }
      },
      handleDialogClose() {
        this.dialogVisible = false
        this.selectIds = []
        this.selectedData = []

        this.selectItemsMap.clear()
      },
      select(selection, row) {
        this.$emit('select', selection, row)
      },

      //获取所有选中数据
      getSelectedData() {
        let result = []
        this.selectItemsMap.forEach((item) => result.push(item))

        return result
      },

      // 计算选中多少下级
      handleSelectCount() {
        Object.keys(this.orgListChildCache).forEach((id) => {
          const { item, rows } = this.orgListChildCache[id]

          if (item && item.userNumber) {
            let selectCount = 0
            if (rows.length > 0) {
              rows.forEach((it) => {
                if (
                  it[this.primaryFieldProp] != id &&
                  this.selectItemsMap.has(it[this.primaryFieldProp])
                ) {
                  selectCount += 1
                }
              })
            } else {
              this.selectItemsMap.forEach((it) => {
                if (it.paths) {
                  for (let i = 0; i < it.paths.length; i++) {
                    if (
                      it.paths[i].indexOf(
                        this.orgListChildCache[id].item.path
                      ) > -1
                    ) {
                      selectCount += 1
                      break
                    }
                  }
                }
              })
            }

            this.$set(this.orgListChildCache, id, {
              ...this.orgListChildCache[id],
              ...{
                selectCount,
              },
            })
          }
        })
      },

      //弹框数据list
      handlePopupSelectList() {
        let result = []
        this.selectItemsMap.forEach((item) => {
          if (this.selectSearchWord) {
            if (
              item[this.selectLabel].includes(this.selectSearchWord) ||
              item.account.includes(this.selectSearchWord)
            ) {
              result.push(item)
            }
          } else {
            result.push(item)
          }
        })

        this.popupSelectList = result
      },

      // 限制提示
      showMaxLimitDialog(fn) {
        this.$dialog
          .alert({
            title: '提示',
            message: `您最多只能选择${this.maxLimit}个用户`,
            confirmButtonText: '我知道了',
            confirmButtonColor: '#409EFF',
          })
          .then(() => {
            // on close
            fn && fn()
          })
      },
      //点击
      async rowClick(row, column, event) {
        // 选中的是用户时
        if (row.dataType != 'org') {
          !this.selectItemsMap.has(row[this.primaryFieldProp])
            ? this.onSelectItem(row)
            : this.unSelectItem(row)
        } else {
          // 选中的是组织时 判断当前组织是否被选中
          if (this.getCheckedItemState(row) == 'van-checkbox__icon--checked') {
            this.unSelectItem(row)
          } else {
            this.onSelectItem(row)
          }
        }
        this.$forceUpdate()
        this.$emit('row-click', row, column, event)
      },
      /**
       *
       * @param {*} item
       * @param {*} type  has? 替换：push
       */
      //选中
      selectItem(item, type) {
        let items = []
        let dataList = new Map()
        Array.isArray(item) ? (items = item) : items.push(item)

        items.forEach((it) => {
          if (this.selectItemsMap.size >= this.maxLimit) {
            this.showMaxLimitDialog()

            return
          }
          this.selectItemsMap.set(it[this.primaryFieldProp], {
            ...it,
            ...{
              selectFlag: true,
            },
          })
        })
        // 主动触发map数据更新 否则双向绑定不会触发
        this.selectItemsMap = new Map(this.selectItemsMap)
      },

      //选择
      async onSelectItem(item, type = false) {
        if (this.single) {
          //没有下级用户
          if (!item.userNumber || item.userNumber == 0) {
            this.selectItemsMap.clear()
            this.selectItem(item)
          } else {
            this.showMaxLimitDialog()
          }
        } /*多选*/ else {
          if (item.dataType == 'org' && item.userNumber == 0 && !type) {
            this.$dialog.alert({
              title: '提示',
              message: `该组织下没有用户了`,
              confirmButtonText: '我知道了',
              confirmButtonColor: '#409EFF',
            })

            return
          }

          if (this.selectItemsMap.size > this.maxLimit) {
            this.showMaxLimitDialog()

            return
          }

          this.showLoading = true
          setTimeout(() => {
            this.showLoading = false
          }, 500)
          //获取下级用户并选中
          if (
            item.dataType == 'org' &&
            item.userNumber &&
            item.userNumber > 0
          ) {
            const { rows } = await this.getOrgData(item)
            rows && rows.length > 0 && this.selectItem(rows)
          } else {
            if (item.dataType != 'org') this.selectItem(item)
          }
        }
        this.handleSelectCount()
        this.$forceUpdate()
      },
      //取消选择
      unSelectItem(item) {
        if (this.single) {
          //单选

          //取消选择
          this.selectItemsMap.delete(item[this.primaryFieldProp])
        } /*多选*/ else {
          //取消选择
          this.selectItemsMap.has(item[this.primaryFieldProp]) &&
            this.selectItemsMap.delete(item[this.primaryFieldProp])
          //取消子组织
          if (item.userNumber > 0) {
            this.orgListChildCache[item[this.primaryFieldProp]] &&
              this.orgListChildCache[item[this.primaryFieldProp]].rows &&
              this.orgListChildCache[item[this.primaryFieldProp]].rows.forEach(
                (it) => {
                  this.selectItemsMap.has(it[this.primaryFieldProp]) &&
                    this.selectItemsMap.delete(it[this.primaryFieldProp])
                }
              )

            this.selectItemsMap.forEach((it) => {
              if (it.paths && it.paths.length > 0) {
                for (let i = 0; i < it.paths.length; i++) {
                  if (it.paths[i].indexOf(item.path) > -1) {
                    this.selectItemsMap.has(it[this.primaryFieldProp]) &&
                      this.selectItemsMap.delete(it[this.primaryFieldProp])
                  }
                }
              }
            })
          }
        }
        this.handleSelectCount()
        // 主动触发map数据更新 否则双向绑定不会触发
        this.selectItemsMap = new Map(this.selectItemsMap)
        this.$forceUpdate()
      },

      // 获取数据
      async getOrgData(item) {
        if (
          this.orgListChildCache[item[this.primaryFieldProp]] &&
          this.orgListChildCache[item[this.primaryFieldProp]].rows &&
          this.orgListChildCache[item[this.primaryFieldProp]].rows.length
        ) {
          this.showLoading = false
          return this.orgListChildCache[item[this.primaryFieldProp]]
        }

        const { rows } = await this.$requestConfig.getUserList({
          pageBean: {
            page: 1,
            pageSize: this.maxLimit,
          },
          querys: [
            {
              property: 'path_',
              value: item.path,
              group: 'main',
              operation: 'RIGHT_LIKE',
              relation: 'AND',
            },
            {
              property: 'uu.show_status_',
              value: '1',
              group: 'main2',
              operation: 'EQUAL',
              relation: 'AND',
            },
          ],
        })
        this.showLoading = false

        let res = {
          item,
          rows,
          selectCount:
            this.orgListChildCache[item[this.primaryFieldProp]].selectCount ||
            0,
        }
        this.orgListChildCache[item[this.primaryFieldProp]] = res

        return res
      },

      // 全选
      async handleCheckAll() {
        //全选状态取消当前组织下所选用户
        if (this.getCheckedAllState == 'van-checkbox__icon--checked') {
          this.data.forEach((item) => {
            if (item.dataType != 'org') {
              this.selectItemsMap.has(item[this.primaryFieldProp]) &&
                this.unSelectItem(item)
            } else {
              item.userNumber > 0 &&
                this.orgListChildCache[item[this.primaryFieldProp]] &&
                this.orgListChildCache[item[this.primaryFieldProp]].rows &&
                this.orgListChildCache[
                  item[this.primaryFieldProp]
                ].rows.forEach((it) => {
                  this.selectItemsMap.has(it[this.primaryFieldProp]) &&
                    this.unSelectItem(it)
                })
            }
          })
          // 主动触发map数据更新 否则双向绑定不会触发
          this.selectItemsMap = new Map(this.selectItemsMap)
          return
        }

        //临时选中
        // let tmpSelectItemsMap = new Map([...this.selectItemsMap])

        // let tmpCount = 0
        // this.data.forEach((item, index) => {
        //   if (item.dataType != 'org') {
        //     tmpCount++
        //     tmpSelectItemsMap.set(item[this.primaryFieldProp], 1)
        //   } else {
        //     if (item.userNumber) {
        //       tmpCount += item.userNumber
        //       this.orgListChildCache[item[this.primaryFieldProp]] &&
        //         this.orgListChildCache[item[this.primaryFieldProp]].rows &&
        //         this.orgListChildCache[
        //           item[this.primaryFieldProp]
        //         ].rows.forEach((item) => {
        //           tmpSelectItemsMap.set(item[this.primaryFieldProp], 1)
        //         })
        //     }
        //   }
        // })

        //超过限制
        // if (
        //   tmpCount > this.maxLimit ||
        //   tmpSelectItemsMap.size > this.maxLimit
        // ) {
        //   this.showMaxLimitDialog()
        //   return
        // }

        //全选
        this.data.forEach((item) => {
          this.onSelectItem(item, true)
          // if (
          //   item.dataType != 'org' ||
          //   (item.dataType == 'org' && !item.userNumber == 0)
          // ) {

          //   this.onSelectItem(item)
          // }
        })

        this.$forceUpdate()
      },

      // 按照指定策略加载数据
      loadUserWithPolicy(policy) {
        //1-我的主部门 2-我的主部门及下属部门
        if (['1', '2'].includes(policy)) {
          this.getMasterOrg()
        }
        this.loadCurrentUserOrgs()
          .then(() => {
            const param = this.getOrgIdWithPolicy(policy)
            this.$emit('load-policy-user', param)
          })
          .catch(() => {
            /*    this.$message.error(
                      '未获取到当前用户的部门信息，无法按照该策略加载数据。'
                    ) */
            const param = { data: 'noCurrentPolicy' }
            this.$emit('load-policy-user', param)
          })
      },
      // 根据策略构建不同的查询参数
      getOrgIdWithPolicy(policy) {
        let result = { type: policy }
        const masterOrg = this.currentUserOrgs.find((org) => org.isMaster == 1)
        switch (policy) {
          case '1':
            result.id = this.masterOrgInfo
              ? this.masterOrgInfo.id
              : masterOrg
              ? masterOrg.id
              : null
            break
          case '2':
            result.path = this.masterOrgInfo
              ? this.masterOrgInfo.path
              : masterOrg
              ? masterOrg.path
              : null
            break
          case '3':
            result.ids = this.currentUserOrgs.map((org) => org.id)
            break
          case '4':
            result.paths = this.currentUserOrgs.map((org) => org.path)
            break
        }
        return result
      },
      // 获取当前用户所属部门数据
      loadCurrentUserOrgs() {
        return new Promise((resolve, reject) => {
          if (this.currentUserOrgs && this.currentUserOrgs.length > 0) {
            resolve()
          } else if (
            this.$requestConfig.getUserId() &&
            this.$requestConfig.getOrgListByUserId
          ) {
            this.$requestConfig
              .getOrgListByUserId(this.$requestConfig.getUserId())
              .then((orgs) => {
                if (orgs && orgs.constructor == Array && orgs.length > 0) {
                  this.currentUserOrgs = orgs
                  resolve()
                } else {
                  reject()
                }
              })
              .catch(() => reject())
          } else {
            reject()
          }
        })
      },
      //获取默认维度下的主组织
      getMasterOrg() {
        this.$requestConfig.getMasterOrgByDefaultDimension().then((res) => {
          if (res.state && res.value) {
            this.masterOrgInfo = res.value
          }
        })
      },

      // 加载常用联系人
      loadContactUser(group, page) {
        let contactGroupId
        this.mode = 'filter'
        this.currentGroup = group
        const param = {
          pageBean: this.getPageBean(page),
        }
        if (group != 'all') {
          contactGroupId = group
        }
        if (this.$requestConfig.getContactUser) {
          this.$requestConfig
            .getContactUser(param, contactGroupId)
            .then((data) => {
              if (data.state && data.value) {
                const { rows, page, pageSize, total } = data.value
                if (this.isMobile && page > 1) {
                  this.data = this.data.concat(rows)
                } else {
                  this.data = rows
                }
                const paginationResult = { page, pageSize, total }
                this.$set(this, 'pagination', paginationResult)
              }
            })
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  .user-mobile__selector {
    box-sizing: border-box;
    padding-bottom: 64px;
    display: flex;
    flex-direction: column;
    ::v-deep {
      .van-tab--active {
        font-weight: bold;
        color: $base-color-blue;
      }
      .van-nav-bar .van-icon {
        color: var(--van-gray-6);
      }
      .van-search__content {
        border-radius: 8px 8px 8px 8px;
        padding-left: 5px;
      }
    }
    .pullRefresh {
      flex: 1;
      overflow-y: scroll; //设置这个 才能指定高度
      ::v-deep {
        .van-pull-refresh {
          min-height: 90%;
        }
        .van-loading {
          position: fixed !important;
          top: 50%;
          left: 50%;
          transform: translateX(-50%);
        }
      }
    }
    .space {
      display: block;
      clear: both;
      height: 10px;
      background: #f6f6f6;
    }
    .user-mobile__title {
      font-size: 18px;
      color: #1a1a1a;
    }
    .user-mobile__close {
      float: right;
    }
    .contact-group__container {
      padding: 0 12px;
    }
    .user-contact__group {
      margin-right: 6px;
      color: #999999;
      max-width: 72px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      &::before {
        border-width: 0;
      }
      &.current {
        color: $base-color-blue;
      }
      &.current::before {
        border-width: 1px;
      }
    }
    .user-list__container_border {
      display: flex;
      flex: 1;
      align-items: center;
      &::after {
        position: absolute;
        box-sizing: border-box;
        content: ' ';
        pointer-events: none;
        right: 0;
        bottom: 0;
        left: 0px;
        border-bottom: 1px solid #ebedf0;
        -webkit-transform: scaleY(0.5);
        transform: scaleY(0.5);
      }
    }
    .user-list__container {
      position: relative;
      display: flex;
      flex: 1;
      align-items: center;
      .vue-avatar--wrapper {
        // margin-left: 10px;
      }
      .selector-item__detail {
        font-size: 12px;
        display: flex;
        flex-direction: column;
        margin-left: 10px;
        flex: 1;
        .selector-detail__name {
          font-size: 12px;
          max-width: 220px;
          max-width: 240px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          label {
            color: #111;
            font-size: 14px;
          }
          span {
            // margin-left: 10px;
            color: #777;
            font-size: 12px;
          }
          .spaceSpan {
            margin: 0;
          }
        }
        .selector-detail__desc {
          display: flex;
          margin-top: 5px;
          span {
            display: inline-block;
            font-size: 12px;
            color: #777; //max-width: 94px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 118px;
          }
          span + span {
            margin-left: 32px;
          }
        }
      }
      &.user-select__item {
        position: relative;
        padding: 10px 16px;
        ::after {
          position: absolute;
          box-sizing: border-box;
          content: ' ';
          pointer-events: none;
          right: 0;
          bottom: 0;
          left: 16px;
          border-bottom: 1px solid #ebedf0;
          -webkit-transform: scaleY(0.5);
          transform: scaleY(0.5);
        }
      }
    }
    .user-data__list {
      ::v-deep {
        .van-checkbox {
          position: relative;
          padding: 10px 16px;
          ::after {
            position: absolute;
            box-sizing: border-box;
            content: ' ';
            pointer-events: none;
            right: 0;
            bottom: 0;
            left: 16px;
            border-bottom: 1px solid #ebedf0;
            -webkit-transform: scaleY(0.5);
            transform: scaleY(0.5);
          }
        }
        .van-checkbox__label {
          flex: 1;
        }
      }
    }
    .user-data__div {
      display: flex;
      min-height: 56px;
    }
    .user-data__div_padding {
      padding-left: 16px;
    }
    .van-action-sheet__cancel {
      padding: 5px;
      background: $base-color-blue;
      color: $base-color-white;
    }
    .dialog-footer {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      width: 100%;
      height: 64px;
      padding: 0 16px;
      background: #ffffff;
      border-top: 1px solid #e6e6e6;
      .mobile-btn {
        width: 110px;
        height: 44px;
        line-height: 44px;
        border-radius: 10px;
        box-sizing: border-box;
        background: #409eff;
        border-color: #409eff;
        padding: 0 24px;
      }
      .txt {
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 1;
        height: 44px;
        font-size: 14px;
        color: #262626;
        text-align: center;
        .center {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 44px;
          padding: 0 16px;
        }
        span {
          color: #409eff;
          margin: 0 6px;
        }
      }
    }
    .van-checkbox__icon--indeterminate {
      ::v-deep {
        .van-checkbox__icon {
          .van-icon {
            color: #fff;
            background-color: #1989fa;
            border-color: #1989fa;
            &:before {
              content: '';
              position: absolute;
              display: block;
              background-color: #fff;
              height: 2px;
              top: 0;
              bottom: 0;
              left: 50%;
              right: 0;
              top: 50%;
              bottom: 0;
              transform: translate(-50%, -50%) scale(0.8);
            }
          }
        }
      }
    }
    .selectDialog {
      display: flex;
      flex-direction: column;
      .head {
        display: flex;
        height: 44px;
        justify-content: space-between;
        align-items: center;
        .close {
          display: block;
          height: 44px;
          line-height: 44px;
          padding: 0 16px;
          font-size: 14px;
          color: #8c8c8c;
        }
        .title {
          flex: 1;
          height: 44px;
          text-align: center;
          line-height: 44px;
          font-weight: bold;
          color: #1a1a1a;
          font-size: 17px;
          span {
            padding: 0 6px;
            color: #409eff;
          }
        }
        .empty {
          height: 44px;
          line-height: 44px;
          padding: 0 16px;
          font-size: 14px;
          color: $base-color-blue;
        }
      }
      .user-data__list {
        flex: 1;
        overflow-y: auto;
      }

      .cell-close {
        font-size: 16px;
      }
    }
    .selector-item__detail--org {
      display: flex;
      flex-direction: row !important;
      justify-content: space-between;
      flex: 1;
      height: 100%;
      align-items: center;
      .arrow {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 36px;
        width: 36px;
        text-align: center;
        line-height: 36px;
      }
    }
    .org-icon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 36px;
      height: 36px;
      background: rgba(64, 158, 255, 0.16);
      border-radius: 50%;
      text-align: center;
    }
  }

  ::v-deep .changColor {
    color: $base-color-blue;
  }
  .list-selector__nodata {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .el-image {
      width: 80%;
      margin-top: 20px;
    }
    span {
      color: #909399;
      font-size: 12px;
    }
  }
  .van-Loading {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    width: 100%;
    height: 100%;
  }
</style>
