<template>
  <ElDialog
    v-model="visible"
    :title="dialogTitle"
    width="520px"
    :close-on-click-modal="false"
  >
    <ElForm :model="form">
      <ElFormItem
        v-if="showAutoSwitch"
        label="自动排版(烫画工艺推荐自动排版)"
        style="margin-bottom: 10px"
      >
        <el-switch
          v-model="isAuto"
          inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          active-text="是"
          inactive-text="否"
          @change="handleAutoChange"
        />
      </ElFormItem>
      <template v-if="isAuto || !showAutoSwitch">
        <ElFormItem label="排版宽度">
          <el-radio-group v-model="form.templateWidth">
            <el-radio :value="42">40+2cm</el-radio>
            <el-radio :value="60">60cm</el-radio>
          </el-radio-group>
        </ElFormItem>
      </template>
    </ElForm>

    <template #footer>
      <div style="text-align: center">
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit"> 确定 </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { BaseRespData } from '@/types/api'

type OpenPayload = {
  productIdList?: number[]
  title?: string
  showAutoSwitch?: boolean
  id?: number
}

const emit = defineEmits<{
  success: []
}>()
const props = defineProps<{
  submitApi: (params: {
    productIdList?: number[]
    templateWidth?: number
    type?: string
  }) => Promise<BaseRespData<never>>
}>()
const visible = ref(false)
const payload = ref<OpenPayload | null>(null)

const isAuto = ref(true)
const form = ref<{ type?: string; templateWidth?: number }>({})
const showAutoSwitch = ref(true)
const dialogTitle = ref('排单')

const handleAutoChange = () => {
  form.value = {}
}

const open = (p: OpenPayload) => {
  payload.value = p
  showAutoSwitch.value = p.showAutoSwitch ?? true
  dialogTitle.value = p.title || '排单'
  isAuto.value = true
  form.value = {}
  visible.value = true
}

const handleSubmit = async () => {
  if (!payload.value?.productIdList?.length) {
    return ElMessage.warning('请选择订单')
  }

  const { templateWidth } = form.value
  const mustFill = isAuto.value || !showAutoSwitch.value
  if (mustFill && !templateWidth) {
    return ElMessage.warning('请选择排版宽度')
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await props.submitApi({
      productIdList: payload.value.productIdList,
      templateWidth: isAuto.value ? templateWidth : undefined,
      type: isAuto.value ? 'png' : undefined,
    })
    if (res.code !== 200) return
    ElMessage.success(res.message)
    visible.value = false
    emit('success')
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

defineExpose({ open })
</script>
