<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="false"
      :selection="true"
      :table-options="tableOptions"
      :edit-form="editForm"
      :edit-config="editConfig"
      :columns="columns"
      :rows-actions="rowsActions"
      :show-summary="false"
      :apis="apis"
      :custom-style="{ height: 'calc(100vh - 150px)' }"
      :alertTip="alertTip"
      @onResponse="onResponse"
    >
    </YMTable>
    <Dialog ref="dialog">
      <template slot="content"/>
    </Dialog>
  </div>
</template>
<script>
import Dialog from '@/components/Dialog/index.vue'
import { menucheck, withdrawsetNote, withdrawStatus, usdtWithdrawSetIsLocked } 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,
      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: true,
          options: statusOpt
        }
      ],
      columns: [
        {
          label: '会员ID',
          prop: 'member_id',
          width: 120
        },
        {
          label: '会员昵称',
          popover: true,
          width:140,
          props: ['first_name'],
          options: [
            {
              label: '会员ID',
              value: ['member_id']
            }, {
              label: '用户名称',
              value: ['username']
            },
            {
              label: '异常信息',
              vShow: (row) => row?.user_admin_note ? true : false,
              value: ['user_admin_note']
            }
          ]
        },
        {
          label: '提现金额',
          prop: 'amount',
          method: (row) => Number(row.amount)?.toFixed(2) +' USDT'
        },
        {
          label: '手续费',
          prop: 'service_charge',
          method: (row) => Number(row.service_charge)?.toFixed(2)+' USDT'
        },
        {
          label: '费率',
          width: 50,
          prop: 'exchange_rate',
          method: (row) => this.formatNumber(row.exchange_rate, 2)
        },
        {
          label: '到账金额',
          prop: 'to_account',
          html: true,
          method: (row) => {
            return `
              <div class="amount-display">
                <div class="usd-amount">${this.formatNumber(row.to_account_usdt)} USDT</div>
              </div>
            `
          }
        },
        {
          label: '扣除金额',
          html: true,
          method: (row) => {
            const amount = row.amount || 0
            const exchangeRate = row.exchange_rate || 1
            const convertedAmount = amount * exchangeRate
            return `
              <div class="amount-display">
                <div class="cny-amount">${this.formatNumber(convertedAmount)} RMB</div>
              </div>
            `
          }
        },
        {
          label: '提现后余额',
          prop: 'after_balance',
          method: (row) => Number(row.after_balance)?.toFixed(2) +' RMB'
        },
        {
          label: '钱包地址',
          prop: 'address',
          width: 130,
        },
        {
          label: '是否加锁',
          prop: 'is_locked',
          method: (row) => row.is_locked === 1 ? '是' : '否'
        },
        {
          label: '状态',
          method: (row) => {
            return statusOpt.filter(item => item.value === row.status)[0]?.label
          }
        },
        {
          label: '原因',
          prop: 'remark'
        },
        {
          label: '申请时间',
          prop: 'created_at'
        },
        {
          label: '备注',
          prop: 'admin_note'
        }

      ],
      rowsActions: [
        {
          key: 'lock',
          label: '上锁',
          vIF: (row) => row.status === 0 && row.is_locked === 0,
          method: (row) => {
            this.$confirm(`确定要上锁吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              usdtWithdrawSetIsLocked({
                ids: [row.id],
                is_locked: 1
              }).then(() => {
                this.onSubmit()
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              })
            }).catch(() => {})
          }
        },
        {
          key: 'unlock',
          label: '解锁',
          vIF: (row) => row.status === 0 && row.is_locked === 1,
          method: (row) => {
            this.$confirm(`确定要解锁吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              usdtWithdrawSetIsLocked({
                ids: [row.id],
                is_locked: 0
              }).then(() => {
                this.onSubmit()
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              })
            }).catch(() => {})
          }
        },
        {
          key: 'note',
          label: '备注',
          method: (row) => {
            this.$prompt('请输入备注', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /^\S+$/,
              inputErrorMessage: '请输入备注'
            }).then(({ value }) => {
              withdrawsetNote({
                id: row.id,
                admin_note: value
              })
                .then(() => {
                  this.onSubmit()
                  this.$message({
                    type: 'success',
                    message: '操作成功'
                  })
                })
            })
          }
        },
        {
          key: 'no',
          label: '驳回',
          vIF: (row) => row.status === 0,
          method: (row) => {
            this.setStatus({ ids: [row.id], status: 2 })
          }
        },
        {
          key: 'yes',
          label: '通过',
          vIF: (row) => row.status === 0,
          method: (row) => {
            this.setStatus({ ids: [row.id], status: 1 })
          }
        }
      ],
      apis: {
        list: {
          url: 'withdraw',
          dataParam: 'data.data',
          resultParam: 'data',
          init: false
        },
        pass: {
          url: 'withdraw/setStatus',
          method: 'post',
          params: ['ids'],
          status: ['status'],
          statusValue: 1,
        },
        reject: {
          url: 'withdraw/setStatus',
          method: 'post',
          params: ['ids'],
          status: ['status'],
          statusValue: 2,
          remark: ['remark']
        }
      },
      tableOptions: {
        reject: {
          show: true
        },
        pass: {
          show: false
        }
      },
      editForm: [],
      editConfig: {}
    }
  },
  created() {
  },
  mounted() {
    this.onSubmit()
    menucheck('admin/withdraw/setStatus')
      .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 }) => {
          withdrawStatus({
            ...row,
            remark: value
          })
            .then(() => {
              this.onSubmit()
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            })
        })
      } else {
        this.$confirm(`确定通过审核?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          withdrawStatus(row)
            .then(() => {
              this.onSubmit()
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            })
        })
      }
    },
    onValueChange(val) {

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