<template>
  <div class="mainPage flex-v">
    <div class="top">
      <topCaseInfo :data="topCaseInfoData" :fromPage='fromPage' :userName="userInfo.customer.RealName ? userInfo.customer.RealName : userInfo.customer.Name" @selectCase="showVanPicker"></topCaseInfo>
    </div>
    <nav class="flex-h" v-if="userInfo.customer.MapUser !== '' && fromPage === 'sales'">
      <a class="flex-item" v-for="(item,index) in cutNavList" :key="index" :class="{'active': navActive === index}" @click="cutNav(index)">{{item.value}}</a>
    </nav>
      <div class="content">
        <div>
          <ul>
            <li :hidden="navActive !== 0 && userInfo.customer.MapUser !== ''" class="placeOrder">
              <div class="topInfo flex-h" v-if="userInfo.customer.MapUser !== '' && fromPage === 'sales'">
                <div class="flex-item">
                  <div>
                    <span>共计已使用：{{caseTotal.total}}杯</span>
                  </div>
                </div>
                <div class="flex-item">
                  <div>
                    <span>本月已用：{{caseTotal.monthtotal}}杯</span>
                  </div>
                </div>
                <router-link :to="{name: 'orderList'}">点单记录</router-link>
              </div>
              <div class="areaListParent flex-h">
                <div class="flex-item">
                  <div>
                    <ul class="areaList">
                      <li v-for="(item,index) in CaseTableList" :key="index">
                        <div class="title">
                          <!-- <i class="iconfont icon-yinchenglogo"></i> -->
                          <img :src="item.AreaIcon" class="iconfont icon-yinchenglogo">
                          <span>{{item.AreaName}}</span>
                        </div>
                        <ul class="subAreaList flex-h">
                          <!-- <router-link tag="li" class="flex-item flex-h" v-for="(subItem,subIndex) in item.Tables" :key="subIndex" :to="{name: 'placeOrder', query: { tableid: encodeURI(subItem.TableId), tableno: encodeURI(subItem.TableNo), caseid: encodeURI(subItem.CaseId), casename: encodeURI(topCaseInfoData.caseName), areaid: encodeURI(subItem.AreaId), areaname: encodeURI(item.AreaName)}}">
                            <caseTableItem :icon="item.AreaIcon" :item="subItem" :index="subIndex"></caseTableItem>
                          </router-link> -->
                          <li class="flex-item flex-h" v-for="(subItem,subIndex) in item.Tables" :key="subIndex" @click="toOrders(subItem, item)">
                            <caseTableItem :icon="item.AreaIcon" :item="subItem" :index="subIndex"></caseTableItem>
                          </li>
                          <li class="flex-item noData" v-if="(item.Tables || []).length % 2 != 0"></li>
                        </ul>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </li>
            <li :hidden="navActive !== 1" class="my-card">
              <div class="list-box">
                <div class="cardAndCouponInfo flex-h">
                  <div class="flex-item">
                    <div>
                      <span>卡券货值总额：</span>
                      <span>￥{{cardTotalCount}}</span>
                    </div>
                  </div>
                  <a @click="toSalesHistory" v-if="userInfo.customer.UserTypeId == 'manager'">销售记录</a>
                </div>
                <myCard v-for="(item,index) in data[1].list" :ismanager="userInfo.customer.UserTypeId == 'manager'" :isgrey="checkCanDo()" :key="index" :data='item' @share='shareCard' @detail='toCardNumDetail'></myCard>
                <noMore v-if="data[1].hasPic"></noMore>
              </div>
            </li>
            <li :hidden="navActive !== 2" class="my-card">
              <div class="list-box">
                <div class="cardAndCouponInfo flex-h">
                  <div class="flex-item">
                    <div>
                      <span>卡券货值总额：</span>
                      <span>￥{{couponTotalCount}}</span>
                    </div>
                  </div>
                  <a @click="toSalesHistory" v-if="userInfo.customer.UserTypeId == 'manager'">销售记录</a>
                </div>
                <myCard v-for="(item,index) in data[2].list" :ismanager="userInfo.customer.UserTypeId == 'manager'" :isgrey="checkCanDo()" :key="index" :data='item' @share='shareCoupon' @detail='toCouponNumDetail'></myCard>
                <noMore v-if="data[2].hasPic"></noMore>
              </div>
            </li>
            <li :hidden="navActive !== 3" class="customer-card">
              <div class="list-box">
                <div class="search-bar flex-h">
                  <span>共{{this.data[3].list.length}}位客户</span>
                  <van-checkbox v-model="postCustomerData.isrecommend">
                    我推荐的客户({{myRecommendUserList.length}}人)
                    <img
                      slot="icon"
                      slot-scope="props"
                      :src="postCustomerData.isrecommend ? icon.active : icon.normal"
                      style="width:.2rem;height:.2rem;bottom: .02rem;position: relative;"
                    >
                  </van-checkbox>
                  <i class="iconfont icon-sousuo search-icon" @click="searchMask"></i>
                </div>
                <customerCard v-for="(item,index) in postCustomerData.isrecommend ? myRecommendUserList : data[3].list" :key="index" :data='item' @record='record' @history='history' @remark='remark'></customerCard>
                <noMore v-if="data[3].hasPic"></noMore>
              </div>
            </li>
          </ul>
        </div>
      </div>
    <div class="selectCase" :hidden="!showSelect"></div>
    <van-picker :hidden="!showSelect"
      show-toolbar
      title="选择案场"
      :columns="CaseList"
      @cancel="showSelect = false"
      @confirm="selectCase"
      value-key="CaseName"
    />
    <van-dialog
      v-model="showDialog"
      show-cancel-button
      title='添加备注'
      :before-close="beforeClose">
      <van-field
        v-model="message"
        type="textarea"
        placeholder="请输入备注"
        rows="3"
        autosize/>
    </van-dialog>
  </div>
