<template>
  <div>
    <van-popup
      v-model="showSelectorPopup"
      class="ibps-fullscreen-popup"
      position="bottom"
      get-container="body"
      @opened="openedDialog"
    >
      <template v-if="initPage">
        <van-sticky>
          <!-- 头部 -->
          <ibps-picker-toolbar
            :title="title"
            @cancel="onCancel"
            @title="onTitle"
            @confirm="onConfirm"
          />
          <!-- 搜索框 -->
          <van-search
            v-model="search"
            :disabled="currentOrgIdValue===''?false:$store.getters.isSuper?false:!isUseScope"
            :placeholder="searchPlaceholder"
            show-action
            @search="onSearch"
          >
            <template #left>
              <van-icon name="bars" class="ibps-pr-5" @click="clickTree" />
            </template>
            <template #action>
              <van-icon name="filter-o" @click="clickMoreSearch" />
            </template>
          </van-search>
        </van-sticky>

        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list v-model="loading" :finished="finished" @load="loadData">
            <van-checkbox-group
              ref="checkboxGroup"
              v-model="checkbox"
              :max="multiple?0:1"
            >
              <van-cell
                v-for="(data,index) in listData"
                :key="data[valueKey]+index"
                clickable
                @click="toggle(data,index)"
              >
                <template #icon>
                  <van-checkbox
                    ref="checkboxes"
                    :name="data[valueKey]"
                  >
                    <template v-if="!multiple" #icon="props">
                      <div v-if="props.checked" class="ibps-radio-icon">
                        <div class="ibps-radio-icon_inside" />
                      </div>
                      <van-icon v-else name="circle" />
                    </template>
                  </van-checkbox>
                </template>
                <template slot="title">
                  <van-cell
                    :title="data[labelKey]"
                    :label="data.account"
                    clickable
                    style="padding: 10px 5px;"
                    class="ibps-flex-c"
                  >
                    <template #icon>
                      <ibps-avatar
                        :thumb="getPhoto(data['photo'])"
                        :thumb-error="errorImage"
                        :text="data[labelKey]"
                        bg-color="#38f"
                        width="44"
                        height="44"
                        radius="4"
                        class="ibps-mr-10"
                      />
                    </template>
                  </van-cell>
                </template>
              </van-cell>
            </van-checkbox-group>
          </van-list>
          <ibps-list-result-page
            :result-type="resultType"
            :error-type="errorType"
            :result-message="resultMessage"
          />
        </van-pull-refresh>
      </template>
    </van-popup>

    <!--点击明细 -->
    <van-popup
      v-if="multiple"
      v-model="showDetailPopup"
      class="ibps-fullscreen-popup"
      position="right"
      get-container="body"
    >
      <ibps-picker-toolbar
        title="已选择的选项"
        @cancel="onDetailCancel"
        @confirm="onDetailConfirm"
      />
      <div class="ibps-fixed-navbar">
        <van-cell-group>
          <van-swipe-cell
            v-for="(data,index) in selectedData"
            :key="data[valueKey]+index"
            :right-width="65"
            class="ibps-swipe-cell"
          >
            <van-cell
              clickable
            >
              <template slot="title">
                <van-cell
                  :title="data[labelKey]"
                  :label="data.account"
                  clickable
                  style="padding: 10px 5px;"
                >
                  <template slot="icon">
                    <ibps-avatar
                      :thumb="getPhoto(data['photo'])"
                      :thumb-error="errorImage"
                      :text="data[labelKey]"
                      bg-color="#38f"
                      round
                      class="ibps-mr-10"
                    />
                  </template>
                </van-cell>
              </template>
              <template #right-icon>
                <van-icon
                  name="clear"
                  class="van-field__clear ibps-pt-15"
                  @click.stop="removeSelected(index)"
                />
              </template>
            </van-cell>
            <van-button
              slot="right"
              type="danger"
              :text="$t('delete')"
              class="ibps-swipe-button"
              @click="removeSelected(index)"
            />
          </van-swipe-cell>
        </van-cell-group>
      </div>
    </van-popup>
    <!--高级查询-->
    <ibps-more-search
      :show="moreSearchPopup"
      :search-forms="searchForms"
      @callback="onMoreSearch"
      @close="visible => moreSearchPopup = visible"
      @reset-form="resetForm"
    />
    <!--左树-->
    <tree-popup
      ref="elTree"
      :visible="treeVisible"
      :range.sync="partyType"
      :script="script"
      :is-use-scope="isUseScope"
      :party-type-id="partyTypeId"
      :party-type-scope="partyTypeScope"
      :custom-party-type-options="currentFilterOption"
      :current-org-id="currentOrgId"

      @close="visible => treeVisible = visible"
      @node-click="handleNodeClck"
      @change-party-type="changePartyType"
    />
  </div>
