<template>
  <div class="consume-withdraw-container">
    <vab-query-form>
      <vab-query-form-right-panel :span="24">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-select
              v-if="false"
              v-model="queryForm.withdraw_state"
              clearable
              :placeholder="__('请选择提现状态')"
            >
              <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-radio-group v-model="queryForm.withdraw_state" @change="queryData">
              <el-radio-button v-for="item in stateOptions" :key="item.value" :label="item.value" >{{item.label}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model.trim="queryForm.user_id"
              clearable
              filterable
              :loading="loading"
              :placeholder="__('请输入用户昵称')"
              remote
              :remote-method="remoteMethod"
              reserve-keyword
            >
              <el-option
                v-for="item in accountOptions"
                :key="item.user_id"
                :label="item.user_nickname"
                :value="item.user_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              {{ __('查询') }}
            </el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="queryData">
              {{ __('刷新') }}
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      border
      :data="list"
      :height="tableConfig.height"
    >
      <el-table-column
        align="center"
        fixed="left"
        :label="__('操作')"
        width="100"
      >
        <template #default="{ row }">
          <el-button
            :disabled="row.withdraw_state !== 0"
            type="text"
            @click="handleEdit(row)"
          >
            {{ __('审核打款') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        fixed="left"
        :label="__('编号')"
        prop="withdraw_id"
        show-overflow-tooltip
        width="80"
      />

      <el-table-column
        align="center"
        fixed="left"
        :label="__('结算订单')"
        show-overflow-tooltip
        width="80"
      >
        <template #default="{ row }">
          <el-button
            v-if="row.rid === 2 || row.rid === 3"
            type="text"
            @click="showTable(row)"
          >
            {{ __('导出订单') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        fixed="left"
        :label="__('结算退单')"
        show-overflow-tooltip
        width="80"
      >
        <template #default="{ row }">
          <el-button
            v-if="row.rid === 2 || row.rid === 3"
            type="text"
            @click="showReturnTable(row)"
          >
            {{ __('导出退单') }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        fixed="left"
        :formatter="formatState"
        :label="__('提现状态')"
        prop="withdraw_state"
        show-overflow-tooltip
        width="80"
      >
        <template #default="{ row }">
          <el-tag :type='({"0":"waring","1":"success","2":"info"})[row.withdraw_state]'>
            {{ ({"0":"申请中","1":"申请通过","2":"驳回"})[row.withdraw_state] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('用户编号')"
        prop="user_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('用户昵称')"
        prop="user_nickname"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :formatter="formatMode"
        :label="__('提现类型')"
        prop="withdraw_mode"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('提现额度')"
        prop="withdraw_amount"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('提现服务费')"
        prop="withdraw_fee"
        show-overflow-tooltip
        width="100"
      />
      <el-table-column
        align="center"
        :label="__('打款额度')"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <h4 style="color: red">{{ getFinallyAmount(row) }}</h4>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('描述')"
        prop="withdraw_desc"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :label="__('银行')"
        prop="withdraw_bank"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :label="__('银行账户')"
        prop="withdraw_account_no"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        :label="__('开户名称')"
        prop="withdraw_account_name"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :label="__('联系手机')"
        prop="withdraw_mobile"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :formatter="formatTime"
        :label="__('创建时间')"
        prop="withdraw_time"
        show-overflow-tooltip
        width="160"
      />
      <el-table-column
        align="center"
        :label="__('银行流水账号')"
        prop="withdraw_bankflow"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        :label="__('操作管理员')"
        prop="withdraw_user_nickname"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :formatter="forOperTime"
        :label="__('操作时间')"
        prop="withdraw_opertime"
        show-overflow-tooltip
        width="160"
      />
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="edit" @fetch-data="fetchData" />
    <Table ref="Table" @fetch-data="fetchData" />
    <returnTable ref="returnTable" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { getList } from '@/api/consume/withdraw'
  import { getAccounts } from '@/api/user/base'
  import Edit from './components/ConsumeWithdrawEdit'
  import Table from './components/OrderBaseIndex'
  import returnTable from './components/OrderReturnIndex'
  import { renderTime } from '@/utils/date'
  import { exportFile } from '@/api/order/base'
  import { exportFileByIds } from '@/api/order/return'

  export default {
    name: 'ConsumeWithdraw',
    components: { Edit, Table, returnTable },
    data() {
      return {
        tableConfig: {
          height: window.innerHeight - 220 - 90,
        },
        accountOptions: [],
        stateOptions: [
          {
            value: null,
            label: this.__('全部'),
          },
          {
            value: 0,
            label: this.__('待审核'),
          },
          {
            value: 1,
            label: this.__('通过'),
          },
          {
            value: 2,
            label: this.__('驳回'),
          },
        ],
        list: [],
        listLoading: true,
        loading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNum: 1,
          pageSize: 20,
          user_id: '',
          withdraw_state: null,
        },
      }
    },
    created() {
      let query = this.$route.query
      if (query.withdraw_state || query.withdraw_state === 0) {
        this.queryForm.withdraw_state = Number(query.withdraw_state)
      }
      this.queryData()
    },
    methods: {
      getFinallyAmount(row) {
        let withdrawFee = row.withdraw_fee
        let withdraw_amount = row.withdraw_amount
        return withdraw_amount - withdrawFee
      },
      showTable(row) {
        this.$refs['Table'].showTable(row)
      },
      showReturnTable(row) {
        this.$refs['returnTable'].showReturnTable(row)
      },
      exportOrder(row) {
        exportFile({ order_ids: row.order_id }).then((data) => {
          const blob = new Blob([data])
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = decodeURIComponent('订单数据.csv') //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
      },
      exportReturnOrder(row) {
        exportFileByIds({ return_ids: row.return_id }).then((data) => {
          const blob = new Blob([data])
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = decodeURIComponent('售后数据.csv') //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
      },
      formatState(row) {
        const withdrawState = row.withdraw_state
        const obj = this.stateOptions.find(
          (item) => item.value === withdrawState
        )
        if (obj) return obj.label
        return ''
      },
      formatTime(row) {
        return renderTime(row.withdraw_time)
      },
      async remoteMethod(user_nickname) {
        if (user_nickname.trim() !== '') {
          this.loading = true
          const { data } = await getAccounts({ user_nickname })
          this.accountOptions = data
          this.loading = false
        } else {
          this.accountOptions = []
        }
      },
      // formatMoney(row) {
      //   return this.sub(row.withdraw_amount, row.withdraw_fee)
      // },
      __,
      forOperTime(row) {
        return renderTime(row.withdraw_opertime)
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        if (row.withdraw_id) {
          this.$refs['edit'].showEdit(row)
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await getList(this.queryForm)
        this.list = data.items
        this.total = data.records
        this.listLoading = false
      },
      formatMode(row) {
        return row.withdraw_mode == 0 ? '商家提现' : '佣金提现'
      },
    },
  }
</script>
