<script setup lang="ts">
import type { MjFormTextRenderOpts } from '.'
import type { RenderParams } from '../mj-form-plugin'

defineOptions({ name: 'MjFormTextPlugin' })

const props = withDefaults(
  defineProps<{
    renderOpts: MjFormTextRenderOpts
    // 表格、表单相关的一些数据
    renderParams: RenderParams
  }>(),
  {},
)

type MjFormTextMethods = {
  reset: (val?: any, force?: boolean) => any
}

const text = computed(() => props.renderParams.data[props.renderParams.field])

function _getMethods(): MjFormTextMethods {
  const renderProps = props.renderOpts.props
  let methods = renderProps._methods
  if (!methods) {
    methods = {} as any
    renderProps._methods = methods
  }
  return methods as any
}

const linkedRender = computed(() => props.renderOpts.props.linkedRender)
const linkedRenderMethods = computed(() => linkedRender.value?.props?._methods)
// const clickable = computed(() => {
//   const linkedRender = props.renderOpts.props?.linkedRender
//   return linkedRender && !linkedRender.props?.disabled
// })
const clickable = computed(() => props.renderOpts.props?.linkedRender)

const _reset = () => {
  linkedRenderMethods.value?.reset?.()
}

const placeholder = computed(() => props.renderOpts.props?.placeholder)
const showPlaceholder = computed(() => !text.value && placeholder.value)

function click() {
  if (props.renderOpts.props.click) {
    props.renderOpts.props.click()
  } else {
    linkedRenderMethods.value?.show?.()
  }
}

onMounted(() => {
  const methods = _getMethods()
  // 重置
  methods.reset = _reset
})
</script>

<template>
  <div
    class="mj-form-text"
    :class="{
      'mj-form-text-placeholder': showPlaceholder,
      'mj-form-text-clickable': clickable,
    }"
    @click="click"
  >
    {{ text || placeholder }}
  </div>
</template>

<style lang="scss" scoped>
.mj-form-text {
  display: flex;
  align-items: center;
  height: 34px;
  padding: 0 10px;
  color: #000;
  cursor: pointer;
  border-radius: 4px;
  font-size: 16px;
  cursor: not-allowed;
}
</style>
