<template>
  <div>
    <van-popup
      v-model="showDialogPopup"
      class="ibps-fullscreen-popup"
      position="bottom"
      get-container="body"
      @click-overlay="clickOverlay"
      @opened="openedPopup"
    >
      <van-sticky>
        <!-- 头部 -->
        <ibps-picker-toolbar
          :title="title"
          @cancel="onCancel"
          @title="onTitle"
          @confirm="onConfirm"
        />
        <!--查询 -->
        <van-search
          v-show="$utils.isNotEmpty(queryKey)"
          v-model="search"
          :placeholder="searchPlaceholder"
          @search="onSearch"
        />
      </van-sticky>
      <!--树形 -->
      <van-cell-group v-if="isTree">
        <van-cell class="ibps-root-title">
          <div slot="title">
            <template v-for="(data,index) in pathData">
              <span
                :key="data[idKey]"
                :class="{'ibps-is-link':pathData.length-1!==index}"
                @click="changePath(index)"
              >{{ data[labelKey] }}</span>
              <span v-if="pathData.length-1!==index" :key="index">/</span>
            </template>
          </div>
        </van-cell>
      </van-cell-group>
      <!--多选 -->
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadData">
        <van-checkbox-group ref="checkboxGroup" v-model="checkbox" :max="multiple?0:1">
          <van-cell-group>
            <van-cell
              v-for="(data,index) in dataList"
              :key="data[valueKey]+index"
              clickable
              @click="toggle(data,index)"
            >
              <div slot="title">
                <van-checkbox
                  ref="checkboxes"
                  :name="data[valueKey]"
                >
                  <!-- <field-formatter
                    :label-key="labelKey"
                    :data="data"
                    :template-fields="templateFields"
                  /> -->
                  <div>
                    <div v-for="(item, i) in data" :key="i">
                      <span v-if="i!=='id_'">{{ item.label }}</span>
                      <span v-if="i!=='id_'">：</span>
                      <span v-if="item.fieldType!=='selector' && i!=='id_'">{{ item.val }}</span>
                      <span v-else-if="i!=='id_'"><van-tag>{{ selectorArr.find(i=>i.id_ === item.val) ? selectorArr.find(i=>i.id_ === item.val).name_ :'' }}</van-tag></span>
                    </div>
                  </div>
                </van-checkbox>
              </div>
              <span
                v-if="hasChild(data)"
                slot="right-icon"
                @click="toggle(data,index)"
              >
                <span class="van-cell__right-icon" />
                <van-icon name="arrow " class="van-cell__right-icon" />
              </span>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </van-list>
    </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
            clickable
          >
            <template #title>
              <field-formatter
                :label-key="labelKey"
                :data="data"
                :template-fields="templateFields"
                class="van-cell-text"
              />
            </template>
            <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 { queryDataByKey, queryDataById, getByKey } from '@/api/platform/data/dataTemplate'
import { remoteRequest } from '@/utils/remote'
import TreeUtils from '@/utils/tree'
import ActionUtils from '@/utils/action'
import i18n from '@/utils/i18n' // Internationalization 国际化
import FieldFormatter from './field-formatter'
import IbpsPickerToolbar from '@/components/ibps-picker-toolbar'

