<template>
  <div class="mainContent">
    <el-row class="order_tab">
      <el-col class="tab-list-wrap" :span="12">
        <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="12" class="search">
        <div class="header_serch">
          <div class="inp-content">
            <span>门店</span>
            <el-select size="small" @change="changeShopIds" v-model="searchShopIdStr" multiple collapse-tags filterable clearable placeholder="默认全部门店">
              <el-option v-for="i in shopList" :key="i.id" :label="i.name" :value="i.id"></el-option>
            </el-select>
          </div>
          <!-- <div class="inp-content">
            <span>订单来源</span>
            <el-select size="small" v-model="form.searchKeyType" slot="prepend" placeholder="请选择关键字">
              <el-option label="流水号" value="1"></el-option>
            </el-select>
          </div> -->

          <el-input size="small" class="inp input-with-select" v-model="params.searchKey" placeholder="请输入关键字" @keydown.enter.native="seachEnterFun" clearable>
            <el-select v-model="params.searchKeyType" slot="prepend" placeholder="请选择关键字">
              <el-option label="流水号" value="1"></el-option>
              <el-option label="手机号" value="2"></el-option>
              <el-option label="姓名" value="3"></el-option>
              <el-option label="地址" value="4"></el-option>
              <!-- <el-option label="订单号" value="5"></el-option> -->
              <el-option label="外卖订单号" value="6"></el-option>
            </el-select>
          </el-input>
          <el-button size="small" style="background: #0D1E40;color:#fff" type="info" @click.stop="search" slot="append" icon="el-icon-search"></el-button>
          <!-- 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>
    <!-- usb自动打印 -->
    <usb-auto-print @printOver="printOver" :printNum="printNum" :printData="printData"></usb-auto-print>
  </div>
</template>

<script>
import bus from "../common/bus.js";
import sendOrderPopup from "./orderComponents/sendOrderPopup.vue";
import OrderList from "./orderComponents/orderList.vue";
import UsbAutoPrint from "../common/UsbAutoPrint";

import {
  getOrderList,
  getOrderMarker,
  getRefreshOrder,
  getPrintOrderInfos,
} from "../api/order.js";
import { getShopList } from "../api/shop";
export default {
  name: "HomeIndex",
  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,
        },
        {
          name: "近三日订单",
          num: 0,
          status: 94,
        },
      ],
      tabNum: 0,
      needTrack: false,
      orderDetailStutus: 1,
      searchShopIdStr: [],
      params: {
        status: 0,
        searchType: 0,
        searchKey: "",
        searchKeyType: "1",
        pageNum: 1,
        pageSize: 10,
      },
      markerNum: "",
      clickBool: false,
      timer: null,
      timer2: null,
      shopList: [],
      printNum: 0,
      printData: {},
      printList: [],
    };
  },
  components: {
    sendOrderPopup,
    OrderList,
    UsbAutoPrint,
  },
  watch: {
    "$store.state.userInfo": {
      handler(newVal, oldVal) {
        if (newVal.memberType !== 1) {
          this.getShopList();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    if (this.$route.params.tabNum === 2) {
      this.changeTab(2, 1);
    }
    if (this.$route.params.tabNum === 1) {
      this.changeTab(1, 10);
    }
    this.init();
    this.getOrder();
    this.getMarker();
    this.timer = setInterval(() => {
      this.getMarker();
      // 近三日不用插入或者删除数据
      if (this.tabNum !== 7) {
        this.getRefreshOrder();
      }
    }, 5000);
  },
  mounted() {
    this.usbPrint();
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
    clearInterval(this.timer2);
    this.timer2 = null;
  },
  destroyed() {
    bus.$off("pullData");
    bus.$off("refreshData");
  },
  methods: {
    printOver() {
      this.printList = this.printList.slice(1);
    },
    usbPrint() {
      // usb自动打印新订单、预约单
      let orderIdStr = "34441,34442,34443";
      getPrintOrderInfos({ orderIdStr }).then((res) => {
        console.log("返回内容：", res);
        if (res.code === 200 && res.data.length) {
          let len = this.printList.length;
          this.printList = this.printList.concat(res.data);
          if (!len) {
            this.printOver();
          }
        }
      });
    },
    changeShopIds() {
      this.params.searchShopIdStr = String(this.searchShopIdStr);
      localStorage.setItem("searchShopIdStr", this.params.searchShopIdStr);
      this.params.pageNum = 1;
      this.orderList = [];
      this.getOrder();
      this.getMarker();
    },
    getShopList() {
      getShopList().then((res) => {
        if (res.code === 200) {
          this.shopList = res.data;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    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,
      //   },
      // });
      //
      if (!this.params.searchKey) {
        this.params.pageNum = 1;
        this.orderList = [];
        this.getOrder();
      } else {
        this.changeTab(7, 94);
      }
    },
    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({ searchShopIdStr: this.params.searchShopIdStr }).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) {
      // 切换状态不是近三天，搜索输入框清空
      if (i !== 7) {
        this.params.searchKey = "";
      }
      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;
      this.params.searchShopIdStr = String(this.searchShopIdStr);
      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() {
      if (this.params.status === 94) {
        return;
      }
      let orderIds = this.orderList.map((v) => {
        return v.id;
      });
      let params = {
        orderIds: orderIds,
        status: this.tabList[this.tabNum].status,
        searchShopIdStr: this.params.searchShopIdStr,
      };
      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 = appointList.concat(this.orderList);
          } else if (this.tabNum === 0) {
            this.orderList = normalList.concat(this.orderList);
          } else {
            this.orderList = newList.concat(this.orderList);
          }
          deliveryList.forEach((item) => {
            this.orderList = this.orderList.filter((v) => {
              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 {
    display: flex;
    width: 100%;
    min-width: 550px;
    overflow-x: auto;
    height: 74px;
    background: #fff;
    .tab-list-wrap {
      min-width: 550px;
      .tabList {
        display: flex;
        justify-content: space-around;
        width: 100%;
        padding-top: 26px;
        // padding-left: 36px;
        // box-sizing: border-box;

        .tab_item {
          flex-shrink: 0;
          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;
      min-width: 700px;
      .header_serch {
        height: 74px;
        padding-right: 25px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .inp-content {
          display: flex;
          align-items: center;
          font-size: 15px;
          color: #999;
          span {
            flex-shrink: 0;
            margin-right: 5px;
          }
        }
        .inp {
          width: 120px;
          margin-left: 15px;
          /deep/ .el-input-group__prepend {
            background: #fff;
            .el-input__inner {
              width: 114px;
            }
          }
          /deep/ .el-input__inner {
            width: 200px;
          }
        }
        .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;

          .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>
