<template>
  <!-- <div>
    <table>
      <thead>
        <tr>
          <td>卖家平台</td>
          <td>URL</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td colspan="2">北美洲</td>
        </tr>
        <tr v-for="(region, index) in regions" :key="index">
          <td>{{ region.name }}</td>
          <td class="url">{{ region.url }}</td>
          <td>
            <button @click="authorize(region.url)">授权</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div> -->
  <div>
    <div class="absolute inset-0">
      <img src="/assets/images/auth/bg-gradient.png" alt="image" class="h-full w-full object-cover" />
    </div>

    <div class="relative flex items-center justify-center bg-[url(/assets/images/auth/map.png)] bg-cover bg-center bg-no-repeat dark:bg-[#060818] sm:px-16">
      <img src="/assets/images/auth/coming-soon-object3.png" alt="image" class="absolute right-0 top-0 h-[300px]" />

      <div
        class="relative w-full max-w-[870px] rounded-md bg-[linear-gradient(45deg,#fff9f9_0%,rgba(255,255,255,0)_25%,rgba(255,255,255,0)_75%,_#fff9f9_100%)] p-2 dark:bg-[linear-gradient(52.22deg,#0E1726_0%,rgba(14,23,38,0)_18.66%,rgba(14,23,38,0)_51.04%,rgba(14,23,38,0)_80.07%,#0E1726_100%)]"
      >
        <div class="relative flex flex-col justify-center rounded-md bg-white/60 backdrop-blur-lg dark:bg-black/50 px-6 lg:min-h-[758px] py-20">
          <div class="absolute top-6 start-6"></div>

          <div class="mx-auto w-full max-w-[440px]">
            <div class="mb-10">
              <h1 class="text-3xl font-extrabold uppercase !leading-snug text-primary md:text-4xl">{{ '授权-沙盒' }}</h1>
            </div>
            <el-form :model="AuthorizationForm" :rules="loginRules" ref="AuthorizationFormRef" class="login-input" label-width="120px">
              <el-form-item :label="$t('店铺名称') + ':'" prop="store_name">
                <el-input v-model="AuthorizationForm.store_name" :placeholder="$t('卖家自定义,以做区分')" autofocus clearable>
                  <template v-slot:prefix>
                    <svg-icon class="el-input__icon" icon-class="user" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item :label="$t('平台账号') + ':'" prop="platform_account">
                <el-input v-model="AuthorizationForm.platform_account" :placeholder="$t('卖家平台上的账号')" autofocus clearable>
                  <template v-slot:prefix>
                    <svg-icon class="el-input__icon" icon-class="user" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item :label="$t('区域') + ':'" prop="region">
                <el-select v-model="AuthorizationForm.region" placeholder="请选择区域" @change="handleRegionChange">
                  <el-option v-for="(item, index) in regionList" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('站点') + ':'" prop="site">
                <el-checkbox v-model="AuthorizationForm.checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0"></div>
                <el-checkbox-group v-model="AuthorizationForm.site" @change="handleCheckedCitiesChange">
                  <el-checkbox v-for="city in cityOptions" :label="city" :key="city">{{ city }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item :label="$t('店铺类型') + ':'" prop="store_type">
                <el-radio-group v-model="AuthorizationForm.store_type">
                  <el-radio label="1">跨境</el-radio>
                  <el-radio label="2">本土</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item :label="$t('店铺模式') + ':'" prop="store_model">
                <el-checkbox-group v-model="AuthorizationForm.store_model">
                  <el-checkbox label="1">FBM</el-checkbox>
                  <el-checkbox label="2">FBA</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :loading="loading" class="btn" @click="submit()">
                  {{ $t('确定') }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  
  <script lang="ts" setup>
import { computed, onMounted, reactive, ref, Ref } from 'vue';
import Storage from '@/utils/storage';
import { useStore } from 'vuex';
import { useI18n } from 'vue-i18n';
import { v4 as uuidv4 } from 'uuid';
import { ElMessage, FormInstance } from 'element-plus';
import axios from 'axios';

const { t } = useI18n();
const store = useStore();
const i18n = reactive(useI18n());
const AuthorizationForm = ref<any>({
  store_name: '',
  platform_account: '',
  region: 'https://sellingpartnerapi-na.amazon.com',
  site: ['美国', '加拿大', '墨西哥', '巴西'],
  store_type: '1',
  store_model: ['1'],
  checkAll: false,
});
/* 区域列表 */
const regionList = ref([
  { label: '北美', value: 'https://sellingpartnerapi-na.amazon.com', cities: ['美国', '加拿大', '墨西哥', '巴西'] },
  { label: '欧洲', value: 'https://sellingpartnerapi-eu.amazon.com', cities: ['英国', '德国', '法国', '意大利', '西班牙'] },
  { label: '远东', value: 'https://sellingpartnerapi-fe.amazon.com', cities: ['日本', '澳大利亚', '新加坡'] },
]);
const loading = ref(false);
const loginRules = ref({
  store_name: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
  platform_account: [{ required: true, message: '请输入平台账号', trigger: 'blur' }],
  region: [{ required: true, message: '请选择区域', trigger: 'change' }],
  site: [{ type: 'array', required: true, message: '请至少选择一个站点', trigger: 'change' }],
  store_type: [{ required: true, message: '请选择店铺类型', trigger: 'change' }],
  store_model: [{ type: 'array', required: true, message: '请至少选择一个店铺模式', trigger: 'change' }],
});
const cityOptions = ref<string[]>([]);

// ... (other code remains unchanged) ...
onMounted(() => {
  handleRegionChange(AuthorizationForm.value.region);
});
const handleRegionChange = (value: string) => {
  const selectedRegion = regionList.value.find((region) => region.value === value);
  if (selectedRegion) {
    cityOptions.value = selectedRegion.cities;
    AuthorizationForm.value.site = [...selectedRegion.cities];
    AuthorizationForm.value.checkAll = true;
  } else {
    cityOptions.value = [];
    AuthorizationForm.value.site = [];
    AuthorizationForm.value.checkAll = false;
  }
};

const handleCheckAllChange = (val: boolean) => {
  AuthorizationForm.value.site = val ? cityOptions.value : [];
};

const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  AuthorizationForm.value.checkAll = checkedCount === cityOptions.value.length;
};

const AuthorizationFormRef = ref();
/* 授权 */
const submit = async () => {
  if (!AuthorizationFormRef.value) return;

  try {
    await new Promise<void>((resolve, reject) => {
      (AuthorizationFormRef.value as any).validate((valid: boolean) => {
        if (valid) {
          resolve();
        } else {
          reject(new Error('Please fill in all required fields'));
        }
      });
    });

    loading.value = true;
    const uuid = uuidv4();

    // Prepare the form data
    const formData = {
      ...AuthorizationForm.value,
      uuid: uuid,
      site: AuthorizationForm.value.site.join(','),
      store_model: AuthorizationForm.value.store_model.join(','),
    };

    // Make a POST request to the API https://apisaas.raycos.net 192.168.1.141:8082
    const response = await axios.post('https://apisaas.raycos.net/erp/store/add', formData, {
      headers: {
        'Content-Type': 'application/json',
        /* ' Access-Control-Allow-Origin': '*' */
      },
    });

    if (response.data.success) {
      const authUrl = generateAuthUrl(formData.region, uuid);
      window.open(authUrl, '_blank');
      ElMessage.success('提交成功');
    } else {
      ElMessage.error(response.data.message || '提交失败');
    }
  } catch (error) {
    console.error('Authorization error:', error);
    if (error instanceof Error) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error('授权过程中发生错误');
    }
  } finally {
    loading.value = false;
  }
};