export default {
  components: {
    IbpsPickerToolbar,
    FieldFormatter
  },
  props: {
    visible: Boolean,
    templateKey: String,
    templateFields: Object,
    params: Object,
    value: Array,
    multiple: Boolean,
    leftText: String,
    searchPlaceholder: String,
    isTree: Boolean,
    datat: Object,
    idKey: { // 唯一键
      type: String,
      default: 'id_'
    },
    parentIdKey: {
      type: String,
      default: 'parentId'
    },
    valueKey: { // 展示的key showLableKey
      type: String,
      default: 'id_'
    },
    labelKey: {
      type: String,
      default: 'name'
    },
    childrenKey: {
      type: String,
      default: 'children'
    },
    queryKey: String,
    dynamicParams: Object // 动态参数
  },
  data() {
    return {
      search: '',
      checkbox: [], // 多选
      pathData: [],
      dataList: [], // 数据
      cacheData: {}, // 缓存数据
      template: {},
      displayColumns: [],

      checkedValue: [],
      dataTem: {},
      showDialogPopup: false,
      showDetailPopup: false,
      page: 1,
      loading: true,
      finished: false,
      selectorArr: []
    }
  },
  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]
        return this.$utils.isNotEmpty(checked) ? this.cacheData[checked] ? this.cacheData[checked][this.labelKey] : '' : ''
      }
    },
    selectedData() {
      return this.checkbox.map((d) => {
        return this.cacheData[d] || {}
      })
    }
  },
  watch: {
    value: {
      handler(val, oldVal) {
        this.initData()
      },
      deep: true,
      immediate: true
    },
    visible() {
      this.showDialogPopup = this.visible
      if (this.visible && this.params) {
        this.loadData(this.params, true)
      }
    },
    params() {
      this.initTemplate()
    },
    dynamicParams(val, oldVal) {
      if (val !== oldVal && this.$utils.isNotEmpty(val)) {
        this.loadData(this.params, true)
      }
    }

  },
  created() {
    const sql = `select name_,id_ from ibps_party_entity `
    this.$common.request('sql', sql).then((res) => {
      const { data } = res.variables
      this.selectorArr = data
    })
  },
  methods: {
    initData() {
      const data = this.value
      this.checkedValue = []
      this.checkbox = []
      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 || []
    },
    emitInitData(data) {
      this.$emit('init-data', data)
    },

    /**
     * 通过ID获取数据
     */
    getDataInfo(id) {
      const params = {
        key: this.templateKey,
        id: id
      }
      if (this.$utils.isNotEmpty(this.dynamicParams)) {
        params['dynamicParams'] = JSON.stringify(this.dynamicParams)
      }
      remoteRequest('dataTemplate', params, () => {
        return this.getRemoteDataTemplateByIdFunc(params)
      }).then(responseData => {
        if (this.$utils.isNotEmpty(responseData) && this.$utils.isNotEmpty(responseData.data)) {
          const data = responseData.data[0] || {}
          let key = id
          if (this.$utils.isNotEmpty(data[this.valueKey])) {
            key = data[this.valueKey]
          }
          this.cacheData[key] = data
          this.checkedValue.push(data[this.valueKey])
          this.emitInitData(this.getSelectedData(this.checkedValue))
        }
      }).catch(() => {
      })
    },
    getRemoteDataTemplateByIdFunc(params) {
      return new Promise((resolve, reject) => {
        queryDataById(params).then(response => {
          resolve(response.data)
        }).catch((error) => {
          reject(error)
        })
      })
    },

    loadData(p, isInit) {
      if (isInit) {
        this.pathData = []
      }
      const params = {
        key: this.templateKey,
        dynamicParams: JSON.stringify(this.dynamicParams), // 动态参数,获取页面的值
        filterConditionKey: '' // 多个过滤条件
      }
      if (this.search && this.queryKey) {
        params[`Q^${this.queryKey}^SL`] = this.search
      }
      let pagination
      if (!this.isTre) {
        pagination = { page: this.page }
      }
      getByKey({
        dataTemplateKey: this.templateKey
      }).then(response => {
        this.dataTem = this.$utils.parseData(response.data).templates[0]
        // this.loadAjaxOptions()
        // TODO: 分页数据处理
        // 加载数据
        queryDataByKey(ActionUtils.formatParams(params, pagination)).then(response => {
          const dataResult = response.data.dataResult
          const pageResult = response.data.pageResult
          if (this.isTree) {
            this.dataList = TreeUtils.transformToTreeFormat(dataResult, {
              idKey: this.idKey,
              parentIdKey: this.parentIdKey,
              childrenKey: this.childrenKey
            })
            // 初始化最顶级数据
            this.initRootTreeData(response.vars)
            // 缓存数据
            dataResult.map((d) => {
              this.cacheData[d[this.valueKey]] = d
            })
          } else {
            // const mid = []
            const dl = dataResult
            dl.map((d) => {
              this.cacheData[d[this.valueKey]] = d
              // const objName = Object.keys(d)
              const fb = {}

              this.dataTem.display_columns.forEach((it, i) => {
                let b = {}
                // const keyName = objName.find(t => t === it.name)
                // if (typeof keyName !== 'undefined' && keyName) {
                b = { 'label': it.label, 'val': d[it.name], 'fieldType': it.field_type }
                // } else {
                // b = d[it.name]
                // }
                fb[it.name] = b
                // }
              })
              fb['id_'] = d['id_']
              this.dataList.push(fb)
            })
          }
          this.page++
          // 加载状态结束
          this.loading = false
          // 数据全部加载完成
          if (this.dataList.length >= pageResult.totalCount || this.page > pageResult.totalPages) {
            this.finished = true
          }
        }).catch((e) => {
          console.error(e)
        })
      }).catch(() => {
      })
    },
    /**
     * 初始
     */
    initRootTreeData(vars) {
      this.pathData = []
      const data = {
        [this.idKey]: vars.rootPId || '',
        [this.labelKey]: vars.rootLabel || '顶级',
        [this.childrenKey]: this.dataList
      }
      this.pathData.push(data)
    },

    getSelectedData(data) {
      if (this.$utils.isEmpty(data)) {
        return []
      }
      return data.map((d) => {
        return this.cacheData[d]
      })
    },
    openedPopup() {
      // this.initData(this.value)
    },
    onCancel() {
      this.$emit('cancel')
    },
    onConfirm() {
      this.$emit('confirm', this.getSelectedData(this.checkbox))
    },
    clickOverlay() {
      this.$emit('click-overlay')
    },
    toggleChild(data) {
      if (data[this.childrenKey] && data[this.childrenKey].length > 0) {
        this.dataList = data[this.childrenKey]
        this.pathData.push(data)
      }
    },
    changePath(index) {
      this.dataList = this.pathData[index][this.childrenKey]
      this.pathData.splice(index + 1, this.pathData.length - 1)
    },
    // 查询
    onSearch() {
      this.page = 1
      this.list = []
      this.loadData()
    },
    onDetailCancel() {
      this.showDetailPopup = false
    },
    onDetailConfirm() {
      this.showDetailPopup = false
    },
    onTitle() {
      if (this.multiple) {
        this.showDetailPopup = true
      } else {
        this.checkbox = []
      }
    },
    hasChild(data) {
      if (this.isTree) {
        return data[this.childrenKey] && data[this.childrenKey].length
      }
      return false
    },
    toggle(data, index) {
      if (!this.multiple) {
        this.$refs.checkboxGroup.toggleAll(false)
      }
      this.$refs.checkboxes[index].toggle()
    },
    removeSelected(index) {
      this.checkbox.splice(index, 1)
    },
    toggleMore(data, index) {
      this.$dialog.alert({
        message: this.format4popup(data)
      })
    },
    format4popup(data) {
      const res = []
      const displayColumns = this.template.display_columns
      for (let i = 0; i < displayColumns.length; i++) {
        const column = displayColumns[i]
        res.push(column.label + ':' + this.format4Data(data[column.name]))
      }
      return res.join('</br>')
    },
    format4Data(data) {
      // TODO 转换数据
      return data
    },

    // ====私有方法
    initTemplate() {
      const attrs = this.params.attrs
      if (attrs.templates) {
        // 如果是组合
        if (attrs.showType === 'compose') {
          let tpl = {}
          if (attrs.composeType === 'treeList') {
            tpl = attrs.templates[1]
          } else if (attrs.composeType === 'listTree') {
            tpl = attrs.templates[0]
          }
          if (!tpl) {
            this.$dialog.alert('未设置模版！')
            return
          }

          if (tpl.attrs['bind_template'] === 'Y') {
            const t = this.getDataByKey(tpl.attrs['bind_template_key'])
            if (t) {
              this.template = t.templates[0]
            }
          } else {
            this.template = tpl
          }
        } else {
          this.template = attrs.templates[0]
        }
      }
    }

  }
}
</script>
