<template>
  <div class="flex align-center just-between pt8 pb8">
    <div class="flex align-center time_text" v-if="props.isShowText">
      <MOSTY.Assort :title="props.title" style="padding: 0; width: auto" />
      <span style="display: flex;align-items: center;">
        <el-popover placement="bottom-start" :width="750" trigger="hover" :title="props?.popover?.title">
          <template #reference>
            <el-icon :size="16">
              <Warning />
            </el-icon>
          </template>
          <pre v-text="props?.popover?.content"></pre>
        </el-popover>
        <el-button class="ml10" @click="onReportHistory" v-if="props.isShowBtn">上报历史</el-button>
      </span>
    </div>
    <div class="flex align-center just-between">
      <div v-if="props.isCustom">
        <slot name="date"></slot>
      </div>
      <div v-else>
        <template v-for="item in timeType" :key="item">
          <el-select v-model="pageData.yearValue" style="width: 200px" v-if="item == '年'" class="mr5"
            @change="onChange">
            <el-option v-for="item in filterYear(5)" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
          <el-date-picker v-model="pageData.monthValue" type="month" placeholder="请选择月份" class="mr5" @change="onChange"
            value-format="YYYY-MM" v-else-if="item == '月度'" />
          <el-select v-model="pageData.quarterValue" placeholder="请选择季度" size="large" style="width: 200px" class="mr5"
            @change="onChange" v-else-if="item == '季度'">
            <el-option v-for="item in D_BZ_QUARTER" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="pageData.halfValue" placeholder="请选择上半年或者下半年" size="large" style="width: 220px"
            class="mr5" @change="onChange" v-else-if="item == '半年'">
            <el-option v-for="item in D_BZ_HALF_YEAR" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>
        <!-- 自定义筛选条件 -->
        <slot name="select"></slot>
      </div>
      <!-- 自定义右侧按钮 -->
      <el-button class="mr5 ml5" @click="onReset" v-if="props.isShowText">重置</el-button>
      <slot name="right"></slot>
    </div>
  </div>
  <div class="time-wring" v-if="props.isShowText">
    <img :src="getImgUrl('jzw/tips.png')" style="width: 16px; height: 16px; margin-right: 4px" />
    <div class="time-text">
      <!-- 当前数据未上报， -->
      上报周期：{{ period.cycle }} 提交周期：{{ period.startTime }} - {{ period.endTime
      }}<span v-if="countdown" style="margin-left: 6px">{{ countdown.overtime ? "已超时" : "倒计时" }} ： {{
        countdown.timeValue
      }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, defineProps, defineEmits, reactive, onMounted, onBeforeUnmount } from "vue";
import { getApi } from "@/api/tobAcco_api.js";
import { filterYear } from "@/utils/auth.js";
import { countDown, dateFormat, getImgUrl } from "@/utils/tools";
import * as MOSTY from "@/components/MyComponents/index";
import { getReportQuarter } from "../tools/dataReport.js";

const { proxy } = getCurrentInstance();
const { D_BZ_QUARTER, D_BZ_HALF_YEAR } = proxy.$dict("D_BZ_QUARTER", "D_BZ_HALF_YEAR");
const emits = defineEmits(["change", 'handleHistory', 'update']);
const props = defineProps({
  byTime: String, //截至日期
  ywId: String, //业务ID
  isShowText: {
    type: Boolean,
    default: true
  },
  title: {
    type: String,
    default: "台账"
  },
  isShowBtn: {
    type: Boolean,
    default: false
  },
  isCustom: {
    type: Boolean,
    default: false
  },
  popover: Object
});

/**获取上报季度 特殊需求by(s) 4.11日之前都是第一季度
 * @param {Number} month
 * @param {Number} day
 */
const getQuarter = (month, day) => {
  return getReportQuarter(month, day)
}
/**获取是否需要刷新(目前仅做了"年","季度"),即当前时间是否是 上报时间 */
const getIsNeedRefresh = () => {
  let resPeriod = period.value || {}
  let selectPageData = pageData || {}
  let startDay = new Date(resPeriod.startTime);
  let year = startDay.getFullYear();
  let month = startDay.getMonth() + 1;
  const day = startDay.getDate();

  const isSameYear = year == selectPageData.yearValue;
  if (resPeriod.cycle == "年") {
    return isSameYear;
  } else if (resPeriod.cycle == "季度") {
    /** 当前季度 1一季度 */
    let quarter = 0
    // return getQuarter(month, day)+ "";  //季度
    // if ([1, 2, 3].includes(month)) quarter = 1
    // if ([4, 5, 6].includes(month)) quarter = 2
    // if ([7, 8, 9].includes(month)) quarter = 3
    // if ([10, 11, 12].includes(month)) quarter = 4
    quarter = getQuarter(month, day);
    if (isSameYear && quarter == selectPageData.quarterValue) {
      return true;
    }
  } else if (resPeriod.cycle == "月度") {
  } else if (resPeriod.cycle == "半年") {

  }
  return false
}


