<template>
  <div class="invoice-wrapper">
    <div class="mobile-nav">
      <div class="mobile-header mobile-center-header">
        <a @click="goBack()"><i class="iconfont icon-fanhui"></i></a>
        <p>发票管理</p>
        <p class="en-name">
          <img :src="`/images/mobile/center/${user.data.enterprise && user.data.enterprise.uu ? 'en' : 'self'}.png`" alt="">{{currentEnName}}
        </p>
      </div>
    </div>
    <div class="order-nav">
      <nuxt-link to="/mobile/center/user/invoice" tag="div"><span>发票信息</span></nuxt-link>
      <div class="active"><span>待开票订单</span></div>
      <nuxt-link to="/mobile/center/user/invoice/invoiceRecord" tag=div><span>开票记录</span></nuxt-link>
    </div>
    <div class="invoice-wrapper-el">
      <div class="mobile-invoice">
        <div class="mi-remind-area" :class="{less: !showMoreRemind}">
          <p class="title">温馨提示</p>
          <p class="content">
            <span class="inline-block">1、</span>
            <span class="inline-block">申请发票时默认将同一店铺的订单合并开一张发票，如需分开开票，请分别申请；</span>
          </p>
          <p class="content">
            <span class="inline-block">2、</span>
            <span class="inline-block">您只能对订单状态为<b>“交易完成”</b>，且已不能再发起售后的人民币交易订单进行补开发票；</span>
          </p>
          <p class="content">
            <span class="inline-block">3、</span>
            <span class="inline-block">发票金额为产品总金额且不含运费、积分、优惠卷、促销折扣等金额；</span>
          </p>
          <p class="content">
            <span class="inline-block">4、</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" placeholder="商家名称/订单号" v-model="keyword">
          <span @click="searchMore()"><i class="iconfont icon-sousuo"></i></span>
        </div>
        <div class="mi-list-content">
          <ul class="mi-list" v-if="invoiceList.length > 0">
            <li v-for="inv in invoiceList" @click.stop="setActive(inv)" :class="{active: inv.$active}">
              <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" @click.stop="toShopdetails(inv)">{{inv.sellername}}</span>
              </div>
              <div class="line">
                <span class="inline-block title">
                  订单号：
                </span>
                <span class="inline-block content" @click.stop="lookOrderDetail(inv)">
                {{inv.orderid}}
                </span>
              </div>
              <div class="line">
                <span class="inline-block title">
                  可开票金额：
                </span>
                <span class="inline-block content pri">¥{{inv.price}}</span>
              </div>
            </li>
          </ul>
          <div class="com-none-state" v-if="invoiceList.length === 0">
            <img src="/images/mobile/@2x/empty-collect.png">
            <p>抱歉，暂无发票消息</p>
          </div>
        </div>
      </div>
    </div>
    <div class="mobile-invoice">
      <div class="mi-fix-result" v-if="invoiceList.length > 0">
        <label class="bottom-modal-check mobile-cart-check" :class="{active: allChecked}">
          <input type="checkbox" @change="setActive()">
          <span>全选</span>
        </label>
        <button @click="applyInvoice()">申请开票</button>
      </div>
    </div>
    <mobile-footer></mobile-footer>
    <remind-box :title="collectResult" :timeoutCount="timeoutCount"></remind-box>

    <addinvoice
      :chooseItem="addItem"
      @addinvoiceBtn="addinvoiceFn"
      v-if="showAddinvoice"
      :joinType="joinType"
    ></addinvoice>

    <pull-up :searchMore="fetching" :allPage="invoices.data.totalPages" :page="page" @pullUpAction="onPullUp"></pull-up>

    <!-- 申请发票弹窗 -->
    <div class="mobile-modal" @touchmove="preventTouchMove($event)" v-if="showSend">
      <div class="applyinvoice_Alert" >
        <div class="applyinvoice_title">申请开票<span><i class="iconfont icon-guanbi1" @click="showSend = false"></i></span></div>
        <div ref="applyinvoiceAlert" class="scrollContent" >
          <div>
            <div class="applyinvoice-ul" v-if="invoiceArr.length > 0">
              <div class="addinvoice-focus clearfix">
                <div class="pull-left addinvoice-focus-name">发票类型：</div>
                <div class="pull-left clearfix">
                  <div class="normal pull-left" style="margin-right: 0.2rem;" @click="chooseVoice('speci', 1205)" v-if="showSpeciBtn">
                    <div class="icon" :class="waitinvoiceType === 'speci' ? 'active' : ''">
                      <div class="icon-next"></div>
                    </div>
                    增值税专票
                  </div>
                  <div class="normal pull-left" @click="chooseVoice('normal', 1206)" v-if="showNormalBtn">
                    <div class="icon" :class="waitinvoiceType === 'normal' ? 'active' : ''">
                      <div class="icon-next"></div>
                    </div>
                    增值税普票
                  </div>
                </div>
              </div>
              <div class="addinvoice-focus clearfix">
                <div class="pull-left addinvoice-focus-name">发票抬头：</div>
                <div class="pull-left clearfix">
                  {{chooseItem.head}}
                </div>
              </div>
              <div class="addinvoice-focus clearfix" v-if="chooseItem.kind === 1205">
                <div class="pull-left addinvoice-focus-name">单位地址：</div>
                <div class="pull-left clearfix">
                  {{chooseItem.companyAddress}}
                </div>
              </div>
              <div class="addinvoice-focus clearfix" v-if="chooseItem.kind === 1205">
                <div class="pull-left addinvoice-focus-name">单位电话：</div>
                <div class="pull-left clearfix">
                  {{chooseItem.companyPhone}}
                </div>
              </div>
              <div class="addinvoice-focus clearfix" v-if="chooseItem.kind === 1205">
                <div class="pull-left addinvoice-focus-name">税务登记号：</div>
                <div class="pull-left clearfix">
                  {{chooseItem.companyTaxNumber}}
                </div>
              </div>
              <div class="addinvoice-focus clearfix" v-if="chooseItem.kind === 1205">
                <div class="pull-left addinvoice-focus-name">开户银行：</div>
                <div class="pull-left clearfix">
                  {{chooseItem.bankName}}
                </div>
              </div>
              <div class="addinvoice-focus clearfix" v-if="chooseItem.kind === 1205">
                <div class="pull-left addinvoice-focus-name">开户银行账号：</div>
                <div class="pull-left clearfix">
                  {{chooseItem.bankAccount}}
                </div>
              </div>
              <div class="addinvoice-focus clearfix" >
                <div class="pull-left addinvoice-focus-name">收票人：</div>
                <div class="pull-left clearfix">
                  {{chooseItem.name}}
                </div>
              </div>
              <div class="addinvoice-focus clearfix" >
                <div class="pull-left addinvoice-focus-name">联系电话：</div>
                <div class="pull-left clearfix">
                  {{chooseItem.telephone}}
                </div>
              </div>
              <div class="addinvoice-focus clearfix" >
                <div class="pull-left addinvoice-focus-name">收票地址：</div>
                <div class="pull-left clearfix">
                  <p style="line-height:0.4rem">{{chooseItem.area}}</p>
                  <p style="line-height:0.4rem">{{chooseItem.detailAddress}}</p>
                </div>
              </div>
            </div>
            <div class="applyinvoice-ul" v-else>
              <div class="addinvoice-focus clearfix">
                <div class="pull-left addinvoice-focus-name">暂无发票信息：</div>
                <div class="pull-left clearfix" @click="addInvoiceNew()">
                  <img src="/images/mobile/center/user/icon-rm-invoice.png"/>新增发票
                </div>
              </div>
            </div>
            <div class="applyinvoive_infotitle">共<a class="blue">{{applyObj.sellNum.length}}</a>个商家，<a class="blue">{{applyObj.orderNum}}</a>个订单，发票金额总计：<a class="red">¥{{applyObj.allPrice}}</a>元</div>
            <div class="applyinvoive_detailinfo">
              <div class="clearfix" v-for="info in applyObj.sellNum">
                <div class="pull-left">{{info.sellername}}</div>
                <div class="pull-right">金额：¥{{info.orderAllPrice}}</div>
              </div>
            </div>
            <div class="applyinvoice_controll clearfix">
              <div @click="showSend = false" class="pull-left">取消</div>
              <div class="pull-right" @click="applyInvoiceFn()">确认</div>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
  import { EncryptionFilter } from '~utils/tools.js'
  import axios from '~plugins/axios'
  import { RemindBox, PullUp } from '~components/mobile/common'
  import { addinvoice } from '~components/mobile/center'
  import BScroll from 'better-scroll'
  import { MobileFooter } from '~components/mobile'
  export default {
    name: 'invoice-view',
    layout: 'mobile',
    middleware: 'authenticated',
    computed: {
      invoices () {
        return this.$store.state.invoice.data.Buyerinvoices
      },
      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
      }
    },
    fetch ({store}) {
      return Promise.all([
        store.dispatch('invoice/getBuyerInvoices', {count: 10, keyword: '', page: 1, sorting: {'creattime': 'DESC'}, status: 520})
      ])
    },
    watch: {
      '$store.state.invoice.data.Buyerinvoices.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.$active = false
            })
            this.invoiceList = [...this.invoiceList, ...arr]
          }
        },
        immediate: true
      }
    },
    data() {
      return {
        waitinvoiceType: 'speci',
        showNormalBtn: true, // 是否显示普票按钮
        showSpeciBtn: true, // 是否显示专票按钮
        activeType: '',
        invoiceList: [], // 订单列表
        invoiceArr: [], // 当前用户发票数组
        collectResult: '',
        timeoutCount: 0,
        chooseItem: {}, // 当前选中的发票
        showAddinvoice: false, // 是否显示新增发票
        joinType: 'add', // 新增发票状态
        keyword: '',
        page: 1,
        showSend: false, // 是否显示发票申请
        applyObj: { // 申请发票对象
          sellNum: []
        },
        addItem: {}, // 新增发票数组
        showMoreRemind: false
      }
    },
    async asyncData() {
      let { data } = await axios.get('/trade/bill/list/personal')
      let showNormalBtn = data.find(item => {
        return item.kind === 1206
      })
      let showSpeciBtn = data.find(item => {
        return item.kind === 1205
      })
      let chooseItem = showSpeciBtn ? showSpeciBtn : showNormalBtn
      let waitinvoiceType = showSpeciBtn ? 'speci' : 'normal'
      return {
        invoiceArr: data,
        showNormalBtn: showNormalBtn ? true: false,
        showSpeciBtn: showSpeciBtn ? true : false,
        chooseItem: chooseItem,
        waitinvoiceType: waitinvoiceType
      }
    },
    methods: {
      setActive (inv) {
        if (inv) {
          inv.$active = !inv.$active
        } else {
          // 先存储 否则会重新计算
          let flag = !this.allChecked
          this.invoiceList.forEach(item => {
            item.$active = flag
          })
        }
      },
      chooseVoice(str, num) {
        this.waitinvoiceType = str
        this.chooseItem = this.invoiceArr.find(obj => {
          return obj.kind === num
        })
        this._initScroll()
      },
      async addinvoiceFn(ty, item) {
        this.showAddinvoice = false
        if (ty) {
          let { data } = await axios.get('/trade/bill/list/personal')
          let showNormalBtn = data.find(item => {
            return item.kind === 1206
          })
          let showSpeciBtn = data.find(item => {
            return item.kind === 1205
          })
          let chooseItem = showSpeciBtn ? showSpeciBtn : showNormalBtn
          let waitinvoiceType = showSpeciBtn ? 'speci' : 'normal'
          this.invoiceArr = data
          this.showNormalBtn = showNormalBtn ? true: false
          this.showSpeciBtn = showSpeciBtn ? true : false
          this.chooseItem = chooseItem
          this.waitinvoiceType = waitinvoiceType
        }
        this.showSend = true
      },
      setRemindText(str) {
        this.collectResult = str
        this.timeoutCount++
      },
      // 店铺详情页
      toShopdetails(item) {
        this.$router.push(`/mobile/shop/${item.storeid}`)
      },
      // 查看订单详情
      lookOrderDetail(item) {
        let id = EncryptionFilter(item.orderid)
        this.$router.push(`/mobile/order/details?uuid=${id}&type=buyer&paytype=${item.paytype}`)
      },
      // 申请开票
      applyInvoice() {
        let _arr = []
        let _orderNum = 0
        let _AllPice = 0
        this.invoiceList.forEach(obj => {
          if (obj.$active === true) {
            _AllPice += obj.price
            _orderNum++
            let _find = _arr.find($it => {
              return $it.storeid === obj.storeid
            })
            if (_find) {
              _find.orderAllPrice += obj.price
            } else {
              obj.orderAllPrice = obj.price
              _arr.push(obj)
            }
          }
        })
        if (_arr.length === 0) {
          this.setRemindText('请勾选未开票订单')
          return
        }
        this.applyObj = {
          sellNum: _arr,
          orderNum: _orderNum,
          allPrice: _AllPice
        }
        this.showSend = true
        this._initScroll()
      },
      // 申请开票最后阶段
      applyInvoiceFn() {
        if (this.invoiceArr.length === 0) {
          this.setRemindText('请选择发票类型')
          return
        }
        let str = ''
        this.applyObj.sellNum.forEach(obj => {
          str === '' ? str += obj.orderid : str += ',' + obj.orderid
        })
        let json = {
          invoiceid: this.chooseItem.id,
          orderids: str
        }
        this.$http.post('/trade/billSubmit', json).then(res => {
          if (res.data instanceof Array) {
            this.setRemindText('申请成功')
            this.searchMore()
            this.showSend = false
          }
        })
      },
      reloadList () {
        this.isChange = true
        this.$store.dispatch('invoice/getBuyerInvoices', {count: 10, page: this.page, keyword: this.keyword, sorting: {'creattime': 'DESC'}, status: 520})
      },
      searchMore() {
        this.page = 1
        this.reloadList()
      },
      onPullUp () {
        this.page++
        this.reloadList()
      },
      _initScroll() {
        this.$nextTick(res => {
           if (!this.scroll) {
             this.scroll = new BScroll(this.$refs.applyinvoiceAlert, {click: true})
           } else {
             this.scroll.refresh()
           }
        })
      },
      addInvoiceNew() {
        this.showSend = false
        this.addItem = {}
        this.showAddinvoice = true
      }
    },
    components: {
      RemindBox,
      addinvoice,
      PullUp,
      MobileFooter
    }
  }
