<template>
  <div class="mobile-invoice mobile-content mobile-content-long vendor-invoice" :class="{'invoice-record': switchType == 'record'}" @click="showFilterInvoiceType = false">
    <div class="switch-head">
      <div class="com-switch-head">
        <span class="com-switch-item inline-block" :class="{active: switchType == 'apply'}" @click="setSwitchType('apply')">买家开票申请</span>
        <span class="com-switch-item inline-block" :class="{active: switchType == 'record'}" @click="setSwitchType('record')">开票记录</span>
      </div>
    </div>
    <div class="mi-remind-area" :class="{less: !showMoreRemind}" v-if="switchType == 'apply'">
      <p class="title">温馨提示</p>
      <p class="content">
        <span class="inline-block">1、</span>
        <span class="inline-block">买家只能对订单状态为<b>“交易成功”</b>，且已不能再发起售后的人民币交易订单进行补开发票。</span>
      </p>
      <p class="content">
        <span class="inline-block">2、</span>
        <span class="inline-block">发票金额为产品总金额且不含运费、积分、优惠券、促销折扣等金额。</span>
      </p>
      <p class="content">
        <span class="inline-block">3、</span>
        <span class="inline-block">发票邮寄费用将由卖家承担。</span>
      </p>
      <p class="more" @click="showMoreRemind = !showMoreRemind">{{showMoreRemind ? '收起' : '查看更多'}}
        <i v-show="showMoreRemind" class="iconfont icon-shangshuangjiantou"></i>
        <i v-show="!showMoreRemind" class="iconfont icon-xiashuangjiantou"></i>
      </p>
    </div>
    <div class="search-content mi-search-content">
      <input type="text" v-model="filterParams.keyword" @keyup.13="onFilter" placeholder="订单号/发票抬头/收票人/联系电话">
      <span @click="onFilter"><i class="iconfont icon-sousuo"></i></span>
    </div>
    <div class="mi-list-content">
      <div class="mi-lc-filters clearfix">
        <div class="com-select-wrap fr" @click.stop="showFilterInvoiceType = !showFilterInvoiceType">{{filterParams.invoicetype === 1206 ? '普票' : filterParams.invoicetype === 1205 ? '专票' : '全部'}}
          <ul class="select-list" v-show="showFilterInvoiceType">
            <li @click.stop="setInvoiceType(null)" v-if="filterParams.invoicetype">全部</li>
            <li @click.stop="setInvoiceType(1206)" v-if="filterParams.invoicetype != 1206">普票</li>
            <li @click.stop="setInvoiceType(1205)" v-if="filterParams.invoicetype != 1205">专票</li>
          </ul>
        </div>
      </div>
      <ul class="mi-list" v-if="invoiceList.length">
        <li v-for="inv in invoiceList" @click="setActive(inv)" :class="{active: inv.$active && switchType == 'apply'}">
          <div class="line">
            <span class="inline-block title">
               <label class="bottom-modal-check mobile-cart-check" :class="{active: inv.$active}">
                 <!--<input type="checkbox">-->
               </label>
              类型：
            </span>
            <span class="inline-block content">
              <i class="inv" :class="{'spec-inv' : inv.invoicetype === 1205}">{{inv.invoicetype === 1206 ? '普票' : '专票'}}</i>
            </span>
          </div>
          <div class="line">
            <span class="inline-block title">
              申请时间：
            </span>
            <span class="inline-block content">{{inv.createTime | date}}</span>
          </div>
          <div class="line">
            <span class="inline-block title">
              订单号：
            </span>
            <span class="inline-block content">
              <span @click.stop="goOrderDetail(inv, index)" class="block link" :key="id" v-for="(id, index) in inv.orderids.split(',')">
                {{id}}
              </span>
            </span>
          </div>
          <div class="line">
            <span class="inline-block title">
              可开票金额：
            </span>
            <span class="inline-block content price">¥{{inv.price || 0}}</span>
          </div>
          <div class="line">
            <span class="inline-block title">
              发票抬头：
            </span>
            <span class="inline-block content">{{inv.invoicetitle}}</span>
          </div>
          <template v-if="inv.invoicetype == 1205">
            <div class="line">
            <span class="inline-block title">
              单位地址：
            </span>
              <span class="inline-block content">{{inv.billInfo.companyAddress || '-'}}</span>
            </div>
            <div class="line">
            <span class="inline-block title">
              单位电话：
            </span>
              <span class="inline-block content">{{inv.billInfo.companyPhone || '-'}}</span>
            </div>
            <div class="line">
            <span class="inline-block title">
              税务登记号：
            </span>
              <span class="inline-block content">{{inv.billInfo.companyTaxNumber || '-'}}</span>
            </div>
            <div class="line">
            <span class="inline-block title">
              开户银行：
            </span>
              <span class="inline-block content">{{inv.billInfo.bankName || '-'}}</span>
            </div>
            <div class="line">
            <span class="inline-block title">
              开户银行账户：
            </span>
              <span class="inline-block content">{{inv.billInfo.bankAccount || '-'}}</span>
            </div>
          </template>
          <div class="line">
            <span class="inline-block title">
              收票人：
            </span>
            <span class="inline-block content">{{inv.receiverName}}</span>
          </div>
          <div class="line">
            <span class="inline-block title">
              联系电话：
            </span>
            <span class="inline-block content">{{inv.recTel}}</span>
          </div>
          <div class="line">
            <span class="inline-block title">
              收票地址：
            </span>
            <span class="inline-block content">{{inv.invoiceAddress}}</span>
          </div>
        </li>
      </ul>
      <empty-status
        :text="'暂无开票信息'"
        :showLink="false"
        v-else></empty-status>
    </div>
    <div class="mi-fix-result" v-if="invoiceList.length">
      <label class="bottom-modal-check mobile-cart-check" :class="{active: allChecked}">
        <input type="checkbox" @change="setActive()">
        <span>全选</span>
      </label>
      <button @click="submit">确认开票</button>
    </div>
    <remind-box :title="remindText" :timeoutCount="timeoutCount"></remind-box>
    <pull-up :searchMore="fetching" :allPage="invoices.data.totalPages" :page="page" @pullUpAction="onPullUp"></pull-up>
    <remind-ope-modal :text="'点击【确认】系统将通知买家发票已寄出，否则请点击【取消】'"
                      :show="Boolean(operateIds)"
                      @closeAction="closeRemindOpe"
    ></remind-ope-modal>
  </div>
