<template>
  <div class="consume-deposit-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="4">
        <el-button type="primary" @click="batchChangeReview">
          {{ __('批量确认') }}
        </el-button>
        <el-button icon="el-icon-plus" type="primary" @click="exportCsv">
          {{ __('导出') }}
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="20">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.order_id"
              clearable
              :placeholder="__('请输入订单编号')"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="queryForm.user_id"
              clearable
              filterable
              :loading="loading"
              :placeholder="__('请输入买家用户名称')"
              remote
              :remote-method="remoteFindUserList"
              reserve-keyword
            >
              <el-option
                v-for="item in userList"
                :key="item.user_id"
                :label="item.user_account"
                :value="item.user_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="block">
              <el-date-picker
                v-model="queryForm.pay_time_range"
                align="right"
                clearable
                editable
                :end-placeholder="__('付款结束时间')"
                format="yyyy-MM-dd HH:mm:ss"
                :range-separator="__('至')"
                :start-placeholder="__('付款开始时间')"
                type="datetimerange"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              {{ __('查询') }}
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="table"
      v-loading="listLoading"
      border
      :data="list"
      :height="tableConfig.height"
    >
      <el-table-column
        align="center"
        fixed
        show-overflow-tooltip
        type="selection"
      />
      <el-table-column
        align="center"
        fixed="left"
        :label="__('订单编号')"
        prop="order_id"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        fixed="left"
        :label="__('收款确认')"
        prop="deposit_review"
        show-overflow-tooltip
        width="120"
      >
        <template #default="{ row }">
          <el-button
            v-if="row.deposit_review === 1"
            disabled
            plain
            size="small"
            type="success"
          >
            {{ __('已确认') }}
          </el-button>
          <el-button
            v-if="row.deposit_review === 0"
            size="small"
            type="info"
            @click="changeReview(row)"
          >
            {{ __('未确认') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :formatter="formatState"
        :label="__('支付状态')"
        prop="deposit_state"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('交易号')"
        prop="deposit_trade_no"
        show-overflow-tooltip
        width="260"
      />
      <el-table-column
        align="center"
        :label="__('支付渠道')"
        prop="payment_channel_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('支付渠道名称')"
        prop="payment_channel_name"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        :formatter="formatType"
        :label="__('支付方式')"
        prop="deposit_payment_type"
        show-overflow-tooltip
        width="120"
      >
        <template #default="{ row }">
          <el-button
            v-if="row.deposit_payment_type === 1301"
            disabled
            round
            type="danger"
          >
            {{ formatType(row) }}
          </el-button>
          <el-button
            v-if="row.deposit_payment_type == 1302"
            disabled
            round
            type="primary"
          >
            {{ formatType(row) }}
          </el-button>
          <el-button
            v-if="row.deposit_payment_type == 1304"
            disabled
            round
            type="success"
          >
            {{ formatType(row) }}
          </el-button>
          <el-button
            v-if="row.deposit_payment_type == 1304"
            disabled
            round
            type="warning"
          >
            {{ formatType(row) }}
          </el-button>
          <el-button
            v-if="row.deposit_payment_type == 1305"
            disabled
            round
            type="info"
          >
            {{ formatType(row) }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('交易状态')"
        prop="deposit_trade_status"
        show-overflow-tooltip
        width="160"
      />
      <el-table-column
        align="center"
        :label="__('付款时间')"
        prop="deposit_gmt_payment"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        :label="__('卖家户号')"
        prop="deposit_seller_id"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        :label="__('卖家支付账号')"
        prop="deposit_seller_email"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        :label="__('买家支付用户号')"
        prop="deposit_buyer_id"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        :label="__('买家支付宝账号')"
        prop="deposit_buyer_email"
        show-overflow-tooltip
        width="180"
      />
      <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"
        :label="__('交易金额')"
        prop="deposit_total_fee"
        show-overflow-tooltip
      />
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { confirm, getList, exportFile } from '@/api/consume/deposit'
  import { getList as getListAccont } from '@/api/user/base'
  import { renderTime } from '@/utils/date'

  export default {
    name: 'ConsumeDeposit',
    components: {},
    data() {
      return {
        tableConfig: {
          height: window.innerHeight - 220 - 90,
        },
        list: [],
        userList: [],
        listLoading: true,
        loading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNum: 1,
          pageSize: 20,
        },
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      async changeReview(row) {
        if (row.deposit_id) {
          this.$baseConfirm(this.__('确认收款？'), null, async () => {
            const { msg } = await confirm({
              deposit_id: row.deposit_id,
            })
            this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
            await this.fetchData()
          })
        }
      },
      batchChangeReview() {
        const rows = this.$refs.table.selection
        if (!rows || rows.length <= 0) {
          this.$baseMessage('没有选中的数据！', 'error')
          return
        }
        let deposit_ids = rows.map((item) => item.deposit_id)
        this.$baseConfirm(this.__('确认收款？'), null, async () => {
          const { msg } = await confirm({
            deposit_ids: deposit_ids,
          })
          this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
          await this.fetchData()
        })
      },

      __,
      formatType(row) {
        return row.deposit_payment_type === 1301
          ? this.__('货到付款')
          : row.deposit_payment_type === 1302
          ? this.__('在线支付')
          : row.deposit_payment_type === 1303
          ? this.__('白条支付')
          : row.deposit_payment_type === 1304
          ? this.__('现金支付')
          : this.__('线下支付')
      },
      formatState(row) {
        return row.deposit_state === 1 ? this.__('完成') : this.__('未完成')
      },
      formatTime(row) {
        return renderTime(row.order_time)
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      async remoteFindUserList(user_nickname) {
        if (user_nickname !== '') {
          this.loading = true
          setTimeout(() => {
            this.loading = false
            getListAccont({ user_nickname: user_nickname })
              .then((res) => {
                this.userList = res.data.items
              })
              .catch((err) => {
                this.userList = []
              })
          }, 200)
        } else {
          this.userList = []
        }
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        // el-date-picker选取时间范围时传的是数组，GET请求会报400
        if (this.queryForm.pay_time_range) {
          this.queryForm.order_date_start = this.queryForm.pay_time_range[0]
          this.queryForm.order_date_end = this.queryForm.pay_time_range[1]
          this.queryForm.pay_time_range = undefined
        }
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await getList(this.queryForm)
        this.list = data.items
        this.total = data.records
        this.listLoading = false
      },
      exportCsv() {
        const rows = this.$refs.table.selection
        let order_ids = rows.map((item) => item.order_id)
        exportFile({ order_ids: order_ids ? order_ids.toString() : '' }).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对象
          }
        )
      },
    },
  }
</script>
