<template>
  <div class="new-app-container layout-vertical">
    <YMTableSearch :loading="loading" :search-form="searchForm" @onValueChange="onValueChange" @submit="onSubmit"/>
    <YMTable
      ref="table"
      :table-key="1"
      :index="true"
      :selection="false"
      :table-options="tableOptions"
      :edit-form="editForm"
      :edit-config="editConfig"
      :columns="columns"
      :actions-width="120"
      :rows-actions="rowsActions"
      :show-summary="false"
      :apis="apis"
      :alertTip="alertTip"
      :custom-style="{ height: 'calc(100vh - 150px)' }"
      @onResponse="onResponse"
    />
    <!-- 自定义弹窗 -->
    <Dialog ref="dialog">
      <template slot="content"/>
    </Dialog>
  </div>
</template>
<script>
import Dialog from '@/components/Dialog/index.vue'
import { menucheck, verifyRecharge } from '@/api/data'

export default {
  components: {
    Dialog
  },
  data() {
    const statusOpt = [
      {
        value: 0,
        label: '待确认'
      },
      {
        value: 1,
        label: '已确认'
      },
      {
        value: 2,
        label: '失败'
      },
      {
        value: 3,
        label: '已忽略'
      }
    ]
    return {
      loading: false,
      visibleBasicDrawer: false,
      alertTip:'',
      searchForm: [
        {
          label: '会员ID',
          type: 'input',
          prop: 'member_id',
          clearable: false
        },
          {
          label: '会员昵称',
          type: 'input',
          prop: 'first_name',
          clearable: true
        },
        {
          label: '状态',
          type: 'select',
          prop: 'status',
          clearable: false,
          options: statusOpt
        },
        {
          label: '类型',
          type: 'select',
          prop: 'type',
          clearable: false,
          options: [
            {
              value: 1,
              label: '自动'
            },
            {
              value: 2,
              label: '手动'
            }
          ]
        }
      ],
      columns: [
         {
          label: '会员ID',
          prop: 'member_id',
          width: 120
        },
        {
          label: '会员昵称',
          popover: true,
          width: 140,
          tagType: (row) => row?.member.status === 1 ? 'danger' : '',
          props: ['member.first_name'],
          options: [
            {
              label: '会员ID',
              value: ['member.member_id']
            }, {
              label: '用户名称',
              value: ['member.username']
            },
            {
              label: '异常信息',
              vShow: (row) => row?.member.admin_note ? true : false,
              value: ['member.admin_note']
            }
          ]
        },
        {
          label: '链接类型',
          prop: 'net'
        },
        {
          label: '币种',
          prop: 'coin'
        },
        {
          label: '费率',
          prop: 'exchange_rate',
          method: (row) => this.formatNumber(row.exchange_rate, 2)
        },
        {
          label: '充值数量',
          html: true,
          width: 150,
          prop: 'amount',
          method: (row) => {
            const amount = row.amount || 0
            const exchangeRate = row.exchange_rate || 1
            const convertedAmount = amount * exchangeRate

            return `
              <div class="amount-display">
                <div class="usd-amount">${this.formatNumber(amount)} USDT</div>
                <div class="cny-amount">${this.formatNumber(convertedAmount)} RMB</div>
              </div>
            `
          }
        },
        {
          label: '充值地址（平台地址）',
          prop: 'to_address'
        },
        // {
        //   label: '转出地址（用户发起地址）',
        //   prop: 'from_address'
        // },
        // {
        //   label: '链上交易哈希',
        //   prop: 'txid'
        // },
        // {
        //   label: '区块时间',
        //   prop: 'block_time'
        // },
        // {
        //   label: '确认数',
        //   prop: 'confirmations'
        // },
        {
          label: '状态',
          prop: 'status',
          method: (row) => {
            return statusOpt.find(item => item.value === row.status).label
          }
        },
        {
          label: '图片',
          image: true,
          prop: 'image'
        },
        {
          label: '类型',
          method: (row) => row.type === 1 ? '自动' : row.type === 2 ? '手动' : '其他'
        },
        {
          label: '更新时间',
          prop: 'updated_at'
        },
        {
          label: '创建时间',
          prop: 'created_at'
        }
      ],
      rowsActions: [
        {
          key: 'no',
          label: '驳回',
          vIF: (row) => row.status === 0 && row.type === 2,
          method: (row) => {
            this.setStatus({ id: row.id.toString(), status: 2 })
          }
        },
        {
          key: 'yes',
          label: '通过',
          vIF: (row) => row.status === 0 && row.type === 2,
          method: (row) => {
            this.setStatus({ id: row.id.toString(), status: 1 })
          }
        }
      ],
      apis: {
        list: {
          url: 'wallet',
          dataParam: 'data.data',
          resultParam: 'data',
          init: false
        },
        add: {
          url: '',
          cover: true,
          coverMethod: (row, node) => {
            return row.year + '、' + node[0].label
          }
        },
        edit: {
          url: '',
          cover: true,
          coverMethod: (row, node) => {
            return row.year + '、' + node[0].label
          }
        },
        preview: {
          url: '',
          dataParam: 'datas',
          keyParam: 'cache_key'
        },
        import: {
          url: '',
          params: 'cache_key'
        },
        batchDelete: {
          url: '',
          params: 'ids'
        },
        delete: {
          url: '',
          params: 'ids'
        }
      },
      tableOptions: {
        add: {
          show: false,
          initData: () => {
            return { test: 'test' }
          }
        },
        import: {
          show: false,
          tip: '注：备注',
          columns: [
            {
              label: '严控',
              prop: 0,
              required: true
            }
          ]
        },
        export: {
          show: false,
          dataName: 'xxx.xlsx',
          baseApi: process.env.VUE_APP_BASE_IMG + '/',
          theadMap: [
            {
              xxxx: {}
            }
          ],
          theadProps: {
            xxxx: {}
          }
        },
        download: {
          show: false,
          url: '/static/template.xlsx'
        },
        batchDelete: {
          show: false
        }
      },
      editForm: [
        {
          body: [
            {
              label: '年度',
              type: 'year',
              prop: 'year',
              clearable: false,
              rules: [
                {
                  required: true,
                  message: '请选择年度',
                  trigger: 'change'
                }
              ]
            }
          ]
        }
      ],
      editConfig: {
        addTip: '注：备注',
        editTip: '注：备注'
      }
    }
  },
  created() {
  },
  mounted() {
    this.onSubmit()
    menucheck('admin/wallet/verifyRecharge')
      .then(({ code }) => {
        if (code !== 0) {
          this.rowsActions = []
        }
      })
  },
  methods: {
    onResponse(data) {
      this.alertTip = `总金额：${data.total_amount}(USTD)；已处理：${data.total_success}(USTD)；失败金额：${data.total_fail}(USTD)`
    },
    formatNumber(num, decimals = 2) {
      if (isNaN(num)) return '0.00'
      return Number(num).toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    setStatus(row) {
      if (row.status === 2) {
        this.$prompt('请输入原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\S+$/,
          inputErrorMessage: '请输入原因'
        }).then(({ value }) => {
          verifyRecharge({
            ...row,
            remark: value
          })
            .then(() => {
              this.onSubmit()
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            })
        })
      } else {
        this.$confirm(`确定通过审核?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          verifyRecharge(row)
            .then(() => {
              this.onSubmit()
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            })
        })
      }
    },
    onValueChange(val) {

    },
    onSubmit(params) {
      this.$refs.table.getList(params)
    }
  }
}
</script>
