import { ArticleTypeEnum, BooleanFlag, ReleaseStatusTypeEnum, SendTypeEnum } from '@/constants'

import UploadFile from '@/components/common/UploadFile/index.vue'

import { useResetData } from '@/hooks'
import type { TagItemDto } from '@/api/tag/types'
import { useColumnStore } from '@/stores/column'
import { storeToRefs } from 'pinia'
import SelectTags from '@/components/common/SelectTags/index.vue'
import type { AddOrUpdateColumnForm, AddOrUpdateColumnDto } from '@/api/article/types'

export default defineComponent((_, { expose }) => {
  const columnStore = useColumnStore()
  const { columnList } = storeToRefs(columnStore)
  console.log(columnList.value)
  const [form, resetForm] = useResetData<AddOrUpdateColumnForm>({
    title: '',
    content: '',
    faceUrl: '',
    imgUrl: '',
    releaseStatus: ReleaseStatusTypeEnum.PUBLISH,
    mainTagId: '',
    tagList: [],
    sendType: SendTypeEnum.IMMEDIATE,
    sendTime: '',
    isRelateColleague: BooleanFlag.NO,
    relateColumnId: undefined,
    type: ArticleTypeEnum.COLUMN,
    isRecommend: BooleanFlag.NO,
  })
  const formRef = ref<InstanceType<typeof ElForm>>()
  const rules = {
    title: [{ required: true, message: '请输入专栏标题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入专栏内容', trigger: 'blur' }],
    releaseStatus: [{ required: true, message: '请选择发布时间', trigger: 'blur' }],
    mainTagId: [{ required: true, message: '请选择主标签', trigger: 'blur' }],
    sendType: [{ required: true, message: '请选择发布类型', trigger: 'blur' }],
    sendTime: [{ required: true, message: '请选择发布时间', trigger: 'blur' }],
    relateColumnId: [
      { required: true, message: '请选择专栏栏目', trigger: 'blur', type: 'number', min: 1 },
    ],
    isRecommend: [{ required: true, message: '请选择是否推荐', trigger: 'blur' }],
    imgUrl: [{ required: true, message: '请上传图片', trigger: 'blur' }],
  }

  const transformForm = (releaseStatus: ReleaseStatusTypeEnum): AddOrUpdateColumnDto => {
    return {
      ...form.value,
      releaseStatus,
      faceUrl: form.value.imgUrl?.split(',').filter(Boolean)[0] || '',
      tagList: [form.value.mainTagId, ...form.value.tagList].map((tag, index) => {
        return {
          sort: index,
          tagId: Number(tag),
        }
      }),
    }
  }

  // 检验并且获取表单数据
  const getValidatedFormData = async (releaseStatus: ReleaseStatusTypeEnum) => {
    try {
      await formRef.value?.validate()
      return transformForm(releaseStatus)
    } catch (error) {
      console.log(error)
      ElMessage.warning('请检查输入内容')
      return null
    }
  }

  const filterTagsFn = (allTags: TagItemDto[]) => {
    // 引用了form.value.mainTagId
    return allTags.filter((tag) => tag.id !== Number(form.value.mainTagId))
  }

  const resetFields = () => {
    formRef.value?.resetFields()
    resetForm()
  }

  expose({
    getValidatedFormData,
    resetFields,
  })
  return () => (
    <div>
      <el-form
        ref={formRef}
        model={form.value}
        label-width="auto"
        label-position="right"
        rules={rules}
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model={form.value.title}
            placeholder="请输入实践标题"
            maxlength={200}
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model={form.value.content}
            type="textarea"
            placeholder="请输入专栏内容"
            rows={6}
            maxlength={1000}
            show-word-limit
            class="content-input"
          />
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl">
          {/* @ts-ignore */}
          <UploadFile v-model={form.value.imgUrl} />
        </el-form-item>
        <el-form-item label="专栏栏目选择" prop="relateColumnId">
          <el-select v-model={form.value.relateColumnId} placeholder="请选择专栏栏目">
            {columnList.value.map((item) => (
              <el-option value={item.id} label={item.title}></el-option>
            ))}
          </el-select>
        </el-form-item>
        <el-form-item label="主标签" prop="mainTagId">
          {{
            // @ts-ignore
            default: () => <SelectTags v-model={form.value.mainTagId} />,
            label: () => (
              // <el-tooltip content="主标签最多选1个" placement="top">
              <span class="cursor-pointer">
                主标签
                {/* <el-icon class="ml-1">
                  <InfoFilled />
                </el-icon> */}
              </span>
              // </el-tooltip>
            ),
          }}
        </el-form-item>
        <el-form-item label="副标签">
          {{
            default: () => (
              // @ts-ignore
              <SelectTags
                v-model={form.value.tagList}
                filterTagsFn={filterTagsFn}
                maxSelectedTags={3}
              />
            ),
            label: () => (
              // <el-tooltip content="副标签最多选3个" placement="top">
              <span class="cursor-pointer">
                副标签
                {/* <el-icon class="ml-1">
                    <InfoFilled />
                  </el-icon> */}
              </span>
              // </el-tooltip>
            ),
          }}
        </el-form-item>
        <el-form-item label="是否同步同事吧" prop="isRelateColleague">
          <el-radio-group v-model={form.value.isRelateColleague}>
            <el-radio value={BooleanFlag.YES} class="radio-item scheduled">
              是
            </el-radio>
            <el-radio value={BooleanFlag.NO} class="radio-item scheduled">
              否
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-radio-group v-model={form.value.isRecommend} class="radio-group">
            <el-radio value={BooleanFlag.YES} class="radio-item immediate">
              是
            </el-radio>
            <el-radio value={BooleanFlag.NO} class="radio-item scheduled">
              否
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布类型" prop="sendType">
          <el-radio-group v-model={form.value.sendType} class="radio-group">
            <el-radio value={SendTypeEnum.IMMEDIATE} class="radio-item immediate">
              立即发布
            </el-radio>
            <el-radio value={SendTypeEnum.SCHEDULED} class="radio-item scheduled">
              定时发布
            </el-radio>
          </el-radio-group>
        </el-form-item>
        {form.value.sendType === SendTypeEnum.SCHEDULED && (
          <el-form-item label="发布时间" prop="sendTime">
            <el-date-picker
              class="ml-2"
              v-model={form.value.sendTime}
              type="datetime"
              placeholder="请选择发布时间"
              // 不能选现在
              disabled-date={(time: Date) => {
                return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
              }}
              value-format="X"
              style={{ width: '250px' }}
            />
          </el-form-item>
        )}
      </el-form>
    </div>
  )
})