</template>
<script>
import { query } from '@/api/platform/org/user'
import { queryWoutOrg, queryPageList, queryWithOrg4Position } from '@/api/platform/org/employee'
import { get as getUserById } from '@/api/platform/org/employee'
import panelTree from './popup-tree/mixins/otherTreeEven'
// import { getScriptValue as getTreeDataByScriptValue } from '@/api/platform/form/common'
import ActionUtils from '@/utils/action'
import i18n from '@/utils/i18n' // Internationalization 国际化
import { genderOptions } from './constants'
import IbpsAvatar from '@/components/ibps-avatar'
import IbpsListResultPage from '@/components/ibps-list-result-page'
import IbpsMoreSearch from '@/components/ibps-more-search'
import TreePopup from './popup-tree/index.vue'
import IbpsPickerToolbar from '@/components/ibps-picker-toolbar'

export default {
  components: {
    IbpsPickerToolbar,
    IbpsAvatar,
    IbpsListResultPage,
    IbpsMoreSearch,
    TreePopup
  },
  mixins: [panelTree],
  props: {
    showPopup: Boolean,
    multiple: Boolean,
    value: {
      type: [String, Array]
    },
    leftText: {
      type: String,
      default: i18n.t('cancel')
    },
    searchPlaceholder: {
      type: String,
      default: i18n.t('common.input')
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    labelKey: {
      type: String,
      default: 'name'
    },
    idKey: {
      type: String,
      default: 'id'
    },
    parentIdKey: {
      type: String,
      default: 'parentId'
    },
    childrenKey: {
      type: String,
      default: 'children'
    },
    filter: [Object, Array],

    isUseScope: { // 是否启用范围
      type: Boolean,
      default: false
    },
    seetingSearchPartyType: String, // 设置查询用户类型
    partyTypeScope: String,
    script: String,
    partyTypeId: [String, Number],
    currentOrgId: [String, Number],
    customPartyTypeOptions: {
      type: [Object, Array],
      default: () => {}
    }

  },
  data() {
    const { first = '', second = '' } = this.$store.getters.level
    const { isSuper = false } = this.$store.getters
    let level = second || first
    if (isSuper) {
      level = null
    }
    return {
      level,
      search: '',
      partyId: '',
      moreParams: {},
      moreSearchPopup: false,
      treeVisible: false,
      partyType: 'position',

      listData: [],
      pagination: {},
      sorts: {},

      loading: false,
      finished: false,
      refreshing: false,
      resultType: 'init',
      errorType: null,
      resultMessage: null,

      errorImage: this.$baseUrl + 'images/user/default.png',

      searchForms: {
        forms: [
          { prop: 'Q^ACCOUNT_^SL', label: '账号' },
          // { prop: 'Q^PARTY_ALIAS_^SL', label: ''}
          // { prop: 'Q^EMAIL_^SL', label: '邮箱' },
          // { prop: 'Q^WC_ACCOUNT_^SL', label: '微信账户' },
          // { prop: 'Q^QQ_^SL', label: 'QQ' },
          // { prop: 'Q^MOBILE_^SL', label: '电话' },
          {
            prop: 'Q^GENDER_^S',
            label: '性别',
            fieldType: 'select',
            valueKey: 'value',
            options: genderOptions
          }
        ]
      },

      checkbox: [],
      cacheData: {},

      initPage: false,
      showSelectorPopup: false,
      showDetailPopup: false,
      partyTypeIdValue: '',
      currentOrgIdValue: '',
      scriptValue: '',
      moreSearchParams: {},
      currentFilterOption: []

    }
  },
  computed: {
    title() {
      if (this.multiple) {
        const length = this.checkbox.length
        return length > 0 ? i18n.t('components.checkbox.title', { length: length }) : ''
      } else {
        if (this.$utils.isEmpty(this.checkbox)) {
          return ''
        }
        const checked = this.checkbox[0]
        const cuser = this.listData.find(i => i.id === checked)
        return this.$utils.isNotEmpty(checked) ? this.cacheData[checked] ? this.cacheData[checked][this.labelKey] ? this.cacheData[checked][this.labelKey] : '' : cuser.name : ''
      }
    },
    selectedData() {
      return this.checkbox.map((d) => {
        return this.cacheData[d] || {}
      })
    },
    listDatas() {
      return this.listData
    }
    // changeParams() {
    //   const { partyTypeId, currentOrgId, isUseScope, script, partyTypeScope } = this
    //   return {
    //     partyTypeId,
    //     currentOrgId,
    //     isUseScope,
    //     script,
    //     partyTypeScope
    //   }
    // }
  },
  watch: {
    value(val, oldVal) {
      this.initData(val)
    },
    showPopup(val, oldVal) {
      this.showSelectorPopup = val
      if (!val) {
        this.initDefault()
      }
      this.transitionPartyTypeOptions()
    }
  },
  methods: {
    transitionPartyTypeOptions() {
      if (this.$utils.isNotEmpty(this.customPartyTypeOptions)) {
        this.currentFilterOption = this.customPartyTypeOptions.map(c => {
          return {
            text: c.label,
            value: c.value
          }
        })
      }
    },
    initDefault() {
      this.search = ''
      this.partyId = ''
      this.moreParams = {}
      this.pagination = {}
      this.listData = []
      this.initPage = false
    },
    // =============初始化数据==================
    initData(data) {
      this.checkedValue = []
      if (this.$utils.isEmpty(data)) {
        this.emitInitData([])
        return
      }
      data.forEach(v => {
        if (this.cacheData[v]) {
          this.checkedValue.push(v)
        } else {
          this.getDataInfo(v)
        }
      })
      this.checkbox = data
    },
    /**
     * 获取数据信息
     */
    getDataInfo(id) {
      getUserById({ employeeId: id }).then(response => {
        const data = response.data
        if (this.$utils.isEmpty(data)) {
          return
        }
        data[this.labelKey] = data['name']
        this.cacheData[data[this.idKey]] = data
        this.checkedValue.push(data[this.idKey])
        this.emitInitData(this.getSelectedData(this.checkedValue))
      }).catch((e) => {
        console.error(e)
      })
    },
    emitInitData(data) {
      this.$emit('init-data', data)
    },
    // =============初始化数据end==================
    clickTree() {
      this.treeVisible = true
    },
    handleNodeClck(id) {
      this.partyId = id
      this.onSearch()
    },
    changePartyType(value) {
      this.$emit('change-party-type', value)
      this.partyType = value
      this.refreshing = true
      this.loadData()
    },
    openedDialog() {
      this.initPage = true
      this.onSearch()
    },
    /**
     * 加载数据
     */
    loadData() {
      this.loading = true
      let type = this.partyType
      // query(partyType, this.getFormatParams()).then(response => {
      //   ActionUtils.handleListData(this, response.data)
      //   console.log(response.data, 'response.dataresponse.dataresponse.data')
      //   // 缓存
      //   if (this.$utils.isNotEmpty(this.listData
      //     this.listData.forEach((d) => {
      //       this.cacheData[d[this.valueKey]] = d
      //     })
      //   }
      // }).catch((e) => {
      //   ActionUtils.handleErrorData(this, e)
      // })
      console.log(this.treeVisible, '|', this.partyType, '|', this.partyId, '|', this.isUseScope, '|', this.currentOrgIdValue, '|', this.partyTypeIdValue, '|', this.seetingSearchPartyType, 'dddddddddddddd')
      if (!this.treeVisible) {
        if (this.$utils.isNotEmpty(this.partyId) || this.isUseScope) {
          type = this.partyType
        } else if (this.currentOrgIdValue && this.currentOrgIdValue !== '') {
          type = 'org'
        }
        let flag = 0
        if (type === 'position' && !this.partyId && this.partyTypeIdValue === '1') {
          type = 'user'
          flag = '1'
        }
        query(type, this.getFormatParams(flag)).then(response => {
          this.loading = false
          ActionUtils.handleListData(this, response.data)
          this.setSelectRow()
        }).catch(() => {
          this.loading = false
        })
      } else if (this.seetingSearchPartyType === 'position') {
        queryWithOrg4Position(this.getFormatParams()).then(response => {
          this.loading = false
          ActionUtils.handleListData(this, response.data)
          this.setSelectRow()
        }).catch(() => {
          this.loading = false
        })
      } else if (this.$utils.isNotEmpty(this.currentOrgIdValue)) {
        queryWoutOrg(this.getFormatParams()).then(response => {
          this.loading = false
          ActionUtils.handleListData(this, response.data)
          this.setSelectRow()
        }).catch(() => {
          this.loading = false
        })
      } else {
        queryPageList(this.getFormatParams('1')).then(response => {
          this.loading = false
          ActionUtils.handleListData(this, response.data)
          this.setSelectRow()
        }).catch(() => {
          this.loading = false
        })
      }
    },
    /**
     * 获取查询条件格式化参数
     */
    getFormatParams(flag = '0') {
      const storeGetters = this.$store.getters
      const params = this.$refs['crud'] ? this.$refs['crud'].getSearcFormData() : {}
      const key = this.partyType === 'org' ? 'orgId' : this.partyType === 'position' ? 'positionId' : this.partyType === 'role' ? 'roleId' : this.partyType === 'group' ? 'groupId' : ''
      const deptLists = storeGetters.deptList.map((m) => {
        return m.positionId
      })
      if (!this.treeVisible) {
        if (this.$utils.isNotEmpty(this.partyId) || this.currentOrgIdValue !== '') {
          if (this.partyId !== 0 && this.partyId !== '0') {
            params[key] = this.partyId === '' ? this.currentOrgIdValue : this.partyId
          }
          if (!this.partyId && this.partyTypeId === '2' && this.partyType === 'position') {
            const position = storeGetters.userInfo.employee.positions
            params.positionId = position
          }
        } else {
          if (this.partyType === 'position') {
            params[key] = this.partyTypeId ? (this.partyTypeId === '1' ? '' : this.partyTypeId) : deptLists.join(',')
          } else {
            params[key] = this.partyTypeId === '1' ? '' : this.partyTypeId
          }
        }
      }
      if (this.seetingSearchPartyType === 'position') {
        params['positionId'] = this.partyTypeId
      }
      if (this.moreSearchParams && Object.keys(this.moreSearchParams).length !== 0) {
        Object.assign(params, this.moreSearchParams)
      }
      // if (this.$utils.isNotEmpty(this.currentOrgId)) {
      //   params['orgId'] = this.partyId || this.currentOrgId
      // }
      const res = ActionUtils.formatParams(params, this.pagination, this.sorts)
      // 数据过滤
      if (this.level && (flag === '1' || this.partyType === 'role')) {
        res.customs = {
          position: this.level
        }
      }
      return res
    },
    /**
     * 下拉刷新
     */
    onRefresh() {
      this.refreshing = true
      this.finished = false
      this.loading = true
      this.onSearch()
    },
    /**
     * 查询
     */
    onSearch() {
      this.stateActive = false
      this.moreSearchParams = this.search === '' ? {} : { 'Q^NAME_^SL': this.search }
      if (this.moreParams && Object.keys(this.moreParams).length !== 0) {
        Object.keys(this.moreParams).forEach(key => {
          this.moreSearchParams[key] = this.moreParams[key]
        })
      }
      ActionUtils.initListData(this)
      this.loadData()
    },
    /**
     * 高级查询
     */
    onMoreSearch(params) {
      this.moreParams = params
      console.log(params, '.....params,,,,,')
      this.onSearch()
      if (this.$utils.isNotEmpty(params)) {
        this.stateActive = true
      }
    },
    /**
     * 弹窗更多查询条件
     */
    clickMoreSearch() {
      this.moreSearchPopup = true
      this.stateActive = false
    },
    /**
     * 重置表单
     */
    resetForm() {

    },
    getPhoto(photo) {
      if (this.$utils.isNotEmpty(photo)) {
        return photo.split('=')[1]
      } else {
        return
      }
    },
    toggle(data, index) {
      console.log(this.multiple, '2222222222')
      if (!this.multiple) {
        this.$refs.checkboxGroup.toggleAll(false)
      }
      this.$refs.checkboxes[index].toggle()
    },
    getSelectedData(data) {
      const result = []
      data.forEach((d) => {
        if (this.cacheData[d]) {
          result.push(this.cacheData[d])
        }
      })
      return result
    },
    // //////////////明细处理///////////////////
    onTitle() {
      if (!this.multiple) { return }
      this.showDetailPopup = true
    },
    onDetailCancel() {
      this.showDetailPopup = false
    },
    onDetailConfirm() {
      this.showDetailPopup = false
    },
    removeSelected(index) {
      this.checkbox.splice(index, 1)
    },
    // //////////////////////
    onCancel() {
      this.$emit('cancel')
    },
    onConfirm() {
      // const data = this.multiple ? this.checkbox : [this.radio]
      const data = this.checkbox

      console.log(this.multiple, this.listData, this.checkbox, data, this.radio, 'this.multiplethis.multiple')
      const arr = []
      if (this.multiple) {
        for (let i = 0; i < this.listData.length; i++) {
          for (let l = 0; l < data.length; l++) {
            if (this.listData[i].id === data[l]) {
              arr.push(this.listData[i])
              break
            }
          }
        }
      } else {
        for (let j = 0; j < this.listData.length; j++) {
          if (data.length > 0 && this.listData[j].id === data[0]) {
            arr.push(this.listData[j])
            break
          }
        }
        console.log(arr, 'arrrrrrrr')
      }
      this.$emit('confirm', arr)
      this.$emit('callbackData', arr)
    }
  }
}
</script>

