import {
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NSpace,
  NButton,
  useMessage,
  NCascader,
  NDatePicker
} 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 { getTimes } from '@/utils/dateUtil'
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: 'OPEN_SCREEN_AD',
      clientType: null,
      title: null,
      coverImage: null,
      linkUrl: null,
      showTime: null,
      operationTime: null as any,
      onlineTime: null,
      offlineTime: 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 {
          const { operationTime, ...res } = forms
          let onlineTime = '',
            offlineTime = ''
          if (operationTime) {
            onlineTime = dayjs(operationTime[0]).format('YYYY-MM-DD HH:mm:ss')
            offlineTime = dayjs(operationTime[1]).format('YYYY-MM-DD HH:mm:ss')
          }

          btnLoading.value = true
          if (props.type === 'add') {
            await sysNewsInformationSave({
              ...res,
              ...getTimes(operationTime, ['onlineTime', 'offlineTime'], 'YYYY-MM-DD')
            })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await sysNewsInformationUpdate({
              ...res,
              ...getTimes(operationTime, ['onlineTime', 'offlineTime'], 'YYYY-MM-DD'),
              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.showTime = data.showTime
        if (data.onlineTime && data.offlineTime) {
          forms.operationTime = [
            dayjs(data.onlineTime).valueOf(),
            dayjs(data.offlineTime).valueOf()
          ]
        }
        forms.clientType = data.clientType
        forms.status = data.status
      }
    })

    // 只能输入数字
    const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value)
    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="auto">
          <NFormItem
            label="客户端"
            path="clientType"
            rule={[
              {
                required: true,
                message: '请选择客户端'
              }
            ]}
          >
            <NSelect
              options={props.clientTypeList}
              placeholder="请选择客户端"
              v-model:value={forms.clientType}
            />
          </NFormItem>
          <NFormItem
            label="广告标题"
            path="title"
            rule={[
              {
                required: true,
                message: '请输入广告标题'
              }
            ]}
          >
            <NInput
              v-model:value={forms.title}
              placeholder="请输入广告标题"
              clearable
              showCount
              maxlength={15}
            />
          </NFormItem>
          <NFormItem
            label="显示时长"
            path="showTime"
            rule={[
              {
                required: true,
                message: '请输入显示时长'
              }
            ]}
          >
            <NInput
              v-model:value={forms.showTime}
              placeholder="请输入显示时长"
              clearable
              allowInput={onlyAllowNumber}
            >
              {{ suffix: () => '秒' }}
            </NInput>
          </NFormItem>
          <NFormItem
            label="生效时间"
            path="operationTime"
            rule={[
              {
                required: true,
                message: '请输入生效时间'
              }
            ]}
          >
            <NDatePicker
              v-model:value={forms.operationTime}
              type="daterange"
              startPlaceholder="生效开始时间"
              endPlaceholder="生效结束时间"
              clearable
              isDateDisabled={(ts: number) => {
                return ts < dayjs(dayjs().format('YYYY-MM-DD')).valueOf()
              }}
              style={{ width: '100%', textAlign: 'left' }}
            />
          </NFormItem>
          <NFormItem label="跳转链接" path="linkUrl">
            <NInput v-model:value={forms.linkUrl} placeholder="请输入跳转链接" clearable />
          </NFormItem>
          <NFormItem
            label="广告图片"
            path="coverImage"
            rule={[
              {
                required: true,
                message: '请输入广告图片',
                trigger: ['input', 'blur']
              }
            ]}
          >
            <UploadFile
              v-model:fileList={forms.coverImage}
              accept=".jpg,.jpeg,.png"
              cropper
              bucketName="news-info"
              options={{
                enlarge: 2,
                autoCropWidth: 258, //默认生成截图框宽度
                autoCropHeight: 355 //默认生成截图框高度
              }}
              tips="请上传尺寸为516*710，大小1M以内的JPG、PNG图片"
            />
          </NFormItem>
        </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>
    )
  }
})
