<template>
  <van-field
    ref="input"
    v-model="inputValue"
    :label="label"
    :name="name"
    :size="size"
    :border="border"
    :disabled="disabled"
    :required="required"
    :clearable="clearable"
    :clickable="clickable"
    :is-link="isLink"
    :error="error"
    :error-message="errorMessage"

    :arrow-direction="arrowDirection"
    :label-class="labelClass"
    :label-width="labelWidth"
    :label-align="labelAlign"
    :input-align="inputAlign"
    :error-message-align="errorMessageAlign"
    :autosize="autosize"
    :left-icon="leftIcon"
    :right-icon="rightIcon"
    :icon-prefix="iconPrefix"
    :rules="editable?rules:null"
    readonly
    @click-input="onClick"
  >
    <template #input>
      <template v-if="$utils.isEmpty(selectorValue)">
        <template v-if="editable">
          <!-- <van-icon
            slot="left-icon"
            name="add-o"
            class="van-cell__left-icon"
          /> -->
          <div class="van-field__body">
            <input :placeholder="placeholder" class="van-field__control" readonly>
          </div>
        </template>
      </template>
      <template v-else>
        <div class="van-field__control">
          <template v-if="multiple">
            <van-tag
              v-for="(item,index) in selectorValue "
              :key="item[valueKey]"
              :color="color"
              :text-color="textColor"
              class="ibps-tag-span ibps-mr-8"
            >
              <template #default>
                <div :class="multiple?'ibps-ellipsis':''">{{ item[labelKey] }}</div>
                <div v-if="editable" class="ibps-tag-close"><van-icon name="clear" @click="removeData(index)" /></div>
              </template>
            </van-tag>
          </template>
          <template v-else>
            <van-tag
              :color="color"
              :text-color="textColor"
              class="ibps-tag-span ibps-mr-8"
            >
              <template #default>
                <div>{{ selectorValue[labelKey] }}</div>
                <div v-if="editable" class="ibps-tag-close"><van-icon name="clear" @click="removeData" /></div>
              </template>
            </van-tag></template>
        </div>
      </template>

      <van-popup
        v-model="showPopup"
        position="bottom"
        get-container="body"
        class="ibps-fullscreen-popup"
        @opened="loadData"
        @close="handleClose"
      >
        <van-sticky>
          <ibps-picker-toolbar
            :cancel-button-text="cancelButtonText"
            :confirm-button-text="confirmButtonText"
            @cancel="onCancel"
            @confirm="onConfirm"
          />
          <van-search
            v-model="subject"
            placeholder="请输入"
            @search="onSearch"
          />
        </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="checkedIds" :max="multiple?0:1">
              <van-cell
                v-for="(item,index) in listData"
                :key="item[valueKey]+index"
                :title="item.name"
                :value="item.defKey"
                :label="item.desc"
                @click="onCellClick(item,index)"
              >
                <template slot="icon">
                  <van-checkbox
                    ref="checkboxes"
                    :name="item[valueKey]"
                    class="ibps-mr-10"
                  />
                </template>
              </van-cell>
            </van-checkbox-group>
            <ibps-list-result-page
              :result-type="resultType"
              :error-type="errorType"
              :result-message="resultMessage"
            />
          </van-list>
        </van-pull-refresh>
      </van-popup>
    </template>
    <template #right-icon>
      <van-icon name="arrow" class="ibps-gray-b2" @click="onClick" />
    </template>
  </van-field>
</template>
<script>
import { queryPageList, get, getByDefKey } from '@/api/platform/bpmn/bpmDefinition'
import ActionUtils from '@/utils/action'
import { isDef } from 'vant/lib/utils'
import FieldMixin from '@/mixins/field'

