<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="handleDialogClose">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="template-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="模板名称" prop="templateName">
            <el-input
              v-model="formData.templateName"
              placeholder="请输入模板名称"
              :disabled="isDetailMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模板编码" prop="templateCode">
            <el-input v-model="formData.templateCode" placeholder="系统自动生成" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="数据源" prop="dataSource">
            <el-select
              v-model="formData.dataSource"
              placeholder="请选择数据源"
              style="width: 100%"
              :disabled="isEditOrDetailMode"
              @change="handleDataSourceChange"
            >
              <el-option
                v-for="item in dataSourceList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="单据状态" prop="status" v-if="isDetailMode">
        <el-tag :type="statusConfig.type" size="large">
          {{ statusConfig.text }}
        </el-tag>
      </el-form-item>

      <el-form-item label="设计状态" prop="designStatus" v-if="isDetailMode">
        <el-tag :type="designStatusConfig.type" size="large">
          {{ designStatusConfig.text }}
        </el-tag>
      </el-form-item>

      <el-form-item label="设计内容" v-if="isDetailMode">
        <el-button type="primary" link @click="handleGoToDesigner"> 查看 </el-button>
      </el-form-item>
    </el-form>

    <template #footer v-if="!isDetailMode">
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave('save')" :loading="submitLoading">
          保存
        </el-button>
        <el-button
          v-if="props.mode === 'add'"
          type="primary"
          @click="handleSave('saveAndDesign')"
          :loading="submitLoading"
        >
          设计
        </el-button>
      </div>
    </template>

    <template #footer v-else>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </Dialog>

  <!-- 全屏设计器弹窗 -->
  <DesignerDialog v-model="designerShow" :template="designerTemplate" @save="handleDesignerSave" />
</template>
<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { getTemplate } from '@/api/print/template'
import { getApiSettingList } from '@/api/print/apiSetting'
import DesignerDialog from './DesignerDialog.vue'
interface TemplateFormData {
  id?: number
  templateName: string
  templateCode: string
  dataSource: string
  dataSourceName: string
  status: number
  designStatus: number
}

interface Props {
  visible: boolean
  mode: 'add' | 'edit' | 'detail'
  data?: TemplateFormData
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  success: [type: 'save' | 'saveAndDesign', data: TemplateFormData]
}>()

const router = useRouter()
const designerShow = ref(false)
// 表单引用
const formRef = ref()

const designerTemplate = ref({})
// 弹窗可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 数据源列表
const dataSourceList = ref([])

// 加载数据源列表
const loadDataSourceList = async () => {
  try {
    const response = await getApiSettingList({ dictType: 'barcode_rules' })
    // 转换为选项格式
    dataSourceList.value = response.map((item) => ({
      value: item.value,
      label: `${item.label}`
    }))
  } catch (error) {
    dataSourceList.value = []
    console.error('获取数据源列表失败:', error)
    ElMessage.error('获取数据源列表失败')
  }
}
const handleDataSourceChange = (val) => {
  console.log('选择的数据源:', val)
  const selectedDataSource = dataSourceList.value.find((item) => item.value === val)
  if (selectedDataSource) {
    formData.dataSourceName = selectedDataSource.label
  }
}
// 弹窗标题
const dialogTitle = computed(() => {
  switch (props.mode) {
    case 'add':
      return '新增模板'
    case 'edit':
      return '编辑模板'
    case 'detail':
      return '模板详情'
    default:
      return '模板信息'
  }
})

// 是否为详情模式
const isDetailMode = computed(() => props.mode === 'detail')

// 是否为编辑或详情模式（code不可编辑）
const isEditOrDetailMode = computed(() => props.mode === 'edit' || props.mode === 'detail')

// 单据状态配置
const statusConfig = computed(() => {
  const statusConfigMap: Record<
    number,
    { type: 'primary' | 'success' | 'warning' | 'danger' | 'info'; text: string }
  > = {
    0: { type: 'info', text: '草稿' },
    1: { type: 'success', text: '生效' },
    2: { type: 'warning', text: '失效' }
  }
  return statusConfigMap[formData.status] || { type: 'info', text: '未知' }
})

// 设计状态配置
const designStatusConfig = computed(() => {
  const designStatusConfigMap: Record<
    number,
    { type: 'primary' | 'success' | 'warning' | 'danger' | 'info'; text: string }
  > = {
    0: { type: 'info', text: '未设计' },
    1: { type: 'warning', text: '设计中' },
    2: { type: 'success', text: '设计完成' }
  }
  return designStatusConfigMap[formData.designStatus] || { type: 'info', text: '未知' }
})

// 提交加载状态
const submitLoading = ref(false)

// 表单数据
const formData = reactive<TemplateFormData>({
  id: undefined,
  templateName: '',
  templateCode: '',
  dataSource: '',
  dataSourceName: '',
  status: 0,
  designStatus: 0
})

// 表单验证规则
const formRules = {
  templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  templateCode: [{ required: false, message: '请输入模板编码', trigger: 'blur' }],
  dataSource: [{ required: true, message: '请选择数据源', trigger: 'change' }]
}

// 生成模板编码
const generateTemplateCode = () => {
  const timestamp = Date.now().toString(36)
  const random = Math.random().toString(36).substring(2, 7)
  return `TPL_${timestamp.toUpperCase()}${random.toUpperCase()}`
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    templateName: '',
    templateCode: '',
    dataSource: '',
    dataSourceName: '',
    status: 0,
    designStatus: 0
  })
  formRef.value?.clearValidate()
}

// 初始化表单数据
const initFormData = async () => {
  resetForm()

  // 加载数据源列表
  await loadDataSourceList()

  if (props.mode === 'add') {
    // formData.templateCode = generateTemplateCode()
  } else if (props.data) {
    // 编辑或详情模式，如果传入的数据不完整，需要从API获取完整数据
    if (props.data.id && !props.data.templateCode) {
      try {
        const response = await getTemplate(props.data.id)
        Object.assign(formData, response)
      } catch (error) {
        console.error('获取模板详情失败:', error)
        ElMessage.error('获取模板详情失败')
      }
    } else {
      Object.assign(formData, props.data)
    }
  }
}

// 保存表单（草稿状态）
const handleSave = async (type) => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    formData.status = 0 // 保存为草稿状态

    emit('success', type, { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 跳转到设计器
const handleGoToDesigner = () => {
  router.push('/print/print/designer')
}

// 设计器保存
const handleDesignerSave = () => {
  ElMessage.success('设计器保存成功')
  designerShow.value = false
}

// 关闭弹窗
const handleDialogClose = () => {
  resetForm()
}
// 监听弹窗显示变化
watch(
  () => props.visible,
  async (newVal) => {
    if (newVal) {
      await initFormData()
    }
  }
)
</script>

<style scoped>
.template-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 8px 16px;
  font-weight: 500;
}

.designer-content {
  width: 100%;
  height: calc(100vh - 120px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.designer-placeholder {
  text-align: center;
}

.placeholder-text {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
  margin-top: 20px;
}

.placeholder-desc {
  font-size: 14px;
  color: #909399;
  margin-top: 10px;
}

.designer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