</script>

<style lang="scss" scoped>
  @import '~assets/scss/mobileInvoice';
  @mixin overFlowHidden {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  @mixin lineHeight($value) {
    height: $value;
    line-height: $value;
  }
  .invoice-wrapper {
    background: #f1f3f6;
    /*margin: 1.26rem 0 0 0;*/
    left: 0;
    bottom: 0;
    top: 0;
    right: 0;
    z-index: 11;
    /*padding: 0.82rem 0 1.04rem;*/
    /*height: calc(100vh - 1.26rem);*/
    position: absolute;
    width: 100%;
    .invoice-wrapper-el {
      margin: 2.08rem 0 0.98rem;
      height: calc(100vh - 1.26rem - 0.98rem - 1.06rem);
      overflow-y: scroll;
      padding-bottom: 0.98rem;
    }
    .mobile-header{
      position: fixed;
      top: 0;
      z-index: 10;
      width:100%;
      height: 1.26rem;
      line-height: 1.26rem;
      /*border-bottom:.01rem solid #ccc;*/
      background: #3e82f5;
      padding:0 .2rem 0 .1rem;
      color:#fff;
    }
    .mobile-header p{
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size:.36rem;
      text-align: center;
      width: 6rem;
      padding-left: 1rem;
    }
    .mobile-center-header p.en-name {
      font-size: .3rem;
    }
    .mobile-header a{
      font-size:.28rem;
      color:#fff;
      position: absolute;
    }
    .mobile-header a i{
      font-size: .48rem;
      margin-right: -.1rem;
    }
    .order-nav {
      background: #fff;
      position: fixed;
      width: 100%;
      top: 1.26rem;
      z-index: 10;
      div {
        height: 0.82rem;
        line-height: 0.82rem;
        display: inline-block;
        width: 33.3%;
        text-align: center;
        font-size: .28rem;
        color: #666;
        &.active span{
          color: #3f84f6;
          border-bottom: 0.04rem solid #3f84f6;
          padding-bottom: 0.2rem;
        }
      }
    }
    .mi-remind-area {
      margin-top: 0.24rem;
      background: #fff;
    }
    .mi-list-content .mi-list li {
      background: #fff;
      &:nth-child(1) {
        margin-top: 0;
      }
    }
    .mi-search-content input {
      width: 7rem;
      margin: 0;
    }
    .mobile-invoice .mi-list-content .mi-list li .line .content {
      padding: 0;
      color: #3976f4;
      width: 67%;
      &.pri {
        color: #ee1111
      }
    }
    .mobile-invoice .mi-list-content .mi-list li .line .title {
      width: 33%;
    }
    .applyinvoice_Alert {
      background: #fff;
      position: fixed;
      bottom: 0rem;
      left: 0;
      width: 100%;
      border-top-left-radius: 5px;
      border-top-right-radius: 5px;
      padding-bottom: 0.2rem;
      .scrollContent {
        max-height: 6rem;
        overflow: hidden;
      }
      .applyinvoice_title {
        color: #333;
        font-size: 0.42rem;
        text-align: center;
        line-height: 1rem;
        font-weight: 600;
        position: relative;
        i {
          position: absolute;
          font-size: 16px;
          right: 0.2rem;
        }
      }
      .applyinvoice-ul {
        .addinvoice-focus {
          font-size: 0.28rem;
          color: #666;
          line-height: 0.6rem;
          margin: 0 0.2rem;
          img {
            width: 0.29rem;
            vertical-align: top;
            height: 0.33rem;
            margin-top: 0.12rem;
            margin-right: 0.04rem;
          }
          .addinvoice-focus-name {
            width: 2.1rem;
          }
          .normal {
            .icon {
              font-size: 0.28rem;
              color: #333;
              width: 0.5rem;
              height: 0.5rem;
              border-radius: 50%;
              border: 1px solid #dcdcdc;
              position: relative;
              display: inline-block;
              vertical-align: top;
              &.active .icon-next {
                background: #226ce7;
                width: 0.3rem;
                height: 0.3rem;
                border-radius: 50%;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate3d(-50%, -50%, 0);
              }
            }
          }
        }
      }
      .applyinvoive_infotitle {
        color: #333;
        font-size: 0.28rem;
        @include lineHeight(0.6rem);
        background: #e5e5e5;
        padding: 0 0.2rem;
        .blue {
          color: #3e82f5;
        }
        .red{
          max-width: 1.6rem;
          @include overFlowHidden();
          vertical-align: middle;
          display: inline-block;
          color: #f43938
        }
      }
      .applyinvoive_detailinfo {
        color: #333;
        font-size: 0.28rem;
        padding: 0.2rem;
        .clearfix {
          @include lineHeight(0.5rem);
        }
        .pull-left {
          width: 3.5rem;
          @include overFlowHidden()
        }
        .pull-right {
          width: 3.4rem;
          @include overFlowHidden()
        }
      }
      .applyinvoice_controll {
        padding: 0 0.3rem;
        div {
          width: 3.29rem;
          @include lineHeight(0.77rem);
          color: #fff;
          font-size: 0.32rem;
          text-align: center;
          border-radius: 0.07rem;
          background: #bfbfbf;
          &:last-child {
            background: #3e82f5;
          }
        }
      }
    }
  }
</style>

