<template>
  <component
    is="a-modal"
    :width="tool.getDevice() === 'mobile' ? '100%' : '600px'"
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="submit">
    <!-- 表单信息 start -->
    <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
      <a-form-item label="渠道类型" field="media_id">
        <a-select v-model="formData.media_id" placeholder="请选择渠道类型" allow-clear>
          <a-option v-for="item in mediaOptions" :key="item.id" :value="item.id" :label="`${item.id}:${item.name}`" />
        </a-select>
      </a-form-item>
      <a-form-item label="渠道名称" field="name">
        <a-input v-model="formData.name" placeholder="请输入渠道名称" />
      </a-form-item>
      <a-form-item label="后台归属人" field="auth_id">
        <auth-select v-model="formData.auth_id" />
      </a-form-item>
    </a-form>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import tool from '@/utils/tool'
import { Message, Modal } from '@arco-design/web-vue'
import api from '../../api/advert/agenList'
import advertCommonApi from '../../api/advert/common'
import authSelect from '@/components/auth-select/index.vue'
import { useUserStore } from '@/store'
const emit = defineEmits(['success'])
// 引用定义
const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const mode = ref('')
const mediaOptions = ref([])
const authOptions = ref([])
const userStore = useUserStore()

let title = computed(() => {
  return '渠道管理' + (mode.value == 'add' ? '-新增' : '-编辑')
})

// 表单初始值
const initialFormData = {
  id: null,
  auth_id: null,
  name: '',
  media_id: null,
}

// 表单信息
const formData = reactive({ ...initialFormData })

// 验证规则
const rules = {
  auth_id: [{ required: true, message: '后台归属人必需填写' }],
  name: [{ required: true, message: '渠道名称必需填写' }],
  media_id: [{ required: true, message: '媒体ID必需填写' }],
}

// 打开弹框
const open = async (type = 'add') => {
  mode.value = type
  // 重置表单数据
  Object.assign(formData, initialFormData)
  formRef.value.clearValidate()
  visible.value = true
  if (mode.value === 'add') {
    formData.auth_id = userStore.user.id
  }
  await initPage()
}

// 初始化页面数据
const initPage = async () => {
  await getMediaOptions()
  await getAuthList()
}

// 获取媒体列表Options
const getMediaOptions = async () => {
  const res = await advertCommonApi.getMediaOptionsApi()
  if (res.code == 200) {
    mediaOptions.value = res.data
  }
}

// 获取后台归属人列表
const getAuthList = async () => {
  const res = await advertCommonApi.getAuthOptionsApi()
  if (res.code == 200) {
    authOptions.value = res.data
  }
}

// 从缓存中获取用户的id
const getUserId = async () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  userId.value = userInfo.id
}

// 设置数据
const setFormData = async (data) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key]
    }
  }
}

// 数据保存
const submit = async (done) => {
  const validate = await formRef.value?.validate()
  if (!validate) {
    loading.value = true
    let data = { ...formData }
    let result = {}
    if (mode.value === 'add') {
      // 添加数据
      data.id = undefined
      result = await api.save(data)
    } else {
      // 修改数据
      result = await api.update(data.id, data)
    }
    if (result.code === 200) {
      Message.success('操作成功')
      emit('success')
      done(true)
    }
    // 防止连续点击提交
    setTimeout(() => {
      loading.value = false
    }, 500)
  }
  done(false)
}

// 关闭弹窗
const close = () => (visible.value = false)

defineExpose({ open, setFormData })
</script>
