<template>
  <t-dialog
    width="70%"
    :header="header"
    :confirmBtn="confirmBtn"
    :closeOnOverlayClick="false"
    @close="handleCloseDialog"
    @confirm="fetchSaveCarousalData"
  >
    <t-space direction="vertical" style="width: 100%">
      <TForm ref="form" :data="carousalData" :rules="rules" resetType="initial" label-width="100">
        <TFormItem label="轮播图：" name="imageUrl">
          <ImageUpload @on-success="handleSuccessImg" :image-url="imgUrl"/>
        </TFormItem>
        <TFormItem label="跳转类型：" name="targetType" >
          <t-radio-group :default-value="carousalData.targetType" v-model="carousalData.targetType">
            <t-radio-button v-for="(item,index) in typeOption" :key="index" :value="item.value">{{item.label}}</t-radio-button>
          </t-radio-group>
        </TFormItem>
        <TFormItem label="跳转文章路径：" name="targetId" v-if="carousalData.targetType === 'article' ">
          <t-input v-model.trim="carousalData.targetId" clearable placeholder="请输入文章id" />
        </TFormItem>
        <TFormItem label="跳转网址路径：" name="targetUrl" v-else-if="carousalData.targetType === 'url' ">
          <t-input v-model.trim="carousalData.targetUrl" clearable placeholder="请输入网址路径" />
        </TFormItem>
      </TForm>
    </t-space>
  </t-dialog>
</template>
<script lang="ts" setup>
import { computed, ref, reactive, watch } from 'vue'
import type { FormInstanceFunctions, FormProps } from 'tdesign-vue-next'
import ImageUpload from '@/components/ImageUpload.vue'
import { createCarousal, updateCarousalItem } from '@/api/carousal'
const props = defineProps<{
  isEdit?: Boolean | null
  headerTitle?: String | null
  carousal: {} | number
}>()
const emit = defineEmits(['success'])
const form = ref<FormInstanceFunctions | null>(null)
const header = computed(() => `${props.isEdit ? '编辑' : '创建'}${props.headerTitle || ''}`)
const formType = computed(() => `${props.isEdit ? 'update' : 'add'}`)
const confirmBtn = computed(() => (props.isEdit ? '保存' : '确定'))
const carousalData: FormProps['data'] = ref({})
const imgUrl = ref({})
const rules = computed(() => {
  const commonRules = {
    imageUrl: [
      {
        required: true,
        message: '轮播图必须是上传',
        type: 'error',
        trigger: 'change',
      },
    ],
    targetType: [
      {
        required: true,
        message: '请选择跳转类型',
        type: 'error',
        trigger: 'blur',
      },
      {
        required: true,
        message: '请选择跳转类型',
        type: 'error',
        trigger: 'change',
      },
    ],
  };
  return carousalData.value.targetType === 'article'
    ? {...commonRules, targetId: [{ required: true, message: '文章 id 不能为空', type: 'error', trigger: 'blur' }, { required: true, message: '文章 id 不能为空', type: 'error', trigger: 'change' }, { whitespace: true, message: '网址路径不能为空' }] }
    : {...commonRules, targetUrl: [{ required: true, message: '网址路径不能为空', type: 'error', trigger: 'blur' }, { required: true, message: '网址路径不能为空', type: 'error', trigger: 'change' }, { whitespace: true, message: '网址路径不能为空' }] };
});
const handleSuccessImg = (res:string) => {
  console.log(res,'图片地址')
  carousalData.value.imageUrl = res
}
const typeOption = reactive([
  { value: 'article', label: '文章' },
  { value: 'url', label: '地址' },
])
const handleFormTypeData = () => {
  if (carousalData.value.targetType === 'article') {
    delete carousalData.value.targetUrl
  } else if (carousalData.value.targetType === 'url') {
    delete carousalData.value.targetId
  }
}

watch(
  () => props.carousal,
  (newClassify) => {
    carousalData.value = Object.assign({}, newClassify)
    const carousalObj = Object.assign({},newClassify)
    // imgUrl.value.url = carousalObj.imageUrl || ''
    imgUrl.value = { url: carousalObj.imageUrl || '' }
  },
  {
    deep: true,
    immediate: true
  },
)
const fetchSaveCarousalData = async () => {
  /* TODO: 保存分类数据 */
  if (form.value) {
    const valid = await form.value.validate()
    // console.log(valid,'valid')
    if (valid && typeof valid === 'boolean') {
      /* TODO: 校验通过保存分类数据 */
      handleFormTypeData()
      // console.log(formType.value,'formType')
      let res
      switch (formType.value){
        case 'create':
          res = await createCarousal(carousalData.value)
          emit('success')
          break;
        case 'update':
          const fieldsToKeep = ["imageUrl", "targetType", "targetUrl", "targetId"];
          const requestObj = {};

          for (const field of fieldsToKeep) {
            if (carousalData.value[field]!== null && carousalData.value[field]!== undefined) {
              requestObj[field] = carousalData.value[field];
            }
          }
          handleFormTypeData()
          res = await updateCarousalItem(carousalData.value.id,requestObj)
          emit('success')
          break;
        default:
          res = await createCarousal(carousalData.value)
          emit('success')
          break;
      }
      // const createCarousalApi = createCarousal(carousalData.value)
      // console.log(createCarousalApi,'createCarousalApi')
      return
    }
  }
}
const handleCloseDialog = () => {
  // 数据&&规则校验结果重置
  if (form.value) {
    form.value.reset()
    form.value.clearValidate()
  }
}
</script>
