<template>
  <div v-if="showSelectorPopup">
    <van-popup v-model="showSelectorPopup" class="ibps-fullscreen-popup" position="bottom" get-container="body" @click-overlay="clickOverlay">
      <van-sticky>
        <!-- 头部 -->
        <ibps-picker-toolbar
          :title="title"
          @cancel="onCancel"
          @title="onTitle"
          @confirm="onConfirm"
        />
        <van-search
          v-model="search"
          :placeholder="searchPlaceholder"
          @search="onSearchAction"
        >
          <!-- <van-icon slot="action" name="bars" style="padding:0 10px;" @click="onSearchAction"/> -->
        </van-search>
      </van-sticky>
      <van-cell-group>
        <van-cell class="ibps-root-title ibps-size-l ibps-nav">
          <div slot="title">
            <template v-for="(data,index) in pathData">
              <span v-if="index !== pathData.length-1" :key="data[valueKey]" @click="changePath(index)">
                {{ data[labelKey] }}
              </span>
              <span v-else :key="data[valueKey]">
                {{ data[labelKey] }}
              </span>
              <!-- <span v-if="pathData.length-1!==index" :key="index" class="ibps-wingblank ibps-color-gary-5">/</span> -->
              <span v-if="pathData.length>0" :key="index" class="ibps-wingblank ibps-color-gary-5">/</span>
            </template>
            <span class="ibps-is-link ibps-nav_text">请选择<span class="ibps-nav_bar" /></span>
          </div>
        </van-cell>
        <van-cell
          v-for="(data,index) in sysList"
          :key="data[idKey]+index"
          clickable
          :size="size"
          @click="toggleChild(data,index)"
        >
          <div slot="title">
            {{ data[labelKey] }}<van-tag plain type="danger">子系统</van-tag>
          </div>
          <span
            slot="right-icon"
          >
            <span class="van-cell__right-icon" />
            <van-icon name="arrow " class="van-cell__right-icon" />
          </span>
        </van-cell>
      </van-cell-group>

      <!---多选-->
      <van-checkbox-group v-if="multiple" v-model="checkbox">
        <van-cell-group>
          <van-list v-model="loading" :finished="finished" @load="onLoad">
            <van-cell
              v-for="(data,index) in listData"
              :key="data[valueKey]+index"
              :size="size"
              clickable
            >
              <div slot="title" @click="toggle(data,index)">
                <van-checkbox
                  ref="checkboxes"
                  :name="data[valueKey]"
                  @click.native.stop="(e)=>clickCheckbox(e,data,index)"
                >
                  {{ data[labelKey] }}
                </van-checkbox>
              </div>
            </van-cell>
          </van-list>
        </van-cell-group>
      </van-checkbox-group>

      <!---单选-->
      <van-radio-group v-else v-model="radio">
        <van-cell-group>
          <van-list v-model="loading" :finished="finished" @load="onLoad">
            <van-cell
              v-for="(data,index) in listData"
              :key="data[valueKey]+index"
              :size="size"
              clickable
            >
              <div slot="title" @click="toggle(data,index)">
                <van-radio
                  ref="radioes"
                  :name="data[valueKey]"
                >
                  {{ data[labelKey] }}
                  <template #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-radio>
              </div>
            </van-cell>
          </van-list>
        </van-cell-group>
      </van-radio-group>
      <!-- 列表内容 end -->

      <ibps-list-result-page
        :result-type="resultType"
        :error-type="errorType"
        :result-message="resultMessage"
      />
    </van-popup>
    <!--点击明细 -->
    <van-popup
      v-if="multiple"
      v-model="showDetailPopup"
      class="ibps-fullscreen-popup"
      get-container="body"
      position="right"
    >
      <ibps-picker-toolbar
        title="已选择的选项"
        @cancel="onDetailCancel"
        @confirm="onDetailConfirm"
      />
      <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
            :title="data[labelKey]"
            clickable
          >
            <template #right-icon>
              <van-icon
                name="clear"
                class="van-field__clear"
                @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>
    </van-popup>
  </div>
