<template>
  <view class="wk-field wk-field-select">
    <view v-if="_label" class="wk-field__label">
      <view v-if="field.isNull === 1" class="line" />
      {{ _label }}
    </view>
    <view class="wk-field__body" @click.stop="handleChoose">
      <view class="wk-field__body-core">
        {{ valueStr }}
      </view>
      <text class="wk wk-arrow-right icon-right" />
    </view>
    <view
      v-if="showOther"
      class="wk-field__body other-input">
      <input
        ref="core"
        v-model="otherVal"
        type="text"
        :disabled="field.disabled"
        :maxlength="getMaxlength"
        placeholder="请输入"
        placeholder-class="wk-placeholder placeholder"
        class="other-input__core"
        @input="changeText">
    </view>
  </view>
</template>

<script>
  import { QueryBusinessSetting } from 'API/crm/flow'
  import { QueryAllCategory } from 'API/crm/product'
  import { QueryReceivablesPlan } from 'API/crm/contract'

  import mixins from './mixins'
  import { isObject, isArray } from '@/utils/types.js'
  import { deepCopy } from '@/utils/lib.js'

  export default {
    name: 'WkFieldSelect',
    mixins: [mixins],
    data() {
      return {
        guid: null,
        formValue: [],
        keyMap: {
          business_type: {valueField: 'flowId', labelField: 'flowName'},
          business_status: {valueField: 'settingId', labelField: 'settingName'},
          category: {valueField: 'categoryId', labelField: 'name'},
          receivables_plan: { valueField: 'receivablesPlanId', labelField: 'num'}
        },

        dataList: [],
        otherVal: null
      }
    },
    computed: {
      optionsConfig() {
        let obj = this.keyMap[this.field.formType] || {labelField: 'label', valueField: 'value'}
        if (this.config && this.config.optionsConfig) {
          obj = this.config.optionsConfig
        }
        return obj
      },
      labelField() {
        return this.optionsConfig.labelField
      },
      valueField() {
        return this.optionsConfig.valueField
      },

      valueStr() {
        const arr = this.formValue || []
        if (this.$isEmpty(arr)) return ''
        if (!this.labelField) return arr
        if (!isArray(arr)) return arr
        return arr.map(o => o[this.labelField]).join(',')
      },

      list() {
        if (this.field.setting.length === 0) return []
        if (isObject(this.field.setting[0])) {
          return this.field.setting
        } else {
          return this.field.setting.map(o => {
            return {
              label: o,
              value: o
            }
          })
        }
      },

      showOther() {
        // 不是单选或多选类型
        if (![
          'checkbox',
          'select'
        ].includes(this.field.formType)) return false
        // 选中值为空
        if (this.$isEmpty(this.formValue)) return false
        // 选项中没有其他
        if (!this.field.setting.includes('其他')) return false

        console.log('formValue: ', this.field, this.formValue)

        // 选中值不包含其他
        const findIndex = this.formValue.findIndex(o => {
          return o[this.labelField] === '其他' ||
            !this.field.setting.includes(o[this.valueField])
        })
        if (findIndex === -1) return false

        if (this.formValue[findIndex][this.labelField] !== '其他') {
          // 初始有默认值时格式化label和value
          const otherObj = {
            [this.labelField]: '其他',
            [this.valueField]: '其他',
            otherVal: this.formValue[findIndex][this.valueField]
          }

          this.$set(this.formValue, findIndex, otherObj)
        } else if (!this.formValue[findIndex].hasOwnProperty('otherVal')) {
          // 如果选中值包含其他，给otherVal赋初值
          this.$set(this.formValue[findIndex], 'otherVal', null)
          this.$set(this.formValue, findIndex, this.formValue[findIndex])
        }

        return true
      },
      getMaxlength() {
        return this.field.maxlength || 100
      }
    },
    watch: {
      showOther: {
        handler() {
          if (!this.showOther) {
            this.otherVal = null
            return
          }
          const findRes = this.formValue.find(o => o.label === '其他')
          this.otherVal = findRes.value === '其他' ? (findRes.otherVal || '') : findRes.value
        },
        immediate: true
      },
      value: {
        handler(val) {
          this.formValue = this.value
          this.$nextTick(() => {
            if (this.showOther) {
              const findRes = this.formValue.find(o => o.hasOwnProperty('otherVal'))
              if (findRes) {
                this.otherVal = findRes.otherVal
              }
            }
          })
        },
        deep: true,
        immediate: true
      },
      // formValue: {
      // 	handler() {
      // 		this.emitChangeEvt(this.formValue)
      // 	},
      // 	deep: true,
      // 	immediate: true
      // }
    },
    created() {
      this.guid = this.$guid()
    },
    mounted() {
      if (this.field.formType === 'category') {
        this.getAllCategory()
      } else if (this.field.formType === 'receivables_plan') {
        this.getPlanList()
      } else {
        this.emitChangeEvt(this.formValue)
      }
    },
    methods: {
      handleChoose() {
        if (this.field.disabled) {
          if (this.config && this.config.disabledMsg) {
            this.$toast(this.config.disabledMsg)
          }
          return
        }
        const bridge = getApp().globalData.selectedValBridge
        const options = {
          guid: this.guid,
          maxlength: 1,
          title: '选择' + this.field.name,
          defaultVal: this.formValue || []
        }
        if (this.field.formType === 'checkbox') {
          options.maxlength = 1 / 0
        }
        switch (this.field.formType) {
        case 'business_type':
          bridge.options = {
							...options,
							request: QueryBusinessSetting,
							config: this.optionsConfig,
          }
          break
        case 'business_status':
          bridge.options = {
							...options,
							list: this.field.setting,
							config: this.optionsConfig
          }
          break
        case 'category':
          if (this.dataList.length > 0) {
            bridge.options = {
								...options,
								list: this.dataList,
								config: this.optionsConfig
            }
          } else {
            bridge.options = {
								...options,
								request: QueryAllCategory,
								config: this.optionsConfig
            }
          }
          break
        case 'receivables_plan':
          bridge.options = {
							...options,
							request: QueryReceivablesPlan,
							params: this.config.otherParams,
							config: this.optionsConfig
          }
          break
        default:
          bridge.options = {
							...options,
							list: this.list,
							config: this.optionsConfig,
							defaultVal: this.formValue || []
          }
        }
        uni.$on('selected-options', this.selectedOptions)
        this.$Router.navigateTo('/pages_common/selectList/options')
      },

      getAllCategory() {
        QueryAllCategory().then(res => {
          console.log('res', res)
          this.dataList = res
          if (!this.$isEmpty(this.field.value)) {
            const arr = this.field.value || []
            let filterRes = res.filter(o => o.categoryId == arr[arr.length - 1])
            this.selectedOptions({
              data: filterRes,
              guid: this.guid
            })
          }
        }).catch()
      },

      getPlanList() {
        console.log('recei plan: ', this.config)
        if (this.$isEmpty(this.config.otherParams)) return
        QueryReceivablesPlan(this.config.otherParams).then(res => {
          this.dataList = res
          if (!this.$isEmpty(this.field.value)) {
            const arr = this.field.value || []
            let filterRes = res.filter(o => o.receivablesPlanId == arr[arr.length - 1])
            this.selectedOptions({
              data: filterRes,
              guid: this.guid
            })
          }
        }).catch()
      },

      formatValue(oldStr) {
        // 禁止输入 emoji
        const regStr = /[\ud800-\udbff]|[\udc00-\udfff]/g;
        return oldStr.replace(regStr, '');
      },

      /**
       * 修改输入框值
       */
      changeText() {
        let oldStr = String(this.otherVal)
        let valueStr = this.formatValue(this.otherVal)
        if (this.field.setting.includes(valueStr)) {
          valueStr = ''
        }
        this.otherVal = oldStr
        this.$nextTick(function() {
          this.otherVal = valueStr
          const findIndex = this.formValue.findIndex(o => o.label === '其他')
          if (findIndex !== -1) {
            this.formValue[findIndex].otherVal = this.otherVal
            this.$set(this.formValue, findIndex, this.formValue[findIndex])
          }
          oldStr = null
          valueStr = null
          this.emitChangeEvt(this.formValue)
        })
      },

      selectedOptions(data) {
        if (this.guid === data.guid) {
          let val = data.data
          this.formValue = val
          this.emitChangeEvt(this.formValue)
        }
        uni.$off('selected-options')
      }
    }
  }
</script>

<style scoped lang="scss">
	@import './wkField.scss';

	.other-input {
		margin-top: 10rpx;
		.other-input__core {
			width: 100%;
		}
	}
</style>
