<template>
  <div id="todoList">
    <form class="search-form" action="/">
      <van-icon name="bars" size="24" v-show="leftShow"
        @click="leftMenuControl"
        class="search-left"/>
      <van-search
        readonly
        v-model="moreSearchInfo.title"
        :placeholder="timeFieldReplacementAction(moreSearchInfo.startDate)+'/'+timeFieldReplacementAction(moreSearchInfo.endDate)"
        shape="round"
        @click="moreSearch"
        @search="onSearch"
        style="flex: 1"
      />
      <div class="search-action">
        <span @click="onSearch">搜索</span>
        <span @click="moreSearch">高级</span>
<!--        <span @click="moreSearch">高级</span>-->
      </div>
    </form>
    <van-tabs
      :sticky="false"
      :swipeable="swipeable"
      :swipe-threshold="5"
      :line-height="'2px'"
      v-model="activeTab"
      :title-active-color="'#1989fa'"
    >
      <van-tab
        v-for="(item, index) in tabslists"
        :key="index"
        :title="item"
      >
        <div class="tab-list h100" :class="{'tab-listBottom46': (activeTab == 1 || activeTab == 2)}">
          <!-- 客户 -->
          <overview
            v-show="activeTab === 0"
            :clientInfo="moreSearchInfo"
            @itemClickCus="itemClickCus"
          />
          <!-- 订单 -->
          <order-item
            v-show="activeTab === 1"
            ref="order"
            :clientmodel="clientmodel"
            :clientInfo="moreSearchInfo"
            @itemClickOrder="itemClickOrder"
            @orderSwipeableAction="orderSwipeableAction"
          />
          <!-- 商品信息 -->
          <goods-item
            ref="goods"
            v-show="activeTab === 2"
            :clientInfo="moreSearchInfo"
            :ordermodel="ordermodel"
            @itemClickGood="itemClickGood"
            @goodsSwipeableAction="goodsSwipeableAction"
          />
        </div>
      </van-tab>
    </van-tabs>
    <p class="totalCount" v-show="activeTab == 1">
      <van-button @click="orderClick" style="font-size:14PX;float: left;height: 100%;" type="info">{{orderBtnTitle}}</van-button>
      金额合计 :
      <span class="font-red font-bold">{{orderAmount}} 元</span>
    </p>
    <p class="totalCount" v-show="activeTab == 2">
      <van-button @click="commodityClick" style="font-size:14PX;float: left;height: 100%;" type="info">{{commodityBtnTitle}}</van-button>
      金额合计 :
      <span class="font-red font-bold">{{commodityAmount}} 元</span>
    </p>
    <approval-search-detail ref="search" v-model="moreSearchShow" @onsearch="moreSearchStart" @onclean="moreSearchClean" />
    <van-popup
      v-model="leftMenuShow"
      position="left"
      :style="{ width: '70%',height: '100%' }">
      <div class="userInfoLayout">
        <van-image
          round
          width="75px"
          height="75px"
          :src = "userPhotoDefault"
          style="box-shadow: 1px 1px 2px #888888;"
        />
        <div style="margin-top: 10px">{{userName}}</div>
      </div>
      <van-divider style="margin-top: 20px;margin-bottom: 10px"/>
      <van-cell title="修改密码" is-link @click="changePsw"/>
      <van-button class="sign_out" @click="signOutShowAction" type="info">退 出 登 录</van-button>
    </van-popup>
    <van-dialog
      v-model="signOutShow"
      title="提示"
      @confirm="signOutAction"
      show-cancel-button>
      确定退出登录吗？
    </van-dialog>
  </div>
</template>

<script>

