import { computed, defineComponent, inject, onMounted, PropType, ref } from 'vue'
import BlockResize from './block-resize'
export default defineComponent({
  props: {
    block: {
      type: Object,
    },
    formData: {
      type: Object as PropType<any>,
    },
  },
  setup(props) {
    const blockStyles = computed(() => ({
      top: `${props.block.top}px`,
      left: `${props.block.left}px`,
      zIndex: `${props.block.zIndex}`,
    }))

    const config = inject<any>('config')
    const blockRef = ref(null)
    onMounted(() => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const conWidth = document.getElementsByClassName('sk-editor-container-canvas__content')[0].offsetWidth
      const { offsetWidth, offsetHeight } = blockRef.value
      if (props.block.alignCenter) { // 说明是拖拽松手的时候才渲染的，其他的默认渲染到页面上的内容不需要居中
        // eslint-disable-next-line vue/no-mutating-props
        props.block.left = props.block.left - offsetWidth / 2
        // eslint-disable-next-line vue/no-mutating-props
        props.block.leftPercent = props.block.leftPercent - (offsetWidth / 2) / conWidth * 100
        // eslint-disable-next-line vue/no-mutating-props
        props.block.top = props.block.top - offsetHeight / 2 // 原则上重新派发事件
        // eslint-disable-next-line vue/no-mutating-props
        props.block.alignCenter = false // 让渲染后的结果才能去居中
      }
      // eslint-disable-next-line vue/no-mutating-props
      props.block.width = offsetWidth
      // eslint-disable-next-line vue/no-mutating-props
      props.block.height = offsetHeight
    })
    return () => {
      const component = config.componentMap[props.block.key]
      const RenderComponent = component.render({
        size: props.block.hasResize ? { width: props.block.width, height: props.block.height } : {},
        props: props.block.props,
        // model: props.block.model  => {default:'username'}  => {modelValue: FormData.username,"onUpdate:modelValue":v=> FormData.username = v}

        model: Object.keys(component.model || {}).reduce((prev, modelName) => {
          const propName = props.block.model[modelName] // 'username'
          prev[modelName] = {
            modelValue: props.formData[propName],
            // eslint-disable-next-line vue/no-mutating-props
            'onUpdate:modelValue': v => props.formData[propName] = v,
          }
          return prev
        }, {}),
      })
      const { width, height } = component.resize || {}
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      return <div class="sk-editor-block" style={blockStyles.value} ref={blockRef}>
        {RenderComponent}
        {/* 传递block的目的是为了修改当前block的宽高， component中存放了是修改高度还是宽度 */}
        {
          props.block.focus && (width || height) &&
          <BlockResize
            block={props.block}
            component={component}
          ></BlockResize>
        }
      </div>
    }
  },
})
