<template>
  <div class="login-container">
    <el-form ref="dataForm" :model="dataForm" :rules="ruleForm">
      <el-row :gutter="30" class="el-bg-border">
        <el-col :span="5">
          <el-form-item label="游戏平台" prop="pid">
            <el-select v-model="dataForm.pid" placeholder="Select" class="filter-item">
              <el-option
                v-for="item in rechargePlatform"
                :key="item.pid"
                :label="item.platform"
                :value="item.pid"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="渠道余额" style="width: 300px;">
            <el-input v-model="balanceMoney" type="number" class="inline-input filter-item" disabled style="width: 160px;" />&nbsp;元
          </el-form-item> -->
          <el-form-item label="渠道账号" prop="cid">
            <el-select v-model="dataForm.cid" placeholder="Select" class="filter-item">
              <el-option
                v-for="item in rechargeChannelPlatform"
                :key="item.cid"
                :label="item.account"
                :value="item.cid"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择游戏" prop="gfid">
            <el-select v-model="dataForm.gfid" placeholder="Select" class="filter-item">
              <el-option
                v-for="item in rechargeGame"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="充值账户" prop="username" class="filter-item">
            <span style="font-size: 5px; color: #67C23A;">：{{ accountNum }}</span>
            <el-input
              v-model="dataForm.username"
              type="textarea"
              placeholder="待检测账号."
              :autosize="{ minRows: 15, maxRows: 100 }"
              @change="setAccountNum"
            />
          </el-form-item>
          <span v-show="repeatNumList">重复账号：{{ repeatNumList }}</span>
        </el-col>

        <el-col :span="5">
          <el-form-item label="账户余额">
            <span>{{ user_money }}元</span>
          </el-form-item>
          <el-form-item label="充值金额" prop="money">
            <el-input v-model="dataForm.money" type="number" min="0" class="filter-item" />
          </el-form-item>
          <!-- <el-form-item label="平台折扣">
            <span>9.8折</span>
          </el-form-item>
          <el-form-item label="游戏折扣">
            <span>9.8折</span>
          </el-form-item> -->
          <el-form-item label="支付方式">
            <el-radio-group v-model="dataForm.payway" prop="payway" class="filter-item">
              <el-radio :label="1">久币支付</el-radio>
              <!-- <el-radio :label="2">商务币支付</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="支付金额">
            <span>{{ dataForm.money }} 元</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">立即支付</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-row :gutter="30">
            <el-col :span="12">
              <span style="font-size: 5px; color: #67C23A;">成功账户：{{ thenAccountNum }}</span>
              <el-input
                v-model="thenAccount"
                type="textarea"
                :autosize="{ minRows: 15, maxRows: 100 }"
              />
            </el-col>
            <el-col :span="12">
              <span style="font-size: 5px; color: #F56C6C;">失败账户：{{ catchAccountNum }}</span>
              <el-input
                v-model="catchAccount"
                type="textarea"
                :autosize="{ minRows: 15, maxRows: 100 }"
              />
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
var LodashArray = require('lodash/array')
import { Message, MessageBox, Loading } from 'element-ui'
import { rechargeChannelPlatformAccount } from '@/api/common'
// import { validMobile } from '@/utils/validate'