import Container from '@/components/Container.vue'
import Overview from '@/views/todo/Overview/Overview.vue'
import OrderItem from '@/views/todo/Order/OrderItem.vue'
import GoodsItem from '@/views/todo/Goods/GoodsItem.vue'
// import Overview from '@/views/todo/components/CusItem.vue'
// import OrderItem from '@/views/todo/components/OrderItem.vue'
// import GoodsItem from '@/views/todo/components/GoodsItem.vue'
import ApprovalSearchDetail from '@/components/approval/ApprovalSearchDetail.vue'
import {getTodoList} from '@/api/todo'
import { getFormateDate } from '@/utils/common'
import { Dialog } from 'vant'
import { numFormat, AmountNumFormat } from '@/utils/common'
export default {
  name: 'TodoList',
  components: {
    ApprovalSearchDetail,
    Container,
    Overview,
    OrderItem,
    GoodsItem
  },
  data() {
    return {
      signOutShow: false,
      activeTab: 0,
      leftShow: true,
      list: [],
      tabslists: ['订单汇总'],
      loadingStatus: 1,
      isRefreshing: false,
      loading: false,
      finished: false,
      error: false,
      moreSearchShow: false,
      moreSearchInfo: {
        startDate: getFormateDate(new Date(), 'yyyy.MM.dd'),
        endDate: getFormateDate(new Date(), 'yyyy.MM.dd'),
        EDate: getFormateDate(new Date(), 'yyyyMMdd'),
        SDate: getFormateDate(new Date(), 'yyyyMMdd'),
        // SDate: '',
        CustID: '',
        SODoc: '',
        PrnSo: ''
      },
      currentPage: '1',
      pageSize: '20',
      todoList: [],
      detailInfo: {
        type: 1,
        processInstId: '',
        reqUserId: '',
        processDefId: ''
      },
      userId: this.$route.query.userId,
      sysUserId: this.$route.query.sysUserId,
      orderBtnTitle: '含税',
      orderAmount: '',
      orderHttpAmount: '',
      commodityBtnTitle: '含税',
      commodityAmount: '',
      commodityHttpAmount: '',
      leftMenuShow: false,
      userName: this.$route.query.userName,
      userPhotoDefault: require('@/assets/img/icon_start-1.png'),
      clientmodel: {}, // 选中的客户
      ordermodel: {}, // 选中的订单
      swipeable: true, // table 是否滑动
      orderPopup: false,
      goodsPopup: false
    }
  },
  mounted() {
    // 设置标题栏关闭返回按钮
    this.$store.commit('setNavBar', {
      show: false,
      leftArrow: false
    })
    if (this.$route.query.leftShow === 'show') {
      this.leftShow = true
    } else {
      this.leftShow = false
    }
    // 给window添加一个popstate事件，拦截返回键，执行this.onBrowserBack事件，addEventListener需要指向一个方法
    window.addEventListener("popstate", this.onBrowserBack, false);
  },
  destroyed() {
    // 当页面销毁必须要移除这个事件，vue不刷新页面，不移除会重复执行这个事件
    window.removeEventListener("popstate", this.onBrowserBack, false);
  },
  methods: {
    onBrowserBack() {
      // 这里写点击返回键时候的事件
      // 比如判断需求执行back()或者go(-2)或者PopupShow=false隐藏弹框
      // alert(this.swipeable)
      if (this.leftMenuShow) {
        this.leftMenuShow = false
        return
      }
      if (this.moreSearchShow) {
        // this.$refs.search.postShow = false
        this.moreSearchShow = false
        // console.log(this.$refs.search)
        return
      }
      if (!this.swipeable) {
        // console.log(this.$refs.order)
        if (this.orderPopup) {
          this.$refs.order[1].show = false
          return
        }
        // alert(this.$refs.goods[2].show)
        if (this.goodsPopup) {
          this.$refs.goods[2].show = false
          return
        }
      }else{
        // back()
        this.$router.go(-1)
        return
      }
      // go(-2)
    },
    /// 金额转换
    numFormat(num) {
      num = Number(num)
      var c = (num.toString().indexOf ('.') !== -1) ? num.toLocaleString() : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
      return c
    },
    // 禁用开启 tab滑动
    orderSwipeableAction(show){
      this.swipeable = !show
      this.orderPopup = show
      if (show) {
        // 按需使用：A→B→C就需要页面一进来的时候，就添加一个历史记录
        window.history.pushState(null, null, document.URL);
      }
    },
    goodsSwipeableAction(show){
      this.swipeable = !show
      this.goodsPopup = show
      if (show) {
        // 按需使用：A→B→C就需要页面一进来的时候，就添加一个历史记录
        window.history.pushState(null, null, document.URL);
      }
    },
    //
    signOutAction() {
      this.$router.push({path: '/login', query: ''})
    },
    // 退出登录
    signOutShowAction() {
      this.signOutShow = true
      // Dialog.confirm({
      //   title: '提示',
      //   message: '确定退出登录吗？'
      // }).then(() => {
      //   this.$router.push({path: '/login', query: ''})
      // }).catch(() => {
      //   // on cancel
      // });
    },
    // 切换订单总计含税无税金额
    orderClick() {
      if (this.orderBtnTitle === '无税') {
        this.orderBtnTitle = '含税'
        // this.orderAmount = '375,990.80'
        this.orderAmount = AmountNumFormat(this.clientmodel.TotalValue)
      } else {
        this.orderBtnTitle = '无税'
        // this.orderAmount = '365,350.80'
        this.orderAmount = AmountNumFormat(this.clientmodel.NetValue)
      }
    },
    // 切换商品总计含税无税金额
    commodityClick() {
      if (this.commodityBtnTitle === '无税') {
        this.commodityBtnTitle = '含税'
        // this.commodityAmount = '375,990.80'
        this.commodityAmount = AmountNumFormat(this.ordermodel.NetValue)
      } else {
        this.commodityBtnTitle = '无税'
        // this.commodityAmount = '365,350.80'
        this.commodityAmount = AmountNumFormat(this.ordermodel.NetValueWithoutTax)
      }
    },
    // 高级页面状态
    moreSearch() {
      this.moreSearchShow = !this.moreSearchShow
      if (this.moreSearchShow) {
        window.history.pushState(null, null, document.URL);
      }
    },
    moreSearchStart(data) {
      this.activeTab = 0
      this.tabslists = ['订单汇总']
      this.moreSearch()
      this.moreSearchInfo = JSON.parse(JSON.stringify(data))
    },
    onSearch() {
      this.activeTab = 0
      this.tabslists = ['订单汇总']
      this.moreSearchInfo = {
        startDate: getFormateDate(new Date(), 'yyyy.MM.dd'),
        endDate: getFormateDate(new Date(), 'yyyy.MM.dd'),
        EDate: getFormateDate(new Date(), 'yyyyMMdd'),
        SDate: getFormateDate(new Date(), 'yyyyMMdd'),
        CustID: '',
        SODoc: '',
        PrnSo: ''
      }
    },
    moreSearchClean(data) {
      // console.log('高级搜索')
      this.moreSearchInfo = JSON.parse(JSON.stringify(data))
      // this.moreSearch()
      // console.log(this.moreSearchInfo)
    },
    leftMenuControl() {
      this.leftMenuShow = !this.leftMenuShow
      if (this.leftMenuShow) {
        window.history.pushState(null, null, document.URL);
      }
    },
    openDetail(data) {
      this.detailInfo.processInstId = data.processInstID
      // TODO 缺少制单人ID
      this.detailInfo.reqUserId = data.creatorName
      this.detailInfo.processDefId = data.processDefId
      // 进入详情
      this.$router.push({path: '/approvalMainDetail', query: this.detailInfo})

      // this.$router.push({name: 'todoDetail', params: data})
    },
    /// 选中客户
    itemClickCus (clientModel) {
      this.clientmodel = clientModel
      this.orderBtnTitle = '含税'
      this.orderAmount = AmountNumFormat(this.clientmodel.TotalValue)
      console.log(clientModel)
      if (this.tabslists.indexOf('订单列表') === -1) {
        this.tabslists.push('订单列表')
      }
      this.$nextTick(() => {
        this.activeTab = 1
      })
      // console.log(111)
    },
    itemClickOrder (ordermodel) {
      this.ordermodel = ordermodel
      this.commodityBtnTitle = '含税'
      this.commodityAmount = AmountNumFormat(this.ordermodel.NetValue)
      if (this.tabslists.indexOf('订单商品') === -1) {
        this.tabslists.push('订单商品')
      }
      this.$nextTick(() => {
        this.activeTab = 2
      })
    },
    itemClickGood () {
    },
    // 时间-替换.
    timeFieldReplacementAction(data) {
      let reg = new RegExp('-','g')//g代表全部
      return data.replace(reg,'.')
      // return data
    },
    changePsw() {
      this.$router.push({path: '/changePassword',
        query: {
          userId: this.userId
        }
      })
    },
    /// 判断数值是否为空
    isJudgeStrNull(val) {
      if (val !== null && val !== undefined && val !== '') {
        return true
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
#todoList{
  height: calc(100%);
  /deep/ .van-tabs{
    height: calc(100% - 54px);
    &.flex1{
      height: auto;
      overflow: hidden;
    }
    .van-tabs__content{
      height: calc(100% - 44px);
      .van-tab__pane{
        height: 100%;
      }
    }
  }
  .tab-listBottom46{
    height: calc(100% - 47px);
  }
  .van-pull-refresh{
    min-height: 500px;
  }
  .search-form {
    height: 54px;
    position: relative;
    padding-right: 80px;
    background: #FFFFFF;
    display: flex;

    .search-left {
      height: 100%;
      line-height: 54px;
      padding-left: 10px
    }

    .search-action {
      position: absolute;
      top: 0;
      right: 0;
      width: 80px;
      line-height: 54px;
      color: #323233;
      font-size: 16px;
      display: flex;

      span {
        flex: 1;
      }
    }
  }
  .list-amount {
    padding: 10px;
    height: 20px;
    line-height: 20px;
  }
  .red-tips {
    color: #fb1c1c;
    font-weight: bold;
    margin: 0 8px;
  }
  .totalCount {
    font-size: 16px;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 1.22667rem;
    margin: 0;
    line-height: 1.22667rem;
    text-align: center;
    background-color: #fff;
    border-top: 0.02667rem solid #ddd;
  }
  .chooseTime{
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
  }

  .userInfoLayout{
    margin-top: 60px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .sign_out{
    margin: 10%;
    border-radius: 23px;
    top:200px;
    width: 80%;
    background-color: $main1;
    font-size: 14PX;
  }
  .van-dialog{
    font-size: 14PX;
    text-align: center;
    // .van-dialog__header{
      // font-weight: bold;
    // }
  }
}
</style>
