<template>
  <fs-page class="fs-page-custom">
    <fs-crud ref="crudRef" v-bind="crudBinding"> </fs-crud>
  </fs-page>
  <el-dialog v-model="dialogVisible" :title="authType === 'ad' ? '广告授权' : 'SP授权'" width="45%" :destroy-on-close="true" center>
    <el-form :model="formData" label-position="right" label-width="100px" :disabled="formDisabeld">
      <el-form-item label="亚马逊店铺" prop="custom_shop_name" :rules="{ required: true, message: '必填项', trigger: 'blur' }">
        <el-input v-model="formData.custom_shop_name"></el-input>
      </el-form-item>
      <el-form-item label="区域">
        <el-select v-model="formData.region">
          <el-option label="北美" :value="1"></el-option>
          <el-option label="欧洲" :value="2"></el-option>
          <el-option label="远东" :value="3"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="genAuthLink" :disabled="formData.custom_shop_name === ''">生成授权链接</el-button>
    <div v-show="authLink">
      <el-divider />
      <p>请复制下面的授权链接到店铺常用登入浏览器去授权：</p>
      <el-text truncated>{{ authLink }}</el-text>
      <el-button style="display: block" @click="copyLink">复制链接</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, inject, nextTick } from 'vue'
import { useFs, FsPage } from '@fast-crud/fast-crud'
import { createCrudOptions } from './crud'
import useClipboard from 'vue-clipboard3'
import { genAdAuthLink, genSpAuthLink } from './api'
import { ElMessage } from 'element-plus'

const { toClipboard } = useClipboard()
const dialogVisible = ref(false)
const formData = ref({
  region: 1,
  custom_shop_name: '',
})
const formDisabeld = ref(false)
const authLink = ref('')
const authType = ref('ad')
let rowData = { id: 0 }
const showDialog = (type: string, row: any) => {
  authType.value = type
  if (type === 'sp') {
    formData.value.custom_shop_name = row.custom_shop_name
    formData.value.region = row.region
    rowData = row
    formDisabeld.value = true
  } else {
    formData.value.custom_shop_name = ''
    formData.value.region = 1
    formDisabeld.value = false
  }
  authLink.value = ''
  dialogVisible.value = true
}

const genAuthLink = async () => {
  if (authType.value === 'ad') {
    // const resp = await genAdAuthLink(formData.value)
    // authLink.value = resp.data    
    authLink.value = '广告授权'
  } else if (authType.value === 'sp') {
    // const resp = await genSpAuthLink(rowData.id)
    // authLink.value = resp.data
    authLink.value = 'SP授权'
  }
}
const copyLink = async () => {
  try {
    await toClipboard(authLink.value)
    ElMessage({
      message: '复制成功!',
      type: 'success',
    })
  } catch (e) {
    ElMessage.error(e)
  }
}

const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions, context: { showDialog } })

onMounted(() => {
  crudExpose.doRefresh()
})
</script>

<style scoped></style>
