<template>
  <div class="mobile-pay-center vendor-pay 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>

    <!-- 账户信息start -->
    <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">
            <span class="inline-block title">状态：</span>
            <span class="inline-block content text-ellipse">
              {{account.status | bankStatusFilter}}
              <i v-if="account.status == 101" class="iconfont icon-tixing"></i>
            </span>
          </div>
          <div class="content-line clearfix">
            <span class="inline-block title">操作：</span>
            <a class="fr inline-block set-default-icon" @click="reuseAccount(account)" v-if="account.status == 105">重新使用</a>
            <a class="fr inline-block" @click="deleteAccount(account)">删除</a>
          </div>
        </li>
      </ul>
    </div>
    <!-- 账户信息end -->

    <!-- 交易记录start -->
    <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 clearfix">
          <li class="inline-block fl">
            <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>
            </ul>
          </li>
          <li class="inline-block fr">
            <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" v-if="recordList.length">
        <li v-for="record in recordList">
          <div class="content-line">
            <span class="inline-block title">时间：</span>
            <span class="inline-block content text-ellipse">{{record.transferTime | 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.buyerentername || record.buyername}}</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-plus" style="color: #f51c24;"></i>{{record.total}}</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">交易方式：</span>
            <span class="inline-block content text-ellipse">线下付款</span>
          </div>
          <div class="content-line">
            <span class="inline-block title">状态：</span>
            <span class="inline-block content text-ellipse">收款成功</span>
          </div>
        </li>
      </ul>
      <div class="fix-count-wrap" v-if="recordList.length">
        <span class="content">收入总计：<span>{{currencySymbol | currencyFilter}}&nbsp;{{totalRecordPrice}}</span></span>
        <span class="content">支出总计：<span>{{currencySymbol | currencyFilter}}&nbsp;0</span></span>
        <p>结余：{{currencySymbol | currencyFilter}}&nbsp;{{totalRecordPrice}} (共计{{recordList.length || 0}}笔交易)</p>
      </div>
    </div>
    <!-- 交易记录end -->

    <!-- 新增账户弹框start -->
    <modal-wrapper :noHeader="true" :showModal="showModal" @closeAction="showModal = false">
      <div class="add-account-modal in-wrapper">
        <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 upload">
            <span class="inline-block"><i>*</i>上传开户许可证：</span>
            <input type="text" v-model="file.name" disabled>
            <label class="upload-btn">选择文件
              <input type="file" @change="onUpload($event)" accept="image/jpeg,image/jpg,image/png,.pdf">
            </label>
          </div>
          <div class="am-btn-wrap">
            <button @click="showModal = false">取消</button>
            <button @click="addAccount">确认</button>
          </div>
          <p class="am-remind-text clearfix">
            <i class="fl">*声明:</i>
            <span class="fr">
              1. 此账户为卖家收款账户，请仔细核对信息内容，若由信息错误造成的损失，优软商城不承担赔偿责任。
              <br/>
              2. 卖家只能有唯一一个“使用中”的收款账户，新增账户审核通过后，原账户将自动失效。
              <br/>
              3. 如您的企业名称、开户银行及账号变更，您须在优软商城开展资金结算前进行更正，否则发生转账错误优软商城不承担赔偿责任。
              <br/>
              4. 更多的条款请阅读《优软商城代收代付协议》 。
              <br/>
              5. 附件仅支持JPG、PNG、PDF格式，大小超过3M。
            </span>
          </p>
        </div>
      </div>
    </modal-wrapper>
    <!-- 新增账户弹框end -->

    <!-- 重新使用账户提示框start -->
    <div class="mobile-modal reuse-account-modal" v-show="showReuseModal">
      <div class="ra-remind">
        <div class="header"><i class="iconfont icon-guanbi1" @click="showReuseModal = false"></i></div>
        <div class="content"><i class="fa fa-exclamation-circle"></i>
          <span>此操作会让使用中的收款账户失效，是否确定重新使用？</span>
        </div>
        <div class="footer">
          <button @click="showReuseModal = false">取消</button>
          <button @click="setDefaultAccount()">确认</button>
        </div>
      </div>
    </div>
    <!-- 重新使用账户提示框end -->

    <remind-box :title="remindText" :timeoutCount="timeoutCount"></remind-box>
    <pull-up :fixId="'mobileFixContent'" :searchMore="fetching" :allPage="allPage" :page="page" @pullUpAction="onPullUpAction"></pull-up>
    <empty-status v-if="isEmpty" :text="switchType == 'record' ? '暂无交易记录' : '暂无账户信息'" :showLink="true"></empty-status>
  </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: '',
          method: '',
          status: ''
        },
        showSelectMethod: false,
        showSelectStatus: false,
        currentId: '',
        showReuseModal: false,
        totalRecordPrice: 0,
        file: ''
      }
    },
    components: {
      RemindBox,
      PullUp,
      ModalWrapper,
      EmptyStatus
    },
    fetch ({store}) {
      return Promise.all([
        store.dispatch('payCenter/loadVendorRecord', {count: 10, page: 1, sorting: {'transferTime': 'DESC'}, type: 'sup'})
      ])
    },
    watch: {
      'vendorAccount': {
        handler: function (val) {
          if (val && val.content) {
            if (this.isChange) {
              this.accountList = []
              this.isChange = false
            }
            this.accountList = [...this.accountList, ...val.content]
          }
        }
      },
      'vendorRecord': {
        handler: function (val) {
          if (val && val.content) {
            if (this.isChange) {
              this.recordList = []
              this.isChange = false
            }
            this.totalRecordPrice = this.baseUtils.priceFixed(this.totalRecordPrice + this.recordData.data.data.total)
            this.recordList = [...this.recordList, ...val.content]
          }
        },
        immediate: true
      }
    },
    filters: {
      bankStatusFilter: function (status) {
        let result = '未知状态'
        switch (status) {
          case 101 :
            result = '待审核'
            break
          case 104:
            result = '使用中'
            break
          case 103:
            result = '未通过'
            break
          case 105:
            result = '已失效'
            break
          case 112:
            result = '已删除'
            break
        }
        return result
      }
    },
    computed: {
      accountData () {
        return this.$store.state.payCenter.data.vendorAccount
      },
      recordData () {
        return this.$store.state.payCenter.data.vendorRecord
      },
      vendorAccount () {
        return this.accountData.data
      },
      vendorRecord () {
        return this.recordData.data.data.data
      },
      fetching () {
        return this.switchType === 'account' ? this.accountData.fetching : this.recordData.fetching
      },
      allPage () {
        return this.switchType === 'account' ? this.vendorAccount.totalPages : this.vendorRecord.totalPages
      },
      isEmpty () {
        return (this.switchType === 'record' && this.recordList.length === 0) || (this.switchType === 'account' && this.accountList.length === 0)
      },
      currencySymbol () {
        return this.recordList[0] ? this.recordList[0].currencyName : 'RMB'
      }
    },
    methods: {
      setRemindText: function (str) {
        this.remindText = str
        this.timeoutCount++
      },
      reloadList () {
        if (this.switchType === 'account') {
            this.$store.dispatch('payCenter/loadVendorAccount', {
            count: this.count,
            page: this.page,
            sorting: {num: 'ASC'},
            type: 'sup'
          })
        } else {
          this.$store.dispatch('payCenter/loadVendorRecord', {
            count: this.count,
            page: this.page,
            sorting: {'transferTime': 'DESC'},
            type: 'sup',
            fromDate: this.filterParams.fromDate || null,
            toDate: this.filterParams.toDate || 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.showSelectStatus = flag
        } else if (type === 'method') {
          this.showSelectMethod = flag
          this.showSelectStatus = false
        } else if (type === 'status') {
          this.showSelectStatus = flag
          this.showSelectMethod = false
        }
      },
      setSelect (type, val) {
        if (type === 'method') {
          this.filterParams.method = val
          this.setShowSelect('method', false)
        } else if (type === 'status') {
          this.filterParams.status = val
          this.setShowSelect('status', false)
        }
        this.filterRecord()
      },
      setDate (type) {
        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) {
          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()
        }
      },
      reuseAccount (account) {
        this.currentId = account.id
        this.showReuseModal = true
      },
      setDefaultAccount () {
        this.$http.get(`/trade/bankInfo/setDefaultAccount/${this.currentId}`).then(() => {
          this.setRemindText('重新使用完成')
          this.initList()
          this.showReuseModal = false
        })
      },
      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
        }
        this.file = ''
      },
      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) {
              if (res.data.data === 0) {
                this.validBankAccountObj.number = true
              } else {
                this.validBankAccountObj.number = false
                this.setRemindText('银行账号校验失败')
              }
            } 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 if (!this.file) {
          this.setRemindText('请上传开户许可证')
        } else {
          let param = new FormData()
          param.append('file', this.file, this.file.name)
          param.append('bankInfo', JSON.stringify(this.bankAccountObj))
          let config = {
            headers: {'Content-Type': 'multipart/form-data'}
          }
          this.$http.post('/trade/bankInfo/save/enterprise?type=sup', param, config).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)
          })
        }
      },
      onUpload (e) {
        let file = e.target.files[0]
        let arr = file.name.split('.')
        let type = arr[arr.length - 1]
        if ('pdf/png/jpg/jpeg'.indexOf(type.toLowerCase()) === -1) {
          this.setRemindText('仅支持jpg/jpeg/png/pdf格式的文件')
        } else if (file.size > 1024 * 1024 * 3) {
          this.setRemindText('请勿大于3M')
        } else {
          this.file = file
        }
      }
    }
  }
