<template>
  <div :style="{width}">
    <template v-if="!securityConfig.trigger">
      <el-input :placeholder="config.placeholder" readonly v-bind="$attrs" :model-value="proxyOtherValue[0].value || modelValue"  :style="{width: config.width || '100%'}" :disabled="disabled" @click="openDialog">
        <template #append>
          <el-button icon="el-icon-search" :disabled="disabled" @click="openDialog"></el-button>
        </template>
      </el-input>
    </template>
    <template v-if="securityConfig.trigger === 'button'">
      <cip-button type="primary" :disabled="disabled" @click="openDialog">选择({{multiple && (defaultValue?.length || 0)}})</cip-button>

    </template>
    <cip-dialog
                v-model="tableDialog"
                :title="`选择${config.label}`"
                custom-class="select-input__dialog"
                top="6vh"
                :on-confirm="onConfirm">
      <select-table
                    :checked-item="checkItem"
                    :option-props="optionProps"
                    :hide-index="config.tableHideIndex"
                    :entity="config.entity"
                    :curd-fn="config.curdFn"
                    :table-columns="config.tableColumns"
                    :search-field-list="config.searchFieldList"
                    :default-search-filter="config.defaultSearchFilter"
                    :with-pagination="config.withPagination"
                    :with-tags="config.withTags"
                    :check-type="multiple?'checkbox':'radio'"
                    :hide-search="config.hideSearch"
                    class="select-input-table-dialog"
                    @select-value="selectValue">
        </select-table>
    </cip-dialog>
  </div>
</template>

<script>
import CipDialog from '@cip/components/cip-dialog'
import CipButton from '@cip/components/cip-button'
import SelectTable from './components/select-table'
import CipMessage from '@cip/components/cip-message'
import { ElInput, ElButton } from 'element-plus'
import { computed, ref } from 'vue'
import { formInputProps, fromInputEmits } from '../../form-input-props'
import { useFormInput } from '@cip/components/hooks/form-input'
import { isArray } from '@cip/utils/util'
export default {
  components: { ElInput, ElButton, CipDialog, CipButton, SelectTable },
  props: formInputProps,
  emits: [...fromInputEmits],
  setup (props, context) {
    const { emitInput, emitOtherValue, proxyOtherValue, securityConfig, updateStream, ...formInput } = useFormInput(props, context, {
      fromModelValue: () => {},
      maxOtherKey: 2
    })
    const multiple = computed(() => {
      return securityConfig.value.multiple ?? false
    })
    const optionProps = computed(() => {
      return Object.assign({},
        { label: 'label', value: 'value' },
        securityConfig.value.defaultProp, // 兼容历史数据
        securityConfig.value.optionProps
      )
    })
    const tableDialog = ref(false)
    // 打开选择弹框
    const openDialog = () => {
      checkItem.value = multiple.value ? [...defaultValue.value] : { ...defaultValue.value }
      tableDialog.value = true
    }
    const getEmitValue = (type) => { // {'value'| 'label'}
      const rows = checkItem.value
      if (multiple.value) {
        let modelValue = rows.map(i => i[optionProps.value[type]])
        if (!securityConfig.value.array) {
          modelValue = modelValue.join(',')
        }
        return modelValue
      } else {
        return rows[optionProps.value[type]]
      }
    }
    // 确认保存
    const onConfirm = async (resolve, reject) => {
      if (securityConfig.value.validate) {
        const { valid, message = '校验失败' } = await securityConfig.value.validate?.(checkItem.value)
        if (!valid) {
          CipMessage.warning(message)
          reject()
        }
      }
      const value = getEmitValue('value') // multiple.value ? rows.map(i => i[optionProps.value.value]).join(',') : rows[optionProps.value.value]
      const label = getEmitValue('label') // multiple.value ? rows.map(i => i[optionProps.value.label]).join(',') : rows[optionProps.value.label]
      // emitInput(value)
      updateStream.appendValue(value)
      updateStream.appendOtherValue(label)
      // proxyOtherValue[0].value = label
      updateStream.appendOtherValue(checkItem.value, 2)
      // proxyOtherValue[1].value = checkItem.value
      updateStream.end()
      resolve()
    }
    const fromModel = (val) => {
      const result = []
      if (val) {
        if (isArray(val)) {
          return val
        } else {
          return val.split(',')
        }
      }
      return result
    }
    // 选择table组件
    const defaultValue = computed({
      get () {
        if (multiple.value) {
          if (proxyOtherValue[1].value) return proxyOtherValue[1].value
          let code = fromModel(props.modelValue)
          if (securityConfig.value.valueType === 'number') code = code.map(v => Number(v))
          const name = fromModel(proxyOtherValue[0].value) // 没有这个数据怎么办
          return code.map((i, idx) => ({
            [optionProps.value.value]: i,
            [optionProps.value.label]: name[idx]
          }))
        } else {
          return {
            [optionProps.value.value]: props.modelValue,
            [optionProps.value.label]: proxyOtherValue[0].value
          }
        }
      }
    })
    const checkItem = ref()
    const selectValue = async (val) => {
      checkItem.value = val
    }
    return {
      ...formInput,
      securityConfig,
      proxyOtherValue,
      multiple,
      optionProps,
      tableDialog,
      defaultValue,
      openDialog,
      onConfirm,
      checkItem,
      selectValue
    }
  }
}
</script>

<style lang="less">
.select-input-table-dialog{
  .dialog-tags{
    flex-basis: 220px;
  }
}
.select-input__dialog{
  .el-dialog__body{
    padding: 0;
  }
}
</style>
