<template>
  <div
    id="review_Email"
    v-loading="pictLoading"
    class="view"
    element-loading-background="rgba(43, 48, 67, 0.65)"
  >
    <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 select-tag"
                :placeholder="$t('Placeholder.Choose')"
              >
                <el-option :label="$t('Label.CidAccount')" :value="1"></el-option>
                <el-option :label="$t('Ucard.KycAuth.item2')" :value="2"></el-option>
                <el-option :label="$t('Ucard.KycAuth.item3')" :value="3"></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 == 2"
                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-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-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.tradeStatus"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Ucard.CardOrder.item8')"
                @change="toSearch"
              >
                <el-option :label="$t('Ucard.CardOrder.t5')" :value="1"></el-option>
                <el-option :label="$t('Ucard.CardOrder.t8')" :value="2"></el-option>
                <el-option :label="$t('Ucard.CardOrder.t9')" :value="3"></el-option>
                <el-option :label="$t('Ucard.CardOrder.t11')" :value="4"></el-option>
                <el-option :label="$t('Ucard.CardOrder.t12')" :value="5"></el-option>
                <el-option :label="$t('Ucard.CardOrder.t13')" :value="6"></el-option>
              </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('R-Review-Status')"
                @change="toSearch"
              >
                <el-option :label="$t('Ucard.UserOrder.t11')" value="1"></el-option>
                <el-option :label="$t('Ucard.UserOrder.t12')" value="2"></el-option>
                <el-option :label="$t('Ucard.UserOrder.t13')" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="search.status"
                class="crm-border-radius-no"
                clearable
                :placeholder="$t('card.Info.s41')"
                @change="toSearch"
              >
                <el-option :label="$t('Ucard.CardOrder.t10')" value="wait_process"></el-option>
                <el-option :label="$t('Ucard.CardOrder.t5')" value="processing"></el-option>
                <el-option :label="$t('Ucard.CardOrder.t6')" value="success"></el-option>
                <el-option :label="$t('card.New2.p3')" value="cancel"></el-option>
                <el-option :label="$t('Ucard.CardOrder.t7')" value="fail"></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>
          <el-button
            v-if="display['R-CardOrder-Export'] && display['R-CardOrder-Export'].show"
            type="primary"
            style="margin-left: 8px"
            @click="exportAgents"
            ><span>
              {{ $t('Btn.Export') }}
            </span></el-button
          >
        </el-form-item>
      </el-form>

      <div class="card-mock-demo" style="margin: 30px 0">
        <el-table :data="mock_tableData" stripe style="margin-top: 20px; width: 100%">
          <el-table-column prop="" align="left" :label="$t('Label.CidAccount')">
            <template #default="scope">
              <span
                v-if="scope.row.cId && display['R-CardOrder-Btn1'].show"
                class="crm-text-underline"
                @click="accountOpen(scope.row.cId)"
                >{{ scope.row.cId || '--' }}</span
              >
              <span v-else>{{ scope.row.cId || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" align="left" :label="$t('Label.Name')">
            <template #default="scope">
              <span v-if="scope.row.firstName">{{ scope.row.firstName + ' ' }}</span>
              <span v-if="scope.row.middle">{{ scope.row.middle + ' ' }}</span>
              <span v-if="scope.row.lastName">{{ scope.row.lastName }}</span>
              <span v-if="!scope.row.firstName && !scope.row.lastName && !scope.row.middle">{{
                '--'
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" align="left" :label="$t('Label.Email')">
            <template #default="scope">
              {{ scope.row.email || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="mobile" align="left" :label="$t('Ucard.KycAuth.item2')">
            <template #default="scope"> {{ scope.row.areaCode }} {{ scope.row.mobile }} </template>
          </el-table-column>
          <el-table-column prop="cardName" align="left" :label="$t('card.Form.f49')">
          </el-table-column>
          <el-table-column prop="type" align="left" :label="$t('Ucard.KycAuth.item1')">
          </el-table-column>
          <el-table-column prop="cardNumber" align="left" :label="$t('card.Form.f24')">
            <template #default="scope">
              <span>{{ scope.row.cardNumber || '--' }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="tradeStatus" align="left" :label="$t('Ucard.CardOrder.item8')">
            <template #default="scope">
              <template v-if="scope.row.tradeType == '1'">
                <span v-if="scope.row.tradeStatus == '2'" class="state crm_state_blue">
                  {{ $t('Ucard.CardOrder.t8') }}
                </span>
                <span v-else-if="scope.row.tradeStatus == '3'" class="state crm_state_gray">
                  {{ $t('Ucard.CardOrder.t9') }}
                </span>
                <span v-else class="state crm_state_yellow">
                  {{ $t('Ucard.CardOrder.t5') }}
                </span>
              </template>

              <template v-if="scope.row.tradeType == '2'">
                <span v-if="scope.row.tradeStatus == '2'" class="state crm_state_blue">
                  {{ $t('Ucard.CardOrder.t12') }}
                </span>
                <span
                  v-else-if="scope.row.tradeStatus == '3'"
                  v-t="'Ucard.CardOrder.t13'"
                  class="state crm_state_gray"
                >
                  {{ $t('Ucard.CardOrder.t13') }}
                </span>
                <span v-else class="state crm_state_yellow">
                  {{ $t('Ucard.CardOrder.t11') }}
                </span>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="approveStatus" align="left" :label="$t('R-Review-Status')">
            <template #default="scope">
              <span v-if="scope.row.approveStatus == '2'" class="state crm_state_blue">
                {{ $t('Ucard.UserOrder.t12') }}
              </span>
              <span v-else-if="scope.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('card.Info.s41')">
            <template #default="scope">
              <span v-if="scope.row.status === 'success'" class="state crm_state_blue">
                {{ $t('Ucard.UserOrder.t6') }}
              </span>
              <span v-else-if="scope.row.status === 'fail'" class="state crm_state_gray">
                {{ $t('Ucard.UserOrder.t7') }}
              </span>
              <span v-else-if="scope.row.status === 'processing'" class="state crm_state_yellow">
                {{ $t('Ucard.UserOrder.t5') }}
              </span>
              <span
                v-else-if="scope.row.status === 'cancel'"
                v-t="'card.New2.p3'"
                class="state crm_state_red"
              >
                {{ $t('Ucard.UserOrder.t12') }}
              </span>
              <span v-else v-t="'Ucard.CardOrder.t10'" class="state crm_state_orange">
                {{ $t('Ucard.UserOrder.t12') }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="note" align="left" :label="$t('Ucard.CardOrder.item9')">
            <template #default="scope">
              <template v-if="scope.row.approveDesc">
                <span v-if="reasons[scope.row.approveDesc]">{{
                  Session.Get('lang') == 'cn'
                    ? reasons[scope.row.approveDesc].content
                    : reasons[scope.row.approveDesc].enContent
                }}</span>
                <span v-else>{{ scope.row.approveDesc || '--' }}</span>
              </template>
              <span v-else>{{ scope.row.note || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" align="center" :label="$t('Label.Action')">
            <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-CardOrder-Btn1'].show"
                      :command="{ type: '1', row: scope.row }"
                    >
                      <el-icon><Operation /></el-icon>
                      <span>
                        {{ $t('R-CardOrder-Btn1') }}
                      </span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="
                        display['R-CardOrder-Btn2'].show &&
                        (scope.row.status == 'wait_process' ||
                          scope.row.status == 'processing' ||
                          scope.row.status == null) &&
                        scope.row.tradeStatus == '2' &&
                        scope.row.approveStatus == '2'
                      "
                      :command="{ type: '2', row: scope.row }"
                    >
                      <el-icon><Operation /></el-icon>
                      <span>
                        {{ $t('R-CardOrder-Btn2') }}
                      </span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="
                        display['R-CardOrder-Btn3'].show &&
                        scope.row.approveStatus == '1' &&
                        scope.row.tradeStatus == '2'
                      "
                      :command="{ type: '3', row: scope.row }"
                    >
                      <el-icon><Operation /></el-icon>
                      <span>
                        {{ $t('R-CardOrder-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
        class="page"
        background
        layout="sizes, prev, pager, next"
        :total="pagerInfo.rowTotal"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagerInfo.row"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </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="formList"
      :editor-type="editorType"
      @close-single="closeSingle"
    >
    </ViewCardSingle>
    <div v-if="dialogInfoTradingSingle" class="crm_verified_info_mask" @click="closeSingle"></div>
    <VirtualCard
      :dialog-info-trading-add="dialogInfoTradingAdd"
      :editor="editor"
      :add-type="addType"
      :my-info="myInfo"
      :form-list="formList"
      @confirm-to-reload="confirmToReload"
      @close-add="closeAdd"
    ></VirtualCard>
    <div v-if="dialogInfoTradingAdd" class="crm_verified_info_mask" @click="closeDiaAdd"></div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, watch, onMounted, nextTick, inject } from 'vue'
  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 DetailedInfoCid from '@/views/components/DetailedInfoCid/index.vue'
  import VirtualCard from '@/views/components/VirtualCard/index.vue'
  import ViewCardSingle from '@/views/components/ViewCardSingle/index.vue'
  import { exportExcel } from '@/utils/export.js'
  import { useI18n } from 'vue-i18n'
  import { Operation, Search } from '@element-plus/icons-vue'
  // 混入
  const Session = inject('session')
  const pigeon = inject('pigeon')
  const { Code } = Config
  const router = useRouter()

  const { t } = useI18n()
  // 响应式数据
  const reasons = ref({})
  const pictLoading = ref(false)
  const dialogInfoTradingSingle = ref(false)
  const dialogInfoTradingAdd = ref(false)
  const search = reactive({
    tag: 1,
    mobile: '',
    cId: '',
    email: '',
    status: '',
  })
  const formRef = ref()
  const editor = ref('')
  let addType = ref('')
  const myInfo = ref({})
  const dInfo = ref({})
  const formList = ref({})
  const editorType = ref(1)
  const mock_tableData = ref([])
  const pagerInfo = reactive({ row: 10, current: 1, pageTotal: 0, rowTotal: 0 })
  const dialogInfoCid = ref(false)
  const formInfo = ref({})

  // 计算属性
  const display = computed(() => {
    try {
      return JSON.parse(Session.Get('display', true) || '{}')
    } catch (error) {
      console.error('Error parsing display data:', error)
      return {}
    }
  })

  const user = computed(() => {
    try {
      return JSON.parse(Session.Get('user', true) || '{}')
    } catch (error) {
      console.error('Error parsing user data:', error)
      return {}
    }
  })

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

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

  // 导出
  const exportAgents = async () => {
    exportExcel(pigeon, '/wasabi/card/apply/list/export', { ...search }, 'Card_Applications')
  }

  const getDetail = async (row) => {
    try {
      const res = await Service.applyDetails({
        id: row.id,
      })
      dInfo.value = res.data
    } catch (error) {
      pigeon.MessageError(t('Msg.SearchFail'))
    }
  }

  // 详细信息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
        dialogInfoTradingAdd.value = true
      } else {
        formInfo.value = res.data
        searchRealAll(cId)
      }
    } else {
      pigeon.MessageError(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.MessageError(res.msg)
    }
  }

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

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

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

  const closeDiaAdd = () => {
    formList.value = {}
    dialogInfoTradingAdd.value = false
  }

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

  // 详情
  const closeSingle = () => {
    dialogInfoTradingSingle.value = false
  }

  // 点击操作的回调
  const handleCommand = async (command) => {
    switch (command.type) {
      case '1':
        await getDetail(command.row)
        await nextTick(() => {
          formList.value = { ...command.row, ...dInfo.value }
          dialogInfoTradingSingle.value = true
        })
        break
      case 2:
        if (!(command.row.status == 'success' || command.row.status == 'fail')) {
          updateCardTypes(command.row)
        } else {
          pigeon.MessageOK(t('Msg.Success9'))
        }
        break
      case '3':
        addType.value = '4'
        dialogInfoTradingAdd.value = true
        formList.value = { ...command.row }
        break
      default:
        break
    }
  }

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

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

  // 更新
  const updateCardTypes = async (row) => {
    const res = await Service.ucardApplyProgress({
      holderMerchantOrderNo: row.holderMerchantOrderNo,
      id: row.id,
    })
    if (res.code == Code.StatusOK) {
      pigeon.MessageOK(t('Msg.SearchSuccess'))
      searchFunc()
    } else {
      pigeon.MessageError(res.msg)
    }
  }

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

    try {
      const res = await Service.applyList({
        ...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
        }
        pigeon.MessageOK(t('Msg.SearchSuccess'))
      } else {
        pigeon.MessageError(res.msg)
      }
      pictLoading.value = false
    } catch (error) {
      // pigeon.MessageError('搜索失败')
    } finally {
      pictLoading.value = false
    }
  }

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

  const handleCurrentChange = (val) => {
    pagerInfo.current = val
    searchFunc()
  }
</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>
