<template>
  <div class="home-dashboard-outware" :class="heightType == 'auto' ? 'flx-1' : ''" ref="homeDashboardOutwareRef">
    <el-tabs
      v-model="tabsActive"
      type="border-card"
      class="h-full"
      stretch
      v-loading="loading"
      @tab-remove="handleRemoveTabs"
      @tab-click="handleClickTab"
    >
      <el-tab-pane
        :label="$t('business.home.outwareOverview.index')"
        name="index"
        class="h-full"
        :closable="false"
        :style="tabStyle"
      >
        <div class="outware-dashboard flx-justify-between">
          <div class="statistic-card is-current" ref="statisticCardMoveRef"></div>
          <div
            class="statistic-card flx-center flx-1"
            :class="{ 'is-show': statusTabs == 0 }"
            :ref="(el:any) => setItemRef(el, '0')"
            @click="handleClickMiniTab(0)"
          >
            <el-statistic :value="allOutware.length">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  {{ $t("business.home.outwareOverview.notReceived") }}
                  <el-tooltip effect="dark" :content="$t('business.home.outwareOverview.notReceivedTips')" placement="top">
                    <el-icon class="ml-4" :size="12">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-statistic>
          </div>
          <el-divider direction="vertical" />
          <div
            class="statistic-card flx-center flx-1"
            :class="{ 'is-show': statusTabs == 1 }"
            :ref="(el:any) => setItemRef(el, '1')"
            @click="handleClickMiniTab(1)"
          >
            <el-statistic :value="thflagOutware.length" :title="$t('business.home.outwareOverview.returning')"> </el-statistic>
          </div>
        </div>
        <el-empty v-if="!showOutwares.length" :description="$t('business.home.outwareOverview.empty')" />
        <template v-else>
          <div class="home-dashboard-outware__grid">
            <section
              class="lj_common-information-item"
              v-for="(item, index) in showOutwares"
              :key="index"
              style="cursor: pointer"
              @click="handleClickOutware(item)"
            >
              <header class="flx-justify-between">
                <div class="title flx-start">
                  <div class="lj_common-information-item-avatars flx-center flx-shrink">
                    <i class="iconfont iconPaper_light"></i>
                  </div>
                  <div class="name flx-col flx-1">
                    <div class="code flx-start">
                      {{ item.outwarecode }}
                    </div>
                    <div class="tag-list mt-2">
                      <span class="text-body-m text-secondary-text">
                        <span class="text-f-c">
                          {{ $t("table.fx_outware.outwaredate") + ":" }}
                        </span>
                        {{ formatToDate(item.outwaredate) }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="flx-col" style="text-align: right">
                  <div>
                    <!-- <el-tag type="danger" class="ml-4" effect="dark" v-if="item.thflag">
                      {{ t("table.fx_outware.thflag") }}
                    </el-tag> -->
                    <OutwareTag class="ml-4" :data="item" />
                  </div>
                  <span class="text-f-c text-secondary-text">
                    {{ item.cusname }}
                  </span>
                </div>
              </header>
            </section>
          </div>
        </template>
      </el-tab-pane>
      <el-tab-pane v-for="tabItem in outwareTabs" :key="tabItem.name" v-bind="tabItem" :style="tabStyle">
        <template #label>
          <header class="flx-justify-between">
            <div class="title">
              {{ $t("business.home.outwareOverview.outwareDetail") }}
              <el-tag :effect="outwares.length ? 'dark' : 'plain'" round size="small">
                {{ outwares.length }}
              </el-tag>
            </div>
          </header>
        </template>
        <el-empty v-if="!outwares.length" :description="$t('business.home.outwareOverview.empty')" />
        <template v-else>
          <div class="home-dashboard-outware__grid">
            <section
              class="lj_common-information-item"
              v-for="(item, index) in outwares"
              :key="index"
              style="cursor: pointer"
              @click="handleClickOutware(item)"
            >
              <header class="flx-justify-between">
                <div class="title flx-start">
                  <div class="lj_common-information-item-avatars flx-center flx-shrink">
                    <i class="iconfont iconPaper_light"></i>
                  </div>
                  <div class="name flx-col flx-1">
                    <div class="code flx-start">
                      {{ item.outwarecode }}
                      <OutwareTag class="ml-4" :data="item" />
                      <!-- <el-tag type="danger" class="ml-4" effect="dark" v-if="item.thflag">
                        {{ t("table.fx_outware.thflag") }}
                      </el-tag> -->
                    </div>
                    <div class="tag-list mt-2">
                      <span class="text-body-m text-secondary-text">
                        <span class="text-f-c">
                          {{ $t("table.fx_outware.outwaredate") + ":" }}
                        </span>
                        {{ formatToDate(item.outwaredate) }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="flx-col" style="text-align: right">
                  <span class="text-h4-r text-primary-text">
                    {{ numberFormat(item.mxoutqty, 0) }}
                  </span>
                  <span class="text-f-c text-secondary-text">
                    {{ $t("business.home.outwareOverview.mxoutqty") }}
                  </span>
                </div>
              </header>
            </section>
          </div>
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="tsx" name="home_widget-dashboard-outware">
import { ref, inject, provide, defineComponent, onUnmounted, nextTick, onMounted, computed } from "vue";
import { useDesign } from "@/hooks/useDesign";
import { homeWidgetProps } from "../../interface";
import { ElMessage, type TabsPaneContext } from "element-plus";
// import { getFxOutware } from "@/api/modules/outware";
// import { FxOutware } from "@/api/interface/index";
import { numberFormat } from "@/utils/index";
import { outwareStatus } from "@/config/common";
import { useI18n } from "vue-i18n";
import { formatToDate } from "@/utils/dateUtil";
import { useRouter } from "vue-router";
import { useGlobalStore } from "@/stores/modules/global";

interface outwareTabItem {
  name: string;
  label: string;
  closable: boolean;
}

interface outwareProps extends homeWidgetProps {
  /**
   * @description 表格高度
   */
  height?: number;
  /**
   * @description 高度类型
   */
  heightType?: string;
}

const prop = withDefaults(defineProps<outwareProps>(), {
  id: "",
  initParam: {}
});

const { t } = useI18n();
const tabsActive = ref("index");
const tabsTitle = ref("");
const outwares = ref<any>([]);
/**
 * @description 未收货的发货单
 */
const allOutware = ref<any>([]);
/**
 * @description 退货中的发货单
 */
const thflagOutware = ref<any>([]);
const emit = defineEmits(["refresh"]);
const router = useRouter();
const globalStore = useGlobalStore();
const statusTabs = ref(0);
const statisticCardMoveRef = ref();
const homeDashboardOutwareRef = ref();
const loading = ref(false);
const iframeRefs: any = {};
const setItemRef = (el: any, key: string) => {
  if (el) {
    iframeRefs[key] = el;
  }
};

const outwareTabs = ref<outwareTabItem[]>([]);

const showOutwares = computed(() => {
  return statusTabs.value ? thflagOutware.value : allOutware.value;
});
const tabStyle = computed(() => {
  let style: any = {};
  if (prop.heightType != "auto") {
    style.height = `${prop.height}px`;
  }
  return style;
});

const onRefresh = async (data: any, label: string) => {
  console.log("data :>> ", data);
  console.log("label :>> ", label);
  // let res = await getFxOutware(data);
  // outwares.value = res.FxOutwares;
  // outwareTabs.value = [
  //   {
  //     name: "outware",
  //     label: label,
  //     closable: true
  //   }
  // ];
  // nextTick(() => {
  //   tabsActive.value = "outware";
  // });
};

const handleRemoveTabs = (name: any) => {
  console.log("name :>> ", name);
  outwareTabs.value = [];
};

/**
 * @description 动态组件:发货单状态标签
 */
const OutwareTag = defineComponent({
  name: "OutwareTag",
  props: {
    data: {
      type: Object,
      required: true
    }
  },
  render() {
    switch (this.data.status) {
      case 1:
        return (
          <el-tag type={"warning"} plain>
            {t(`table.fx_outware.status${this.data.status}`)}
          </el-tag>
        );
      case 2:
        return <el-tag type={"warning"}>{t(`table.fx_outware.status${this.data.status}`)}</el-tag>;
      case 3:
        return (
          <el-tag type={"success"} plain>
            {t(`table.fx_outware.status${this.data.status}`)}
          </el-tag>
        );
      case 4:
        return <el-tag type={"info"}>{t(`table.fx_outware.status${this.data.status}`)}</el-tag>;
      case 5:
        return (
          <el-tag type={"info"} plain>
            {t(`table.fx_outware.status${this.data.status}`)}
          </el-tag>
        );
      default: // 0
        return <el-tag type={"danger"}>{t(`table.fx_outware.status${this.data.status}`)}</el-tag>;
    }
  }
});

const openDialogOutware = inject("openDialogOutware", (data: any) => {});
const handleClickOutware = (data: any) => {
  openDialogOutware({
    outwareid: data.outwareid,
    code: data.outwarecode
  });
  // if (globalStore.detailBlank) {
  //   const routeUrl = router.resolve({
  //     path: `/outware/detail/${data.outwareid}`,
  //     query: {
  //       code: data.outwarecode,
  //       cuscomid: data.cuscomid
  //     }
  //   });
  //   window.open(routeUrl.href, "_blank");
  // } else {
  //   router.push(`/outware/detail/${data.outwareid}?code=${data.outwarecode}&cuscomid=${data.cuscomid}`);
  // }
};

const handleClickMiniTab = (index: number) => {
  statusTabs.value = index;
  changeMenuTab();
};

const changeMenuTab = () => {
  nextTick(() => {
    let addition = statusTabs.value > 0 ? 8 : 0;
    statisticCardMoveRef.value.style.left = iframeRefs[statusTabs.value].offsetLeft - addition + "px";
    statisticCardMoveRef.value.style.width = iframeRefs[statusTabs.value].offsetWidth + "px";
  });
};

/**
 * @description 获取发货单概况数据,未收货+退货中
 */
const refreshOutwareFunc = async (showMessage = false) => {
  // loading.value = true;
  // let res = await getFxOutware({ statusList: [0, 1, 2] });
  // allOutware.value = res.FxOutwares;
  // let res2 = await getFxOutware({ statusList: [4] });
  // thflagOutware.value = res2.FxOutwares;
  // loading.value = false;
  // showMessage && ElMessage.success(t("sys.api.sueccessToRefresh"));
};

/**
 * @description 重复点击"发货单概况", 刷新数据
 */
const handleClickTab = (data: any) => {
  if (data.props.name == tabsActive.value && tabsActive.value == "index") {
    refreshOutwareFunc(true);
  }
};

/**
 * @description 根据容器宽邸,自适应布局
 */
const adaptiveFunc = () => {
  let _width = homeDashboardOutwareRef.value.offsetWidth;
  let cls = "";

  switch (true) {
    case _width >= 1200:
      cls = " adaptive_4"; // 25
      break;
    case _width >= 992:
      cls = " adaptive_3"; // 33.33
      break;
    case _width >= 768:
      cls = " adaptive_2"; // 50
      break;
    default:
      cls = " adaptive_1"; // 100
      break;
  }
  let classArray = homeDashboardOutwareRef.value.className.split(" ");
  let index = classArray.findIndex((item: any) => item.indexOf("adaptive") > -1);
  if (index > -1) {
    classArray.splice(index, 1);
  }
  homeDashboardOutwareRef.value.className = classArray.join(" ");
  homeDashboardOutwareRef.value.className += cls;
};

onMounted(() => {
  handleClickMiniTab(0);
  refreshOutwareFunc();
  console.log("完成渲染onMounted outware:>> ", prop);

  adaptiveFunc();

  // window.onresize = () => {
  //   adaptiveFunc();
  //   handleClickMiniTab(statusTabs.value);
  // };
  window.addEventListener("resize", adaptiveFunc);
  window.addEventListener("resize", changeMenuTab);
});

onUnmounted(() => {
  window.removeEventListener("resize", adaptiveFunc);
  window.removeEventListener("resize", changeMenuTab);
});

defineExpose({
  onRefresh,
  refreshOutwareFunc
});
</script>

<style lang="scss" scope>
.home-dashboard-outware {
  .el-tabs {
    border-radius: $br-md;
    overflow: hidden;
  }

  .el-empty {
    padding-top: $space-b2;
    .el-empty__image {
      width: 20%;
      min-width: 100px;
    }
  }
  .el-tabs__content {
    // height: 250px;
    max-height: 100vh;
    overflow: auto;
    margin-bottom: $space-b2;
  }
  .el-loading-mask {
    z-index: 1;
  }

  @for $i from 1 through 4 {
    &.adaptive_#{$i} {
      .lj_common-information-item {
        $item-width: calc(100% / $i);
        width: $item-width;
        width: -webkit-calc($item-width - $space-a1 * 2);
        width: -moz-calc($item-width - $space-a1 * 2);
        width: -o-calc($item-width - $space-a1 * 2);
        width: calc($item-width - $space-a1 * 2);
      }
    }
  }
}

.home-dashboard-outware__grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 $space-a1 * -1;
}
/* 通用信息模块布局 */
.lj_common-information-item {
  border-radius: $br-md;
  overflow: hidden;
  border: 1px solid $color-gray-4;
  transition: all 0.2s ease-in-out;

  margin: $space-a1 $space-a1;
  // width: 50%;
  // width: -webkit-calc(50% - $space-a1 * 2);
  // width: -moz-calc(50% - $space-a1 * 2);
  // width: -o-calc(50% - $space-a1 * 2);
  // width: calc(50% - $space-a1 * 2);
  box-sizing: border-box;

  &:hover {
    border-color: $color-primary-300;
  }

  // & + .lj_common-information-item {
  //   margin-top: $space-b1;
  // }

  & > header {
    position: relative;
    padding: $space-b1 $space-b2;
    align-items: flex-start;
  }

  & > main {
    position: relative;
    padding: $space-b1 $space-b2;
  }

  &-avatars {
    width: $space-b4;
    height: $space-b4;
    .iconfont {
      font-size: $space-b3;
      color: $color-gray-7;
    }
  }

  .tag-list {
    span + span {
      margin-left: 8px;
    }
    .iconfont {
      // margin-right: 2px;
      font-size: 13px;
    }
  }

  &-dashboard {
    text-align: center;
  }
}

.el-statistic {
  --el-statistic-content-font-size: 28px;
}

.outware-dashboard {
  position: relative;
  background-color: $color-gray-3;
  border-radius: 4px;
  margin-bottom: $space-b1;
  box-shadow: $shadow-3-down-inset;

  .statistic-card {
    margin: $space-a1;
    padding: $space-b1 $space-b1;
    box-sizing: border-box;
    border-radius: 4px;
    cursor: pointer;
    z-index: 1;

    .el-statistic__content {
      color: $color-text-secondary-text;
      @include text-style-h-4-medium;
      line-height: 20px;
    }

    &.is-show {
      .el-statistic__content {
        color: $color-text-primary-text;
      }
    }

    &.is-current {
      position: absolute;
      top: $space-a1;
      left: $space-a1;
      background-color: $color-gray-1;
      bottom: $space-a1;
      box-shadow: 0px 1px 2px -2px rgba(0, 0, 0, 0.06), 0px 3px 6px rgba(0, 0, 0, 0.03), 0px 5px 12px 4px rgba(0, 0, 0, 0.02);
      z-index: 0;
      transition: all 0.2s ease-in-out;
    }
  }
}
</style>
