<template>
  <div class="consump-layout">
    <div class="c-header">
      <ul class="tab-list">
        <li @click="active = i" :class="{active:i===active}" v-for="(item,i) in tabList" :key="i">
          {{item.name}}
        </li>
      </ul>
      
      <!-- <div class="tab-search" v-else :style="{border:!deviceLogin?'1px solid #ccc':'none'}">
         <template v-if="!deviceLogin">
          <input v-model="searchKey" @keyup.enter="getList(searchKey)" type="text" :placeholder="$t('manage.Spending.placeholdersearchID')">
          <i class="iconfont icon-sousuo" @click="getList(searchKey)"></i>
         </template>
      </div> -->
    </div>
    

    <div class="table-list">
      <div class="invoices" v-if="active===2">
      <span>相机</span>
      <div v-if="!deviceLogin" class="tab-select" ref="deviceMenu" @click="deviceActive=!deviceActive" :class="{'tab-active':deviceActive}">
        {{activeDevice||'暂无相机'}}
        <ul>
          <li v-for="(item,i) in invoicedevice" @click="selectInId(item)" :key="i" >{{item.childName}}</li>
        </ul>
      </div>
      <span v-else>{{deviceLogin}} </span>
      <div v-if="active===2 && !deviceLogin" class="tab-select" ref="invoiceMenu" @click="tabActive=!tabActive" :class="{'tab-active':tabActive}">
        {{activeType}}
        <ul>
          <li v-for="(item,i) in cameraList"  @click="selectCamTy(item)" :key="i">{{item.name}}</li>
        </ul>
      </div>
      <span>可开票额度（元）{{max}}</span>
      <div class="btn default" :class="{parmary:max>0&&!deviceLogin}" @click="openInvice">开票</div>
    </div>
      <tableList :header='tabHeader' :data='data'  >
        <div slot-scope="{data}" slot="header">
          {{data.name}}
        </div>
        <div slot-scope="{data,canclick,item, subKey}" slot="item">
          <span class="edit" v-if="canclick" @click="showDetail(item)">{{data}}</span>
          <span v-else-if="subKey === 'payType'">{{ PAYSIDMAP[data] }}</span>
          
          <span v-else>{{data}}</span>
        </div>
      </tableList>
      <div class="paging" v-if="total">
        <vcenter>
          <Paging @clickHandle="pageChange" :current="currentPage" :total="total" :equable="pageSize" />
        </vcenter>
      </div>
      <div class="scene-nothing"  v-if="!total">
        <img :src="`${$cdn}images/nothing.png`" >
        <div>{{$t('manage.Spending.norecord')}}</div>
      </div>
    </div>
    
  </div>
</template>

<script>
import { mapState } from 'vuex'
import tableList from '@/components/table'
import {capacity, recharge, invoice} from './iconsumption'
import Paging from '@/components/Paging'
import vcenter from '@/components/vcenter'
import MemberApi from '@/apis/member'
import MallConfig from '@/config/mall'

let AMOUNTSTR = {
  0: '￥',
  1: '￥',
  2: '$'
}

let methodStr = {
  0: 'getMemberOrderList',
  1: 'getChargeList',
  2: 'getInvoiceList'
}
let rechargeType = {
  0: '系统赠送',
  '-1': '支出',
  1: '充值',
  2: '系统退充值'
}

let invoceStatusType = {
  0: '未开票',
  1: '已开票'
}

let invoiceType = {
  1: '不需要发票',
  2: '增值税普通发票',
  3: '增值税专用发票'
}

