<template>
  <div class="mobile-pay-center mobile-fix-content mobile-centerfix-content" id="mobileFixContent" @click="setShowSelect('all', false)">
    <div class="mp-head">
      <span class="inline-block" :class="{'active': switchType === 'record'}" @click="setSwitchType('record')">交易记录</span>
      <span class="inline-block" :class="{'active': switchType === 'account'}" @click="setSwitchType('account')">付款账户</span>
    </div>
    <div class="mp-content" v-if="switchType == 'account'">
      <p class="mp-content-header">已设置的账户信息<span class="fr" @click="openAddAccount"><i class="iconfont icon-xinzeng"></i>新增账户</span></p>
      <ul class="mp-list">
        <li v-for="account in accountList">
          <div class="content-line">
            <span class="inline-block title">开户银行：</span>
            <span class="inline-block content text-ellipse">{{account.bankname}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">开户支行：</span>
            <span class="inline-block content text-ellipse">{{account.branchname}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">银行账户：</span>
            <span class="inline-block content text-ellipse">{{account.number}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">开户名称：</span>
            <span class="inline-block content text-ellipse">{{account.accountname}}</span>
          </div>
          <div class="content-line clearfix">
            <span class="inline-block title">操作：</span>
            <a class="fr inline-block default-icon" v-if="account.num == 1">默认账户</a>
            <a class="fr inline-block set-default-icon" v-if="account.num != 1" @click="setDefaultAccount(account)">设为默认</a>
            <a class="fr inline-block" @click="deleteAccount(account)">删除</a>
          </div>
        </li>
      </ul>
    </div>
    <div class="mp-record" v-if="switchType == 'record'">
      <div class="search-content">
        <input type="text" placeholder="商家名称/订单号" v-model="filterParams.keyword" @keyup.13="filterRecord">
        <span @click="filterRecord"><i class="iconfont icon-sousuo"></i></span>
      </div>
      <div class="filters-wrap">
        <div class="date-wrap">
          <label>
            <i class="iconfont icon-ico-date"></i>
            <input type="date" v-model="filterParams.fromDate" @change="setDate('fromDate')">
            <p v-if="filterParams.fromDate">{{filterParams.fromDate | date}}</p>
          </label>
          <span>—</span>
          <label>
            <i class="iconfont icon-ico-date"></i>
            <input type="date" v-model="filterParams.toDate" @change="setDate('toDate')">
            <p v-if="filterParams.toDate">{{filterParams.toDate | date}}</p>
          </label>
        </div>
        <ul class="select-wrap">
          <li class="inline-block">
            <div @click.stop="setShowSelect('method', !showSelectMethod)">{{filterParams.method ? filterParams.method == 1103 ? '线下支付' : '线上支付' : '交易方式'}}</div>
            <ul class="select-list" v-show="showSelectMethod">
              <li @click.stop="setSelect('method', null)">交易方式</li>
              <li @click.stop="setSelect('method', 1103)">线下支付</li>
              <li @click.stop="setSelect('method', 1102)">线上支付</li>
            </ul>
          </li>
          <li class="inline-block">
            <div @click.stop="setShowSelect('currencyName', !showSelectCurrency)">{{filterParams.currencyName || '币种'}}</div>
            <ul class="select-list" v-show="showSelectCurrency">
              <li @click.stop="setSelect('currencyName', null)">币种</li>
              <li @click.stop="setSelect('currencyName', 'RMB')">RMB</li>
              <li @click.stop="setSelect('currencyName', 'USD')">USD</li>
            </ul>
          </li>
          <li class="inline-block">
            <div @click.stop="setShowSelect('status', !showSelectStatus)">{{filterParams.status || '状态'}}</div>
            <ul class="select-list" v-show="showSelectStatus">
              <li @click.stop="setSelect('status', null)">状态</li>
              <li @click.stop="setSelect('status', '支付成功')">支付成功</li>
            </ul>
          </li>
        </ul>
      </div>
      <ul class="mp-list record-list">
        <li v-for="record in recordList">
          <div class="content-line">
            <span class="inline-block title">时间：</span>
            <span class="inline-block content text-ellipse">{{record.paytime | time}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">订单号：</span>
            <span class="inline-block content text-ellipse">{{record.orderid}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">商家名称：</span>
            <span class="inline-block content text-ellipse">{{record.sellername}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">币种：</span>
            <span class="inline-block content text-ellipse">{{record.currencyName}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">金额：</span>
            <span class="inline-block content text-ellipse"><i class="fa fa-minus" style="color: #1da902;"></i>{{record.ensurePrice}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">交易方式：</span>
            <span class="inline-block content text-ellipse">{{record.paytype == 1103 ? '线下支付' : '线上支付'}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">状态：</span>
            <span class="inline-block content text-ellipse">支付成功</span>
          </div>
        </li>
      </ul>
    </div>
    <remind-box :title="remindText" :timeoutCount="timeoutCount"></remind-box>
    <pull-up :fixId="'mobileFixContent'" :searchMore="fetching" :allPage="allPage" :page="page" @pullUpAction="onPullUpAction"></pull-up>
    <!-- 新增账户弹框start -->
    <div class="mobile-modal account-modal" @click="showSimilar = false" v-if="showModal">
      <div class="account-modal-wrap add-account-modal">
        <div class="account-modal">
          <p class="title">新增账户</p>
          <div class="modal-content-line">
            <span class="inline-block"><i>*</i>开户银行：</span>
            <input type="text" readonly placeholder="例如：中国银行" v-model="bankAccountObj.bankname" @click.stop="showSimilar = !showSimilar">
            <ul v-if="showSimilar" class="similar">
              <li class="text-ellipse" v-for="bank in bankList" @click.stop="setBankName(bank)">{{bank}}</li>
            </ul>
          </div>
          <div class="modal-content-line">
            <span class="inline-block"><i>*</i>开户支行：</span>
            <input type="text" placeholder="例如：乔香支行" v-model="bankAccountObj.branchname" @blur="checkBranchname">
          </div>
          <div class="modal-content-line">
            <span class="inline-block"><i>*</i>银行账号：</span>
            <input type="text" placeholder="请填写银行账号" v-model="bankAccountObj.number" @blur="checkNumber">
          </div>
          <div class="modal-content-line">
            <span class="inline-block"><i>*</i>开户名称：</span>
            <input type="text" placeholder="请填写开户人姓名或企业名称" v-model="bankAccountObj.accountname" @blur="checkAccountname">
          </div>
          <div class="modal-content-line clearfix">
            <p class="remind"><i>*</i>为保障您的资金安全，账户信息加密显示且不可修改，只能删除后重新提交。</p>
          </div>
          <div class="am-btn-wrap">
            <button @click="showModal = false">取消</button>
            <button @click="addAccount">确认</button>
          </div>
        </div>
      </div>
    </div>
    <empty-status v-if="isEmpty" :text="switchType == 'record' ? '暂无支付记录，请下单购买商品吧！' : '暂无账户信息'" :showLink="true"></empty-status>
    <!-- 新增账户弹框end -->
  </div>
</template>
<script>
  import { RemindBox, PullUp, EmptyStatus } from '~components/mobile/common'
  import { ModalWrapper } from '~components/mobile/base'
  export default {
    layout: 'mobile',
    middleware: 'authenticated',
    data () {
      return {
        remindText: '',
        timeoutCount: '',
        page: 1,
        count: 10,
        accountList: [],
        recordList: [],
        switchType: 'record',
        // 分页重置标志
        isChange: false,
        showModal: false,
        bankList: [],
        showSimilar: false,
        bankAccountObj: {
          bankname: '',
          branchname: '',
          number: '',
          accountname: ''
        },
        validBankAccountObj: {
          bankname: false,
          branchname: false,
          number: false,
          accountname: false
        },
        filterParams: {
          keyword: '',
          fromDate: '',
          toDate: '',
          currencyName: '',
          // 交易方式
          method: ''
        },
        showSelectMethod: false,
        showSelectCurrency: false,
        showSelectStatus: false
      }
    },
    components: {
      RemindBox,
      PullUp,
      ModalWrapper,
      EmptyStatus
    },
    fetch ({store}) {
      return Promise.all([
//        store.dispatch('payCenter/loadBuyerAccount', {count: 10, page: 1, sorting: {num: 'ASC'}, type: 'buyer'})
        store.dispatch('payCenter/loadBuyerRecord', {count: 10, page: 1, sorting: {'paytime': 'DESC'}})
      ])
    },
    watch: {
      'buyerAccount': {
        handler: function (val) {
          if (val && val.content) {
            if (this.isChange) {
              this.accountList = []
              this.isChange = false
            }
            this.accountList = [...this.accountList, ...val.content]
          }
        }
      },
      'buyerRecord': {
        handler: function (val) {
          if (val && val.content) {
            if (this.isChange) {
              this.recordList = []
              this.isChange = false
            }
            this.recordList = [...this.recordList, ...val.content]
          }
        },
        immediate: true
      }
    },
    computed: {
      accountData () {
        return this.$store.state.payCenter.data.buyerAccount
      },
      recordData () {
        return this.$store.state.payCenter.data.buyerRecord
      },
      buyerAccount () {
        return this.accountData.data
      },
      buyerRecord () {
        return this.recordData.data
      },
      fetching () {
        return this.switchType === 'account' ? this.accountData.fetching : this.recordData.fetching
      },
      allPage () {
        return this.switchType === 'account' ? this.buyerAccount.totalPages : this.buyerRecord.totalPages
      },
      isEmpty () {
        return (this.switchType === 'record' && this.recordList.length === 0) || (this.switchType === 'account' && this.accountList.length === 0)
      }
    },
    methods: {
      setRemindText: function (str) {
        this.remindText = str
        this.timeoutCount++
      },
      reloadList () {
        if (this.switchType === 'account') {
          this.$store.dispatch('payCenter/loadBuyerAccount', {
            count: this.count,
            page: this.page,
            sorting: {num: 'ASC'},
            type: 'buyer'
          })
        } else {
          this.$store.dispatch('payCenter/loadBuyerRecord', {
            count: this.count,
            page: this.page,
            sorting: {'paytime': 'DESC'},
            currencyName: this.filterParams.currencyName || null,
            fromDate: this.filterParams.fromDate || null,
            toDate: this.filterParams.toDate || null,
            method: this.filterParams.method || null,
            keyword: this.filterParams.keyword || null
          })
        }
      },
      initList () {
        this.isChange = true
        this.page = 1
        this.reloadList()
      },
      onPullUpAction () {
        this.page++
        this.reloadList()
      },
      setSwitchType (type) {
        this.switchType = type
        if (type === 'record') {
          this.initFilterParams()
        }
        this.initList()
      },
      initFilterParams () {
        this.filterParams = {
          keyword: '',
          fromDate: '',
          toDate: '',
          currencyName: '',
          method: ''
        }
      },
      filterRecord () {
        this.isChange = true
        this.reloadList()
      },
      setShowSelect (type, flag) {
        if (type === 'all') {
          this.showSelectMethod = flag
          this.showSelectCurrency = flag
          this.showSelectStatus = flag
        } else if (type === 'method') {
          this.showSelectMethod = flag
          this.showSelectCurrency = false
          this.showSelectStatus = false
        } else if (type === 'currencyName') {
          this.showSelectCurrency = flag
          this.showSelectStatus = false
          this.showSelectMethod = false
        } else if (type === 'status') {
          this.showSelectStatus = flag
          this.showSelectMethod = false
          this.showSelectCurrency = false
        }
      },
      setSelect (type, val) {
        if (type === 'method') {
          this.filterParams.method = val
          this.setShowSelect('method', false)
        } else if (type === 'currencyName') {
          this.filterParams.currencyName = val
          this.setShowSelect('currencyName', false)
        } else if (type === 'status') {
          this.filterParams.status = val
          this.setShowSelect('status', false)
        }
        this.filterRecord(this.filterParams.currencyName)
      },
      setDate (type) {
        // 00:00:00
        this.filterParams[type] = new Date(this.filterParams[type]).getTime() - 8 * 60 * 60 * 1000
        if (this.filterParams.fromDate && this.filterParams.toDate && this.filterParams.fromDate > this.filterParams.toDate) {
          if (type === 'fromDate') {
            this.setRemindText('起始时间不能大于结束时间')
          } else {
            this.setRemindText('结束时间不能小于起始时间')
          }
          this.filterParams[type] = null
        } else {
          if (this.filterParams.fromDate && this.filterParams.toDate && this.filterParams.fromDate === this.filterParams.toDate) {
            // 23:59:59
            this.filterParams.toDate += 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000
          }
          this.filterRecord()
        }
      },
      setDefaultAccount (account) {
        this.$http.get(`/trade/bankInfo/setDefaultAccount/${account.id}`).then(() => {
          this.setRemindText('设置完成')
          this.initList()
        })
      },
      deleteAccount (account) {
        this.$http.delete(`/trade/bankInfo/delete/${account.id}`).then(res => {
          if (res.data === 'success') {
            this.setRemindText('删除成功')
            this.initList()
          }
        })
      },
      initAccount () {
        this.bankAccountObj = {
          bankname: '',
          branchname: '',
          number: '',
          accountname: ''
        }
        this.validBankAccountObj = {
          bankname: false,
          branchname: false,
          number: false,
          accountname: false
        }
      },
      openAddAccount () {
        if (!this.bankList || !this.bankList.length) {
          this.$http.get('/data/bank.json').then(res => {
            this.bankList = res.data.list
            this.initAccount()
            this.showModal = true
          })
        } else {
          this.initAccount()
          this.showModal = true
        }
      },
      setBankName (name) {
        this.bankAccountObj.bankname = name
        this.showSimilar = false
        this.validBankAccountObj.bankname = true
      },
      checkBranchname () {
        this.validBankAccountObj.branchname = true
        if (!(this.bankAccountObj.branchname && this.bankAccountObj.branchname.length)) {
          this.setRemindText('开户支行不能为空')
          this.validBankAccountObj.branchname = false
        } else if (this.baseUtils.getRealLen(this.bankAccountObj.branchname) > 40) {
          this.setRemindText('开户支行不能大于40字符')
          this.validBankAccountObj.branchname = false
        } else if (!/^[\u2E80-\u9FFF]+$/.test(this.bankAccountObj.branchname)) {
          this.setRemindText('请输入正确的开户支行')
          this.validBankAccountObj.branchname = false
        }
      },
      checkNumber () {
        this.validBankAccountObj.number = true
        if (!(this.bankAccountObj.number && this.bankAccountObj.number.length)) {
          this.validBankAccountObj.number = false
          this.setRemindText('银行账号不能为空')
        } else if (this.baseUtils.getRealLen(this.bankAccountObj.number) > 30) {
          this.setRemindText('银行账号不能大于30字符')
          this.validBankAccountObj.number = false
        } else if (!/^[0-9]+$/.test(this.bankAccountObj.number)) {
          this.setRemindText('请输入正确的银行账号')
          this.validBankAccountObj.number = false
        }
        if (this.validBankAccountObj.number) {
          this.$http.get('/trade/bankInfo/number/count', {params: {type: 1061, number: this.bankAccountObj.number}}).then(res => {
            if (res.data.success) {
              this.validBankAccountObj.number = res.data.data === 0
            } else {
              this.validBankAccountObj.number = false
              this.setRemindText(res.data.message || '银行账号校验失败')
            }
          }, err => {
            this.validBankAccountObj.number = false
            this.setRemindText(err.response.data || '银行账号校验失败')
            console.log(err)
          })
        }
      },
      checkAccountname () {
        this.validBankAccountObj.accountname = true
        if (!(this.bankAccountObj.accountname && this.bankAccountObj.accountname.length)) {
          this.validBankAccountObj.accountname = false
          this.setRemindText('账户名称不能为空')
        } else if (this.baseUtils.getRealLen(this.bankAccountObj.accountname) > 100) {
          this.setRemindText('账户名称不能大于100个字符')
          this.validBankAccountObj.accountname = false
        }
      },
      addAccount () {
        if (!this.validBankAccountObj.bankname) {
          this.setRemindText('请选择开户银行')
        } else if (!this.validBankAccountObj.branchname) {
          this.setRemindText('请填写正确的开户支行')
        } else if (!this.validBankAccountObj.number) {
          this.setRemindText('请填写正确的银行账号')
        } else if (!this.validBankAccountObj.accountname) {
          this.setRemindText('请填写正确的开户名称')
        } else {
          this.$http.post('/trade/bankInfo/save/personal?type=buyer', this.bankAccountObj).then(res => {
            if (res.data.id) {
              this.setRemindText('新增账户成功')
              this.initList()
              this.showModal = false
            } else {
              this.setRemindText('新增账户失败')
            }
          }, err => {
            this.setRemindText(err.response.data || '新增账户失败')
            console.log(err)
          })
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  @import '~assets/scss/mobilePayCenter';
</style>
