<template>
  <div style="display: inline-block">
    <!-- <span @click="showPicker">{{ getLangText(label.datetimePicker) }}</span> -->
    <div class="date-picker-bg" v-show="isShow" @click="closePicker"></div>
    <div class="date-picker" v-show="isShow" style="width: 350px">
      <div class="picker-top">
        <span class="picker-arrow" @click="preYear">&lsaquo;&lsaquo;</span>
        <span class="picker-arrow" @click="preMonth">&lsaquo;</span>
        <span class="date-text"
          >{{ year }}-{{ month > 9 ? month : "0" + month }}</span
        >
        <span class="picker-arrow" @click="nextMonth">&rsaquo;</span>
        <span class="picker-arrow" @click="nextYear">&rsaquo;&rsaquo;</span>
      </div>
      <div class="picker-content1 picker-content">
        <table>
          <thead>
            <tr>
              <th v-for="(item, idx) in weekList" :key="'week' + idx">
                {{ getLangText(item) }}
              </th>
            </tr>
          </thead>
          <div class="contain"></div>
          <tbody>
            <tr v-for="idx in weekNum" :key="'weekNum' + idx">
              <td
                v-for="m in 7"
                :key="'monthDay' + idx + '_' + m"
                :class="[
                  new Date(monthList[idx - 1][m - 1]).getMonth() + 1 == month
                    ? ''
                    : 'gray',
                  selectDate == monthList[idx - 1][m - 1] ? 'active' : '',
                  new Date(monthList[idx - 1][m - 1]).getTime() < currentDate
                    ? 'bggray'
                    : '',
                ]"
                @click="onSelectDate(monthList[idx - 1][m - 1])"
              >
                <div>{{ new Date(monthList[idx - 1][m - 1]).getDate() }}</div>
              </td>
            </tr>
          </tbody>
        </table>
        <ul class="hour-list">
          <li
            v-for="(n, index) in hourList"
            :key="'hourList' + index"
            @click="onSelectHour(n, index)"
            :class="[index == clicktime ? 'active' : '']"
          >
            {{ n }}:<span v-if="index % 2 === 0">00</span><span v-else>30</span>
          </li>
        </ul>
        <!-- <ul class="minutes-list">
          <li
            v-for="n in [1, 31]"
            :key="'hourList' + n"
            @click="onSelectMinute(n - 1)"
            :class="[selectMinute == n - 1 ? 'active' : '']"
            @dblclick="onConfirmHour(n - 1)"
          >
            {{ n - 1 }}:00
          </li>
        </ul> -->
      </div>
      <div class="picker-footer">
        <button @click="closePicker">{{ getLangText(label.close) }}</button>
        <button @click="setNow">{{ getLangText(label.ok) }}</button>
        <!-- <button @click="confirmPicker">{{getLangText(label.ok)}}</button> -->
      </div>
    </div>
  </div>