export default {
  components: {
    tableList,
    Paging,
    vcenter
  },
  data () {
    let cameraList = [
      {
        name: '全部',
        id: ''
      },
      {
        name: '二目充值',
        id: 0
      },
      {
        name: '会员权益',
        id: 4
      }
    ]
    return {
      PAYSIDMAP: MallConfig.PAYSIDMAP,
      tabHeader: capacity,
      data: [],
      cameraList,
      active: 0,
      recharge,
      total: 30,
      pageSize: 10,
      currentPage: 1,
      tabActive: false,
      deviceActive: false,
      max: 0,
      activeDevice: '',
      activeType: '全部',
      activeId: '',
      activeTypeId: '',
      tabList: [
        {
          name: this.$t('manage.Spending.tabListMember')
        },
        {
          name: this.$t('manage.Spending.tabListRecharge')
        },
        {
          name: this.$t('manage.Spending.tabListInvoice')
        },
      ]
    }
  },
  computed: {
    ...mapState({
      token: state => state.user.token,
      language: state => state.language.current,
      deviceLogin: state => state.user.deviceLogin,
      // myexpansion: state => {
      //   let type = Object.prototype.toString.call(state.user.myexpansion)
      //   if (type === '[object Object]') {
      //     return state.user.myexpansion
      //   }
      //   let condition = state.user.myexpansion && state.user.myexpansion !== 'null' && type !== '[object Array]'
      //   return (condition ? JSON.parse(state.user.myexpansion) : {})
      // },
      mycharge: state => {
        let type = Object.prototype.toString.call(state.user.mycharge)
        if (type === '[object Object]') {
          return state.user.mycharge
        }
        let condition = state.user.mycharge && state.user.mycharge !== 'null' && type !== '[object Array]'
        return (condition ? JSON.parse(state.user.mycharge) : {})
      },
      myinvoicelist: state => {
        let type = Object.prototype.toString.call(state.user.myinvoicelist)
        if (type === '[object Object]') {
          return state.user.myinvoicelist
        }
        let condition = state.user.myinvoicelist && state.user.myinvoicelist !== 'null' && type !== '[object Array]'
        return (condition ? JSON.parse(state.user.myinvoicelist) : {})
      },
      invoicedevice: state => {
        let type = Object.prototype.toString.call(state.user.invoicedevice)
        if (type === '[object Object]') {
          return state.user.invoicedevice
        }
        let condition = state.user.invoicedevice && state.user.invoicedevice !== 'null'
        return (condition ? state.user.invoicedevice : [])
      },
      searchKey () {
        return this.$parent.searchKey
      }
    })
  },
  watch: {
    currentPage (newVal) {
      this.getList()
    },
    language (newVal) {
      this.active = 0
      this.data.forEach(item => {
        let condition = item['validDate'] === '终身有效' ? (newVal === 'en' ? 'N/A' : '终身有效') : item['validDate']
        item['validDateStr'] = condition
        item['unitSize1'] = item['unitSize'] + item['unit'] + '/' + this.$t(`manage.shixian.${item['month']}`)
        item['channel'] = this.$t(`manage.channelType.${item['status']}`)
        item['amount1'] = AMOUNTSTR[item['payType']] + item['amount']
        item['payTypeStr'] = this.$t(`manage.PAYSSTR.${item['payType']}`)
      })
    },
    activeId (newVal) {
      if (this.active === 2) {
        this.getList()
      }
      this.getInvoiceMax()
    },
    activeTypeId (newVal) {
      if (this.active === 2) {
        this.getList()
      }
    },
    active (newVal) {
      switch (newVal) {
        case 1:
          this.tabHeader = recharge
          break
        case 2:
          !this.deviceLogin && this.getAllDevice()
          this.tabHeader = invoice
          break
        default:
          this.tabHeader = capacity
          break
      }
      if (newVal !== 1) {
        this.$emit('changeSearchShow', false)
      } else {
        this.$emit('changeSearchShow', true)
      }
      this.currentPage === 1 ? this.getList() : this.currentPage = 1
    }
  },
  methods: {
    pageChange (data) {
      this.currentPage = data
    },
    selectInId (item) {
      this.activeDevice = item.childName
      this.activeId = item.id
    },
    selectCamTy (item) {
      this.activeType = item.name
      this.activeTypeId = item.id
    },
    showDetail (item) {
      this.$toast.showInvoiceDetail(item)
    },
    getList (searchKey = '') {
      window.scrollTo(0, 0)
      let str = methodStr[this.active]
      this[str](searchKey)
    },
    openInvice () {
      let params = {
        max: this.max,
        cameraId: this.activeId
      };
      (this.max && !this.deviceLogin) && this.$toast.showInvoice(params)
    },
    async getAllDevice (searchKey = '') {
      let params = {
        cameraType: ''
      }
      await this.$store.dispatch('getInvoiceDevice', params)
      this.activeDevice = this.invoicedevice[0].childName
      this.activeId = this.invoicedevice[0].id
    },

    // 扩容记录
    async getConsumpList (searchKey = '') {
      if (this.deviceLogin) {
        searchKey = this.deviceLogin
      }
      let data = {
        params: {
          childName: searchKey.trim(),
          pageNum: searchKey ? 1 : this.currentPage,
          pageSize: this.pageSize
        },
        url: this.deviceLogin ? '/device/virtualOrder/expansionList' : '/user/virtualOrder/expansionList'
      }
      await this.$store.dispatch('getUserExpansion', data)
      if (!this.myexpansion.total && searchKey && !this.deviceLogin) {
        return this.$toast.show('warn', this.$t('toast.25'), () => {
          this.getList()
        })
      }
      console.log(this.myexpansion, 'this.myexpansion')
      this.pageSize = this.myexpansion.pageSize
      this.total = this.myexpansion.total || 0
      this.data = this.myexpansion.list
      this.data.forEach(item => {
        let condition = item['validDate'] === '终身有效' ? (this.language === 'en' ? 'N/A' : '终身有效') : item['validDate']
        item['validDateStr'] = condition
        item['statusStr'] = this.$t(`manage.myOrders.${item['status']}`)
        item['unitSize1'] = item['unitSize'] + item['unit'] + '/' + this.$t(`manage.shixian.${item['month']}`)
        item['channel'] = this.$t(`manage.channelType.${item['status']}`)
        item['amount1'] = AMOUNTSTR[item['payType']] + item['amount']
        item['payTypeStr'] = this.$t(`manage.PAYSSTR.${item['payType']}`)
      })
    },
    getMemberOrderList () {
      let data = {
        snCode: this.searchKey,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      MemberApi.getVirtualOrderList(data).then(res => {
        this.data = res.data.data.list
        console.log(this.data)
        this.total = res.data.data.total
      })
    },
    async getInvoiceMax () {
      let res = await this.$http({
        method: 'post',
        data: {
          cameraId: this.activeId
        },
        headers: {
          token: this.token
        },
        url: '/user/invoice/max'
      })

      let data = res.data
      if (data.code !== 0) return
      this.max = data.data.maxInvoice
    },

    // 充值记录
    async getChargeList (searchKey = '') {
      if (this.deviceLogin) {
        searchKey = this.deviceLogin
      }
      let data = {
        params: {
          childName: searchKey,
          pageNum: searchKey ? 1 : this.currentPage,
          pageSize: this.pageSize
        },
        url: this.deviceLogin ? '/device/virtualOrder/chargeList' : '/user/virtualOrder/chargeList'
      }
      await this.$store.dispatch('getChargeList', data)
      if (!this.mycharge.total && searchKey && !this.deviceLogin) {
        return this.$toast.show('warn', this.$t('toast.25'), () => {
          this.getList()
        })
      }
      this.pageSize = this.mycharge.pageSize
      this.total = this.mycharge.total || 0
      this.data = this.mycharge.list
      this.data.forEach(item => {
        item['status'] = rechargeType[item['status']]
      })
    },

    // 发票记录
    async getInvoiceList () {
      let data = {
        params: {
          cameraId: this.activeId,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          type: this.activeTypeId
        },
        url: this.deviceLogin ? '/device/invoice/list' : '/user/invoice/list'
      }

      await this.$store.dispatch('getInvoiceList', data)
      this.pageSize = this.myinvoicelist.pageSize
      this.total = this.myinvoicelist.total || 0
      this.data = this.myinvoicelist.list
      this.data.forEach(item => {
        item['detail'] = '详细'
        item['money'] = '￥' + item['money']
        item['finish'] = invoceStatusType[item['finish']]
        item['type'] = invoiceType[item['type']]
      })
    },
    handleSearch (keyword) {
      this.getList(keyword)
    }
  },
  mounted () {
    this.getList()

    this.$bus.$off('refreshInvoice')
    this.$bus.$on('refreshInvoice', () => {
      if (this.active === 2) {
        this.getList()
      }
      this.getInvoiceMax()
    })

    document.addEventListener('click', (e) => {
      if (this.$refs.invoiceMenu) {
        if (!this.$refs.invoiceMenu.contains(e.target)) {
          this.tabActive = false
        }
      }
      if (this.$refs.deviceMenu) {
        if (!this.$refs.deviceMenu.contains(e.target)) {
          this.deviceActive = false
        }
      }
    })
  }
}
</script>

<style lang="scss" scoped>
$theme-color: #15BEC8;
$font-color: #2d2d2d;
$border-color: #d9d9d9;
.btn {
    text-align: center;
    cursor: pointer;
  }
.default {
  width: 88px;
  height: 28px;
  line-height: 28px;
  font-size: 14px;
  background-color: #e7e7e7;
  cursor: initial;

}
.parmary {
  background-color: $theme-color;
  cursor: pointer;
}

.consump-layout{
  .c-header{
    .tab-list{
      display: flex;
      color: #323233;
      li{
        line-height: 32px;
        cursor: pointer;
        font-size: 14px;
        background: #EBEBEB;
        width: 104px;
        text-align: center;
        margin-right: 1px;
      }
      .active{
        background: #ffff;
        position: relative;
        border: 1px solid rgba(235, 235, 235, 1);
        border-bottom: none;
        &::after {
          content: '';
          display: block;
          height: 1px;
          width: 100%;
          background: #fff;
          position: absolute;
          bottom: -1px;
        }
      }
    }

  }
  .invoices{
    display: flex;
    align-items: center;
    margin-top: 17px;
    position: relative;
    span{
      font-size: 14px;
      margin-right: 20px;
    }
    .tab-select{
      margin-right: 20px;
    }
    .default {
      position: absolute;
      right: 0;
      cursor: pointer;
      line-height: 32px;
      width: 104px;
      height: 32px;
    }
  }
  .tab-search{
      float: right;
      position: relative;
      width: 200px;
      padding-left: 10px;
      margin-right: 15px;
      border: 1px solid #ccc;
      display: flex;
      .iconfont{
        width: 28px;
        height: 28px;
        padding: 6px;
        background: #e4e4e4;
        cursor: pointer;
      }
      input{
        width: 100%;
        font-size: 14px;
        appearance: none;
        line-height: 28px;
        height: 28px;
        border: 0;
      }
    }
  .tab-select{
      float: right;
      position: relative;
      width: 200px;
      height: 32px;
      line-height: 32px;
      padding-left: 10px;
      border: 1px solid $border-color;
      font-size: 14px;
      color: #969696;
      cursor: pointer;
      &::after{
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(calc(-50% + 3px));
        content: '';
        width: 0;
        height: 0;
        border: 5px solid;
        display: inline-block;
        border-color: #828282 transparent transparent;
      }
      ul{
        position: absolute;
        max-height: 0;
        left: 0;
        top: 34px;
        background: #fff;
        overflow: hidden;
        width: 100%;
        transition:all 0.3s ease;
        box-shadow: 0 0 10px rgba($color: #000000, $alpha: 0.4);
        li{
          padding-left: 10px;
          &:hover{
            background: $theme-color;
            color: #2d2d2d;
          }
        }
      }
    }
    .tab-active{
      ul{
        max-height: 220px;
        overflow: auto;
      }
    }
  .table-list{
    padding: 0 30px;
    &>div{
      width: 100%;
    }
    .edit{
      color: $theme-color;
      cursor: pointer;
    }
  }
  .scene-nothing{
    padding: 42px 0 0 40px;
    text-align: center;
    img{
      padding-bottom: 22px;
    }
    div{
      font-size: 16px;
      color: #969696;
      text-align: center;
    }
  }
  .paging {
    height: 100%;
  }
}

</style>

<style lang="less">
.consump-layout {
  .table-list {
    border: 1px solid rgba(235, 235, 235, 1);
    .t-header, .t-item {
      line-height: 52px;
      border-bottom: 1px solid rgba(32, 32, 32, 0.2);
      font-size: 14px;
      padding: 0 !important;
    }
  }
}
</style>