<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="22" :md="22" :lg="22">
            <el-form-item style="margin-right: 10px">
              <el-input
                v-model.trim="search.cId"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Label.CidAccount')"
                @keyup.enter="toSearch"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-input
                v-model.trim="search.mobile"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Ucard.KycAuth.item2')"
                @keyup.enter="toSearch"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-input
                v-model.trim="search.email"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Ucard.KycAuth.item3')"
                @keyup.enter="toSearch"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-input
                v-model.trim="search.cardNumber"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Ucard.Recharge.s1')"
                @keyup.enter="toSearch"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.approveStatus"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('R-Review-Status')"
                @change="toSearch"
              >
                <el-option
                  v-for="option in approveStatusOptions"
                  :key="option.value"
                  :label="t(option.label)"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.rechargeType"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Ucard.Recharge.item11')"
                @change="toSearch"
              >
                <el-option
                  v-for="(value, key) in rechargeTypes"
                  :key="key"
                  :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.Recharge.item10')"
                @change="toSearch"
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="t(option.label)"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <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-Recharge-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; margin-left: 10px"
          v-if="display['R-Recharge-Btn2']?.show"
        >
          <el-button type="primary" :disabled="!multipleSelection.length" @click="approvalAll">
            {{ t('R-Recharge-Btn4') }}
          </el-button>
          <!--          <div class="search_action_btn">-->
          <!--            <span-->
          <!--              v-if="multipleSelection.length"-->
          <!--              class="crm-cursor delete active"-->
          <!--              @click="approvalAll"-->
          <!--            >-->
          <!--              {{ t('R-Recharge-Btn4') }}-->
          <!--            </span>-->
          <!--            <span v-if="!multipleSelection.length" class="crm-cursor delete">-->
          <!--              {{ t('R-Recharge-Btn4') }}-->
          <!--            </span>-->
          <!--          </div>-->
        </el-form-item>
      </el-form>

      <div class="card-mock-demo" style="margin: 30px 0">
        <el-table
          :data="mock_tableData"
          show-summary
          :summary-method="getSummaries1"
          stripe
          style="margin-top: 20px; width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="left" type="selection" width="60" :selectable="checkSelectable">
          </el-table-column>
          <el-table-column prop="" align="left" :label="t('Label.CidAccount')">
            <template #default="{ row }">
              <span>{{ row.cId || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" align="left" :label="t('Label.Name')">
            <template #default="{ row }">
              <span v-if="row.firstName">
                {{ row.firstName + ' ' }}
              </span>
              <span v-if="row.middle">{{ row.middle + ' ' }}</span>
              <span v-if="row.lastName">{{ row.lastName }}</span>
              <span v-if="!row.firstName && !row.lastName && !row.middle">
                {{ '--' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="" align="left" :label="t('Label.Email')">
            <template #default="{ row }">
              {{ row.email || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="mobile" align="left" :label="t('Ucard.KycAuth.item2')">
            <template #default="{ row }"> {{ row.areaCode }} {{ row.mobile }} </template>
          </el-table-column>
          <el-table-column prop="cardNumber" align="left" :label="t('Ucard.Recharge.item2')">
            <template #default="{ row }">
              <span
                v-if="row.cardNumber"
                class="crm-text-underline"
                @click="cardOpen(row.cardNumber)"
              >
                {{ row.cardNumber || '--' }}
              </span>
              <span v-else>{{ row.cardNumber || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="currency" align="left" :label="t('Ucard.Recharge.item3')" />
          <el-table-column
            prop="amount"
            width="120"
            align="left"
            :label="t('Ucard.Recharge.item4')"
          />
          <el-table-column prop="fee" width="120" align="left" :label="t('card.CardType.item23')" />
          <el-table-column
            prop="rechargeFee"
            width="120"
            align="left"
            :label="t('Ucard.Recharge.item5')"
          />
          <el-table-column prop="receivedAmount" align="left" :label="t('Ucard.Recharge.item6')" />
          <el-table-column
            prop="receivedCurrency"
            align="left"
            :label="t('Ucard.Recharge.item7')"
          />
          <el-table-column prop="rechargeType" align="left" :label="t('Ucard.Recharge.item11')">
            <template #default="{ row }">
              {{ t(rechargeTypes[row.rechargeType]) }}
            </template>
          </el-table-column>
          <el-table-column prop="approveStatus" align="left" :label="t('R-Review-Status')">
            <template #default="{ row }">
              <span v-if="row.approveStatus == '2'" class="state crm_state_blue">
                {{ t('Ucard.UserOrder.t12') }}
              </span>
              <span v-else-if="row.approveStatus == '3'" class="state crm_state_gray">
                {{ t('Ucard.UserOrder.t13') }}
              </span>
              <span v-else class="state crm_state_yellow">
                {{ t('Ucard.UserOrder.t11') }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" align="left" :label="t('Ucard.Recharge.item10')">
            <template #default="{ row }">
              <span v-if="row.status === 'success'" class="state crm_state_blue">
                {{ t('Ucard.Recharge.t1') }}
              </span>
              <span v-else-if="row.status === 'fail'" class="state crm_state_gray">
                {{ t('Ucard.Recharge.t2') }}
              </span>
              <span v-else-if="row.status === 'wait_process'" class="state crm_state_yellow">
                {{ t('Ucard.VirtualCard.t11') }}
              </span>
              <span v-else class="state crm_state_orange">
                {{ t('Ucard.Recharge.t3') }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="transactionTime" align="left" :label="t('Ucard.Recharge.item9')" />
          <el-table-column prop="" align="center" :label="t('Label.Action')">
            <template #default="{ row }">
              <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-Recharge-Btn2']?.show &&
                        (row.status == 'wait_process' ||
                          row.status == 'processing' ||
                          row.status == null) &&
                        row.approveStatus == '2'
                      "
                      :command="{ type: 4, row: row }"
                    >
                      <el-icon><Operation /></el-icon>
                      <span>{{ t('R-Recharge-Btn2') }}</span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="display['R-Recharge-Btn1']?.show"
                      :command="{ type: 1, row: row }"
                    >
                      <el-icon><Operation /></el-icon>
                      <span>{{ t('R-Recharge-Btn1') }}</span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="display['R-CardOrder-Btn3']?.show && row.approveStatus == '1'"
                      :command="{ type: 3, row: row }"
                    >
                      <el-icon><Operation /></el-icon>
                      <span>{{ t('R-Recharge-Btn3') }}</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
        v-model:current-page="pagerInfo.current"
        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>

    <!-- 组件引用 -->
    <add
      :dialog-info-trading-add="dialogInfoTradingAdd"
      :editor="editor"
      :my-info="myInfo"
      :form-list="formList"
      @confirm-to-reload="confirmToReload"
      @close-add="closeAdd"
    ></add>
    <div v-if="dialogInfoTradingAdd" class="crm_verified_info_mask" @click="closeDiaAdd"></div>

    <detailed-info-cid
      :dialog-info-cid="dialogInfoCid"
      :form-info="formInfo"
      :is-trading="true"
      @close="close"
    >
    </detailed-info-cid>
    <div v-if="dialogInfoCid" class="crm_verified_info_mask" @click="closeDia"></div>

    <ViewCardSingle
      :dialog-info-trading-single="dialogInfoTradingSingle"
      :form-list="formSingle"
      :editor-type="editorType"
      @close-single="closeSingle"
    >
    </ViewCardSingle>
    <div v-if="dialogInfoTradingSingle" class="crm_verified_info_mask" @click="closeSingle"></div>

    <!-- 批量审批弹窗 -->
    <el-dialog v-model="approvalAllDialog" :title="t('R-Recharge-Btn4')" width="900px">
      <el-form
        :rules="rules"
        :model="approvalForm"
        label-width="130px"
        label-position="right"
        class="business-edit-form"
      >
        <el-form-item prop="amount" :label="t('Ucard.Recharge.item4') + '：'">
          <el-input
            v-model.trim="approvalForm.amount"
            class="crm-border-radius-no"
            disabled
            clearable
            :placeholder="t('Ucard.Recharge.item4')"
          ></el-input>
        </el-form-item>
        <el-form-item prop="fee" :label="t('Ucard.Recharge.item5') + '：'">
          <el-input
            v-model.trim="approvalForm.fee"
            class="crm-border-radius-no"
            disabled
            clearable
            :placeholder="t('card.CardType.item23')"
          ></el-input>
        </el-form-item>
        <el-form-item prop="status" :label="t('Label.CheckResults') + '：'">
          <el-select
            v-model="approvalForm.status"
            class="crm_search_down"
            :placeholder="t('Placeholder.Choose')"
          >
            <el-option
              v-for="option in checkResultOptions"
              :key="option.value"
              :label="t(option.label)"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="approvalForm.status == 3"
          prop="approveDesc"
          :label="t('Label.Descr') + '：'"
        >
          <el-select
            v-model="approvalForm.approveDesc"
            filterable
            class="crm_search_down"
            :placeholder="t('Placeholder.Choose')"
            allow-create
            @change="selectChange"
          >
            <el-option
              v-for="item in reasonsList"
              :key="item.id"
              :label="langZh ? item.content : item.enContent"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="approvalAllDialog = false">
            {{ t('Ucard.Business.p32') }}
          </el-button>
          <el-button type="primary" @click="rechargeApprove">
            {{ t('card.Btn.Confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, watch, inject, defineAsyncComponent } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { useRouter } from 'vue-router'
  import Service from '@/service/ucard'
  import Config from '@/config/index'
  import Service1 from '@/service/customer'
  import Service2 from '@/service/apply'
  import { exportExcel } from '@/utils/export'
  import { rechargeTypes } from '@/enum/card/recharge'
  import { Operation, Search } from '@element-plus/icons-vue'
  import {
    approveStatusOptions,
    checkResultOptions,
    statusOptions,
  } from '@/views/card/CardRecharge/const'
  import Add from '@/views/card/CardRecharge/components/add.vue'

  const { t } = useI18n()
  const { Code } = Config
  const router = useRouter()
  const Session = inject('session')
  const pigeon = inject('pigeon')

  // 异步加载组件
  const DetailedInfoCid = defineAsyncComponent(() =>
    import('@/views/components/DetailedInfoCid/index.vue')
  )
  const ViewCardSingle = defineAsyncComponent(() =>
    import('@/views/components/ViewCardSingle/index.vue')
  )

  // 响应式数据
  const pictLoading = ref(false)
  const dialogInfoTradingAdd = ref(false)
  const dialogInfoTradingSingle = ref(false)
  const approvalAllDialog = ref(false)
  const dialogInfoCid = ref(false)
  const multipleSelection = ref([])
  const mock_tableData = ref([])
  const reasons = ref({})
  const formRef = ref(null)

  const search = reactive({
    tag: 1,
    cardNumber: '',
    mobile: '',
    cId: '',
    email: '',
    currency: '',
    approveStatus: '',
    rechargeType: '',
    status: '',
  })

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

  const allData = reactive({
    fee: 0,
    amount: 0,
    rechargeFee: 0,
  })

  const formSingle = reactive({})
  const editorType = ref(3)
  const editor = ref('')
  const addType = ref('')
  const myInfo = ref({})
  const formList = ref({})
  const formInfo = ref({})

  const approvalForm = reactive({
    approveDesc: null,
    status: null,
    approveStatus: null,
    fee: 0,
    amount: 0,
    rechargeFee: 0,
  })

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

  const user = computed(() => {
    return JSON.parse(Session.Get('user', true))
  })

  const langZh = computed(() => {
    return Session.Get('lang') === 'cn'
  })

  const reasonsList = computed(() => {
    return Object.values(reasons.value)
  })

  const combined = computed(() => {
    let fee = 0
    let amount = 0
    let rechargeFee = 0

    if (!multipleSelection.value.length) {
      return { ...allData }
    }

    mock_tableData.value.forEach((item) => {
      if (multipleSelection.value.includes(item.id)) {
        if (!isNaN(item.fee)) {
          fee += Number(item.fee)
        }
        if (!isNaN(item.amount)) {
          amount += Number(item.amount)
        }
        if (!isNaN(item.rechargeFee)) {
          rechargeFee += Number(item.rechargeFee)
        }
      }
    })

    return {
      fee: parseFloat(fee.toFixed(2)),
      amount: parseFloat(amount.toFixed(2)),
      rechargeFee: parseFloat(rechargeFee.toFixed(2)),
    }
  })

  const rules = computed(() => ({
    status: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'blur',
      },
    ],
    approveDesc: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'blur',
      },
    ],
  }))

  // 方法
  // 导出
  const exportAgents = async () => {
    try {
      await exportExcel(
        pigeon,
        '/wasabi/card/recharge/list/export',
        { ...search },
        'CWG_Card_Recharges'
      )
    } catch (error) {
      pigeon.error(t('Msg.ExportFail'))
    }
  }

  const getSummaries1 = () => {
    return [
      t('Label.Total'),
      '',
      '',
      '',
      '',
      '',
      '',
      combined.value.amount ? NumberFormatAll(combined.value.amount) : 0,
      combined.value.fee ? NumberFormatAll(combined.value.fee) : 0,
      '',
      '',
      '',
      '',
      '',
    ]
  }

  // 处理总计中的数据千分位
  const NumberFormatAll = (value) => {
    if (value === '***') {
      return '***'
    }

    const numValue = Number(value)
    if (isNaN(numValue)) {
      return '0'
    }

    return new Intl.NumberFormat('en-US', {
      minimumFractionDigits: 0,
      maximumFractionDigits: 20,
    }).format(numValue)
  }

  // 银行卡详情
  const cardOpen = (cardNumber) => {
    router.push({
      name: 'R-CardDetail',
      params: { cardNumber: cardNumber },
    })
  }

  // 详细信息cid
  const accountOpen = (cId) => {
    router.push({ name: 'R-CustomerDetail', params: { cId: cId } })
  }

  const searchSingleCid = async (cId) => {
    const res = await Service1.cidRealSingle({
      id: cId,
    })
    if (res.code == Code.StatusOK) {
      if (editor.value) {
        formList.value = res.data
        // 这里需要根据实际情况调整
      } else {
        formInfo.value = res.data
        await searchRealAll(cId)
      }
    } else {
      pigeon.error(res.msg)
    }
  }

  // 获取原因列表
  const searchReasons = async () => {
    const res = await Service2.reasonsRefusalList({ type: 15 })
    if (res.code == Code.StatusOK) {
      reasons.value = res.data || {}
    } else {
      pigeon.error(res.msg)
    }
  }

  // 选择多项
  const handleSelectionChange = (val) => {
    multipleSelection.value = val
      .filter((item) => item.approveStatus !== '2' && item.approveStatus !== '3')
      .map((item) => item.id)
  }

  const checkSelectable = (row) => {
    return row.approveStatus == '1'
  }

  const approvalAll = () => {
    searchReasons()
    approvalAllDialog.value = true
    Object.assign(approvalForm, combined.value)
  }

  // 审核充值
  const rechargeApprove = async () => {
    const res = await Service.rechargeApprove({
      cId: user.value.cId,
      approveDesc: approvalForm.approveDesc,
      approveStatus: approvalForm.status,
      ids: multipleSelection.value,
    })
    if (res.code == 200) {
      Object.assign(approvalForm, {
        approveDesc: null,
        status: null,
        approveStatus: null,
        fee: 0,
        amount: 0,
        rechargeFee: 0,
      })
      approvalAllDialog.value = false
      pigeon.success('审核成功')
      confirmToReload()
    } else {
      pigeon.error(res.msg)
    }
  }

  // 获取cid下的真实账户信息
  const searchRealAll = async (cId) => {
    const res = await Service1.realCustomerListAll({
      cId: cId,
      page: {
        current: 1,
        row: 1,
      },
    })
    if (res.code == Code.StatusOK) {
      formInfo.value.realList = res.data
      dialogInfoCid.value = true
    } else {
      pigeon.error(res.msg)
    }
  }

  // 详细信息关闭cid/pibno
  const closeDia = () => {
    dialogInfoCid.value = false
  }

  // 查看
  const closeSingle = () => {
    dialogInfoTradingSingle.value = false
  }

  const close = (val) => {
    dialogInfoCid.value = val
  }

  const handleCommand = (command) => {
    console.log(command)
    switch (command.type) {
      case 1:
        dialogInfoTradingSingle.value = true
        Object.assign(formSingle, command.row)
        break
      case 3:
        addType.value = 11
        dialogInfoTradingAdd.value = true
        formList.value = { ...command.row }
        break
      case 4:
        if (!(command.row.status == 'success' || command.row.status == 'fail')) {
          ucardRechargeOrder(command.row)
        }
        break
    }
  }

  const closeAdd = (val) => {
    dialogInfoTradingAdd.value = val
  }

  // 新增
  const closeDiaAdd = () => {
    dialogInfoTradingAdd.value = false
    editor.value = ''
  }

  const confirmToReload = () => {
    closeDiaAdd()
    searchFunc()
  }

  // 查询充值订单
  const ucardRechargeOrder = async ({ merchantOrderNo }) => {
    const res = await Service.ucardRechargeOrder({
      merchantOrderNo,
      cId: user.value.cId,
    })
    if (res.code == Code.StatusOK) {
      pigeon.success(t('Msg.SearchSuccess'))
      searchFunc()
    } else {
      pigeon.error(res.msg)
    }
  }

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

  // 列表
  const searchFunc = async () => {
    pictLoading.value = true
    if (!display.value['R-Recharge-Search']?.show) {
      pigeon.warning(t('Msg.NotDisplay'))
      pictLoading.value = false
      return
    }

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

    if (res.code == Code.StatusOK) {
      mock_tableData.value = res.data
      Object.assign(allData, res.sum || { fee: 0, amount: 0, rechargeFee: 0 })

      if (res.page != null) {
        pagerInfo.rowTotal = res.page.rowTotal
        pagerInfo.pageTotal = res.page.pageTotal
      } else {
        pagerInfo.rowTotal = 0
      }

      pigeon.success(t('Msg.SearchSuccess'))
    } else {
      pigeon.error(res.msg)
    }
    pictLoading.value = false
  }

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

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

  const selectChange = () => {
    // Vue 3 中不需要 $forceUpdate
  }

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

  // 监听器
  watch(
    () => search.tag,
    () => {
      search.mobile = ''
      search.email = ''
      search.cId = ''
      search.cardNumber = ''
      search.currency = ''
      search.approveStatus = ''
    }
  )
</script>

<style scoped lang="scss">
  #review_Email {
    .crm_search {
      .search_action_btn {
        .delete {
          background-color: #a1a1a1;
        }

        .delete.active {
          background-color: #368fec;
        }
      }
    }

    .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 lang="scss">
  #review_Email {
    .dialog_header_w {
      .crm_search_down {
        width: 400px;
      }
    }
  }
</style>
