import {
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NSpace,
  NButton,
  useMessage,
  NCascader,
  NDatePicker,
  NGrid,
  NFormItemGi,
  NRadioGroup,
  NRadio
} from 'naive-ui'
import type { TreeSelectOption } from 'naive-ui'
import { defineComponent, onMounted, PropType, provide, reactive, ref } from 'vue'
import UploadFile from '@/components/upload-file'
import { sysNewsInformationSave, sysNewsInformationUpdate } from '../api'
import dayjs from 'dayjs'
import Editor from '@/components/editor'
import UEditor from '@/components/u-editor'

export default defineComponent({
  name: 'ad-operation',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    data: {
      type: Object as PropType<any>,
      default: () => {}
    },
    clientTypeList: {
      type: Array as PropType<Array<TreeSelectOption>>,
      default: () => []
    }
  },
  emits: ['close', 'getList'],
  setup(props, { slots, attrs, emit }) {
    const forms = reactive({
      type: 'HOT_CONSULTATION',
      clientType: null,
      title: null,
      coverImage: null,
      linkUrl: null,
      linkType: null as any,
      content: null,
      summary: null,
      status: false
    })

    const btnLoading = ref(false)
    const formsRef = ref()
    const message = useMessage()

    // 提交记录
    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return
        try {
          btnLoading.value = true
          if (props.type === 'add') {
            await sysNewsInformationSave({ ...forms })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await sysNewsInformationUpdate({ ...forms, id: props.data.id })
            message.success('修改成功')
          }
          emit('getList')
          emit('close')
        } catch {
          //
        }
        setTimeout(() => {
          btnLoading.value = false
        }, 100)
      })
    }

    onMounted(async () => {
      // 初始化数据
      if (props.type === 'edit') {
        const data = props.data
        forms.title = data.title
        forms.coverImage = data.coverImage
        forms.linkUrl = data.linkUrl
        forms.linkType = data.linkType
        forms.clientType = data.clientType
        forms.content = data.content
        forms.summary = data.summary
        forms.status = data.status
      }
    })

    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="100">
          <NGrid cols={2}>
            <NFormItemGi
              label="客户端"
              path="clientType"
              rule={[
                {
                  required: true,
                  message: '请选择客户端'
                }
              ]}
            >
              <NSelect
                options={props.clientTypeList}
                placeholder="请选择客户端"
                v-model:value={forms.clientType}
              />
            </NFormItemGi>

            <NFormItemGi
              label="跳转方式"
              path="linkType"
              rule={[
                {
                  required: true,
                  message: '请输入跳转方式'
                }
              ]}
            >
              <NRadioGroup v-model:value={forms.linkType}>
                <NRadio value={'IN'}>内容跳转</NRadio>
                <NRadio value={'OUT'}>外部链接</NRadio>
              </NRadioGroup>
            </NFormItemGi>
            <NFormItemGi
              label="资讯标题"
              path="title"
              rule={[
                {
                  required: true,
                  message: '请输入资讯标题'
                }
              ]}
            >
              <NInput
                v-model:value={forms.title}
                placeholder="请输入资讯标题"
                clearable
                showCount
                maxlength={15}
              />
            </NFormItemGi>
            {forms.linkType === 'OUT' && (
              <NFormItemGi
                label="跳转链接"
                path="linkUrl"
                rule={[
                  {
                    required: true,
                    message: '请输入跳转链接'
                  },
                  {
                    pattern:
                      /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/,
                    message: '跳转链接输入有误'
                  }
                ]}
              >
                <NInput v-model:value={forms.linkUrl} placeholder="请输入跳转链接" clearable />
              </NFormItemGi>
            )}
          </NGrid>
          <NGrid cols={2}>
            <NFormItemGi
              label="资讯封面"
              path="coverImage"
              rule={[
                {
                  required: true,
                  message: '请输入资讯封面',
                  trigger: ['input', 'blur']
                }
              ]}
            >
              <UploadFile
                v-model:fileList={forms.coverImage}
                accept=".jpg,.jpeg,.png"
                cropper
                size={5}
                bucketName="news-info"
                options={{
                  enlarge: 2,
                  autoCropWidth: 208, //默认生成截图框宽度
                  autoCropHeight: 144 //默认生成截图框高度
                }}
                tips="请上传尺寸为208*144，JPG、PNG图片"
              />
            </NFormItemGi>
            <NFormItemGi label="描述" path="summary">
              <NInput
                placeholder="请输入描述"
                v-model:value={forms.summary}
                type="textarea"
                rows={3}
              />
            </NFormItemGi>
          </NGrid>
          {forms.linkType === 'IN' && (
            <NGrid cols={1}>
              <NFormItemGi
                label="内容"
                path="content"
                rule={[
                  {
                    required: true,
                    message: '请输入内容'
                  }
                ]}
              >
                <UEditor v-model:modelValue={forms.content} bucketName="news-info"></UEditor>
                {/* <Editor v-model:value={forms.content} height={300} bucketName="news-info" /> */}
              </NFormItemGi>
            </NGrid>
          )}
        </NForm>

        <NSpace justify="end">
          <NButton type="default" onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton
            type="primary"
            onClick={() => onSubmit()}
            loading={btnLoading.value}
            disabled={btnLoading.value}
          >
            保存
          </NButton>
        </NSpace>
      </div>
    )
  }
})
