<script lang="ts" setup>
/**
 * 签名查看和更新模态框组件
 *
 * @description 用于查看和更新医生签名
 * @author 系统
 * @date 2024
 */
import { ref, computed } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, Image, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import type { VbenFormProps } from '#/adapter/form';
import { updateSignatureApi } from '../api';

// ==================== 表单配置 ====================

const formProps: VbenFormProps = {
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'Avatar',
      componentProps: {
        placeholder: '请上传签名图片',
      },
      fieldName: 'sign_image',
      formItemClass: 'col-span-12',
      label: '签名图片',
      rules: 'required',
    },
  ],
  showDefaultActions: false,
};

const [Form, formApi] = useVbenForm(formProps);

// ==================== 模态框配置 ====================

const currentSignature = ref<string>('');

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    try {
      const valid = await formApi.validate();
      if (valid.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        
        await updateSignatureApi({ sign_image: values.sign_image });
        
        message.success('更新签名成功');
        
        // 调用回调刷新数据
        const data = modalApi.getData<{ onSuccess?: () => void }>();
        if (data?.onSuccess) {
          data.onSuccess();
        }
        
        modalApi.close();
      }
    } catch (error: any) {
      message.error(error?.message || '更新签名失败');
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{ signature?: string }>();
      if (data?.signature) {
        currentSignature.value = data.signature;
        // 设置表单初始值
        formApi.setValues({ sign_image: data.signature });
      } else {
        currentSignature.value = '';
        formApi.resetForm();
      }
    }
  },
});

// ==================== 计算属性 ====================

/**
 * 签名图片URL
 * 处理base64格式或URL格式
 */
const signatureImageUrl = computed(() => {
  if (!currentSignature.value) return '';
  
  // 如果是base64格式
  if (currentSignature.value.startsWith('data:')) {
    return currentSignature.value;
  }
  
  // 如果是URL格式
  if (currentSignature.value.startsWith('http://') || currentSignature.value.startsWith('https://')) {
    return currentSignature.value;
  }
  
  // 其他情况，尝试作为base64处理
  return `data:image/jpeg;base64,${currentSignature.value}`;
});

/**
 * 是否有签名
 */
const hasSignature = computed(() => {
  return !!currentSignature.value;
});
</script>

<template>
  <Modal title="查看和更新签名" class="w-[600px]">
    <div class="space-y-6">
      <!-- 当前签名查看区域 -->
      <div v-if="hasSignature" class="space-y-2">
        <div class="text-sm font-medium text-gray-700 dark:text-gray-300">
          当前签名：
        </div>
        <div class="flex items-center justify-center rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800">
          <Image
            :src="signatureImageUrl"
            alt="医生签名"
            :preview="true"
            style="max-height: 160px; max-width: 100%; object-fit: contain;"
          />
        </div>
      </div>
      
      <!-- 无签名提示 -->
      <div v-else class="rounded-lg border border-dashed border-gray-300 bg-gray-50 p-8 text-center dark:border-gray-600 dark:bg-gray-800">
        <div class="text-sm text-gray-500 dark:text-gray-400">
          暂无签名，请上传签名图片
        </div>
      </div>
      
      <!-- 更新签名表单区域 -->
      <div class="space-y-2">
        <div class="text-sm font-medium text-gray-700 dark:text-gray-300">
          更新签名：
        </div>
        <Form />
      </div>
    </div>
  </Modal>
</template>

<style lang="scss" scoped>
/* 自定义样式 */
</style>