const generateAuthUrl = (region: string, uuid: string) => {
  const baseUrl = region;
  const applicationId = 'amzn1.sp.solution.b50697a2-e3d3-47e0-8de3-9ae03fbdcd9b';
  return `${baseUrl}/apps/authorize/consent?application_id=${applicationId}&state=${uuid}&version=beta`;
};
/* export default {
  name: 'AmazonAuthorization',
  data() {
    return {
      id_: 'amzn1.sp.solution.b50697a2-e3d3-47e0-8de3-9ae03fbdcd9b',
      regions: [
        { name: '加拿大', url: 'https://sellercentral.amazon.ca' },
        { name: '美国', url: 'https://sellercentral.amazon.com' },
        { name: '墨西哥', url: 'https://sellercentral.amazon.com.mx' },
        { name: '巴西', url: 'https://sellercentral.amazon.com.br' },
        { name: '西班牙', url: 'https://sellercentral-europe.amazon.com' },
        { name: '英国', url: 'https://sellercentral-europe.amazon.com' },
        { name: '法国', url: 'https://sellercentral-europe.amazon.com' },
        { name: '荷兰', url: 'https://sellercentral.amazon.nl' },
        { name: '德国', url: 'https://sellercentral-europe.amazon.com' },
        { name: '意大利', url: 'https://sellercentral-europe.amazon.com' },
        { name: '瑞典', url: 'https://sellercentral.amazon.se' },
        { name: '南非', url: 'https://sellercentral.amazon.co.za' },
        { name: '波兰', url: 'https://sellercentral.amazon.pl' },
        { name: '埃及', url: 'https://sellercentral.amazon.eg' },
        { name: '土耳其', url: 'https://sellercentral.amazon.com.tr' },
        { name: '沙特阿拉伯', url: 'https://sellercentral.amazon.sa' },
        { name: '阿联酋', url: 'https://sellercentral.amazon.ae' },
        { name: '印度', url: 'https://sellercentral.amazon.in' },
        { name: '比利时', url: 'https://sellercentral.amazon.com.be' },
        { name: '新加坡', url: 'https://sellercentral.amazon.sg' },
        { name: '澳大利亚', url: 'https://sellercentral.amazon.com.au' },
        { name: '日本', url: 'https://sellercentral.amazon.co.jp' },
      ],
    };
  },
  methods: {
    authorize(url) {
      window.open(`${url}/apps/authorize/consent?application_id=${this.id_}&version=beta`);
    },
  },
}; */
</script>
  
  <style scoped>
/* Add your styles here if needed */
</style>