<script setup>
import { onMounted, reactive, ref, watch } from "vue"
import border from "@/components/border.vue";
import * as echarts from 'echarts';
import mitt from "@/utils/mitt";
import { dateCangeCrderCount, orderList as getOrderList } from "@/api/index.js";
import { useAppStore } from "@/store/app.js";

const appStore = useAppStore();

const scrollBoardRef = ref(null);
const initData = (data) => {
  let arr = [];
  for (let i = 0; i < data.length; i++) {
    let calss = 'div';
    if (i % 2 != 0) {
      calss = 'div div2'
    }
    arr.push(
      [
        `<div class="${calss}">${i + 1}</div>`,
        `<div class="${calss}">${data[i].real_name || '-'}</div>`,
        `<div class="${calss}">${data[i].user_phone || '-'}</div>`,
        `<div class="${calss}">${data[i].store_name || '-'}</div>`,
        `<div class="${calss}">${data[i].user_address || '-'}</div>`,
      ]
    )
  }
  list.data = arr;
  scrollBoardRef.value?.updateRows(list.data);
}

const list = reactive({
  header: [
    `<div style='width: 100%;text-align: center; height: 100%; color: aliceblue; background: linear-gradient(rgba(0, 168, 255, 0.76), rgba(0, 84, 128, 0.73));'>序号</div>`,
    `<div style='width: 100%;text-align: center; height: 100%; color: aliceblue; background: linear-gradient(rgba(0, 168, 255, 0.76), rgba(0, 84, 128, 0.73));'>收货人</div>`,
    `<div style='width: 100%;text-align: center; height: 100%; color: aliceblue; background: linear-gradient(rgba(0, 168, 255, 0.76), rgba(0, 84, 128, 0.73));'>收货人电话</div>`,
    `<div style='width: 100%;text-align: center; height: 100%; color: aliceblue; background: linear-gradient(rgba(0, 168, 255, 0.76), rgba(0, 84, 128, 0.73));'>商品名称</div>`,
    `<div style='width: 100%;text-align: center; height: 100%; color: aliceblue; background: linear-gradient(rgba(0, 168, 255, 0.76), rgba(0, 84, 128, 0.73));'>收货人地址</div>`,
  ],
  data: [],
  //   index: true,
  // headerBGC: 'rgba(0, 168, 255, 0.76)',
  // oddRowBGC: 'rgba(91, 219, 246, 0.20)',
  // evenRowBGC: 'rgba(0, 168, 255, 0.16)',
  oddRowBGC: '',
  evenRowBGC: "",
  columnWidth: [40, 80],
  align: ['center'],
  rowNum: 7
})

initData(list);

const orderList = ref([
  {
    name: '今日订单',
    value: '0'
  },
  {
    name: '待取货订单',
    value: '0'
  },
  {
    name: '配送中订单',
    value: '0'
  },
  {
    name: '已完成订单',
    value: '0'
  },
])

watch(() => appStore.delivery, (n, o) => {
  orderList.value[0].value = n.order_count;
  orderList.value[1].value = n.pending_order_count;
  orderList.value[2].value = n.delivering_order_count;
  orderList.value[3].value = n.finished_order_count;
}, { deep: true, immediate: true })

const cOrderValue = (e) => {
  let str = e;
  if (str > 9999) str = 9999 + '';
  else str = str + '';
  str = str.split('');
  if (str.length < 4) {
    let t = 4 - str.length;
    for (let i = 0; i < t; i++) {
      str.unshift('0');
    }
  }
  str.splice(-3, 0, ',');
  return str;
}

const echartsRef = ref(null)