export default {
  name: 'Recharge',
  data() {
    return {
      // accountHandleSuccess: '', // 处理成功账号
      repeatNumList: [], // 重复账号
      dataForm: {
        pid: 'd65aa6d7614589bffe62456b88e98811', // 游戏平台ID;默认魅族平台
        cid: '', // 渠道账号ID
        gfid: '', // 游戏ID
        paypwd: '', // 支付密码
        // username: '13121776520\n13121776521\n13121776522\n\n13121776523\n13121776524\n13121776525', // 充值账户
        username: '', // 充值账户
        money: 1, // 充值金额(单位：元)
        recharge: 2, //
        payway: 1, // 充值方式
        type: 3 //
      },
      ruleForm: {
        pid: [{ required: true, message: '请选择平台.', trigger: 'change' }],
        cid: [{ required: true, message: '请选择渠道账号.', trigger: 'change' }],
        gfid: [{ required: true, message: '请选择游戏.', trigger: 'change' }],
        username: [{ required: true, message: '缺少充值账户.', trigger: 'blur' }],
        money: [{ required: true, message: '请输入充值金额，最低一元.', trigger: 'blur' }]
      },
      // 游戏平台列表
      rechargePlatform: [
        {
          'pid': 'd65aa6d7614589bffe62456b88e98811',
          'platform': 'MM',
          'disRate': 9.8,
          'rate': 9.7,
          'type': 0,
          'length': 2
        }
      ],
      // balanceMoney: 0, // 渠道余额
      user_money: 0, // 账户余额
      rechargeChannelPlatform: [], // 渠道账号
      rechargeGame: [], // 游戏列表

      accountNum: 0, // 总账户个数
      thenAccount: '', // 成功账户
      thenAccountNum: 0, // 成功个数
      catchAccount: '', // 失败账户
      catchAccountNum: 0 // 失败个数
      // loadingText: '处理中，请稍等。。。',
      // loadingTextNum: 0 // 操作百分比
    }
  },
  created() {
    // this.getBalanceMoney(this.dataForm.pid)
    this.getRechargePlatform(this.dataForm.pid)
    this.getRechargeGame(this.dataForm.pid)
    this.updateUserMoney()
  },
  methods: {
    // 更新用户余额
    updateUserMoney() {
      this.$store.dispatch('user/getInfo').then((res) => {
        const { data } = res
        this.user_money = data.user_money
      })
    },
    // 统计充值账户数量并处理行数不是账号的
    setAccountNum() {
      if (!this.dataForm.username) {
        return false
      }
      this.accountNum = 0
      this.repeatNumList = []
      var newQuestion = this.dataForm.username.replace(/\n\n/, '\n')
      const list = newQuestion.split('\n')

      var newList = [] // 处理重复数据
      for (var i = 0; i < list.length; i++) {
        // 账户去重，并提示
        if (newList.indexOf(list[i]) === -1) {
          this.accountNum++
          newList.push(list[i])
        } else {
          if (this.repeatNumList.indexOf(list[i]) === -1) {
            this.repeatNumList.push(list[i])
          }
        }
      }
      this.dataForm.username = newList.join().replace(new RegExp(',', 'g'), '\n')
    },
    async onSubmit() {
      // this.setAccountNum()

      this.thenAccount = ''
      this.catchAccount = ''

      // TODO: 正式服务器未上线，暂时不需要
      // if ((this.balanceMoney - this.dataForm.money) < 0) {
      //   return Message({
      //     type: 'info',
      //     message: '余额不足以充值.'
      //   })
      // }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 截取数据
          var userLists = this.dataForm.username.split('\n')

          MessageBox.prompt('输入支付密码', 'Tip', {
            confirmButtonText: '确认',
            cancelButtonText: '取消'
          }).then(({ value }) => {
            // 提取第一条账号数据，针对接口提交判断数据是否有误
            var oneData = { pid: this.dataForm.pid, cid: this.dataForm.cid, gfid: this.dataForm.gfid, paypwd: value, username: userLists[0], money: this.dataForm.money, recharge: this.dataForm.recharge, payway: this.dataForm.payway, type: this.dataForm.type }
            this.$store.dispatch('common/rechargePlayer', oneData).then((res) => {
              const { code, status } = res
              if (code === 200 && status === true) {
                this.thenAccount = this.thenAccount + oneData.username + '\n'
                this.thenAccountNum++

                // 遮屏
                const loading = Loading.service({
                  lock: true,
                  text: '处理中, 请稍等...',
                  background: 'rgba(0, 0, 0, 0.7)'
                })

                // 成功后处理剩下账号数据
                // const loadingNum = userLists.length - 1
                console.log('# AAA:', userLists)
                userLists = LodashArray.drop(userLists)
                console.log('# BBBB:', userLists)
                loading.close()
                // userLists.forEach(async(item, index) => {
                //   var _data = { pid: this.dataForm.pid, cid: this.dataForm.cid, gfid: this.dataForm.gfid, paypwd: value, username: item, money: this.dataForm.money, recharge: this.dataForm.recharge, payway: this.dataForm.payway, type: this.dataForm.type }
                //   await this.rechargePlayer(_data, index)
                //   if (loadingNum === index) {
                //     loading.close()
                //     this.updateUserMoney()
                //   }
                // })
              } else {
                this.catchAccount = this.catchAccount + oneData.username + '\n'
                this.catchAccountNum++
              }
            }).catch((res) => {
              this.catchAccount = this.catchAccount + oneData.username + '\n'
              this.catchAccountNum++
            })
          }).catch(() => {
            return Message({
              type: 'info',
              message: '取消充值.'
            })
          })
        } else {
          return Message({
            type: 'error',
            message: '请完善提交内容.'
          })
        }
      })
    },
    // 异步进行账户充值
    rechargePlayer(data, index) {
      return new Promise((resolve, reject) => {
        setTimeout((_data) => {
          this.$store.dispatch('common/rechargePlayer', _data).then((res) => {
            const { code, status } = res
            if (code === 200 && status === true) {
              this.thenAccount = this.thenAccount + _data.username + '\n'
              this.thenAccountNum++
              resolve()
            } else {
              this.catchAccount = this.catchAccount + _data.username + '\n'
              this.catchAccountNum++
              resolve()
            }
          }).catch((res) => {
            this.catchAccount = this.catchAccount + _data.username + '\n'
            this.catchAccountNum++
            resolve()
          })
        }, 2000 * index, data)
      })
    },

    // 账户余额 -- 弃用
    getBalanceMoney(val) {
      this.$store.dispatch('common/getMainChannelMoney', val).then((res) => {
        this.balanceMoney = res
      }).catch((res) => {
        return Message({
          message: res,
          type: 'error',
          duration: 5 * 1000
        })
      })
    },
    // 渠道账号列表
    getRechargePlatform(val) {
      rechargeChannelPlatformAccount(val).then(response => {
        // console.log('# getRechargePlatform:', response)
        this.rechargeChannelPlatform = response.data.data
        this.dataForm.cid = response.data.data[0]['cid']
      }).catch(res => {
        return Message({
          message: res,
          type: 'error',
          duration: 5 * 1000
        })
      })
    },
    // 游戏列表
    getRechargeGame(pid) {
      this.$store.dispatch('common/rechargeGame', pid).then((res) => {
        this.rechargeGame = res

        // TODO: 判断当前账户是否有默认选项，没有则选中第一条。
        this.dataForm.gfid = 42670
      }).catch((res) => {
        return Message({
          message: res,
          type: 'error',
          duration: 5 * 1000
        })
      })
    }

  }
}
</script>

<style lang="scss">
  .login-container{
    margin: 20px;
    background-color: #FFFFFF;

    .el-bg-border{
      border: 2px dashed #909399;
      padding: 10px;
    }
  }
</style>