/**
 * 是否是上半年 和 季度
 * @param {*} type   half  半年    quarter  季度
 */
const isFirstHalfOfYear = (type) => {
  const now = new Date(); // 获取当前日期
  const month = now.getMonth() + 1; // 获取当前月份（0-11）  1
  const day = now.getDate(); // 获取当前日期（1-31）
  // 由于月份是从0开始的，所以我们将月份加1来与1-12月对应
  // 如果月份（加1后）小于或等于6，则为上半年
  if (type == "half") {
    //半年
    if (month <= 6) {
      return "1";
    } else {
      return "2";
    }
  } else {
    /** @type {Date} 第一季度重新定义 4月11之前是第一季度 */
    return getQuarter(month, day) + "";  //季度
    // let quarter1Date = new Date(now.getFullYear(), 3, 10) // 4月11日 之前是第一季度
    //季度
    // if (month <= 3 || now < quarter1Date) {
    //   return "1";
    // } else if (month > 3 && month <= 6) {
    //   return "2";
    // } else if (month > 6 && month <= 9) {
    //   return "3";
    // } else {
    //   return "4";
    // }
  }
};
const pageData = reactive({
  yearValue: dateFormat({ type: "year" }),
  monthValue: dateFormat({ type: "month" }),
  quarterValue: isFirstHalfOfYear("quarter"),
  halfValue: isFirstHalfOfYear("half")
});
const period = ref({
  startTime: '00:00',
  endTime: '00:00',
}); //周期对象
const countdown = ref(null); //倒计时
const timer = ref(); //计时器
const timeType = ref(["年"]); //查询时间类型
onMounted(() => {
  _getJzsj();
});
onBeforeUnmount(() => {
  clearInterval(timer.value);
  timer.value = null;
});
const onReportHistory = () => {
  emits('handleHistory')
}
//h获取信息
const _getJzsj = () => {
  getApi({ type: props.ywId }, "/mosty-jcgl/data/cycle/getCurrentCycle").then((res) => {
    if (res) {
      period.value = res;
      //   年  半年 季度 月度
      switch (res.cycle) {
        case "年":
          timeType.value = ["年"];
          break;
        case "半年":
          timeType.value = ["年", "半年"];
          break;
        case "季度":
          timeType.value = ["年", "季度"];
          break;
        case "月度":
          timeType.value = ["月度"];
          break;
      }
      emits("change", pageData, getIsNeedRefresh());
      emits("update", getIsNeedRefresh());
      timer.value = setInterval(() => {
        countdown.value = countDown(res.endTime);
      }, 1e3);
    } else {
      emits("change", pageData, getIsNeedRefresh());
    }
  });
};

const onChange = (val) => {
  emits("change", pageData, getIsNeedRefresh());
  emits("update", getIsNeedRefresh());
};
const onReset = () => {
  pageData.yearValue = dateFormat({ type: "year" });
  pageData.monthValue = dateFormat({ type: "month" });
  pageData.quarterValue = isFirstHalfOfYear("quarter");
  pageData.halfValue = isFirstHalfOfYear("half");
  emits("change", pageData, getIsNeedRefresh());
};
</script>

<style lang="scss" scoped>
::v-deep .el-input--large .el-input__inner {
  height: 32px;
  line-height: 32px;
}

.time_text {
  color: var(--el-color-primary);
}

.time-wring {
  width: 100%;
  height: 36px;
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #faad14;
  background: #fff8ea;
  margin: 3px 0;
  display: flex;
  align-items: center;
  padding: 0 10px;
  box-sizing: border-box;

  .time-text {
    font-weight: 400;
    font-size: 16px;
    color: #faad14;
  }
}

::v-deep .el-button.is-disabled:hover {
  background-color: #808596;
  border-color: var(--el-button-disabled-border-color);
}
</style>
