<template>
  <div
    id="review_Email"
    v-loading="pictLoading"
    class="view"
    element-loading-background="rgba(43, 48, 67, 0.65)"
    element-loading-spinner="el-icon-loading"
  >
    <div class="crm_search">
      <el-form ref="formRef" :model="search" label-width="">
        <el-row>
          <el-col :span="24" :md="24" :lg="24">
            <el-form-item>
              <el-select
                v-model="search.tag"
                class="crm_search_down crm-border-radius-no"
                :placeholder="$t('Placeholder.Choose')"
              >
                <el-option :label="$t('Ucard.Business.text2')" :value="1"></el-option>
                <el-option :label="$t('Ucard.Business.text4')" :value="3"></el-option>
                <el-option :label="$t('Ucard.Business.text5')" :value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-input
                v-if="search.tag == 1"
                v-model.trim="search.cId"
                class="crm-border-left-no crm-border-radius-no"
                clearable
                :placeholder="$t('Placeholder.Input')"
                @keyup.enter="toSearch"
              ></el-input>
              <el-input
                v-if="search.tag == 3"
                v-model.trim="search.email"
                class="crm-border-left-no crm-border-radius-no"
                clearable
                :placeholder="$t('Placeholder.Input')"
                @keyup.enter="toSearch"
              ></el-input>
              <el-input
                v-if="search.tag == 4"
                v-model.trim="search.mobile"
                class="crm-border-left-no crm-border-radius-no"
                clearable
                :placeholder="$t('Placeholder.Input')"
                @keyup.enter="toSearch"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-input
                v-model.trim="search.merchantOrderNo"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('global.p15')"
                @keyup.enter="toSearch"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.payoutCurrency"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('global.p25')"
                @change="toSearch"
              >
                <el-option
                  v-for="(item, index) in globalCurrenciesOpt"
                  :key="index"
                  :label="item.payoutCurrency"
                  :value="item.payoutCurrency"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.status"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('global.p20')"
                @change="toSearch"
              >
                <el-option
                  v-for="(item, key) in statusOpt"
                  :key="key"
                  :label="$t(item.label)"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.complianceStatus"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('global.p21')"
                @change="toSearch"
              >
                <el-option
                  v-for="(value, key) in complianceText"
                  :key="key"
                  :label="$t(value)"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.approveStatus"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('global.p22')"
                @change="toSearch"
              >
                <el-option
                  v-for="(value, key) in approvalText"
                  :key="key"
                  :label="$t(value)"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="search.date"
                class="crm_date_pick crm-border-radius-no"
                type="daterange"
                align="right"
                unlink-panels
                value-format="yyyy-MM-dd"
                range-separator="-"
                :start-placeholder="$t('Placeholder.Start')"
                :end-placeholder="$t('Placeholder.End')"
              >
              </el-date-picker>
              <el-button
                class="crm-border-radius-no crm-border-left-no"
                :icon="Search"
                @click="toSearch"
              ></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="align-items: baseline">
          <el-button
            v-if="display['R-GlobalOrder-Export'] && display['R-GlobalOrder-Export'].show"
            type="primary"
            style="margin-left: 8px"
            @click="exportAgents"
            >{{ $t('Btn.Export') }}</el-button
          >
        </el-form-item>
        <el-form-item style="align-items: baseline">
          <div class="search_action_btn">
            <span
              v-if="display['R-GlobalOrder-Add'] && display['R-GlobalOrder-Add'].show"
              class="crm-cursor"
              @click="addOrder"
            >
              <el-icon><Plus /></el-icon>
              <span>{{ $t('Btn.Add') }}</span>
            </span>
          </div>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <div class="business-mock-demo" style="margin: 30px 0">
        <el-table :data="businessList" stripe style="margin-top: 20px; width: 100%">
          <el-table-column prop="cId" :label="$t('Ucard.Business.item1')">
            <template #default="scope">
              <span v-if="scope.row.cId">{{ scope.row.cId }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="merchantOrderNo" :label="$t('global.p15')" />
          <el-table-column :label="$t('Ucard.Business.item5')">
            <template #default="scope">
              {{ scope.row.lastName }} {{ scope.row.firstName }}
            </template>
          </el-table-column>
          <el-table-column prop="email" :label="$t('Ucard.Business.item4')" />
          <el-table-column :label="$t('Ucard.Business.item3')">
            <template #default="scope"> {{ scope.row.areaCode }} {{ scope.row.mobile }} </template>
          </el-table-column>
          <el-table-column prop="deductionAmount" :label="$t('global.p16')">
            <template #default="scope">
              {{ scope.row.deductionAmount }}
              <div>
                {{ scope.row.sendCurrency }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="deductionFee" :label="$t('global.p17')" />
          <el-table-column prop="transferAmount" :label="$t('global.p19')">
            <template #default="scope">
              {{ scope.row.transferAmount }}
              <div>
                {{ scope.row.payoutCurrency }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="status" :label="$t('global.p20')">
            <template #default="scope">
              <span :class="`state ${getStatusColor('status', scope.row.status)}`">{{
                $t(statusText[scope.row.status])
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="complianceStatus" :label="$t('global.p21')">
            <template #default="scope">
              <span
                v-if="scope.row.complianceStatus"
                :class="`state ${getStatusColor('compliance', scope.row.complianceStatus)}`"
                >{{ $t(complianceText[scope.row.complianceStatus]) }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="approveStatus" :label="$t('global.p22')">
            <template #default="scope">
              <span :class="`state ${getStatusColor('approve', scope.row.approveStatus)}`">{{
                $t(approvalText[scope.row.approveStatus])
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deductionAccountStatus" :label="$t('global.p24')">
            <template #default="scope">
              <span
                :class="`state ${getStatusColor('deduction', scope.row.deductionAccountStatus)}`"
                >{{ $t(deductionAccountText[scope.row.deductionAccountStatus]) }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="addTime" :label="$t('global.p23')" />

          <el-table-column :label="$t('Ucard.Business.item20')" align="center">
            <template #default="scope">
              <el-dropdown trigger="click" @command="handleCommand">
                <span class="el-dropdown-link crm-cursor">
                  <i style="font-weight: bold; font-size: 20px" class="iconfont iconcaidan"></i>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="display['R-GlobalOrder-Single'].show"
                      :command="{ type: '1', row: scope.row }"
                    >
                      <el-icon><View /></el-icon>
                      <span>{{ $t('R-Business-Single') }}</span>
                    </el-dropdown-item>
                    <!-- 审批 -->
                    <el-dropdown-item
                      v-if="
                        display['R-GlobalOrder-Approve'].show &&
                        scope.row.deductionAccountStatus == 2 &&
                        scope.row.approveStatus == 1 &&
                        scope.row.status != 'cancel'
                      "
                      :command="{ type: '2', row: scope.row }"
                    >
                      <el-icon><EditPen /></el-icon>
                      <span>{{ $t('R-Business-Approve') }}</span>
                    </el-dropdown-item>
                    <!-- 提交待补充资料 -->
                    <el-dropdown-item
                      v-if="
                        display['R-GlobalOrder-Submit'].show &&
                        scope.row.complianceStatus == complianceStatusEnum.PendingCheck
                      "
                      :command="{ type: '3', row: scope.row }"
                    >
                      <el-icon><EditPen /></el-icon>
                      <span>
                        {{ $t('R-GlobalOrder-Submit') }}
                      </span>
                    </el-dropdown-item>
                    <!-- 取消订单 -->
                    <el-dropdown-item
                      v-if="
                        display['R-GlobalOrder-Close'].show &&
                        scope.row.approveStatus == 1 &&
                        scope.row.status != 'cancel'
                      "
                      :command="{ type: '4', row: scope.row }"
                    >
                      <el-icon><Close /></el-icon>
                      <span>
                        {{ $t('Ucard.GlobalOrder.CancelOrder') }}
                      </span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div v-if="pagerInfo.rowTotal" class="crm_pagination">
      <div class="crm_page_total">
        <span>{{ $t('Page.total.item1') }}</span>
        <span>{{ pagerInfo.rowTotal }}</span>
        <span>{{ $t('Page.total.item2') }}</span>
      </div>
      <el-pagination
        class="page"
        background
        layout="sizes, prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagerInfo.row"
        :total="pagerInfo.rowTotal"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      v-if="globalFormDialog"
      v-model="globalFormDialog"
      :title="$t('Ucard.Business.p1')"
      width="1000px"
      :close-on-click-modal="false"
    >
      <DynamicForm
        ref="dynamicFormRef"
        :fields="globalCurrenciesField"
        :global-form="globalForm"
        @update:global-form="changeGlobalForm"
      >
        <el-col v-if="isAdd" :span="8">
          <el-form-item prop="cId" :label="$t('global.t1')">
            <el-select
              v-model="globalForm.cId"
              filterable
              :placeholder="$t('global.placeholder.p1')"
              @change="selectOption"
            >
              <el-option
                v-for="item in cardUserData"
                :key="item.cId"
                :label="
                  item.cId +
                  ' / ' +
                  item.lastName +
                  ' ' +
                  item.firstName +
                  ' / ' +
                  item.areaCode +
                  '' +
                  item.mobile +
                  ' / ' +
                  item.email
                "
                :value="item.cId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="deductionAccount" :label="$t('global.t2')">
            <el-select
              v-model="globalForm.deductionAccount"
              :disabled="!globalForm.cId || !cardAccountDropdown.length"
              :placeholder="$t('global.placeholder.p2')"
              @change="clearAmount"
            >
              <el-option
                v-for="(item, index) in cardAccountDropdown"
                :key="index"
                :disabled="item.disabled"
                :label="item.lable"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="receiver" :label="$t('global.t6')">
            <el-select
              v-model="globalForm.receiver"
              :disabled="!globalForm.cId"
              filterable
              :placeholder="$t('global.placeholder.p8')"
              @change="selectReceiver"
            >
              <el-option
                v-for="item in receiverList"
                :key="item.id"
                :label="`${item.receiverFirstName} ${item.receiverLastName} / ${item.receiverBankAccountNumber}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item
                :rules="rules['payoutCurrency']"
                prop="payoutCurrency"
                :label="$t('global.p1')"
              >
                <el-select
                  v-model="globalForm.payoutCurrency"
                  :disabled="!globalForm.cId || !currencyList.length"
                  :placeholder="$t('global.placeholder.p3')"
                  @change="selectOption1(1)"
                >
                  <el-option
                    v-for="(item, index) in currencyList"
                    :key="index"
                    :label="item.payoutCurrency"
                    :value="item.payoutCurrency"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :rules="rules['payType']" prop="payType" :label="$t('global.p2')">
                <el-select
                  v-model="globalForm.payType"
                  :disabled="!globalForm.payoutCurrency || !transferTypeList.length"
                  :placeholder="$t('global.placeholder.p6')"
                  @change="selectOption1(2)"
                >
                  <el-option
                    v-for="(item, index) in transferTypeList"
                    :key="index"
                    :label="item.transferType"
                    :value="item.transferTypeId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :rules="rules['payMethod']" prop="payMethod" :label="$t('global.p3')">
                <el-select
                  v-model="globalForm.payMethod"
                  :disabled="!globalForm.payType || !payoutMethodList.length"
                  :placeholder="$t('global.placeholder.p7')"
                  @change="selectOption1(3)"
                >
                  <el-option
                    v-for="(item, index) in payoutMethodList"
                    :key="index"
                    :label="item.payoutMethodValue"
                    :value="item.payoutMethodId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="8">
          <el-form-item :rules="rules['amount']" prop="amount">
            <template #label>
              <span>
                <span>{{ $t('global.t4') }}</span>
                <!-- 提示输入值的大小 -->
                <span v-if="exchangeRateData && exchangeRateData.maxQuota" class="quota-tip">{{
                  `(${$t('Ucard.GlobalOrder.quoteTip')}  ${exchangeRateData.minQuota} - ${
                    exchangeRateData.maxQuota
                  })`
                }}</span>
              </span>
            </template>
            <el-input
              v-model="globalForm.amount"
              type="number"
              :disabled="amountDisabled"
              :min="exchangeRateData.minQuota ? exchangeRateData.minQuota : -Infinity"
              :max="exchangeRateData.maxQuota ? exchangeRateData.maxQuota : Infinity"
              :placeholder="$t('global.placeholder.p4')"
              @change="globalExchangeRate"
              @keydown="keyDown"
            />
            <span v-if="feeNum != undefined" class="fee-text">
              {{ `${$t('Ucard.GlobalOrder.fee')}：${feeNum}` }}
            </span>
          </el-form-item>
        </el-col>
      </DynamicForm>

      <template #footer>
        <el-button @click="globalFormDialog = false">{{ $t('Ucard.Business.p32') }}</el-button>
        <el-button
          :loading="addLoading"
          type="primary"
          :disabled="isAdd && !isBusinessFormValid()"
          @click="saveBusiness"
          >{{ $t('Btn.Add') }}</el-button
        >
      </template>
    </el-dialog>
    <GlobalOrderDialog
      v-if="detailDialog"
      :visible="detailDialog"
      :detail-data="detailData"
      :type="detailData.type"
      @close="detailDialog = false"
      @update="searchFunc()"
    ></GlobalOrderDialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, watch, onMounted, nextTick, inject } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, View, EditPen, Close, Plus } from '@element-plus/icons-vue'
  import _ from 'lodash'
  import Config from '@/config/index'
  import UcardService from '@/service/ucard'
  import { exportExcel } from '@/utils/export.js'
  import DynamicForm from './components/DynamicForm.vue'
  import GlobalOrderDialog from './components/GlobalOrderDialog.vue'
  import {
    approvalText,
    complianceStatusEnum,
    deductionAccountText,
    statusOpt,
  } from '@/enum/card/globalOrder'
  import { useI18n } from 'vue-i18n'

  // 常量定义
  const { Code } = Config
  const Session = inject('session')
  const pigeon = inject('pigeon')
  const { t } = useI18n()

  const complianceText = {
    no_process: 'Ucard.GlobalOrder.no_process',
    pending_check: 'Ucard.GlobalOrder.pending_check',
    pending: 'Ucard.GlobalOrder.pending',
    approved: 'Ucard.GlobalOrder.approved',
    rejected: 'Ucard.GlobalOrder.rejected',
  }
  const statusText = {
    null: 'Ucard.GlobalOrder.wait',
    wait_process: 'Ucard.GlobalOrder.wait',
    success: 'Ucard.GlobalOrder.success',
    fail: 'Ucard.GlobalOrder.fail',
    processing: 'Ucard.GlobalOrder.processing',
    partner_processing: 'Ucard.GlobalOrder.partner',
    cancel: 'Ucard.GlobalOrder.cancel',
  }

  // ref和reactive
  const formRef = ref(null)
  const dynamicFormRef = ref(null)
  const router = useRouter()

  // 响应式数据
  const pictLoading = ref(false)
  const addLoading = ref(false)
  const globalFormDialog = ref(false)
  const detailDialog = ref(false)
  const isAdd = ref(true)

  const search = reactive({
    tag: 1,
    cId: '',
    email: '',
    mobile: '',
    merchantOrderNo: '',
    payoutCurrency: '',
    status: '',
    complianceStatus: '',
    approveStatus: '',
    date: null,
    startDate: '',
    endDate: '',
  })

  const pagerInfo = reactive({ row: 10, current: 1, pageTotal: 0, rowTotal: 0 })

  const businessList = ref([])
  const globalForm = reactive({})
  const businessForm = reactive({})

  const cardUserData = ref([])
  const cardAccountDropdown = ref([])
  const receiverList = ref([])
  const currencyList = ref([])
  const globalCurrenciesOpt = ref([])
  const globalCurrenciesField = ref([])
  const globalCurrenciesDropdown = ref([])

  const feeNum = ref(undefined)
  const exchangeRateData = ref({})
  const detailData = reactive({})

  // 计算属性
  const display = computed(() => JSON.parse(Session.Get('display', true)))
  const AccessToken = computed(() => {
    const token = Session.Get('access_token')
    return token ? { 'Access-Token': token } : {}
  })
  const user = computed(() => JSON.parse(Session.Get('user', true)))

  const transferTypeList = computed(() => {
    return (
      currencyList.value.find((item) => item.payoutCurrency == globalForm.payoutCurrency)?.types ||
      []
    )
  })

  const payoutMethodList = computed(() => {
    return (
      transferTypeList.value.find((item) => item.transferTypeId == globalForm.payType)?.methods ||
      []
    )
  })

  const amountDisabled = computed(() => {
    const { payoutCurrency, payType, payMethod } = globalForm
    return !payoutCurrency || !payType || !payMethod
  })

  const deductionAccountTextComputed = computed(() => deductionAccountText)

  const rules = computed(() => ({
    payoutCurrency: [
      {
        required: true,
        message: t('global.placeholder.p3'),
        trigger: 'change',
      },
    ],
    payType: [
      {
        required: true,
        message: t('global.placeholder.p6'),
        trigger: 'change',
      },
    ],
    payMethod: [
      {
        required: true,
        message: t('global.placeholder.p7'),
        trigger: 'change',
      },
    ],
    amount: [
      {
        required: true,
        message: t('global.placeholder.p4'),
        trigger: 'change',
      },
    ],
  }))

  // 方法
  const changeGlobalForm = (data) => {
    console.log(data)
    Object.assign(globalForm, data)
  }
  const getStatusColor = (type, status) => {
    let color = 'crm_state_blue'
    if (type == 'status') {
      switch (status) {
        case null:
        case 'wait_process':
          color = 'crm_state_orange'
          break
        case 'success':
          color = 'crm_state_blue'
          break
        case 'fail':
          color = 'crm_state_red'
          break
        case 'processing':
        case 'partner_processing':
          color = 'crm_state_yellow'
          break
        case 'cancel':
          color = 'crm_state_gray'
          break
      }
    }
    if (type == 'compliance') {
      switch (status) {
        case 'no_process':
        case 'approved':
          color = 'crm_state_blue'
          break
        case 'rejected':
          color = 'crm_state_red'
          break
        case 'pending_check':
          color = 'crm_state_orange'
          break
        case 'pending':
          color = 'crm_state_yellow'
          break
      }
    }
    if (type == 'approve') {
      switch (status) {
        case 1:
          color = 'crm_state_orange'
          break
        case 2:
          color = 'crm_state_blue'
          break
        case 3:
          color = 'crm_state_red'
          break
      }
    }
    if (type == 'deduction') {
      switch (status) {
        case '1':
          color = 'crm_state_yellow'
          break
        case '2':
          color = 'crm_state_blue'
          break
        case '3':
          color = 'crm_state_red'
          break
        case '4':
          color = 'crm_state_orange'
          break
        case '5':
          color = 'crm_state_gray'
          break
        case '6':
          color = 'crm_state_red'
          break
      }
    }
    return color
  }

  const divideNum = (quote, fee) => {
    return _.floor(_.divide(quote, fee), 2)
  }

  const exportAgents = async () => {
    exportExcel(pigeon, '/wasabi/global/order/list/export', { ...search }, 'Global_Order_List')
  }

  const addOrder = () => {
    isAdd.value = true
    globalFormDialog.value = true
    clearForm()
    cardUserList()
  }

  const clearForm = () => {
    Object.keys(businessForm).forEach((key) => delete businessForm[key])
    Object.keys(globalForm).forEach((key) => delete globalForm[key])
    exchangeRateData.value = {}
    feeNum.value = undefined
  }

  const cardUserList = async () => {
    const res = await UcardService.cardUserList()
    if (res.code === 200) {
      cardUserData.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }

  const clearAmount = () => {
    globalForm.amount = undefined
  }

  const selectOption = async (item) => {
    businessForm.deductionAccount = ''
    globalForm.deductionAccount = undefined
    globalForm.amount = undefined
    globalForm.receiver = undefined

    cardAccountDropdown.value = []
    businessForm.cId = item
    changeSelect(item)
    await getAccountDropdown(item)
    setData(globalCurrenciesField.value)
    await getGlobalCurrenciesDropdown(item)
    await getMostReceiverList(item)
  }

  const changeSelect = (cId) => {
    const selectedUser = cardUserData.value.find((item) => item.cId === cId)
    if (selectedUser) {
      Object.assign(businessForm, selectedUser)
    }
  }

  const selectOption1 = async (type) => {
    if (type === 1) {
      const list1 = currencyList.value.find(
        (item) => item.payoutCurrency == globalForm.payoutCurrency
      )?.types
      if (list1 && list1.length == 1) {
        globalForm.payType = list1[0].transferTypeId
      } else {
        globalForm.payType = undefined
      }
      const list2 = list1?.[0]?.methods || []
      if (list2.length == 1) {
        globalForm.payMethod = list2[0].payoutMethodId
      } else {
        globalForm.payMethod = undefined
      }
    } else if (type === 2) {
      globalForm.payMethod = undefined
    }
    globalForm.amount = undefined
    feeNum.value = undefined

    const { payoutCurrency, payType, payMethod } = globalForm
    if (!payoutCurrency || !payType || !payMethod) {
      return
    }

    const row = globalCurrenciesDropdown.value.filter((currency) => {
      return (
        currency.payoutCurrency === payoutCurrency &&
        currency.transferTypeId === payType &&
        currency.payoutMethodId === payMethod
      )
    })

    Object.assign(businessForm, {
      fieldData: { ...row[0] },
    })

    await getGlobalCurrenciesField(row[0])

    const res = await UcardService.globalExchangeRate({
      uniqueId: businessForm.uniqueId,
      country: businessForm.fieldData.country,
      payoutCurrency: businessForm.fieldData.payoutCurrency,
      transferTypeId: businessForm.fieldData.transferTypeId,
      payoutMethodId: businessForm.fieldData.payoutMethodId,
    })

    if (res.code === 200) {
      exchangeRateData.value = res.data
    }
  }

  const getAllGlobalCurrencies = async () => {
    const res = await UcardService.globalCurrenciesDropdown({})
    if (res.code === 200 || res.code === 0) {
      globalCurrenciesOpt.value = res.data || []
    }
  }

  const getMostReceiverList = async (cId) => {
    const data = cardUserData.value.find((item) => item.cId === cId)
    const res = await UcardService.globalReceiverList({ uniqueId: data.uniqueId })
    if (res.code === 200 || res.code === 0) {
      receiverList.value = res.data || []
    }
  }

  const getGlobalCurrenciesDropdown = async (cId) => {
    const res = await UcardService.globalCurrenciesDropdown({ cId, code: '', status: 'online' })
    if (res.code === 200 || res.code === 0) {
      globalCurrenciesDropdown.value = res.data || []
      const data = _.cloneDeep(res.data)

      const array = Object.entries(
        data.reduce((acc, item) => {
          const {
            payoutCurrency,
            transferTypeValue,
            transferTypeId,
            payoutMethodId,
            payoutMethodValue,
          } = item

          if (!acc[payoutCurrency]) {
            acc[payoutCurrency] = {}
          }

          if (!acc[payoutCurrency][transferTypeValue]) {
            acc[payoutCurrency][transferTypeValue] = {
              transferTypeId,
              methods: [],
            }
          }

          acc[payoutCurrency][transferTypeValue].methods.push({
            payoutMethodId,
            payoutMethodValue,
          })

          return acc
        }, {})
      ).map(([payoutCurrency, typesObj]) => ({
        payoutCurrency,
        types: Object.entries(typesObj).map(([transferType, { transferTypeId, methods }]) => ({
          transferType,
          transferTypeId,
          methods,
        })),
      }))
      currencyList.value = array
    }
  }

  const getGlobalCurrenciesField = async (row) => {
    const res = await UcardService.globalCurrenciesField({
      ...row,
    })
    if (res.code === 200) {
      await setData(res.data || [])
    }
  }

  const selectReceiver = (id) => {
    const data = receiverList.value.find((item) => item.id === id)
    Object.assign(globalForm, data)

    nextTick(() => {
      dynamicFormRef.value.globalFormRef.value.clearValidate()
    })
  }

  const keyDown = (e) => {
    console.log(e)
  }

  const globalExchangeRate = async (e) => {
    feeNum.value = undefined
    const { usedQuota, yearTransferAmountQuota, minQuota, maxQuota } = exchangeRateData.value

    if (!/^(0|([1-9][0-9]*))(\.[\d]{1,2})?$/.test(e)) {
      ElMessage.error(t('vaildate.amount.NonNegFormat'))
      return
    }

    const amount = Number(e)
    if (amount < minQuota || amount > maxQuota) {
      ElMessage.error(t('global.validator.v14', { minQuota, maxQuota }))
      return
    }

    if (yearTransferAmountQuota) {
      const add = _.add(usedQuota, amount)
      if (add > yearTransferAmountQuota) {
        ElMessage.error(t('Ucard.GlobalOrder.rateTip'))
        return
      }
    }

    const res = await UcardService.globalExchangeRate({
      amount: e,
      uniqueId: businessForm.uniqueId,
      country: businessForm.fieldData.country,
      payoutCurrency: businessForm.fieldData.payoutCurrency,
      transferTypeId: businessForm.fieldData.transferTypeId,
      payoutMethodId: businessForm.fieldData.payoutMethodId,
    })

    if (res.code === 200) {
      Object.assign(businessForm, {
        exchangeRate: res.data,
      })
      feeNum.value = divideNum(res.data.deductionFee, businessForm.fieldData.exchangeRate)
      await setData(globalCurrenciesField.value)
    } else {
      ElMessage.error(res.msg)
    }
  }

  const setData = async (data) => {
    const { idType, idNumber } = businessForm
    const senderIdType =
      idType === 'PASSPORT' ? '1' : idType === 'GOVERNMENT_ISSUED_ID_CARD' ? '2' : ''
    const senderIdNumber =
      idType === 'PASSPORT' ? idNumber : idType === 'GOVERNMENT_ISSUED_ID_CARD' ? idNumber : ''

    const senderData = {
      senderFirstName: businessForm.firstName,
      senderLastName: businessForm.lastName,
      senderGender: businessForm.gender,
      senderIdType,
      senderIdNumber,
      transferAmount: businessForm?.exchangeRate?.transferAmount?.toFixed(2) || '',
      senderNationality: businessForm.nationality,
      senderIdIssueCountry: businessForm.senderIdIssueCountry,
      senderDateOfBirth: businessForm.birthday,
      senderCountry: businessForm.country,
      senderState: businessForm.senderState,
      senderRegion: businessForm.senderRegion,
      senderCity: businessForm.townEnName,
      senderAddress: businessForm.address,
      senderZipCode: businessForm.postCode,
      senderMobileAreaCode: businessForm.areaCode,
      senderMobileNumber: businessForm.mobile,
      senderEmail: businessForm.email,
      senderOccupation: businessForm.occupation,
      transferType: businessForm.fieldData?.transferTypeId || '',
      PayoutMethod: businessForm.fieldData?.payoutMethodId || '',
    }

    const mergedFields = await Promise.all(
      data.map(async (field) => {
        const { fieldName } = field
        const key = Object.keys(senderData).find((k) => k.toLowerCase() === fieldName.toLowerCase())
        const fixedValue = key ? senderData[key] : field.fixedValue

        if (fieldName === 'transferAmount') {
          field.disabled = true
        }

        if (['payoutCurrency', 'payoutMethod', 'transferType'].includes(fieldName)) {
          field.hidden = true
        }

        if (field.fieldName === 'receiverBankCity') {
          try {
            const res = await UcardService.globalQueryBankCities({
              payoutCurrency: businessForm.fieldData.payoutCurrency,
              country: businessForm.fieldData.country,
            })

            if (res.code === 200 && Array.isArray(res.data)) {
              field.availableDtos = res.data.map((item) => ({
                value: item.bankCitiesValue,
                valueId: item.bankCitiesKey,
              }))
            }
          } catch (e) {
            console.error('加载 receiverBankCity 城市数据失败:', e)
          }
        }

        if (field.fieldType === 'select') {
          if (fieldName.includes('receiver')) {
            let rValue = globalForm[fieldName]
            const label = field.availableDtos?.find((item) => item.valueId == rValue)?.value ?? null
            globalForm[fieldName + 'Value'] = label
          } else {
            const label =
              field.availableDtos?.find((item) => item.valueId == fixedValue)?.value ?? null
            globalForm[fieldName + 'Value'] = label
          }
        }
        return { ...field, fixedValue }
      })
    )
    globalCurrenciesField.value = mergedFields
  }

  const getAccountDropdown = async (cId) => {
    const res = await UcardService.cardAccountDropdown({ cId })
    if (res.code === 200) {
      cardAccountDropdown.value = res.data.map((item) => {
        if (item.type == '1') {
          item.lable = `${t('Ucard.GlobalOrder.cardNo')} - ${item.cardNumber} ${t(
            'Ucard.GlobalOrder.bal'
          )}: ${item.balance}`
        } else {
          item.lable = `${t('Ucard.GlobalOrder.bagBal')}: ${item.balance}`
        }
        item.value = item.cardNumber + ',' + item.type

        item.disabled = item.balance == 0
        return item
      })
    } else {
      ElMessage.error(res.msg)
    }
  }

  const handleCommand = async (command) => {
    if (command.type !== '4') {
      const res = await UcardService.globalOrdersDetail({ id: command.row.id })
      if (res.code === 200) {
        Object.assign(detailData, {
          ...res.data,
          type: command.type,
        })
      }
    }

    switch (command.type) {
      case '1':
      case '2':
      case '3':
        detailDialog.value = true
        break
      case '4':
        ElMessageBox.confirm(
          t('Ucard.GlobalOrder.ConfirmCancelOrder'),
          t('Ucard.GlobalOrder.CancelOrder'),
          {
            confirmButtonText: t('Btn.Confirm'),
            cancelButtonText: t('Btn.Cancel'),
            type: 'warning',
          }
        )
          .then(async () => {
            const res = await UcardService.globalCancelOrder({
              id: command.row.id,
              cId: user.value.cId,
            })
            if (res.code == Code.StatusOK) {
              ElMessage.success(t('Ucard.GlobalOrder.CancelOrderSuccess'))
              searchFunc()
            } else {
              ElMessage.error(res.msg)
            }
          })
          .catch(() => {})
        break
    }
  }

  const toSearch = () => {
    pagerInfo.current = 1
    searchFunc()
  }

  const searchFunc = async () => {
    if (!display.value['R-GlobalOrder-List']?.show) {
      ElMessage.warning($t('Msg.NotDisplay'))
      return
    }

    pictLoading.value = true
    if (search.date == null) {
      search.startDate = ''
      search.endDate = ''
    } else if (search.date.length == 0) {
      search.startDate = ''
      search.endDate = ''
    } else {
      search.startDate = search.date[0]
      search.endDate = search.date[1]
    }

    try {
      const params = {
        ...search,
        page: {
          current: pagerInfo.current,
          row: pagerInfo.row,
        },
      }
      const res = await UcardService.globalOrdersList(params)
      if (res.code === Code.StatusOK) {
        businessList.value = res.data
        pagerInfo.rowTotal = res.page?.rowTotal || 0
        pagerInfo.pageTotal = res.page?.pageTotal || 0
        ElMessage.success(t('Msg.SearchSuccess'))
      } else {
        ElMessage.error(res.msg || t('Ucard.Business.ms2'))
      }
    } catch (error) {
      console.error('Search error:', error)
      ElMessage.error(t('Ucard.Business.ms2'))
    } finally {
      pictLoading.value = false
    }
  }

  const handleSizeChange = (val) => {
    pagerInfo.row = val
    searchFunc()
  }

  const handleCurrentChange = (val) => {
    pagerInfo.current = val
    searchFunc()
  }

  const saveBusiness = async () => {
    console.log(dynamicFormRef.value.globalFormRef, 'value1')
    console.log(dynamicFormRef.value.globalFormRef, 'value')
    const valid = await dynamicFormRef.value.globalFormRef.validate()
    const [cardNumber, deductionAccountType] = globalForm.deductionAccount.split(',')

    if (valid) {
      const otherData = {}
      globalCurrenciesField.value
        .map((item) => ({
          fieldName: item.fieldName,
          fieldType: item.fieldType,
        }))
        .forEach((item) => {
          otherData[item.fieldName] = globalForm[item.fieldName]
          if (item.fieldType == 'select') {
            const key = item.fieldName + 'Value'
            otherData[key] = globalForm[key]
          }
        })

      const params = {
        amount: globalForm.amount,
        cId: globalForm.cId,
        ...otherData,
        cardNumber,
        deductionAccountType,
        uniqueId: businessForm.uniqueId,
        ...businessForm.exchangeRate,
      }

      addLoading.value = true
      const res = await UcardService.globalOrdersCreate(params)

      if (res.code === Code.StatusOK) {
        ElMessage.success(res.msg)
        globalFormDialog.value = false
        searchFunc()
      } else {
        ElMessage.error(res.msg)
      }
      addLoading.value = false
    } else {
      console.log('表单校验失败')
    }
  }

  const isBusinessFormValid = () => {
    const requiredFields = ['areaCode', 'mobile', 'email', 'lastName', 'firstName', 'address']
    return requiredFields.every((field) => !!businessForm[field])
  }

  // 挂载
  onMounted(() => {
    getAllGlobalCurrencies()
    searchFunc()
  })

  // 监听器
  watch(
    () => search.tag,
    () => {
      search.cId = ''
      search.email = ''
      search.mobile = ''
    }
  )

  watch(
    () => globalForm.amount,
    (val) => {
      if (!val) {
        feeNum.value = undefined
        delete businessForm.exchangeRate
        setData(globalCurrenciesField.value)
      }
    }
  )

  watch(globalFormDialog, (val) => {
    if (!val) {
      Object.keys(globalForm).forEach((key) => delete globalForm[key])
      Object.keys(businessForm).forEach((key) => delete businessForm[key])
      globalCurrenciesField.value = []
    }
  })
</script>

<style scoped>
  .fee-text {
    font-size: 12px;
    color: #666;
    margin-top: 4px;
    display: block;
  }
</style>

<style scoped lang="scss">
  @import 'index.scss';
</style>
<style lang="scss">
  #review_Email {
    .dialog_header_w {
      .crm_search_down {
        width: 400px;
      }
    }
  }
</style>