</template>
<script>
Date.prototype.format = function (fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
export default {
  name: "DateTimePicker",
  props: {
    langType: {
      type: String,
      default: window.localStorage.getItem("langType"),
    },
    datetime: {
      type: String,
      default: new Date().format("yyyy-MM-dd hh:00"),
    },
    isShow: {
      type: Boolean,
      default: true,
    },
  },
  data: () => ({
    label: {
      ok: { zh: "确定", en: "OK" },
      close: { zh: "关闭", en: "close" },
      today: { zh: "确定", en: "now" },
      datetimePicker: { zh: "日期时间选择", en: "datetimePicker" },
    },
    clicktime: null,
    weekList: [
      { zh: "日", en: "Sun" },
      { zh: "一", en: "Mon" },
      { zh: "二", en: "Tue" },
      { zh: "三", en: "Wed" },
      { zh: "四", en: "Thu" },
      { zh: "五", en: "Fir" },
      { zh: "六", en: "Sat" },
    ],
    hourList: [
      8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17,
      17, 18, 18,
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),
    currentDate: new Date(new Date().format("yyyy-MM-dd 00:00")).getTime(),
    startDay: 0,
    endDay: 0,
    weekNum: 0,
    selectDate: new Date(new Date().format("yyyy-MM-dd 00:00")).getTime(),
    monthList: [],
    selectHour:
      new Date().getHours() > 8 && new Date().getHours() < 18
        ? new Date().getHours()
        : "8",
    selectMinute:
      new Date().getMinutes() >= 0 && new Date().getMinutes() < 30 ? "0" : "30",
  }),
  created() {
    console.log(this.selectDate);
    console.log(this.selectMinute);
  },
  watch: {
    year() {
      this.getMonthDay();
    },
    month() {
      this.getMonthDay();
    },
    isShow() {
      if (this.isShow) {
        // console.log(this.selectHour);
        let ind =
          (this.selectHour - 8) * 2 + (this.selectMinute === "0" ? 0 : 1);
        this.onSelectHour(this.selectHour, ind);
        this.$emit(
          "update:datetime",
          new Date(
            this.selectDate +
              this.selectHour * 3600000 +
              this.selectMinute * 60000
          ).format("yyyy-MM-dd hh:mm")
        );
      }
    },
  },
  methods: {
    getLangText(item) {
      if (item) {
        if (this.langType == "en") {
          if (item.en && item.en.length > 1) {
            return item.en.substring(0, 1).toUpperCase() + item.en.substring(1);
          } else if (item.en && item.en.length == 1) {
            return item.en.toUpperCase();
          } else {
            return "--";
          }
        } else {
          return item.zh ? item.zh : "--";
        }
      } else {
        return "--";
      }
    },
    preYear() {
      this.year = this.year - 1;
    },
    nextYear() {
      this.year = this.year + 1;
    },
    nextMonth() {
      if (this.month == 12) {
        this.year = this.year + 1;
        this.month = 1;
      } else {
        this.month++;
      }
    },
    preMonth() {
      if (this.month == 1) {
        this.year = this.year - 1;
        this.month = 12;
      } else {
        this.month--;
      }
    },
    showPicker() {
      this.$emit("update:is-show", true);

      var time = new Date(this.datetime).getTime();
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.selectDate = new Date(
        new Date(time).format("yyyy-MM-dd 00:00")
      ).getTime();
      this.selectHour = new Date(time).getHours();
    },
    onConfirmDate(time) {
      this.onSelectDate(time);
      this.confirmPicker();
    },
    onConfirmHour(n) {
      this.onSelectHour(n);
      this.confirmPicker();
    },
    closePicker() {
      this.$emit("update:is-show", false);
    },
    setNow() {
      // this.year = new Date().getFullYear();
      // this.month = new Date().getMonth() + 1;
      // this.day = new Date().getDate();
      // this.selectDate = new Date(
      //   new Date().format("yyyy-MM-dd 00:00")
      // ).getTime();
      // this.selectHour = new Date().getHours();
      // this.selectMinute =
      //   new Date().getMinutes() > 0 && new Date().getMinutes() <= 30
      //     ? "0"
      //     : "30";
      this.$emit("update:is-show", false);
    },
    confirmPicker() {
      // console.log(this.selectMinute);
      // this.$emit(
      //   "update:datetime",
      //   new Date(
      //     this.selectDate +
      //       this.selectHour * 3600000 +
      //       this.selectMinute * 60000
      //   ).format("yyyy-MM-dd hh:mm")
      // );
      // this.$emit(
      //   "pickerresult",
      //   new Date(this.selectDate + this.selectHour * 3600000).format(
      //     "yyyy-MM-dd hh:00"
      //   )
      // );
      this.closePicker();
    },
    getMonthDay() {
      var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();

      this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }

      var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
      this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
    },
    onSelectHour(n, index) {
      // console.log(n);
      this.selectHour = n;

      this.clicktime = index;
      if (index % 2 === 0) {
        this.selectMinute = "0";
      } else {
        this.selectMinute = "30";
      }
      this.$emit(
        "update:datetime",
        new Date(
          this.selectDate +
            this.selectHour * 3600000 +
            this.selectMinute * 60000
        ).format("yyyy-MM-dd hh:mm")
      );
    },
    onSelectMinute(n) {
      this.selectMinute = n;
      console.log(this.selectMinute);

      this.$emit(
        "update:datetime",
        new Date(
          this.selectDate +
            this.selectHour * 3600000 +
            this.selectMinute * 60000
        ).format("yyyy-MM-dd hh:mm")
      );
    },
    onSelectDate(time) {
      console.log(time);
      if (time < this.currentDate) {
        return;
      } else {
        this.selectDate = time;
      }
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      // console.log(this.year, "--------", this.month, "--------", this.day);
      this.$emit(
        "update:datetime",
        new Date(time + this.selectHour * 3600000).format("yyyy-MM-dd hh:00")
      );
    },
  },
  mounted() {
    this.getMonthDay();
  },
};
</script>
<style lang="less">
.date-picker-bg {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
}

