<template>
  <div class="mainContent">
    <el-row class="order_tab">
      <el-col :span="15">
        <div class="tabList">
          <div class="tab_item" @click="changeTab(i, item.status)" :class="{ tab_item_ac: tabNum == i ? true : false }" v-for="(item, i) in tabList" :key="i">
            <div class="point" v-show="item.num">{{ item.num }}</div>
            <span>{{ item.name }}</span>
            <div class="tab_line"></div>
          </div>
        </div>
      </el-col>
      <el-col :span="9" class="search">
        <div class="header_serch">
          <div class="search_inp">
            <el-input size="small" class="inp" v-model="searchKey" placeholder="请输入手机号/姓名/地址/订单编号" @keydown.enter.native="seachEnterFun" clearable></el-input>
            <el-button size="small" style="background: #0D1E40;color:#fff" type="info" @click.stop="search" slot="append" icon="el-icon-search"></el-button>
          </div>
          <!-- 1.0.0版本暂不开发该功能 -->
          <el-button class="btn" size='small' @click="$router.push({path:'/manualCreate'})">手动发单</el-button>
        </div>
      </el-col>
    </el-row>

    <el-row class="order_list">
      <el-col :span="24" v-loading="isLoading" v-if="orderList.length">
        <order-list class="list" :list="orderList" :tabNum="tabNum"></order-list>
        <div style="text-align: center">
          <el-pagination :current-page.sync="params.pageNum" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 50, 100]" :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background>
          </el-pagination>
        </div>
      </el-col>
      <el-col class="empty-data" v-else>
        <img src="../../static/image/empty-data.png" />
        <div class="no-data">暂无订单数据</div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import bus from "../common/bus.js";