const initEcahrts = (yData1 = [], yData2 = [], yData3 = [], yData4 = []) => {
  let xData = ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'],
    // yData1 = [400, 410, 350, 320, 280, 340, 360, 400, 420, 410],
    // yData2 = [350, 320, 260, 240, 220, 280, 300, 360, 340, 340],
    // yData3 = [200, 260, 200, 190, 180, 220, 260, 300, 280, 300],
    // yData4 = [120, 300, 230, 240, 190, 290, 103, 456, 230, 270],
    borderData = [],
    legend = ["未取货订单", "配送中订单", "已完成订单", "小时订单数"],
    colorArr = [{
      start: "rgba(0, 168, 255,",
      end: "rgba(0, 168, 255, 1)"
    },
    {
      start: "rgba(91, 219, 246,",
      end: "rgba(91, 219, 246, 1)"
    },
    {
      start: "rgba(75, 95, 219,",
      end: "rgba(75, 95, 219, 1)"
    },
    {
      color: "rgba(91, 219, 246, 1)"
    }
    ];
  let normalColor = "#DEEBFF";
  //   let fontSize = 20;
  let seriesData = [];
  let borderHeight = 4;
  xData.forEach(element => {
    borderData.push(borderHeight);
  });
  [yData1, yData2, yData3, yData4].forEach((item, index) => {
    let obj1 = {};
    if (index < 3) {
      obj1 = {
        name: legend[index],
        type: "bar",
        stack: legend[index],
        data: item,
        barWidth: "15%",
        itemStyle: {
          normal: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: colorArr[index].start + "0.2)"
              },
              {
                offset: 0.5,
                color: colorArr[index].start + "0.4)"
              },
              {
                offset: 1,
                color: colorArr[index].end
              }
              ],
              globalCoord: false
            },
            borderWidth: 1,
            borderColor: colorArr[index].end,
          }
        }
      };
      seriesData.push(obj1);
    } else {
      let obj3 = {
        name: legend[index],
        type: "line",
        yAxisIndex: 1,
        smooth: false,
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(255,255,255, 0.8)'
        },
        symbol: "circle",
        symbolSize: 16,
        lineStyle: {
          normal: {
            width: 2
          }
        },
        itemStyle: {
          normal: {
            color: colorArr[index].color,
            borderColor: "#fff",
            borderWidth: 1
          }
        },
        data: item,
        label: {
          normal: {
            show: false
          }
        }
      };
      seriesData.push(obj3);
    }
  });
  // console.log(seriesData);
  const option = {
    backgroundColor: "rgba(0,0,0,0)",
    grid: {
      left: "3%",
      top: "12%",
      right: "12%",
      bottom: '2%',
      containLabel: true
    },
    legend: {
      show: true,
      // icon: "rect",
      orient: 'vertical', // 将图例竖直布局

      itemWidth: 16,
      itemHeight: 10,
      right: "right",
      bottom: "center",
      textStyle: {
        color: "#fff"
      },
      data: legend
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: 'rgba(18, 57, 60, .8)', //设置背景颜色
      textStyle: {
        color: '#fff'
      },
      borderColor: "rgba(18, 57, 60, .8)",
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(0, 11, 34, .4)',
        }
      },
      formatter: function (params) {
        let str = "";
        for (let i = 0; i < params.length; i++) {
          if (params[i].seriesName !== "") {
            str +=
              params[i].name +
              ':' +
              params[i].seriesName +
              '-' +
              params[i].value +
              "<br/>";
          }
        }
        return str;
      }
    },
    xAxis: [{
      type: "category",
      data: xData,
      name: '小时(工作时间)',
      nameTextStyle: {
        color: '#fff',
        fontSize: 12
      },
      axisPointer: {
        type: "shadow"
      },
      axisLabel: {
        interval: 0,
        align: 'center',
        textStyle: {
          color: normalColor,
          fontSize: 12
        }
      },
      axisLine: {
        lineStyle: {
          color: '#1C82C5'
        }
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      }
    }],
    yAxis: [{
      type: "value",
      // name: "亿千瓦时",
      // nameTextStyle: {
      //     color: normalColor,
      //     fontSize: 12
      // },
      // "min": 0,
      // "max": 50,
      axisLabel: {
        formatter: "{value}",
        textStyle: {
          color: normalColor,
          fontSize: 14
        }
      },
      axisLine: {
        lineStyle: {
          color: '#1C82C5'
        }
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: "solid",
          color: 'rgba(28, 130, 197, .3)'
        }
      }
    },
    {
      type: "value",
      // name: "%",
      // nameTextStyle: {
      //     color: normalColor,
      //     fontSize: 12
      // },
      // min: -100,
      // max: 100,
      axisLabel: {
        show: false,
        formatter: "{value}",
        textStyle: {
          color: normalColor,
          fontSize: 12
        }
      },
      axisLine: {
        lineStyle: {
          color: '#1C82C5'
        }
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false,
        lineStyle: {
          type: "dashed",
          color: "rgba(255,255,255,0.2)"
        }
      }
    }
    ],
    series: seriesData
  };

  // 基于DOM元素初始化echarts实例
  const chart = echarts.init(echartsRef.value);

  // 使用配置项显示图表
  chart.setOption(option);
}

const openList = () => {
  mitt.emit('showBusinesses')
}