</template>
<script>
  import { RemindBox, PullUp, EmptyStatus } from '~components/mobile/common'
  import { RemindOpeModal } from '~components/mobile/base'
  export default {
    layout: 'mobile',
    middleware: 'authenticated',
    data () {
      return {
        remindText: '',
        timeoutCount: '',
        invoiceList: [],
        isChange: false,
        page: 1,
        count: 10,
        filterParams: {
          invoicetype: '',
          keyword: ''
        },
        showFilterInvoiceType: false,
        operateIds: null,
        switchType: 'apply',
        showMoreRemind: false
      }
    },
    components: {
      RemindBox,
      PullUp,
      RemindOpeModal,
      EmptyStatus
    },
    fetch ({store}) {
      return Promise.all([
        store.dispatch('invoice/getInvoices', {count: 10, page: 1, role: 'SELLER', sorting: {'createTime': 'DESC'}, status: 101})
      ])
    },
    watch: {
      '$store.state.invoice.data.invoices.data': {
        handler: function (val) {
          if (val && val.content) {
            if (this.isChange) {
              this.invoiceList = []
              this.isChange = false
            }
            let arr = this.baseUtils.deepCopy(val.content)
            arr.forEach(item => {
//              item.orderidArr = item.orderids.split(',')
//              item.purchaseidArr = item.purchaseids ? item.purchaseids.split(',') : null
              item.billInfo = item.billInfo ? JSON.parse(item.billInfo) : {}
              item.$active = false
            })
            this.invoiceList = [...this.invoiceList, ...arr]
          }
        },
        immediate: true
      }
    },
    computed: {
      invoices () {
        return this.$store.state.invoice.data.invoices
      },
      fetching () {
        return this.invoices.fetching
      },
      listActiveFlag () {
        let allChecked = true
        for (let i = 0; i < this.invoiceList.length; i++) {
          if (!this.invoiceList[i].$active) {
            allChecked = false
            break
          }
        }
        return allChecked
      },
      allChecked () {
        return this.invoiceList.length && this.listActiveFlag
      }
    },
    methods: {
      setRemindText: function (str) {
        this.remindText = str
        this.timeoutCount++
      },
      initParams () {
        this.page = 1
        this.filterParams.invoicetype = null
        this.filterParams.keyword = null
        this.operateIds = null
      },
      setActive (inv) {
        if (inv) {
          inv.$active = !inv.$active
        } else {
          // 先存储 否则会重新计算
          let flag = !this.allChecked
          this.invoiceList.forEach(item => {
            item.$active = flag
          })
        }
      },
      reloadList () {
        return this.$store.dispatch('invoice/getInvoices', {count: this.count, page: this.page, role: 'SELLER', sorting: {'createTime': 'DESC'}, status: this.switchType === 'record' ? 102 : 101, invoicetype: this.filterParams.invoicetype, keyword: this.filterParams.keyword})
      },
      onPullUp () {
        this.page++
        this.reloadList()
      },
      onFilter () {
        this.isChange = true
        this.page = 1
        return this.reloadList()
      },
      setInvoiceType (type) {
        this.filterParams.invoicetype = type
        this.showFilterInvoiceType = false
        this.onFilter()
      },
      submit () {
        let arr = []
        this.invoiceList.forEach(item => {
          if (item.$active) {
            arr.push(item.id)
          }
        })
        if (arr.length) {
          this.operateIds = arr.join(',')
        } else {
          this.setRemindText('请先勾选开票申请')
        }
      },
      doSubmit () {
        return this.$http.put(`/trade/billSubmit/${this.operateIds}`).then(res => {
          if (res.data.length) {
            this.setRemindText('开票成功')
            this.initParams()
            this.onFilter()
          } else {
            this.setRemindText('开票失败，请重试')
          }
        }, err => {
          this.setRemindText(err.response.data || '开票失败，请重试')
        })
      },
      closeRemindOpe (flag) {
        if (flag) {
          this.doSubmit()
        } else {
          this.operateIds = null
        }
      },
      setSwitchType (type) {
        this.initParams()
        this.switchType = type
        this.onFilter()
//          .then(() => {
//          this.switchType = type
//        })
      },
      goOrderDetail (inv, index) {
        if (inv.purchaseids) {
          this.$router.push(`/mobile/order/details?uuid=${this.baseUtils.enidfilter(inv.purchaseids.split(',')[index])}&type=saler`)
        } else {
          this.setRemindText('获取订单号失败')
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  @import '~assets/scss/mobileInvoice';
  .com-switch-head .com-switch-item.active {
    border-bottom: 0.04rem solid #3f84f6;
  }
  .vendor-invoice {
    .mi-list {
      padding-bottom: 2rem !important;
    }
    &.invoice-record {
      .mi-list {
        padding-bottom: .68rem !important;
      }
    }
  }
</style>
