<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" label-position="" :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
                  v-for="item in tagOptions"
                  :key="item.value"
                  :label="$t(item.label)"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <!-- 动态输入框 -->
              <el-input
                v-if="search.tag <= 5"
                v-model.trim="search[searchFields[search.tag]]"
                class="crm-border-left-no crm-border-radius-no"
                clearable
                :placeholder="$t('Placeholder.Input')"
                @keyup.enter="toSearch"
              />
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.operateType"
                filterable
                clearable
                class="crm-border-radius-no select_down"
                :placeholder="$t('card.Form.f52')"
                @change="toSearch"
              >
                <el-option
                  v-for="(value, key) in typeOpts"
                  :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-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>
          <el-button
            v-if="display['R-CardOperate-Export'] && display['R-CardOperate-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="cId" align="left" :label="$t('Ucard.UserOrder.item1')">
            <template #default="scope">
              <span
                v-if="scope.row.cId"
                class="crm-text-underline"
                style="cursor: pointer"
                @click="accountOpen(scope.row.cId)"
                >{{ scope.row.cId }}</span
              >
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('Ucard.UserOrder.item14')">
            <template #default="scope">
              {{ scope.row.lastName }}{{ scope.row.firstName }}
            </template>
          </el-table-column>
          <el-table-column prop="email" align="left" :label="$t('Ucard.UserOrder.item15')" />
          <el-table-column prop="mobile" align="left" :label="$t('Ucard.UserOrder.item16')">
            <template #default="scope">
              <span>{{ scope.row.areaCode }} {{ scope.row.mobile }}</span>
            </template>
          </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="operateType" align="left" :label="$t('card.Form.f52')">
            <template #default="scope">
              <span>{{ $t(typeOpts[scope.row.operateType]) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="operateUser" align="left" :label="$t('card.Status.v17')" />
          <el-table-column prop="addTime" align="left" :label="$t('card.Form.f51')" />
        </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>
    <detailed-info-cid
      :dialog-info-cid="dialogInfoCid"
      :form-info="formInfo"
      :is-trading="true"
      @close="closeCidDialog"
    />
  </div>
</template>

<script setup>
  import { ref, reactive, computed, watch, onMounted, inject } from 'vue'
  import { useRouter } from 'vue-router'
  import { useI18n } from 'vue-i18n'
  import Service from '@/service/ucard'
  import Config from '@/config/index'
  import DetailedInfoCid from '@/views/components/DetailedInfoCid'
  import { Search } from '@element-plus/icons-vue'
  import { exportExcel } from '@/utils/export'

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

  // 响应式数据
  const pictLoading = ref(false)
  const dialogInfoTradingAdd = ref(false)
  const dialogInfoCid = ref(false)
  const formInfo = ref({})
  const formRef = ref(null)

  // 搜索条件
  const search = reactive({
    tag: 1,
    cId: '',
    mobile: '',
    email: '',
    cardNumber: '',
    operateType: '',
    operateUser: '',
    date: [],
    startDate: '',
    endDate: '',
  })

  // 搜索标签选项
  const tagOptions = [
    { value: 1, label: 'Label.CidAccount' },
    { value: 2, label: 'Ucard.KycAuth.item2' },
    { value: 3, label: 'Ucard.KycAuth.item3' },
    { value: 4, label: 'card.Form.f24' },
    { value: 5, label: 'card.Status.v17' },
  ]

  // 搜索字段映射
  const searchFields = {
    1: 'cId',
    2: 'mobile',
    3: 'email',
    4: 'cardNumber',
    5: 'operateUser',
  }

  const editor = ref('')
  const addType = ref('')
  const formList = ref({})
  const myInfo = ref({})
  const mock_tableData = ref([])
  const pagerInfo = reactive({ row: 10, current: 1, pageTotal: 0, rowTotal: 0 })
  const banksData = ref([])

  // 操作类型选项
  const typeOpts = ref({
    1: 'card.Status.v1',
    2: 'card.Status.v2',
    3: 'card.Status.v3',
    4: 'card.Status.v4',
    5: 'card.Status.v5',
    6: 'card.Status.v6',
    7: 'card.Status.v7',
    8: 'card.Status.v8',
    9: 'card.Status.v9',
    10: 'card.Status.v10',
    11: 'card.Status.v11',
    12: 'card.Status.v12',
    13: 'card.Status.v13',
    14: 'card.Status.v14',
    15: 'card.Status.v15',
    16: 'card.Status.v16',
    17: 'R-Business-Btn2',
    18: 'R-VirtualCard-Btn11',
    19: 'card.Status.v19',
    20: 'card.Status.v20',
    21: 'card.Status.v21',
    22: 'card.Status.v22',
    23: 'card.Status.v23',
  })

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

  // 方法
  const exportAgents = async () => {
    if (search.date === null || search.date.length === 0) {
      search.startDate = ''
      search.endDate = ''
    } else {
      search.startDate = search.date[0]
      search.endDate = search.date[1]
    }

    exportExcel(
      pigeon, // 这里需要传递合适的上下文，可能需要调整
      '/wasabi/card/operate/record/export',
      { ...search },
      'Card_Operate'
    )
  }

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

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

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

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

  // 列表查询
  const searchFunc = async () => {
    if (!display.value['R-CardOperate-Page']?.show) {
      console.warn(t('Msg.NotDisplay'))
      return
    }

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

    pictLoading.value = true
    try {
      const res = await Service.operatePage({
        ...search,
        page: {
          current: pagerInfo.current,
          row: pagerInfo.row,
        },
      })

      if (res.code === Code.StatusOK) {
        mock_tableData.value = res.data || []
        pagerInfo.rowTotal = res.page?.rowTotal || 0
        pagerInfo.pageTotal = res.page?.pageTotal || 0
        pigeon.MessageOK(t('Msg.SearchSuccess'))
      } else {
        pigeon.MessageError(res.msg)
      }
    } catch (error) {
      pigeon.MessageError(t('Msg.SearchFailed'))
    } finally {
      pictLoading.value = false
    }
  }

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

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

  // 打开账户详情
  const accountOpen = (cId) => {
    router.push({ name: 'R-CustomerDetail', params: { cId: cId } })
  }

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

  // 监听器
  watch(
    () => search.tag,
    () => {
      // 清空所有搜索字段
      search.cId = ''
      search.mobile = ''
      search.email = ''
      search.cardNumber = ''
      search.operateType = ''
      search.operateUser = ''
      search.date = []
      search.startDate = ''
      search.endDate = ''
    }
  )

  // 生命周期
  onMounted(() => {
    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>