const initInfo = () => {
  dateCangeCrderCount({
    areaCode: appStore.delivery_address.areaCode,
    streetCode: appStore.delivery_address.streetCode,
    courier_id: appStore.delivery_address.courier_id
  }).then(({ data }) => {
    let y1 = [], y2 = [], y3 = [], y4 = [];
    data.forEach((item) => {
      y1.push(item.pendingOrderCount);
      y2.push(item.undeliveredOrderCount);
      y3.push(item.doneOrderCount);
      y4.push(item.hourOrderCount);
    })
    setTimeout(() => {
      initEcahrts(y1, y2, y3, y4);
    })
  })
}

const pages = ref({
  areaCode: appStore.delivery_address.areaCode,
  streetCode: appStore.delivery_address.streetCode,
  courier_id: appStore.delivery_address.courier_id,
  page: 1,
  limit: 30
})
const loadOrderList = () => {
  getOrderList(pages.value).then((res) => {
    initData(res.data.currOrderList);
    orderList.value[0].value = res.data.currOrderCount;
    orderList.value[1].value = res.data.pendingOrderCount;
    orderList.value[2].value = res.data.undeliveredOrderCount;
    orderList.value[3].value = res.data.doneOrderCountQuery;
  }).catch(err => {
    console.error(err);
  })
}

onMounted(() => {
  initInfo();
  loadOrderList();
})

</script>

<template>
  <border>
    <div class="box">
      <div class="title">配送详情</div>
      <div class="body-box">
        <div class="left">
          <div class="top">
            <div class="view" v-for="(item, index) in orderList" :key="index">
              <div class="num">
                <div v-for="(t, i) in cOrderValue(item.value)" :key="i">
                  {{ t }}
                </div>
              </div>
              <div>{{ item.name }}</div>
            </div>
          </div>
          <div class="bottom echarts" ref="echartsRef"></div>
        </div>
        <div class="right">
          <div class="top">
            <div class="t-right">
              <img src="/src/assets/img/item.png" />
              <div>今日订单</div>
            </div>
            <div class="flex" @click="openList">
              <div>查看更多</div>
              <div>{{ "〉" }}</div>
            </div>
          </div>
          <dv-scroll-board
            ref="scrollBoardRef"
            :config="list"
            style="width: 100%; height: 90%"
          />
        </div>
      </div>
    </div>
  </border>
</template>

<style scoped lang="scss">
.box {
  height: 100%;
  width: 100%;
  padding: 1.25rem 1.25rem;
  font-size: 0.8rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  .title {
    width: 100%;
    background-image: url(../../../assets/img/title3.png);
    background-size: 100% 100%;
    height: 2.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: "ifonts";
    font-size: 1.2rem;
  }
  .body-box {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    .left {
      width: 60%;
      height: 100%;
      .top {
        display: flex;
        justify-content: space-evenly;
        height: 25%;
        margin-top: 1rem;
        .view {
          width: 21%;
          height: 100%;
          background-image: url(../../../assets/delivery_img/box4.png);
          background-size: 100% 100%;
          font-size: 1.2rem;
          font-family: "ifonts";
          display: flex;
          flex-direction: column;
          justify-content: space-evenly;
          .num {
            display: flex;
            justify-content: center;
            div {
              width: 1.5rem;
              height: 1.8rem;
              background-image: url(../../../assets/delivery_img/icon_num.png);
              background-size: 100% 100%;
              margin: 0.2rem;
            }
          }
        }
      }
      .bottom {
        height: 70%;
        width: 100%;
      }
    }
    .right {
      width: 38%;
      height: 95%;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: center;
      .top {
        height: 10%;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .t-right {
          display: flex;
          align-items: center;
          img {
            width: 1rem;
            height: 1rem;
            margin-right: 0.5rem;
          }
        }
        .flex {
          display: flex;
          cursor: pointer;
          div {
            margin-left: 0.5rem;
          }
        }
      }

      :deep(.div) {
        width: 100%;
        text-align: center;
        height: 100%;
        color: aliceblue;
        background: rgba(91, 219, 246, 0.2);
        white-space: nowrap; /* 防止文本换行 */
        overflow: hidden; /* 溢出部分隐藏 */
        text-overflow: ellipsis; /* 显示省略号 */
      }

      :deep(.div2) {
        background: rgba(0, 168, 255, 0.16);
      }

      :deep(.ceil) {
        padding: 0 !important;
        margin-bottom: 0.3rem;
        font-size: 0.8rem;
      }

      :deep(.header-item) {
        padding: 0 !important;
        font-size: 0.9rem;
      }
    }
  }
}
</style>