</template>

<script>
import caseTableItem from '../../../../components/caseTableItem/index'
import topCaseInfo from '../../../../components/topCaseInfo/index'
import myCard from '../../../../components/myCard/myCard'
import customerCard from '../../../../components/customerCard/customerCard'
import active from '../../../../common/icon/check-box-checked.png'
import normal from '../../../../common/icon/check-box-empty.png'
import logo from '../../../../common/icon/indexlogo.jpg'
import wxsdk from '../../../../util/share'
import noMore from '../../../../components/noMore/noMore'
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapActions: actions } = createNamespacedHelpers('app')
const { mapActions: caseTableActions } = createNamespacedHelpers('placeOrderForCoffee')
const { mapState: mapCaseState, mapActions: mapCaseActions } = createNamespacedHelpers('case')
const { mapState: mpRemarkState, mapActions: mapRemarkActions } = createNamespacedHelpers('remark')
const { mapState: mapCardState, mapActions: mapCardActions } = createNamespacedHelpers('myCard')
const { mapActions: mapUserCenterActions } = createNamespacedHelpers('userCenter')
const wx = require('weixin-js-sdk')

export default {
  name: '',
  data () {
    return {
      fromPage: '',
      myRecommendUserList: [],
      forbidList: [],
      postCustomerData: {
        page: 1,
        pagesize: 10000,
        isrecommend: false,
      },
      couponTotalCount: 0,
      cardTotalCount: 0,
      postCouponData: {
        page: 1,
        pagesize: 10000
      },
      postCardData: {
        page: 1,
        pagesize: 10000
      },
      pullUpLoad: true,
      pullUpLoadThreshold: 40,
      startY: 0,
      isloading: true,
      icon: {
        active: active,
        normal: normal
      },
      active,
      normal,
      navActive: 0,
      showDialog: false,
      message: '',
      logo,
      cutNavList: [{
        value: '城咖啡',
        id: '1',
      }, {
        value: '我的卡',
        id: '2',
      }, {
        value: '我的券',
        id: '3',
      }, {
        value: '我的客户',
        id: '4',
      }],
      topCaseInfoData: {
        caseName: '',
        caseId: '',
        ShowSelect: false,
        recommendCode: ''
      },
      caseInfo: {
        value: '',
        id: ''
      },
      showSelect: false,
      list: [{
        name: '案场名称1',
        list: [{}, {}, {}, {}, {}],
      }, {
        name: '案场名称2',
        list: [{}, {}, {}, {}, {}],
      }],
      data: [
        {
          hasPic: false,
          hasMore: true,
          page: 1,
          pagesize: 1,
          list: []
        },
        {
          hasPic: false,
          hasMore: true,
          page: 1,
          pagesize: 1,
          list: []
        },
        {
          hasPic: false,
          hasMore: true,
          page: 1,
          pagesize: 1,
          list: []
        },
        {
          hasPic: false,
          hasMore: true,
          page: 1,
          pagesize: 1,
          list: []
        }
      ],
      remarkCustomerId: ''
    }
  },
  computed: {
    ...mapState({
      userInfo: x => x.userCenter.userInfo,
      CaseList: x => x.app.CaseList,
      CaseTableList: x => x.placeOrderForCoffee.CaseTableList,
    }),
    ...mapCaseState({
      caseTotal: x => x.caseTotal,
      choosedCase: x => x.choosedCase
    }),
    ...mapCardState({
      cardList: x => x.cardList
    }),
  },
  components: {
    topCaseInfo,
    caseTableItem,
    myCard,
    customerCard,
    noMore
  },
  created () {
    this.fromPage = sessionStorage.getItem('from')
    if (!this.userInfo.customer.MapUser || (this.userInfo.customer.MapUser && this.fromPage !== 'sales')) {
      this.topCaseInfoData.ShowSelect = true
    }
    if (this.userInfo.customer.MapUser !== '') {
      this.getForbidInfo().then((res) => {
        this.forbidList = res || []
        this.getCustomerList({
          ...this.postCustomerData
        }).then((res) => {
          if (res) {
            for (var n = 0; n < res.length; n++) {
              if (res[n].RecommendId === this.userInfo.customer.MapUser) {
                this.myRecommendUserList.push(res[n])
                res[n].showTag = true
              } else {
                res[n].showTag = false
              }
              this.data[3].list.push(res[n])
            }
          } else {
            this.data[3].hasPic = true
          }
        })
        this.getMyCouponList({
          ...this.postCouponData
        }).then((res) => {
          res.list = res.list || []
          if (res.list.length > 0) {
            for (var n = 0; n < res.list.length; n++) {
              this.data[2].list.push({
                invalid: this.returnInvalid(res.list[n], 'coupon'),
                price: parseInt(res.list[n].Price),
                title: res.list[n].CouponName,
                desc: res.list[n].Share.UseRule,
                startDate: this.toolClass.dateFormat(res.list[n].StartDate, 'yyyy年MM月dd日'),
                endDate: this.toolClass.dateFormat(res.list[n].EndDate, 'yyyy年MM月dd日'),
                totalCount: res.list[n].TotalCount,
                SentCount: res.list[n].SentCount,
                usedCount: res.list[n].UsedCount,
                CardId: res.list[n].CouponId,
                CustomerList: res.list[n].CustomerCoupon || [],
                ValidDays: res.list[n].ValidDays
              })
            }
            var count = 0
            for (var n = 0; n < this.data[2].list.length; n++) {
              count += this.data[2].list[n].price * this.data[2].list[n].totalCount - 0
            }
            this.couponTotalCount = count.toFixed(2)
          } else {
            this.data[2].hasPic = true
          }
        })
        this.getMyCardList({
          ...this.postCardData
        }).then((res) => {
          res.list = res.list || []
          if (res.list.length > 0) {
            for (var n = 0; n < res.list.length; n++) {
              this.data[1].list.push({
                invalid: this.returnInvalid(res.list[n], 'card'),
                price: parseInt(res.list[n].Price),
                title: res.list[n].CardName,
                desc: res.list[n].Share.CardUseRule,
                startDate: this.toolClass.dateFormat(res.list[n].StartDate, 'yyyy年MM月dd日'),
                endDate: this.toolClass.dateFormat(res.list[n].EndDate, 'yyyy年MM月dd日'),
                totalCount: res.list[n].TotalCount,
                SentCount: res.list[n].SentCount,
                usedCount: res.list[n].UsedCount,
                CardId: res.list[n].CardId,
                CustomerList: res.list[n].CustomerCard || []
              })
            }
            var count = 0
            for (var n = 0; n < this.data[1].list.length; n++) {
              count += this.data[1].list[n].price * this.data[1].list[n].totalCount - 0
            }
            this.cardTotalCount = count.toFixed(2)
          } else {
            this.data[1].hasPic = true
          }
        })
      })
      this.getRecommendCode().then((res) => {
        this.topCaseInfoData.recommendCode = res
      })
    } else {

    }
    this.getCaseList().then((res) => {
      this.locationMapping()
    })
  },
  methods: {
    ...mapUserCenterActions([
      'getMyCardList',
      'getMyCouponList',
      'getForbidInfo',
      'getCustomerList',
      'getRecommendCode'
    ]),
    ...actions([
      'getCaseList',
    ]),
    ...caseTableActions([
      'getCaseTableList',
    ]),
    ...mapCaseActions([
      'getCaseTotal',
      'getCaseConf',
      'changeChoosedCase'
    ]),
    ...mapCardActions(['getCardList']),
    ...mapRemarkActions(['setRemark']),
    checkCanDo () {
      const _that = this
      return this.forbidList.filter(x => x.UserId === _that.userInfo.customer.MapUser && x.ForbidType === 'coupon').length > 0
    },
    checkCanOrder () {
      const _that = this
      return this.forbidList.filter(x => x.UserId === _that.userInfo.customer.MapUser && x.ForbidType === 'goods').length > 0
    },
    toCardNumDetail (item) {
      if (this.userInfo.customer.UserTypeId === 'manager') {
        window.location.href = `${this.getUrl('cardAndCouponNum')}?id=${item.CardId}&type=card`
      }
    },
    toCouponNumDetail (item) {
      if (this.userInfo.customer.UserTypeId === 'manager') {
        window.location.href = `${this.getUrl('cardAndCouponNum')}?id=${item.CardId}&type=coupon`
      }
    },
    returnInvalid (item, type) {
      console.log(item)
      if (item.ValidDays && item.ValidDays > 0) {
        return false
      }
      for (var n = 0; n < this.forbidList.length; n++) {
        if (this.forbidList[n].UserId === this.userInfo.customer.CustomerId && this.forbidList[n].ForbidType === type) {
          return true
        }
      }
      if (item.TotalCount - 0 === item.SentCount - 0 + item.UsedCount - 0 || new Date(item.EndDate).getTime() < Date.now()) {
        return true
      }
      return false
    },
    toSalesHistory () {
      window.location.href = this.getUrl('salesRecord')
    },
    getUrl (val) {
      var url = window.location.pathname
      return url.replace('user.html', 'sales.html') + '#/' + val
    },
    showVanPicker () {
      this.showSelect = true
    },
    selectCase (val) { // 选择案场
      this.topCaseInfoData.caseName = val.CaseName
      this.topCaseInfoData.caseId = val.CaseId
      this.getCaseTableList({
        caseid: this.topCaseInfoData.caseId
      })
      this.showSelect = false
      this.changeChoosedCase({ CaseName: val.CaseName, CaseId: val.CaseId })
    },
    cutNav (index) { // 切换nav
      this.navActive = index
      // this.getList('change')
    },
    getList (param) {
      if (this.navActive === 0) {
        return
      } else {
        if (param === 'change') {
          this.data[this.navActive].page = 0
        }
        if (this.data[this.navActive].hasMore) {
        }
      }
    },
    shareCard (item) {
      let query = {
        id: item.CardId,
        type: 'card',
        sharetype: 'share',
        salesid: this.userInfo.customer.MapUser,
        random: this.random()
      }
      this.$router.push({ name: 'receive', query: query })
    },
    shareCoupon (item) {
      let query = {
        id: item.CardId,
        type: 'coupon',
        sharetype: 'share',
        salesid: this.userInfo.customer.MapUser,
        random: this.random()
      }
      this.$router.push({ name: 'receive', query: query })
    },
    random () {
      let rnd = ''
      for (let i = 0; i < 5; i++) {
        rnd += Math.floor(Math.random() * 10)
      }
      let timestamp = new Date().valueOf()
      return `${rnd}${timestamp}`
    },
    remark (item) {
      // console.log(item)
      this.showDialog = true
      this.remarkCustomerId = item.CustomerId
    },
    history (item) {
      // console.log(item)
      window.location.href = this.getUrl(`history?customerId=${item.CustomerId}`)
    },
    record (item) {
      // console.log(item)
      window.location.href = this.getUrl('getRecord') + '?name=' + item.Name + '&phone=' + item.Phone + '&id=' + item.CustomerId
    },
    searchMask () {
      window.location.href = this.getUrl('customerSearch')
    },
    locationMapping () {
      let that = this
      // that.topCaseInfoData.caseName = that.CaseList[0].CaseName
      // that.topCaseInfoData.caseId = that.CaseList[0].CaseId
      if (this.userInfo.customer.MapUser !== '') {
        wxsdk({ url: encodeURIComponent(window.location.href.split('#')[0]) }, {
          title: '城的空间',
          desc: '城的空间',
          link: `${window.location.origin}${window.location.pathname}#/mainPage/indexPage`,
          thu_image: `https://spaceofcheng.oss-cn-beijing.aliyuncs.com/indexlogo.jpg?x-oss-process=style/wxicon`
        })
        this.topCaseInfoData.caseId = this.userInfo.customer.BelongCaseId
        for (let i = 0; i < this.CaseList.length; i++) {
          if (this.CaseList[i].CaseId === this.topCaseInfoData.caseId) {
            this.topCaseInfoData.caseName = this.CaseList[i].CaseName
          }
        }
        that.getCaseTableList({
          caseid: that.topCaseInfoData.caseId
        })
        if (this.userInfo.customer.MapUser !== '') {
          that.getCaseTotal({
            caseid: that.topCaseInfoData.caseId
          })
        }
      } else {
        // console.log(this.choosedCase)
        if (this.choosedCase.CaseId) {
          that.topCaseInfoData.caseName = this.choosedCase.CaseName
          that.topCaseInfoData.caseId = this.choosedCase.CaseId
          // that.getCaseTableList({
          //   caseid: that.topCaseInfoData.caseId
          // })
          // if (this.userInfo.customer.MapUser !== '') {
          //   that.getCaseTotal({
          //     caseid: that.topCaseInfoData.caseId
          //   })
          // }
        } else {
          wxsdk({ url: encodeURIComponent(window.location.href.split('#')[0]) }, {
            title: '城的空间',
            desc: '城的空间',
            link: `${window.location.origin}${window.location.pathname}#/mainPage/indexPage`,
            thu_image: `https://spaceofcheng.oss-cn-beijing.aliyuncs.com/indexlogo.jpg?x-oss-process=style/wxicon`
          }).then(() => {
            wx.getLocation({
              type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
              success: function (res) {
                let latitude1 = res.latitude // 纬度，浮点数，范围为90 ~ -90
                let longitude1 = res.longitude // 经度，浮点数，范围为180 ~ -180。
                for (let i = 0; i < that.CaseList.length; i++) {
                  let result = that.CaseList[i].Coordinate.split(",")
                  let latitude2 = parseFloat(result[0])
                  let longitude2 = parseFloat(result[1])
                  if (that.toolClass.getGreatCircleDistance(latitude1, longitude1, latitude2, longitude2) < 500) {
                    that.topCaseInfoData.caseName = that.CaseList[i].CaseName
                    that.topCaseInfoData.caseId = that.CaseList[i].CaseId
                    that.getCaseTableList({
                      caseid: that.topCaseInfoData.caseId
                    })
                    if (this.userInfo.customer.MapUser !== '') {
                      that.getCaseTotal({
                        caseid: that.topCaseInfoData.caseId
                      })
                    }
                  }
                }
                if (!that.topCaseInfoData.caseId || !that.topCaseInfoData.caseName) {
                  that.$toast('当前位置无案场')
                  that.topCaseInfoData.caseName = '当前位置无案场'
                }
              }
            })
          })
        }
      }
    },
    beforeClose (action, done) {
      if (action === 'confirm') {
        this.setRemark({ salesId: this.userInfo.customer.MapUser, customerId: this.remarkCustomerId, remark: this.message }).then(() => {
          this.getCustomerList({
            ...this.postCustomerData
          }).then((res) => {
            this.message = null
            this.data[3].list = []
            if (res) {
              for (var n = 0; n < res.length; n++) {
                if (res[n].RecommendId === this.userInfo.customer.MapUser) {
                  this.myRecommendUserList.push(res[n])
                  res[n].showTag = true
                } else {
                  res[n].showTag = false
                }
                this.data[3].list.push(res[n])
              }
            } else {
              this.data[3].hasPic = true
            }
          })
          done()
        })
      } else {
        done()
      }
    },
    toOrders (subItem, item) {
      const _that = this
      this.getCaseConf({ caseid: subItem.CaseId }).then(res => {
        if (this.checkCanOrder() && sessionStorage.getItem('from') === 'sales') {
          _that.$toast('您的点单功能已被关闭！')
          return
        }
        if (res.Status === 1) {
          this.$router.push({ name: 'placeOrder', query: { tableid: encodeURI(subItem.TableId), tableno: encodeURI(subItem.TableNo), caseid: encodeURI(subItem.CaseId), casename: encodeURI(_that.topCaseInfoData.caseName), areaid: encodeURI(subItem.AreaId), areaname: encodeURI(item.AreaName) } })
        } else {
          _that.$toast('当前案场已歇业！')
          return
        }
      })
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import 'page.scss';
</style>