import IbpsPickerToolbar from '@/components/ibps-picker-toolbar'
import IbpsListResultPage from '@/components/ibps-list-result-page'
export default {
  name: 'ibps-bpmn-definition',
  components: {
    IbpsPickerToolbar,
    IbpsListResultPage
  },
  mixins: [FieldMixin],
  props: {
    // 存储类型 ,
    // ①、id:只存储id 字符串，
    // ②、json： json字符串,
    // ③、 array：存储数组数据(完整数据，包含key和value)。
    // ④、 bind：绑定ID，需要回调和返回
    store: {
      type: String,
      default: 'id',
      validator: function(value) {
        return ['id', 'json', 'array', 'arrayId', 'bind'].indexOf(value) !== -1
      }
    },
    storeSeparator: { // 存储值分割符，对于设置字符串类型的分隔符
      type: String,
      default: ','
    },
    multiple: {
      type: Boolean
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    labelKey: {
      type: String,
      default: 'name'
    },
    cancelButtonText: String,
    confirmButtonText: String,
    isSuper: {
      type: Boolean,
      default: true
    },
    color: {
      type: String,
      default: '#D6EAFE'
    },
    textColor: {
      type: String,
      default: '#3396FB'
    }
  },
  data() {
    return {
      showPopup: false,
      subject: '',

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

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

      checkedIds: [],
      selectedData: [],
      cacheData: {}
    }
  },
  computed: {
    showClear() {
      return this.clearable && this.$utils.isNotEmpty(this.value) && isDef(this.value) && this.editable
    }
  },
  watch: {
    value: {
      handler(val, oldVal) {
        this._setInputValue()
        this.initData()
      },
      immediate: true
    }
  },
  methods: {

    onClick() {
      if (!this.editable) { return }
      this.showPopup = true
    },
    handleClose() {
      this.showPopup = false
    },
    toggle(index) {
      this.$refs.checkboxes[index].toggle()
    },
    onTitleClick() {
      if (!this.$listeners['title-click']) { // 标题事件
        this.checkbox = []
      }
      this.$emit('title-click', this)
    },
    removeData(index) {
      if (this.multiple) {
        this.checkedIds.splice(index, 1)
      } else {
        this.checkedIds = []
      }
      this.$emit('input', this.getValue())
    },
    onCancel() {
      this.showPopup = false
      this.$emit('cancel', this)
    },
    onConfirm() {
      this.showPopup = false
      this.$emit('input', this.getValue())
      this.$emit('confirm', this)
    },
    onRightIconClick() {
      this.showClear ? this.onClear() : this.onClick()
    },
    onClear() {
      this.$emit('input', '')
    },
    /**
     * 初始化数据
     */
    initData() {
      const data = this.getArrayValue(this.value)
      this.selectorValue = this.multiple ? [] : {}
      this.checkedIds = []
      if (this.$utils.isEmpty(data)) {
        return
      }
      data.forEach(v => {
        if (this.cacheData[v]) {
          this.setSelectorValue(v)
        } else {
          this.getDataInfo(v)
        }
      })
    },
    setCacheData() {
      if (this.$utils.isEmpty(this.selectorValue)) return
      const data = this.multiple ? this.selectorValue : [this.selectorValue]
      data.forEach(v => {
        this.cacheData[v[this.valueKey]] = v
      })
    },
    setSelectorValue(v, flag = true) {
      if (this.multiple) {
        this.selectorValue.push(this.cacheData[v])
      } else {
        this.selectorValue = JSON.parse(JSON.stringify(this.cacheData[v]))
      }

      if (flag) {
        let checkedIds = []
        if (this.multiple) {
          this.selectorValue.forEach((d) => {
            checkedIds.push(d[this.valueKey])
          })
        } else {
          checkedIds = [this.selectorValue[this.valueKey]]
        }
        this.checkedIds = checkedIds
      }
    },

    /**
     * 获得数组数据
     */
    getArrayValue(value, bindId) {
      if (this.$utils.isEmpty(value)) {
        return []
      }
      if (this.store === 'json') { // json
        try {
          const data = this.$utils.parseData(value)
          return data.map((d) => {
            return d[this.valueKey]
          })
        } catch (error) {
          console.warn(error)
          return []
        }
      } else if (this.store === 'id') { // id
        return value.split(this.storeSeparator)
      } else if (this.store === 'bind') { // 绑定id
        if (this.$utils.isEmpty(bindId)) {
          return []
        }
        return bindId.split(this.storeSeparator)
      } else { // array
        return value.map((d) => {
          return d[this.valueKey]
        })
      }
    },
    getStoreValue(value) {
      const res = []
      if (this.store === 'json') { // json
        if (this.$utils.isEmpty(value)) {
          return ''
        }
        if (this.multiple) {
          value.forEach(v => {
            const o = {}
            o[this.valueKey] = v[this.valueKey]
            o[this.labelKey] = v[this.labelKey]
            res.push(o)
          })
          return JSON.stringify(res)
        } else {
          const o = {}
          o[this.valueKey] = value[this.valueKey]
          o[this.labelKey] = value[this.labelKey]
          return JSON.stringify(o)
        }
      } else if (this.store === 'id') { // id
        if (this.$utils.isEmpty(value)) {
          return ''
        }
        if (this.multiple) {
          value.forEach(v => {
            res.push(v[this.valueKey])
          })
        } else {
          res.push(value[this.valueKey])
        }
        return res.join(this.storeSeparator)
      } else if (this.store === 'bind') { // 绑定id
        const res = []
        const bindIdValue = []
        value.forEach(v => {
          bindIdValue.push(v[this.valueKey])
          res.push(v[this.labelKey])
        })
        this.bindIdValue = bindIdValue.join(this.storeSeparator)

        return res.join(this.storeSeparator)
      } else { // 数组 array
        return value || []
      }
    },
    getValue() {
      if (this.$utils.isNotEmpty(this.checkedIds)) {
        this.checkedIds.forEach((d) => {
          this.setSelectorValue(d, false)
        })
      } else {
        this.selectorValue = []
      }

      return this.getStoreValue(this.selectorValue)
    },
    /**
     * 通过ID获取数据
     */
    getDataInfo(id) {
      if (this.valueKey === 'id') {
        get({
          defId: id
        }).then(response => {
          const data = response.data
          this.cacheData[data[this.valueKey]] = data
          this.setSelectorValue(data[this.valueKey])
        }).catch(() => {
        })
      } else if (this.valueKey === 'defKey') {
        getByDefKey({
          defKey: id
        }).then(response => {
          const data = response.data
          this.cacheData[data[this.valueKey]] = data
          this.setSelectorValue(data[this.valueKey])
        }).catch(() => {
        })
      }
    },
    // =========列表数据
    loadData() {
      this.loading = true
      queryPageList(this.getSearcFormData()).then(response => {
        ActionUtils.handleListData(this, response.data)
        this.listData.forEach((d) => {
          this.cacheData[d[this.valueKey]] = d
        })
        this.loading = false
      }).catch((e) => {
        ActionUtils.handleErrorData(this, e)
        this.loading = false
      })
    },
    /**
     * 获取格式化参数
     */
    getSearcFormData() {
      const params = {}
      if (this.$utils.isNotEmpty(this.subject)) {
        params['Q^name_^SL'] = this.subject
      }

      params['Q^status_^S'] = 'deploy'
      if (this.isSuper) {
        params['isSuper'] = this.isSuper
      }
      return ActionUtils.formatParams(
        params,
        this.pagination,
        this.sorts)
    },
    /**
     * 下拉刷新
     */
    onRefresh() {
      this.refreshing = true
      this.finished = false
      this.loading = true
      this.onSearch()
    },
    /**
     * 查询
     */
    onSearch() {
      ActionUtils.initListData(this)
      this.loadData()
    },
    onCellClick(item, index) {
      if (!this.multiple) {
        this.$refs.checkboxGroup.toggleAll(false)
      }
      this.$refs.checkboxes[index].toggle()
    }
  }
}
</script>

