<template>
  <div id="myOrder">
    <!-- <van-tabs class="tabs" v-model="activeTab">
      <van-tab title="全部">
        <my-order-list/>
      </van-tab>
      <van-tab title="已开单">
      </van-tab>
      <van-tab title="已发货">
      </van-tab>
      <van-tab title="已完成">
      </van-tab>
      <van-tab title="已取消">
      </van-tab>
    </van-tabs> -->
    <van-tabs class="tabs" v-model="activeTab"
      :line-width="40"
      :line-height="2"
      v-if="tabsTitle.length"
      swipeable>
      <van-tab
        v-for="(item, index) in tabsTitle"
        :key="index"
        :title="item.title">
        <my-order-list :more-search-info="moreSearchInfo" :ref="item.name" :orderTypeCode="item.orderTypeCode" :activeTab="activeTab" @orderItemAction="orderItemAction"/>
      </van-tab>
    </van-tabs>
    <high-search :more-search-info="moreSearchInfo" v-model="moreSearchShow" @onsearch="moreSearchConfirm" @onclean="moreSearchClean"/>
  </div>
</template>

<script>
import myOrderList from './myOrderList.vue'
// import HighSearch from './components/HighSearch.vue'
import HighSearch from './components/HighSearchNewDelete.vue'
import {getEmployeeOrgQueryList, getConsignorSetList} from '@/api/common'
import {getFormateDate} from '@/utils/common'
import { bridge } from "@/utils";
const allTabsTitle = [
  {title: '全部', name: 'all', orderTypeCode: ''},
  {title: '待发货', name: 'billing', orderTypeCode: '100'},
  {title: '待收货', name: 'ship', orderTypeCode: '220'},
  {title: '已签收', name: 'carryOut', orderTypeCode: '400'},
  {title: '已取消', name: 'cancel', orderTypeCode: '110'}
]
export default {
  components: {
    myOrderList,
    HighSearch
  },
  data() {
    return {
      tabsTitle: [],
      moreSearchShow: false,
      activeTab: 'all',
      isFirst: false,
      moreSearchInfo: {
        supplier: [], // 供应商
        consignor: [], // 货主
        goods: '', // 商品
        client: [], // 客户
        orderNo: '',
        time: {
          start: getFormateDate(new Date(), 'yyyy-MM-dd'),
          end: getFormateDate(new Date(), 'yyyy-MM-dd')
        }
      }
    }
  },
  computed: {
    linkInfo () {
      return this.$store.state.linkInfo
    },
    routKey() {
      return this.$route.path
    },
    searchTime() {
      let time = this.time.start + '/' + this.time.end
      return time
    }
  },
  activated() {
    // let _this = this
    // 设置标题栏关闭返回按钮
    this.$store.commit('setNavBar', {
      show: true,
      leftArrow: true,
      rightIcon: true,
      title: '我的订单',
      leftText: '',
      leftClick: this.closeAppPage,
      rightClick: this.onMoreSearch
    })
    // 给window添加一个popstate事件，拦截返回键，执行this.onBrowserBack事件，addEventListener需要指向一个方法
    window.addEventListener('popstate', this.onBrowserBack, false)
  },
  deactivated() {
    // 当页面销毁必须要移除这个事件，vue不刷新页面，不移除会重复执行这个事件
    window.removeEventListener('popstate', this.onBrowserBack, false)
  },
  mounted() {
    // this.moreSearchShow = true
    // this.getConsignorPostData()
    // this.tabsTitleData()
    this.moreSearchShow = true
  },
  destroyed() {
  },
  methods: {
    // 查询是否货主为单个
     getConsignorPostData() {
      let _this = this
      let data = {
        'attr': {
            'empid': this.linkInfo.userId
        },
        'filters': [
          {
            key: 'companyname',
            opt: 'LIKE',
            type: 'S',
            value: ''
          }
        ],
        'logic': 'or',
        'sort': 'desc',
        'orderby': 'createon',
        'pageNum': 1,
        'pageSize': 10
      }
      getConsignorSetList(data).then(rt => {
        if (rt.code === 200) {
          // this.postDataList = rt.data.list
          if (rt.data.length !== 1) {
            this.moreSearchShow = true
          } else if (rt.data.length === 1) {
            this.moreSearchInfo.consignor.push(this.postDataListAction(rt.data[0]))
            this.getEmployeeOrgPostData(rt.data[0])
          } else if (rt.data.length === 0) {
            _this.$toast('暂无货主！')
          }
        } else {
          _this.$toast(rt.message)
        }
      }).catch(e => {
        _this.$toast('列表获取失败')
      })
    },
    postDataListAction(item) {
      const removeItem = item
      removeItem.cellId = item.id + item.erp_user
      return item
    },
    // 获取供应商
    getEmployeeOrgPostData(item) {
      let _this = this
      const companyList = []
      const removeItem = {
        'length': '100',
        'attr': {
            'empid': this.linkInfo.userId + ',1',
            'userid': item.erp_user,
            'sysname': item.sysname,
            'companyname': item.companyname
        },
        'dbName': '',
        'start': '1'
      }
      companyList.push(removeItem)
      let data = {
        list: companyList
      }
      getEmployeeOrgQueryList(data).then(rt => {
        if (rt.code === 200) {
          // this.postDataList = rt.data
          if (rt.data.length !== 0 && rt.data.length > 1) {
            this.moreSearchShow = true
          } else if (rt.data.length === 1) {
            this.moreSearchInfo.supplier = rt.data
            this.getClienPostData(item,rt.data[0])
          } else if (rt.data.length === 0) {
            this.moreSearchShow = true
          }
        } else {
          _this.$toast(rt.message)
        }
      }).catch(e => {
        _this.$toast('列表获取失败')
      })
    },
    // 判断客户是否为一个
    getClienPostData(consignorModel,clienItem) {
      let _this = this
      const companyList = []
      const removeItem = {
        'beforeP': consignorModel.db_source,
        'middleP': process.env.appRealDb,
        'afterP': [clienItem.org],
        'saler': consignorModel.erp_user,
        'companyname': consignorModel.companyname,
        'companynameId': consignorModel.id
      }
      companyList.push(removeItem)
      let data = {
        'customer': _this.keywords,
        'list': companyList,
        'start': _this.currentPage,
        'length': _this.pageSize
      }
      _this.loading = true
      getOrderCustomerSetList(data).then(rt => {
        if (rt.code === '1') {
          if (rt.data.length !== 0 && rt.data.length > 1) {
            this.moreSearchShow = true
          } else if (rt.data.length === 1) {
            this.moreSearchInfo.client = rt.data
            this.moreSearchConfirm(this.moreSearchInfo)
          } else if (rt.data.length === 0) {
            this.moreSearchShow = true
          }
        } else {
          _this.$toast(rt.msg)
        }
      }).catch(e => {
        _this.$toast('列表获取失败')
      })
    },
    // 单个发票点击事件
    orderItemAction(model) {
      // console.log(model)
      switch (true) {
        case model.actionType === 'invoice':
          // 查看发票
          this.gotoOrderInvoice(model)
          break
        case model.actionType === 'logistics':
          // 查看物流
          this.openPager('logisticsDetail')
          break
        case model.actionType === 'clearance':
          // 清货单
          this.gotoOrderClearance(model)
          break
        case model.actionType === 'details':
          // 订单详情
          this.gotoOrderDetail(model)
          break
      }
    },
    openPager(path) {
      this.$router.push({
        path: path,
        query: this.$store.state.linkInfo
      })
    },
    // 查看订单详情
    gotoOrderDetail (model) {
      this.$router.push({
        path: '/orderDetail',
        query: model
      })
    },
    // 查看发票
    gotoOrderInvoice (model) {
      // console.log(window.location.href.split('?')[1])
      this.$router.push({
        path: '/orderInvoice',
        query: model
      })
    },
    // 查看 清货单
    gotoOrderClearance(model) {
      this.$router.push({
        path: '/clearance',
        query: Object.assign(this.$store.state.linkInfo, model)
      })
    },
    onBrowserBack() {
      if (this.moreSearchShow) {
        this.moreSearchShow = false
        return
      }
      this.$router.go(-1)
    },
    onSearch() {

    },
    onMoreSearch() {
      this.moreSearchShow = !this.moreSearchShow
      if (this.moreSearchShow) {
        window.history.pushState(null, null, document.URL)
      }
    },
    // 高级搜索查询
    moreSearchConfirm(data) {
      this.moreSearchInfo = JSON.parse(JSON.stringify(data))
      if (this.tabsTitle.length === 0) {
        this.isFirst = true
      } else {
        this.isFirst = false
      }
      this.tabsTitleData()
      this.$nextTick(() => {
        this.activeTab = 'all'
        // console.log(Object.keys(this.$refs))
        // this.$refs.all[0].httpAction(this.moreSearchInfo)
        if (!this.isFirst) {
          this.isFirst = true
          this.$EventBus.$emit('myOrderMoreSearch', this.moreSearchInfo)
        }
      })
    },
    // 高级搜索取消
    moreSearchClean(data) {
      console.log(this.moreSearchInfo)
      this.moreSearchInfo = JSON.parse(JSON.stringify(data))
      this.$EventBus.$emit('myOrderMoreSearch', this.moreSearchInfo)
      this.tabsTitle = []
      this.isFirst = false
      this.activeTab = 'all'
    },
    /// 处理tabsTitle
    tabsTitleData() {
      this.tabsTitle = []
      for (let i = 0; i < allTabsTitle.length; i++) {
        let dic = allTabsTitle[i]
        this.tabsTitle.push(dic)
      }
    },
    closeAppPage() {
      console.log('关闭页面')
      bridge.closeWindow_c()
    }
  }
}
</script>

<style lang="scss" scoped>
  #myOrder {
    height: 100%;
    .tabs {
      height: calc(100vh - 46px);
      /deep/ .van-tab {
      max-width: 23%;
      }
      /deep/ .van-tab__pane {
        height: calc(100vh - 90px);
      }
    }
  }
</style>