.date-picker {
  background-color: white;
  position: absolute;
  top: 28px;
  left: 0;
  display: block;
  padding: 4px;
  z-index: 6;
  // border: solid 1px gainsboro;
  border-radius: 8px;
  box-shadow: 2px 2px 8px #ddd;
  .picker-top {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 30px;
    line-height: 30px;
    .picker-arrow {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      line-height: 20px;
      width: 30px;
      height: 30px;
      color: #8a8a8a;
      cursor: pointer;
      .iconfont {
        color: #8a8a8a;
      }
      .iconfont:active,
      .iconfont:hover {
        color: #388dea;
      }
    }

    .date-text {
      flex: 1;
      font-weight: bold;
      display: inline-block;
      text-align: center;
      font-size: 14px;
    }
  }

  .picker-content {
    display: block;
    border-top: solid 1px #eee;
    border-bottom: solid 1px #eee;
    height: 200px;
    table {
      width: 100%;
      border-collapse: collapse;
      border-spacing: 0;
      font-size: 12px;
      line-height: 20px !important;
      .contain {
        height: 2px;
      }
      thead {
        padding-bottom: 5px;
        tr {
          margin-bottom: 5px;
          background-color: #fff4e3;
          color: rgba(77, 87, 94);
          th {
            text-align: center;
            font-weight: 600;
            font-size: 14px;
            line-height: 26px;
          }
        }
      }
      tbody {
        margin-top: 10px;
        tr {
          td {
            // height: 50px;
            box-sizing: border-box;
            color: rgba(77, 87, 94);
            // font-weight: 600;
            padding: 0 4px;
            font-size: 14px;
            cursor: pointer;
            // border-radius: 4px;
            div {
              border: 1px solid transparent;
              position: relative;
              width: 30px;
              height: 25px;
              line-height: 23px;
              border-radius: 4px;
              text-align: center;
              margin: 0 2px;
              z-index: 99;
              box-sizing: border-box;
            }
          }
          td.gray {
            font-weight: 400;
            color: rgba(138, 138, 138, 0.7);
          }
          td.bggray {
            position: relative;
            cursor: default;
            &::after {
              content: "";
              position: absolute;
              display: block;
              width: 100%;
              height: 26px;
              background-color: #f5f5f5;
              top: 50%;
              transform: translateY(-50%);
              left: 0;
              z-index: 9;
            }
          }
          td:not(.bggray):hover {
            div {
              border: 1px solid #ff6a00;
              color: #ff6a00;
            }
          }
          td.active {
            div {
              background: #ff6a00;
              color: white !important;
              font-weight: bold;
            }
          }
        }
      }
    }
  }

  .picker-content1:extend(.picker-content all) {
    // &: extend ;
    display: flex;
    flex-direction: row;
    table {
      width: calc(100% - 40px);
      border-right: 1px solid #eee;
    }
    .hour-list,
    .minutes-list {
      display: inline-block;
      list-style: none;
      padding: 0 2px 0 5px;
      margin: 0;
      height: 100%;
      overflow-x: hidden;
      width: 80px;
      font-size: 12px;
      overflow-y: auto;
      &::-webkit-scrollbar {
        /*滚动条整体样式*/
        width: 0px !important; /*高宽分别对应横竖滚动条的尺寸*/
        height: 4px;
      }
      &::-webkit-scrollbar-thumb {
        /*滚动条里面小方块*/
        border-radius: 5px;
        // -webkit-box-shadow: inset 0 0 5px rgba(126, 126, 126, 0.06);
        background: #ddd !important;
      }
      // &::-webkit-scrollbar-track {
      //   /*滚动条里面轨道*/
      //   -webkit-box-shadow: inset 0 0 5px rgba(112, 112, 112, 0.06);
      //   border-radius: 0;
      //   background: rgba(0, 0, 0, 0.1);
      // }
      li {
        padding: 0;
        margin: 0;
        // color: #4d575e;
        color: rgba(77, 87, 94, 0.8);

        font-weight: 600;
        display: flex;
        line-height: 13px;
        font-size: 13px;
        justify-content: center;
        align-items: center;
        padding: 0 4px;
        height: 26px;
        cursor: pointer;
      }
      // li:not(:last-child) {
      // border-bottom: solid 1px gainsboro;
      // }
      li.active {
        color: white;
        background: #ff6a00;
      }
    }
    .minutes-list {
      width: 60px;
    }
    .hour-list::-webkit-scrollbar {
      background: transparent;
      height: 8px;
      width: 8px;
      border: none;
    }

    .hour-list::-webkit-scrollbar-thumb {
      background: lightgray;
      border-radius: 5px;
    }
    //设置滚动条 end
  }

  .picker-footer {
    display: block;
    line-height: 42px;
    text-align: right;
    white-space: nowrap;
    button {
      outline: none;
      border: solid 1px gainsboro;
      border-radius: 2px;
      text-align: center;
      padding-left: 1px;
      color: #8a8a8a;
      height: 24px;
      width: 50px;
      line-height: 20px;
      font-size: 12px;
      margin-right: 12px;
      background-color: #f3f3f3;
      &:first-child {
        background-color: #fff;
        &:active,
        &:hover {
          border-color: #eee;
          background-color: #eee;
        }
      }
      &:last-child {
        background-color: #ff6a00;
        border-color: #ff6a00;
        color: #fff;
        &:active,
        &:hover {
          border-color: #ff6a00;
          background-color: #ff832a;
        }
      }
    }
  }
}
</style>