import sendOrderPopup from "./orderComponents/sendOrderPopup.vue";
import OrderList from "./orderComponents/orderList.vue";
import { getOrderList, getOrderMarker, getRefreshOrder } from "../api/order.js";
export default {
  data() {
    return {
      isLoading: false,
      total: 0,
      orderList: [],
      tabList: [
        {
          name: "新订单",
          num: 0,
          status: 0,
        },
        {
          name: "预约单",
          num: 0,
          status: 10,
        },
        {
          name: "待接单",
          num: 0,
          status: 1,
        },
        {
          name: "取货中",
          num: 0,
          status: 2,
        },
        {
          name: "配送中",
          num: 0,
          status: 3,
        },
        {
          name: "异常单",
          num: 0,
          status: -2,
        },
        {
          name: "已取消",
          num: 0,
          status: -1,
        },
      ],
      tabNum: 0,
      needTrack: false,
      orderDetailStutus: 1,
      params: {
        status: 0,
        searchType: 0,
        pageNum: 1,
        pageSize: 10,
      },
      markerNum: "",
      clickBool: false,
      timer: null,
      timer2: null,
      searchKey: "",
    };
  },
  components: {
    sendOrderPopup,
    OrderList,
  },

  created() {
    this.init();
    this.getOrder();
    this.getMarker();
    this.timer = setInterval(() => {
      this.getMarker();
      this.getRefreshOrder();
    }, 5000);
    // this.timer2 = setInterval(() => {
    //   this.getMarker();
    //   if (this.tabNum >= 2) {
    //     this.getOrder();
    //   }
    // }, 60000);
  },
  mounted() {},
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
    clearInterval(this.timer2);
    this.timer2 = null;
  },
  destroyed() {
    bus.$off("pullData");
    bus.$off("refreshData");
  },
  methods: {
    init() {
      bus.$on("pullData", (index) => {
        this.tabNum = index;
        this.params.status = this.tabList[index].status;
        this.params.pageNum = 1;
        this.orderList = [];
        Promise.all([this.getOrder(), this.getMarker()]);
      });
      bus.$on("refreshData", () => {
        console.log("执行refreshData");
        this.params.pageNum = 1;
        this.orderList = [];
        Promise.all([this.getOrder(), this.getMarker()]);
      });
    },
    seachEnterFun(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.search();
      }
    },
    search() {
      this.$router.push({
        path: "/orderSearch",
        query: {
          searchKey: this.searchKey,
        },
      });
      // this.params.pageNum = 1;
      // this.orderList = [];
      // this.getOrder();
    },
    handleSizeChange(val) {
      this.params.pageNum = 1;
      this.params.pageSize = val;
      this.orderList = [];
      this.getOrder();
    },
    handleCurrentChange(val) {
      this.params.pageNum = val;
      this.orderList = [];
      this.getOrder();
    },
    getMarker() {
      getOrderMarker().then((res) => {
        if (res.code === 200) {
          this.markerNum = res.data;
          this.tabList[0].num = res.data.toBeBillNum;
          this.tabList[1].num = res.data.appointNum;
          this.tabList[2].num = res.data.toBeReceivedNum;
          this.tabList[3].num = res.data.toBePickedNum;
          this.tabList[4].num = res.data.inDeliveryNum;
          this.tabList[5].num = res.data.exceptionNum;
          this.tabList[6].num = res.data.cancelNum;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    sendOrder() {
      this.$refs.sendOrderPopup.init();
    },
    changeTab(i, status) {
      this.tabNum = i;
      this.params.status = status;
      this.orderList = [];
      this.params.pageNum = 1;
      this.getOrder();
    },
    getOrder() {
      let _this = this;
      var minute = 1000 * 60;
      var hour = minute * 60;
      var day = hour * 24;
      this.isLoading = true;
      getOrderList(this.params).then((res) => {
        this.isLoading = false;
        if (res.code == 200) {
          this.orderList = [];
          this.total = res.data.totalNums || 0;
          this.params.pageNum = res.data.pageNum;
          res.data.data.forEach((element) => {
            element.takeTimeTxt = this.$tool.timeago(
              new Date(element.sendTime).getTime()
            );
            if (element.exceptTime && element.delayTime) {
              element.timeTxt = _this.$tool.eosFormatTime2(
                element.exceptTime,
                element.delayTime
              );
            } else {
              element.timeTxt = "";
            }
            this.orderList.push(element);
          });
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    getRefreshOrder() {
      let orderIds = this.orderList.map((v) => {
        return v.id;
      });
      let params = {
        orderIds: orderIds,
        status: this.tabList[this.tabNum].status,
      };
      getRefreshOrder(params).then((res) => {
        if (res.code === 200) {
          let newList = res.data.newList;
          let deliveryList = res.data.deliveryList;
          if (!newList.length && !deliveryList.length) return;
          // 根据exceptTime判断是新订单还是预约单
          let normalList = newList
            .filter((v) => {
              return !v.exceptTime;
            })
            .map((item) => {
              item.buttonStatus = 0;
              return item;
            });

          let appointList = newList
            .filter((v) => {
              return v.exceptTime;
            })
            .map((item) => {
              item.buttonStatus = 10;
              item.exceptTime = this.$tool.getFormatDate(
                item.exceptTime * 1000
              );
              return item;
            });
          // tabNum  0 是新订单 1是预约单
          if (this.tabNum === 1) {
            this.orderList = this.orderList.concat(appointList);
          } else if (this.tabNum === 0) {
            this.orderList = this.orderList.concat(normalList);
          } else {
            this.orderList = this.orderList.concat(newList);
          }
          console.log("1111", deliveryList);
          deliveryList.forEach((item) => {
            this.orderList = this.orderList.filter((v) => {
              console.log("2222", v, item);
              return v.id !== item;
            });
          });
          this.total = this.orderList.length;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped="scoped">
/deep/ .el-input__inner {
  padding-right: 30px;
}

.mainContent {
  width: 100%;
  height: 100%;
  .order_tab {
    width: 100%;
    height: 74px;
    background: #fff;

    .tabList {
      display: flex;
      justify-content: space-around;
      width: 100%;
      padding-top: 20px;
      padding-left: 36px;
      box-sizing: border-box;
      overflow-x: auto;

      .tab_item {
        font-size: 16px;
        font-weight: 500;
        color: #b1b1b1;
        position: relative;
        text-align: center;
        cursor: pointer;

        .tab_line {
          width: 58px;
          height: 6px;
          background: #fff;
          border-radius: 3px;
          margin-top: 15px;
        }

        .point {
          width: 16px;
          height: 16px;
          border-radius: 50%;
          background: #f74141;
          font-size: 12px;
          font-weight: 400;
          color: #ffffff;
          position: absolute;
          top: -5px;
          right: -10px;
          text-align: center;
          line-height: 16px;
        }
      }

      .tab_item_ac {
        color: #fc7200;

        .tab_line {
          background: #fc7200;
        }
      }
    }
    .search {
      display: flex;
      justify-content: flex-end;
      .header_serch {
        width: 80%;
        height: 74px;
        padding-right: 25px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .Manual {
          width: 118px;
          height: 44px;
          background: #fc7200;
          border-radius: 6px;
          font-size: 16px;
          font-weight: 500;
          color: #ffffff;
          text-align: center;
          line-height: 44px;
          margin-left: 18px;
        }
        .btn {
          background: #fc7200;
          border-color: #fc7200;
          color: #fff !important;
          margin-left: 10px;
        }
        .search_inp {
          width: 380px;
          height: 44px;
          display: flex;
          align-items: center;
          position: relative;

          .inp {
            width: 100%;
            // height: 44px;
            border: none;
          }

          .btn {
            font-size: 22px;
            position: absolute;
            right: 15px;
          }
        }
      }
    }
  }

  .order_list {
    width: 100%;
    height: calc(100vh - 180px);
    margin-top: 10px;
    .list {
      position: relative;
      height: calc(100vh - 210px);
      overflow: hidden;
    }
    .empty-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background-color: #fff;
      height: 100%;

      img {
        width: 349px;
        height: 222px;
      }
      .no-data {
        color: #9EA7B7;
      }
    }
  }
}
</style>
