import { prepareImagePath } from '@/common/js/image-compress.js';
import { checkImage, handleSecurityError, SCENE_PROFILE } from '@/common/js/content-security.js';

export function chooseAvatarImage(options = {}) {
  const {
    uploadUrl = 'https://api.xiaokang88.com/open-api/upload/old-admin-img',
    formData = { store_id: '11001' },
    onSuccess,
    onFail,
    onCancel,
  } = options;

  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      uni.showLoading({ title: '请稍后...' });

      try {
        const tempFile = res.tempFiles[0];
        const prepared = await prepareImagePath({
          path: tempFile.path,
          size: tempFile.size,
        });

        if (!prepared) {
          uni.hideLoading();
          onCancel && onCancel();
          return;
        }

        try {
          await checkImage(prepared.path, SCENE_PROFILE);
        } catch (error) {
          uni.hideLoading();
          handleSecurityError(error);
          onFail && onFail(error);
          return;
        }

        uni.uploadFile({
          url: uploadUrl,
          filePath: prepared.path,
          name: 'file',
          header: {
            authorization: `Bearer ${uni.getStorageSync('token')}`,
          },
          formData,
          success: (uploadRes) => {
            uni.hideLoading();
            onSuccess && onSuccess(uploadRes);
          },
          fail: (error) => {
            uni.hideLoading();
            onFail && onFail(error);
          },
        });
      } catch (error) {
        uni.hideLoading();
        onFail && onFail(error);
      }
    },
    complete: (res) => {
      if (res.errMsg === 'chooseImage:fail cancel') {
        onCancel && onCancel();
      }
    },
  });
}
