/** @jsxImportSource vue */
import { defineComponent, ref, computed, watch, onMounted, defineEmits } from 'vue'
import { ElCard, ElTag, ElButton, ElIcon, ElCheckbox } from 'element-plus'
import { Bottom, Tickets, Edit } from '@element-plus/icons-vue'
import Scrollbar from '../Scrollbar'
// import { $emit, $off, $on } from '@/utils/gogocodeTransfer'
import { useI18n } from 'vue-i18n'

export default defineComponent({
  name: 'CardView',
  components: {
    Scrollbar
  },
  props: {
    // 当前行数据
    form: {
      type: Object,
      default: () => {}
    },
    // 当前序号
    no: {
      type: [Number, String, undefined],
      default: () => undefined
    },
    // 是否选中
    isChecked: {
      type: Boolean,
      default: () => false
    },
    // 是否展示多选
    isCheck: {
      type: Boolean,
      default: () => false
    },
    // 是否展示子表按钮
    isSubTable: {
      type: Boolean,
      default: () => false
    },
    // 是否展示更多按钮
    isShowDetailsMore: {
      type: Boolean,
      default: () => false
    },
    // 是否收起
    isMore: {
      type: Boolean,
      default: () => true
    },
    setMaxHeight: {
      type: [Function, undefined],
      default: () => undefined
    },
    setHeight: {
      type: [Function, undefined],
      default: () => undefined
    },
    // 列表是否启用行编辑
    isEnableEdit: {
      type: Boolean,
      default: () => false
    },
    // 是否默认开启行编辑
    allRowDefaultEditable: {
      type: Boolean,
      default: () => false
    }
  },
  setup(props, { attrs, emit, slots }) {
    console.log('*card-view.jsx**********************************************=>', props, attrs, slots)
    defineEmits(['checked', 'showSubTable', 'rowDblclick', 'rowClick'])
    const isMore = ref(props.isShowDetailsMore)
    const { t } = useI18n()
    const scrollHeight = ref(undefined)

    const scrollbarRef = ref(null)

    // 点击了卡片事件
    const onChecked = () => {
      emit('checked')
    }
    const getSlotHtml = (slotFun) => {
      const datas = { ...props, isMore: isMore.value }
      return ['function'].includes(typeof slotFun) ? slotFun(datas) : slotFun
    }

    const footerSlot = computed(() => {
      return getSlotHtml(slots.footerSlot).filter((item) => item?.children) ?? []
    })

    const setMaxHeight = (data) => {
      if (props.setMaxHeight) return props.setMaxHeight(data)
      if (data?.windowHeight) {
        // const height = data?.windowHeight - 200
        if (data.windowHeight * 0.4 <= scrollHeight.value) return 300
        return scrollHeight.value && scrollHeight.value >= 300 ? scrollHeight : 300
      }
    }

    watch(
      () => props.isShowDetailsMore,
      (newValue) => {
        isMore.value = newValue
      }
    )

    watch(
      () => props.isMore,
      (newValue) => {
        isMore.value = newValue
      }
    )

    onMounted(() => {
      const scrollElement = scrollbarRef.value?.$el?.querySelector?.('.el-scrollbar__view')
      if (scrollElement) {
        scrollHeight.value = scrollElement.clientHeight
      }
    })

    // 点击事件
    const onClick = (event) => {
      onChecked()
      emit('rowClick', event)
    }

    // 双击事件
    const onDblclick = (event) => {
      emit('rowDblclick', event)
    }

    const getCardBody = () => <div class="yx-card-body">{getSlotHtml(slots.children)}</div>

    return () => (
      <ElCard
        key={`card_${props.form?.$rowDataGuId || `${props.form?.id}_${props.no}`}`}
        header-padding
        body-padding
        shadow="hover"
        class={{ 'yx-card-main': true, 'is-checked': props.isChecked }}
        v-slots={{
          header: () => (
            <div class="yx-flex-wrap" justify="space-between" align="center" onClick={onClick} onDblclick={onDblclick}>
              <div
                class="yx-flex-wrap"
                align="center"
                style={{ gap: '10px', flex: '1 1 auto', maxWidth: 'calc(100% - 80px)' }}
              >
                {props.no && (
                  <ElTag type="primary" size="small">
                    {props.no}
                  </ElTag>
                )}
                <div layout-title class="ellipsis">
                  {getSlotHtml(slots.titleSlot)}
                </div>
              </div>
              <div class="yx-flex-wrap" align="center" style={{ gap: '10px' }}>
                {getSlotHtml(slots.headerRightSlot)}
                {props.isEnableEdit && !props.allRowDefaultEditable && (
                  <ElButton
                    text
                    icon={
                      <ElIcon>
                        <Edit />
                      </ElIcon>
                    }
                    onClick={(event) => {
                      event.stopPropagation()
                      emit('rowDblclick', event)
                    }}
                  />
                )}
                {props.isSubTable && (
                  <ElButton
                    text
                    icon={
                      <ElIcon>
                        <Tickets />
                      </ElIcon>
                    }
                    onClick={(event) => {
                      event.stopPropagation()
                      emit('showSubTable', props.form)
                    }}
                  />
                )}
                {props.isCheck && (
                  <ElCheckbox
                    model-value={props.isChecked}
                    disabled={!!props.form.$editing}
                    style="height: auto;"
                    onClick={(event) => {
                      event.stopPropagation()
                    }}
                    onChange={onChecked}
                  />
                )}
              </div>
            </div>
          ),
          ...(footerSlot.value.length > 0
            ? {
                footer: footerSlot.value
              }
            : {})
        }}
      >
        <div
          class="yx-flex-wrap"
          vertical
          style={{ gap: '0', height: '100%' }}
          onClick={onClick}
          onDblclick={onDblclick}
        >
          <Scrollbar
            ref={scrollbarRef}
            dispatch={props.isShowDetailsMore && isMore.value}
            scrollable-main
            max-height={!isMore.value ? '50vh' : '100%'}
            set-max-height={setMaxHeight}
            set-height={props.setHeight}
          >
            {getCardBody()}
          </Scrollbar>
          {props.isShowDetailsMore && (
            <ElButton
              text
              icon={<ElIcon>{!isMore.value ? <Top /> : <Bottom />}</ElIcon>}
              onClick={(event) => {
                event.stopPropagation()
                isMore.value = !isMore.value
              }}
            >
              {!isMore.value ? t('imatrixUIPublicModel.collapse') : t('imatrixUIPublicModel.expand')}
            </ElButton>
          )}
        </div>
      </ElCard>
    )
  }
})