</template>
<script>
import { getScriptValue } from '@/api/platform/form/formDef'// 脚本
import { queryPageList, queryRoleScope, get as getRoleById } from '@/api/platform/org/role'
import { getScriptValue as getTreeDataByScriptValue } from '@/api/platform/form/common'
import { findAllSubsystem } from '@/api/platform/auth/subsystem'
import ActionUtils from '@/utils/action'
import i18n from '@/utils/i18n' // Internationalization 国际化
import IbpsListResultPage from '@/components/ibps-list-result-page'
import IbpsPickerToolbar from '@/components/ibps-picker-toolbar'

export default {
  components: {
    IbpsPickerToolbar,
    IbpsListResultPage
  },
  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'
    },
    otherFilter: String,
    otherFilterIncludeSub: [String, Boolean],
    otherFilterCondition: {
      type: Object,
      default: () => {
        return {}
      }
    },
    partyTypeId: { // 类型节点ID
      type: [String, Number],
      default: ''
    },
    currentOrgId: { // 用户组ID
      type: [String, Number],
      default: ''
    },
    script: String,
    isUseScope: { // 是否启用范围
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      search: '',
      pathData: [],
      radio: '',
      checkbox: [],
      sysList: [],
      listData: [],
      cacheData: {},
      showSelectorPopup: false,
      showDetailPopup: false,

      pagination: {},
      loading: false,
      finished: false,
      refreshing: false,
      resultType: 'init',
      errorType: null,
      resultMessage: null,
      size: 'large'
    }
  },
  computed: {
    title() {
      if (this.multiple) {
        const length = this.checkbox.length
        return length > 0 ? i18n.t('components.checkbox.title', { length: length }) : ''
      } else {
        return this.$utils.isNotEmpty(this.radio) ? this.cacheData[this.radio] ? this.cacheData[this.radio][this.labelKey] : '' : ''
      }
    },
    selectedData() {
      return this.checkbox.map((d) => {
        return this.cacheData[d] || {}
      })
    }
  },
  watch: {
    value() {
      this.initData(this.value)
    },
    showPopup() {
      this.showSelectorPopup = this.showPopup
      if (this.showPopup) {
        this.initPageData()
        this.cacheData = []
        if (this.otherFilter === 'script') {
          this.loadDataByScript()
        } else {
          this.loadData({
            name: this.$t('components.selector.role')
          }, true)
        }
      } else {
        this.radio = ''
        this.checkbox = []
      }
    }
  },
  methods: {
    onLoad() {
      const params = {}
      const pathData = this.pathData
      if (this.search) {
        params['Q^NAME_^SL'] = this.search
      }
      if (pathData.length > 1 && pathData[pathData.length - 1]) {
        params['Q^SYSTEM_ID_^S'] = pathData[pathData.length - 1].id
      }
      this.loadRoleData(params)
    },
    initData(data) {
      this.checkbox = []
      if (this.$utils.isEmpty(data)) {
        return
      }
      data.forEach(v => {
        if (this.cacheData[v]) {
          this.checkbox.push(v)
        } else {
          this.getDataInfo(v)
        }
      })
      if (this.multiple) {
        this.checkbox = data
      } else {
        this.radio = data[0]
      }
    },
    /**
     * 获取数据信息
     */
    getDataInfo(id) {
      getRoleById({ roleId: id }).then(response => {
        const data = response.data
        if (this.$utils.isEmpty(data)) {
          return
        }
        data[this.labelKey] = data['name']
        this.cacheData[data[this.idKey]] = data
        if (this.checkbox && this.checkbox.indexOf(data[this.idKey]) === -1) {
          this.checkbox.push(data[this.idKey])
        }
        this.$emit('init-data', this.getSelectedData(this.checkbox))
      }).catch((e) => {
        console.error(e)
      })
    },
    loadData(data, isInit) {
      if (isInit) {
        this.pathData = []
        // 加载
        findAllSubsystem().then(res => {
          this.sysList = res.data
          data[this.childrenKey] = this.sysList
          this.pathData.push(data)
          this.listData = []
          this.resultType = 'init'
        }).catch((e) => {
          console.error(e)
        })
      } else {
        this.sysList = []
        this.resultType = 'init'
        if (data[this.idKey]) {
          this.loadRoleData({ 'Q^SYSTEM_ID_^SL': data[this.idKey] })
        }
        this.pathData.push(data)
      }
    },
    /**
     * 获取格式化参数
     */
    getSearcFormData(param) {
      const params = param
      if (this.isUseScope) {
        const obj = {}
        obj.type = this.partyTypeId
        if (obj.type === '3') {
          obj.partyId = this.currentOrgId
        }
        obj.type === 'script' ? obj.script = this.script : null
        Object.assign(params, obj)
      }
      return ActionUtils.formatParams(
        params,
        this.pagination,
        this.sorts)
    },
    // 加载角色数据
    loadRoleData(params) {
      this.loading = true
      if (this.isUseScope) {
        if (this.partyTypeId === 'script') {
          getScriptValue({
            script: this.script,
            vars: ''
          }).then(response => {
            const data = JSON.parse(response.data)
            ActionUtils.handleListData(this, data.data)
            this.setSelectRow()
            this.reset()
          }).catch(() => {
            this.reset()
          })
        } else {
          queryRoleScope(this.getSearcFormData(params)).then(response => {
            ActionUtils.handleListData(this, response.data)
            this.setSelectRow()
            this.loading = false
            this.refreshing = false
            this.finished = true
          }).catch(() => {
            this.reset()
          })
        }
      } else {
        queryPageList(this.getSearcFormData(params)).then(response => {
          this.reset()
          ActionUtils.handleListData(this, response.data)
          this.setSelectRow()
        }).catch(() => {
          this.reset()
        })
      }
    },
    reset() {
      this.loading = false
      this.refreshing = false
      this.finished = true
    },
    getSelectedData(data) {
      const result = []
      data.forEach((d) => {
        if (this.cacheData[d]) {
          result.push(this.cacheData[d])
        }
      })
      return result
    },
    onCancel() {
      this.$emit('cancel')
    },
    onConfirm() {
      const data = this.multiple ? this.checkbox : [this.radio]
      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 (this.listData[j].id === this.radio) {
            arr.push(this.listData[j])
            break
          }
        }
      }
      this.$emit('confirm', arr)
      this.$emit('callbackData', arr) // 返回原数据
    },
    clickOverlay() {
      this.$emit('click-overlay')
    },
    toggleChild(data) {
      this.initPageData()
      this.loadData(data)
    },
    changePath(index) {
      const parentOrg = this.pathData[index]
      this.sysList = parentOrg[this.childrenKey]
      this.pathData.splice(index + 1, this.pathData.length - 1)
      this.loadData({
        name: this.$t('components.selector.role')
      }, true)
      this.loadRoleData({})
    },
    // 查询
    onSearchAction() {
      this.initPageData()
      this.loadRoleData({ 'name': this.search })
    },
    onDetailCancel() {
      this.showDetailPopup = false
    },
    onDetailConfirm() {
      this.showDetailPopup = false
    },
    onTitle() {
      if (!this.multiple) { return }
      this.showDetailPopup = true
    },
    getPhoto() {

    },
    clickCheckbox(event, data, index) {
      let flag = true
      const target = event.target
      if (target && target.className.indexOf('van-checkbox__label') > -1) {
        flag = false
      } else if (target && target.parentNode.className.indexOf('van-checkbox__icon') > -1) {
        flag = false
      }
      if (flag) {
        this.toggle(data, index)
      }
    },
    toggle(data, index) {
      if (this.multiple) { // 多选
        this.toggleCheckbox(data, index)
      } else {
        this.toggleRadio(data, index)
      }
    },
    // 单选
    toggleRadio(data, index) {
      this.radio = data[this.valueKey]
    },
    toggleCheckbox(data, index) {
      this.$refs.checkboxes[index].toggle()
    },
    removeSelected(index) {
      this.checkbox.splice(index, 1)
    },
    initPageData() {
      this.pagination = {
        page: 1
      }
      this.sysList = []
      this.listData = []
      this.resultType = 'init'
      // this.cacheData = []
    },
    loadDataByScript() {
      getTreeDataByScriptValue({ 'script': this.otherFilterCondition.scriptContent }).then(response => {
        ActionUtils.handleListData(this, response.data)
        // 缓存
        if (this.$utils.isNotEmpty(this.listData)) {
          this.listData.forEach((d) => {
            this.cacheData[d[this.valueKey]] = d
          })
        }
      }).catch((e) => {
        ActionUtils.handleErrorData(this, e)
      })
    }

  }
}
</script>
<style lang="scss" scoped>
  .text_move{
    position: relative;
    top: -3px;
  }
</style>
