<script lang="ts" setup>
import AppUpload from '@/components/base/AppUpload.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useMapStore } from '@/stores/map'
import { updateCover, createCover } from '../api'
const store = useMapStore()
const emit = defineEmits<Emits>()
const ruleFormRef = ref<FormInstance>()
// 封面类型
const typeList = store.getMapValuesByKey('system_cover_type')
// 封面状态
const statusList = store.getMapValuesByKey('system_status')
const form = reactive({
  title: '',
  status: '1',
  url: '',
  type: '1'
})
const rules = reactive<FormRules>({
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  url: [{ required: true, message: '请上传图片', trigger: 'change' }],
  type: [{ required: true, message: '请选择封面类型', trigger: 'blur' }]
})
const props = defineProps({
  isShowDialog: {
    type: Boolean,
    required: true
  },
  editData: {
    type: Object,
    required: true
  },
  isEdit: {
    type: Boolean,
    required: true
  }
})
interface Emits {
  (e: 'update:isShowDialog', isShowDialog: boolean): void
  (e: 'updatePage'): void
}

// 取消
const handleCancel = () => {
  emit('update:isShowDialog', false)
}
// 确定
const handleConfirm = () => {
  if (props.isEdit === true) {
    // emit('createCover', { form, isUpdate: 1, id: props.editData.id })
    const params = Object.assign({ id: props.editData.id }, form)
    updateCover(params).then(() => {
      emit('update:isShowDialog', false)
      emit('updatePage')
    })
  } else {
    form.title = form.url
    const params = Object.assign({}, form)
    createCover(params).then(() => {
      emit('update:isShowDialog', false)
      emit('updatePage')
    })
  }
}

onMounted(() => {
  if (props.isEdit) {
    form.status = props.editData.status
    form.url = props.editData.url
    form.type = props.editData.type
    form.title = props.editData.title
  }
})
</script>
<template>
  <el-dialog
    :model-value="isShowDialog"
    draggable
    :before-close="handleCancel"
    width="25%"
    :title="props.isEdit ? '修改预置封面信息' : ' 新增封面'"
  >
    <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="120px" label-suffix="：">
      <el-form-item label="封面类型" prop="type">
        <el-select v-model="form.type">
          <el-option v-for="(item, id) in typeList" :key="id" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片地址" prop="url">
        <AppUpload v-model="form.url" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio v-for="(item, id) in statusList" :key="id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
