<template>
  <Popup
    v-model:show="popupShow"
    :closeIcon="false"
    position="bottom"
    size="auto"
    closeable
  >
    <template #default="{ show }">
      <FlexCol v-if="show" :padding="16">
        <ActionSheetTitle 
          cancelText="取消"
          confirmText="确定"
          v-bind="titleProps"
          :title="title"
          @cancel="popupShow = false"
          @confirm="onConfirm"
        />
        <Signature 
          ref="signatureRef" 
          v-bind="props"
        />
      </FlexCol>
    </template>
  </Popup> 
  <FlexCol width="100%" :gap="10">
    <Text v-if="!value && outerPlaceholder" :text="outerPlaceholder" />
    <Image v-else-if="value" :src="value" width="600rpx" mode="widthFix" v-bind="previewImageProps" />
    <Text v-else text="暂无签名" />
  </FlexCol>
</template>

<script setup lang="ts">
import { ref, toRef } from 'vue';
import type { SignatureInstance, SignatureProps } from '@/components/form/Signature.vue';
import { useFieldChildValueInjector } from './FormContext';
import Signature from '@/components/form/Signature.vue';
import FlexCol from '../layout/FlexCol.vue';
import Image, { type ImageProps } from '../basic/Image.vue';
import Popup from '../dialog/Popup.vue';
import ActionSheetTitle, { type ActionSheetTitleProps } from '../dialog/ActionSheetTitle.vue';
import Text from '../basic/Text.vue';
import type { UploaderAction } from './Uploader';

export interface SignatureFieldProps extends Omit<SignatureProps, 'value'> {
  modelValue?: string | null;
  /**
   * 预览图片属性
   */
  previewImageProps?: ImageProps;
  /**
   * 初始值
   */
  initalValue?: string | null;
  /**
   * 标题
   */
  title?: string;
  titleProps?: ActionSheetTitleProps;
  /**
   * 占位符
   */
  outerPlaceholder?: string;
  /**
   * 上传处理。允许用户在签名后自动上传图片。不提供则返回临时图片路径。
   */
  upload?: (item: UploaderAction) => (() => void);
}

const props = withDefaults(defineProps<SignatureFieldProps>(), {
  outerPlaceholder: '请签名',
  title: '签名',
  border: true,
  innerStyle: () => ({
    width: '100%',
    height: '400rpx',
  }),
  borderStyle: 'dashed',
  borderWidth: 1,
  borderColor: '#ddd',
});
const emit = defineEmits<{
  (e: 'update:modelValue', value: string | null): void;
}>();

const popupShow = ref(false);

const {
  value,
  updateValue,
} = useFieldChildValueInjector(
  toRef(props, 'modelValue'), 
  (v) => emit('update:modelValue', v ?? null),
  undefined,
  () => {
    console.log('11111');
    
    popupShow.value = true;
  },
  props.initalValue,
);

const signatureRef = ref<SignatureInstance>();

function onConfirm() {
  if (signatureRef.value) {
    uni.showLoading();
    signatureRef.value.export().then((res) => {
      // 如果上传处理，则上传图片
      if (props.upload) {
        props.upload({
          item: {
            filePath: res,
            state: 'uploading',
          },
          onProgress: () => {},
          onStart: () => {},
          onError: (error) => {
            uni.showToast({
              title: '' + error,
              icon: 'none',
            })
          },
          onFinish: (result) => {
            updateValue(result.uploadedUrl);
          },
        });
      } else
        updateValue(res);
      popupShow.value = false;
    }).catch((e) => {
      uni.showToast({
        title: e.message,
        icon: 'none',
      })
    }).finally(() => {
      uni.hideLoading();
    });
  }
}
</script>