<template>
  <Modal
    :options="getModalOptions"
    :on-positive-click="handleConfirm"
    :on-negative-click="handleClose"
    :on-close="handleClose"
  >
    <template #Context>
      <n-form
        ref="formRef"
        :model="advertisingForm"
        :rules="advertisingRules"
        :label-width="100"
        label-placement="left"
        require-mark-placement="left"
        :disabled="disabled"
      >
        <div class="flex__body">
          <template v-for="(item,index) in getFormOptions" :key="index">
            <n-form-item :label="item.label" :path="item.key" :class="{ 'flex__item': !['oss','editor'].includes(item.type) }">
              <UploadOss v-if="item.type === 'oss'" :ref="el=>{ossRefs[item.refIndex] = el}" :default-list="advertisingForm[item.file]" @upload-status="handleUploadStatus" />
              <n-input v-if="item.type === 'input'" v-model:value="advertisingForm[item.key]" v-bind="item.props" />
              <n-select v-if="item.type === 'select'" v-model:value="advertisingForm[item.key]" v-bind="item.props" />
              <n-radio-group v-if="item.type === 'radio'" v-model:value="advertisingForm[item.key]" :name="item.key">
                <n-space>
                  <n-radio v-for="(cItem,cIndex) in item.options" :key="`${item.key}_${cIndex}`" :value="cItem.value"> {{ cItem.label }}</n-radio>
                </n-space>
              </n-radio-group>
              <n-date-picker v-if="item.type === 'date'" v-model:formatted-value="advertisingForm[item.key]" v-bind="item.props" />
              <n-input-number v-if="item.type === 'number'" v-model:value="advertisingForm[item.key]" v-bind="item.props" />
              <TinymceEditor v-if="item.type === 'editor'" v-model:modelValue="advertisingForm[item.key]" :disabled="disabled" v-bind="item.props" />
            </n-form-item>
          </template>
        </div>

      </n-form>
    </template>
  </Modal>
</template>

<script>
import { form } from '../tools/form.js'
import Modal from '@/components/Modal/index.vue'
import UploadOss from '@/components/UploadOss/index.vue'
import TinymceEditor from '@/components/TinymceEditor/index.vue'
import { advertisingCreate, advertisingUpdate } from '@/api/setting/advertising.js'
import { defineComponent, ref, reactive, computed, toRefs } from 'vue'

export default defineComponent({
  name: 'UserModal',
  components: { Modal, UploadOss, TinymceEditor },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'create'
    },
    data: {
      type: Object,
      default: () => {}
    }
  },
  emits: {
    'update:visible': null,
    'reload': null
  },
  setup(props, { emit }) {
    const MODAL_TYPE = {
      'create': '新建广告',
      'preview': '广告详情',
      'update': '编辑广告'
    }
    const { advertisingForm, advertisingRules } = form
    const formRef = ref()
    const ossRefs = ref([])
    const data = reactive({
      advertisingForm: {
        ...advertisingForm,
        imageStatus: '',
        ...props.data
      },
      advertisingRules: {
        ...advertisingRules
      },
      disabled: props.type === 'preview'
    })
    const getModalOptions = computed(() => {
      return {
        title: MODAL_TYPE[props.type],
        width: 800,
        show: props.visible,
        trapFocus: false,
        negativeText: '取消',
        positiveText: '确认'
      }
    })

    const getFormOptions = computed(() => {
      return {
        ...form.formItem
      }
    })

    function handleConfirm() {
      formRef.value.validate((errors) => {
        if (!errors) {
          const uploads = ossRefs.value.map((item, index) => {
            return item.startUpload()
          })
          Promise.all(uploads)
            .then(response => {
              const isError = response.map((item) => {
                return item.includes('error')
              })
              if (!isError.includes(true)) {
                const imageStr = response.join()
                const params = { ...data.advertisingForm, cover: imageStr }
                if (params.id) {
                  advertisingUpdate(params).then(res => {
                    if (res.code === 0) {
                      emit('reload')
                      handleClose()
                    }
                  }).catch(e => {
                    console.log(e)
                  })
                } else {
                  advertisingCreate(params).then(res => {
                    if (res.code === 0) {
                      emit('reload')
                      handleClose()
                    }
                  })
                }
              } else {
                $message.error('文件上传失败，请稍后重试')
              }
            })
        }
      })
    }

    /* 关闭弹窗 */
    const handleClose = () => {
      emit('update:visible', false)
    }

    function handleUploadStatus(status) {
      data.advertisingForm.imageStatus = status
    }

    return {
      ...toRefs(data),
      formRef,
      ossRefs,
      getModalOptions,
      getFormOptions,
      handleConfirm,
      handleClose,
      handleUploadStatus
    }
  }
})
</script>

<style scoped lang='scss'>
.n-input-number{
  width: 100%;
}

.flex__body{
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  .n-form-item{
    width: 100%;
  }
  .flex__item{
    width: 50%;
  }
}

.n-date-picker{
  width: 100%;
}
</style>
