<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="searchForm" label-position="" :model="search" label-width="">
        <el-row>
          <el-col :span="24" :md="24" :lg="24">
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.payoutCurrency"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('global.p1')"
                @change="toSearch"
              >
                <el-option
                  v-for="(item, index) in currenciesDropdown"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.transferTypeId"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('global.p2')"
                @change="toSearch"
              >
                <el-option
                  v-for="([key, value], index) in Object.entries(transferType)"
                  :key="index"
                  :label="value"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.payoutMethodId"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('global.p3')"
                @change="toSearch"
              >
                <el-option
                  v-for="([key, value], index) in Object.entries(payoutMethod)"
                  :key="index"
                  :label="$t(value)"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="search.status"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('Ucard.CardType.s3')"
                @change="toSearch"
              >
                <el-option :label="$t('Ucard.CardType.t5')" value="offline"></el-option>
                <el-option :label="$t('Ucard.CardType.t6')" value="online"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button class="crm-border-radius-no crm-border-left-no" @click="toSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <div class="search_action_btn">
            <el-button
              v-if="display['R-GlobalCurrency-Sync'].show"
              type="primary"
              :loading="syncLoading"
              class="crm-cursor"
              @click="updateCardTypes"
            >
              {{ $t('R-GlobalCurrency-Sync') }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <div class="card-mock-demo" style="margin-top: 30px">
        <el-table :data="mergeFirstRowData" stripe style="margin-top: 20px; width: 100%">
          <el-table-column prop="feeRateConfig" align="left" :label="$t('global.p5')" />
          <el-table-column prop="fixedFeeConfig" align="left" :label="$t('global.p6')" />
          <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-GlobalCurrency-Update'] &&
                        display['R-GlobalCurrency-Update'].show
                      "
                      :command="{ type: 1, row: scope.row }"
                    >
                      <el-icon><Edit /></el-icon>
                      <span>
                        {{ $t('R-GlobalCurrency-Update') }}
                      </span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="card-mock-demo" style="margin-bottom: 30px">
        <el-table :data="mock_tableData" stripe style="margin-top: 20px; width: 100%">
          <el-table-column prop="payoutCurrency" align="left" :label="$t('global.p1')">
          </el-table-column>
          <el-table-column prop="transferTypeValue" align="left" :label="$t('global.p2')" />
          <el-table-column prop="payoutMethodValue" align="left" :label="$t('global.p3')">
            <template #default="scope">
              <span>{{ $t(payoutMethod[scope.row.payoutMethodId]) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="country" align="left" :label="$t('global.p4')" />
          <el-table-column prop="feeRateConfig" align="left" :label="$t('global.p5')" />
          <el-table-column prop="fixedFeeConfig" align="left" :label="$t('global.p6')" />
          <el-table-column prop="minQuotaConfig" align="left" :label="$t('global.p7')" />
          <el-table-column prop="maxQuotaConfig" align="left" :label="$t('global.p8')" />
          <el-table-column
            prop="yearTransferAmountQuotaConfig"
            align="left"
            :label="$t('global.p9')"
          />

          <el-table-column prop="status" align="left" :label="$t('Ucard.CardType.item7')">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'online' ? 'success' : 'info'"
                >{{
                  scope.row.status === 'online' ? $t('Ucard.CardType.t6') : $t('Ucard.CardType.t5')
                }}
              </el-tag>
            </template>
          </el-table-column>
          <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-GlobalCurrency-Update1'] &&
                        display['R-GlobalCurrency-Update1'].show
                      "
                      :command="{ type: 2, row: scope.row }"
                    >
                      <el-icon><Edit /></el-icon>
                      <span>
                        {{ $t('R-GlobalCurrency-Update1') }}
                      </span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <PagePagination
      :pager-info="pagerInfo"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <el-dialog
      v-model="approvalAllDialog"
      :title="form.type == 1 ? $t('R-GlobalCurrency-Update') : $t('R-GlobalCurrency-Update1')"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :rules="rules"
        :model="form"
        label-position="top"
        class="business-edit-form"
      >
        <el-form-item prop="feeRateConfig" :label="$t('global.p5')">
          <el-input-number
            v-model="form.feeRateConfig"
            :controls="false"
            :disabled-scientific="true"
            :placeholder="$t('Placeholder.Input')"
          />
        </el-form-item>
        <el-form-item prop="fixedFeeConfig" :label="$t('global.p6')">
          <el-input-number
            v-model="form.fixedFeeConfig"
            :controls="false"
            :placeholder="$t('Placeholder.Input')"
          />
        </el-form-item>
        <!--      判断一下全局不用展示下面的，普通的需要展示 乘以汇率比对config的数值 -->
        <template v-if="form.type == '2'">
          <el-form-item prop="minQuotaConfig">
            <template #label>
              <span>
                <span>{{ $t('global.p7') }}</span>
                <span v-if="minRate" class="rate-tip">{{
                  `${$t('Ucard.GlobalOrder.currencyTip')}${minRate}`
                }}</span>
              </span>
            </template>
            <el-input
              v-model="form.minQuotaConfig"
              type="number"
              :max="form.maxMinQuota"
              :min="form.maxQuotaConfig"
              :placeholder="$t('Placeholder.Input')"
            />
          </el-form-item>
          <el-form-item prop="maxQuotaConfig">
            <template #label>
              <span>
                <span>{{ $t('global.p8') }}</span>
                <span v-if="maxRate" class="rate-tip">{{
                  `${$t('Ucard.GlobalOrder.currencyTip')} ${maxRate}`
                }}</span>
              </span>
            </template>
            <el-input
              v-model="form.maxQuotaConfig"
              type="number"
              :placeholder="$t('Placeholder.Input')"
            />
          </el-form-item>
          <el-form-item prop="yearTransferAmountQuotaConfig" :label="$t('global.p9')">
            <template #label>
              <span>
                <span>{{ $t('global.p9') }}</span>
                <span v-if="yearRate" class="rate-tip">{{
                  `${$t('Ucard.GlobalOrder.currencyTip')} ${yearRate}`
                }}</span>
              </span>
            </template>
            <el-input-number
              v-model="form.yearTransferAmountQuotaConfig"
              type="number"
              :controls="false"
              :max="form.minYearTransferAmountQuota"
              :placeholder="$t('Placeholder.Input')"
            />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="approvalAllDialog = false">
            {{ $t('Ucard.Business.p32') }}
          </el-button>
          <el-button type="primary" @click="updateCardTypesConfig">
            {{ $t('card.Btn.Confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { computed, inject, onMounted, reactive, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import { multiply } from 'lodash-es'
  import Service from '@/service/ucard'
  import Config from '@/config/index'
  import PagePagination from '@/components/PagePagination'
  import { payoutMethod, transferType } from './const'
  import { floatReg } from '@/utils/const'
  import { Edit } from '@element-plus/icons-vue'

  const { Code } = Config

  const { t } = useI18n()

  const Session = inject('session')
  const pigeon = inject('pigeon')

  // 响应式数据
  const pictLoading = ref(false)
  const syncLoading = ref(false)
  const approvalAllDialog = ref(false)

  const search = reactive({
    status: '',
    payoutCurrency: '',
    transferTypeId: '',
    payoutMethodId: '',
  })

  const form = reactive({
    feeRateConfig: null,
    fixedFeeConfig: null,
    minQuotaConfig: null,
    maxQuotaConfig: null,
    yearTransferAmountQuotaConfig: null,
  })

  const currenciesDropdown = ref([])
  const mergeFirstRowData = ref([])
  const mock_tableData = ref([])

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

  const minRate = ref(0)
  const maxRate = ref(0)
  const yearRate = ref(0)

  const formRef = ref()
  // 搜索
  const searchForm = ref()
  // 计算属性
  const display = computed(() => {
    return JSON.parse(Session.Get('display', true))
  })

  // 表单验证规则
  const rules = computed(() => ({
    feeRateConfig: [
      {
        validator: (rule, value, callback) => {
          if (value) {
            const test = floatReg.test(value)
            if (test) {
              callback()
            } else {
              callback(new Error(t('global.validator.v13')))
            }
          }
          callback()
        },
        trigger: 'change',
      },
    ],
    fixedFeeConfig: [
      {
        validator: (rule, value, callback) => {
          if (value) {
            const test = floatReg.test(value)
            if (test) {
              callback()
            } else {
              callback(new Error(t('global.validator.v13')))
            }
          }
          callback()
        },
        trigger: 'change',
      },
    ],
    minQuotaConfig: [
      {
        validator: (rule, value, callback) => {
          if (form.type == 1 || !value) {
            return callback()
          }
          const minQuota = Number(form.minQuota)
          const maxQuota = Number(form.maxQuota)
          const maxConfig = Number(form.maxQuotaConfig)
          const exchangeRate = Number(form.exchangeRate)

          const test = floatReg.test(value)
          if (!test) {
            return callback(new Error(t('global.validator.v13')))
          }

          value = Number(value)
          if (isNaN(value)) {
            return callback(new Error(t('global.validator.v12')))
          }

          const val = multiply(value, exchangeRate)
          minRate.value = val

          if (val < minQuota) {
            callback(new Error(t('global.validator.v2', { minQuota })))
          } else if (val > maxQuota) {
            callback(new Error(t('global.validator.v3', { maxQuota })))
          } else if (maxConfig && value > maxConfig) {
            callback(new Error(t('global.validator.v4', { maxConfig })))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    maxQuotaConfig: [
      {
        validator: (rule, value, callback) => {
          if (form.type == 1 || !value) {
            return callback()
          }
          const minQuota = Number(form.minQuota)
          const maxQuota = Number(form.maxQuota)
          const minConfig = Number(form.minQuotaConfig)
          const exchangeRate = Number(form.exchangeRate)

          const test = floatReg.test(value)
          if (!test) {
            return callback(new Error(t('global.validator.v13')))
          }

          value = Number(value)
          if (isNaN(value)) {
            return callback(new Error(t('global.validator.v12')))
          }

          const val = multiply(value, exchangeRate)
          maxRate.value = val

          if (val > maxQuota) {
            callback(new Error(t('global.validator.v6', { maxQuota })))
          } else if (val < minQuota) {
            callback(new Error(t('global.validator.v7', { minQuota })))
          } else if (minConfig && value < minConfig) {
            callback(new Error(t('global.validator.v8', { minConfig })))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    yearTransferAmountQuotaConfig: [
      {
        validator: (rule, value, callback) => {
          if (form.type == 1 || !value) {
            return callback()
          }
          const yearMax = Number(form.yearTransferAmountQuota)
          const maxConfig = Number(form.maxQuotaConfig)
          const exchangeRate = Number(form.exchangeRate)

          const test = floatReg.test(value)
          if (!test) {
            return callback(new Error(t('global.validator.v13')))
          }

          value = Number(value)
          if (isNaN(value)) {
            return callback(new Error(t('global.validator.v12')))
          }

          const val = multiply(value, exchangeRate)
          yearRate.value = val

          if (val > yearMax) {
            callback(new Error(t('global.validator.v10', { yearMax })))
          } else if (maxConfig && val < maxConfig) {
            callback(new Error(t('global.validator.v11', { maxConfig })))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
  }))

  // 方法
  const keydown = (e, s) => {
    console.log(e, s, 'key')
  }

  const handleCommand = async (command) => {
    console.log(command)
    switch (command.type) {
      case 1: {
        const data = {
          ...command.row,
          type: '1',
        }
        Object.assign(form, data)
        approvalAllDialog.value = true
        break
      }
      case 2: {
        let data = {
          ...command.row,
          type: '2',
        }

        const { payoutCurrency, payoutMethodId, transferTypeId } = data
        const res = await Service.globalLatestExchangeRate({
          payoutCurrency,
          payoutMethodId,
          transferTypeId,
        })

        if (res.code == Code.StatusOK) {
          data = {
            ...data,
            exchangeRate: res.data,
          }
        }

        Object.assign(form, data)
        console.log(form.type)
        approvalAllDialog.value = true
        break
      }
    }
  }

  const updateCardTypesConfig = async () => {
    try {
      // 注意：这里需要获取实际的表单引用，假设 formRef 已经绑定到模板
      if (!formRef.value) return
      console.log(formRef)
      const valid = await formRef.value.validate()

      if (!valid) return

      const res = await Service.updateGlobalFee({ ...form })
      if (res.code == Code.StatusOK) {
        Object.assign(form, {
          feeRateConfig: null,
          fixedFeeConfig: null,
          minQuotaConfig: null,
          maxQuotaConfig: null,
          yearTransferAmountQuotaConfig: null,
        })
        approvalAllDialog.value = false
        toSearch()
      } else {
        pigeon.MessageError(res.msg)
      }
    } catch (error) {
      console.log(error, 1212)
    }
  }

  const closeForm = () => {
    minRate.value = 0
    maxRate.value = 0
    yearRate.value = 0
  }

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

  const updateCardTypes = async () => {
    syncLoading.value = true
    const res = await Service.globalCurrenciesSave({})

    if (res.code == Code.StatusOK) {
      pigeon.MessageOK(t('Msg.SearchSuccess'))
      searchFunc()
    } else {
      ElMessage.error(res.msg)
    }
    syncLoading.value = false
  }

  const updateCardType = () => {
    approvalAllDialog.value = true
  }

  const globalCurrenciesDropdown = async () => {
    const res = await Service.globalCurrenciesDropdown({})
    if (res.code == Code.StatusOK) {
      currenciesDropdown.value = [...new Set(res.data.map((item) => item.payoutCurrency))]
    } else {
      ElMessage.error(res.msg)
    }
  }

  const globalCurrenciesConfig = async () => {
    const res = await Service.globalCurrenciesConfig({})
    if (res.code == Code.StatusOK) {
      mergeFirstRowData.value = [res.data]
    } else {
      ElMessage.error(res.msg)
    }
  }

  const searchFunc = async () => {
    pictLoading.value = true

    if (!display.value['R-GlobalCurrency-List'].show) {
      ElMessage.warning(t('Msg.NotDisplay'))
      pictLoading.value = false
      return
    }

    const res = await Service.globalCurrenciesList({
      ...search,
      page: {
        current: pagerInfo.current,
        row: pagerInfo.row,
      },
    })

    if (res.code == Code.StatusOK) {
      mock_tableData.value = res.data
      if (res.page != null) {
        pagerInfo.rowTotal = res.page.rowTotal
        pagerInfo.pageTotal = res.page.pageTotal
      } else {
        pagerInfo.rowTotal = 0
      }
      ElMessage.success(t('Msg.SearchSuccess'))
    } else {
      ElMessage.error(res.msg)
    }
    pictLoading.value = false
  }

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

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

  // 生命周期
  onMounted(() => {
    globalCurrenciesConfig()
    searchFunc()
    globalCurrenciesDropdown()
  })

  // 侦听器
  watch(approvalAllDialog, (newVal) => {
    if (!newVal) {
      closeForm()
    }
  })
</script>
<style scoped lang="scss">
  #review_Email {
    .el-table .state {
      display: inline-block;
      min-width: 80px;
      max-width: 150px;
      box-sizing: border-box;
      line-height: 1.5;
      border-radius: 2px;
      padding: 2px 10px;
      color: #ffffff;
    }
  }
</style>
<style scoped lang="scss">
  #review_Email {
    .dialog_header_w {
      .crm_search_down {
        width: 400px;
      }
    }

    :deep(.business-edit-form) {
      .el-form-item__label {
        width: 100%;
        text-align: left;
        padding: 0;
      }

      .el-form-item {
        width: 100%;
        text-align: left;
        padding: 0;
      }

      .el-input,
      .el-select,
      .el-date-picker,
      .el-date-editor {
        width: 100%;
      }

      .el-form-item__label {
        font-weight: 500;
      }

      .el-row {
        margin-bottom: 0;
      }

      .el-col {
        margin-bottom: 0;
      }
    }

    .rate-tip {
      margin-left: 10px;
      color: #999;
      font-size: 12px;
    }
  }
</style>