</script>
<style lang="scss">
  @import '~assets/scss/mobilePayCenter';
  .reuse-account-modal {
    .ra-remind {
      width: 6.3rem;
      height: 3.5rem;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -1.75rem;
      margin-left: -3.15rem;
      border-radius: .15rem;
      .header {
        height: .6rem;
        line-height: .6rem;
        background: #3976f4;
        border-top-left-radius: .15rem;
        border-top-right-radius: .15rem;
        i {
          font-size: .32rem;
          color: #fff;
          float: right;
          margin-right: .28rem;
        }
      }
      .content {
        background: #fff;
        padding: .53rem .77rem;
        span {
          font-size: .32rem;
        }
        i {
          font-size: .44rem;
          color: #3976f4;
          float: left;
          margin-right: .2rem;
        }
      }
      .footer {
        background: #fff;
        padding-bottom: .37rem;
        text-align: center;
        border-bottom-left-radius: .15rem;
        border-bottom-right-radius: .15rem;
        margin-top: -0.05rem;
        button {
          width: 2.22rem;
          height: .77rem;
          line-height: .77rem;
          color: #fff;
          font-size: .32rem;
          border-radius: .08rem;
          background: #bfbfbf;
          &:last-child {
            background: $base-color;
            margin-left: .3rem;
          }
        }
      }
    }
  }
  .record-list {
    margin-bottom: 1.26rem
  }
  .upload {
    input[disabled] {
      background: #eee;
      width: 2.88rem !important;
    }
    .upload-btn {
      display: inline-block;
      vertical-align: middle;
      width: 1.2rem;
      height: .56rem;
      line-height: .56rem;
      text-align: center;
      color: #fff;
      background: #fe9d03;
      position: relative;
      left: .2rem;
      border-radius: .04rem;
      font-size: .24rem;
      font-weight: normal;
      margin: 0;
      input {
        opacity: 0;
        width: 1.2rem;
        height: .56rem;
        position: absolute;
        top: 0;
      }
    }
  }
  .fix-count-wrap {
    position: fixed;
    bottom: .98rem;
    height: 1.25rem;
    text-align: right;
    background: #fff;
    border-radius: .02rem;
    border-top: 1px solid #bfbfbf;
    line-height: .63rem;
    font-size: .28rem;
    width: 100%;
    padding-right: .3rem;
    .content {
      margin-left: .39rem;
      &:first-child {
        span {
          color: #fd0303;
        }
      }
      &:nth-of-type(2) {
        span {
          color: #15b262;
        }
      }
    }
  }
  .mp-list .content-line .icon-tixing {
    font-size: .32rem;
    color: $base-color;
    margin-left: .05rem;
  }
  .am-remind-text {
    font-size: .26rem;
    color: #999;
    margin-top: .29rem;
    padding: .45rem 0;
    border-top: 1px solid #d2d2d2;
    i {
      color: #fd0303;
      width: 12%;
    }
    .fr {
      width: 88%;
    }
  }
  .vendor-pay {
    bottom: 2.23rem !important;
    .mobile-modal .mobile-modal-wrapper {
      left: .2rem !important;
      right: .2rem !important;
    }
  }
</style>
