<template>
  <div class="news">
    <div class="center-banner">
      <div class="content">
        <div class="user">
          <img v-if="userInfo.avatar" :src="userInfo.avatar" />
          <img v-else src="../../assets/img/default-avatar.png">
          <p>
            <span>Hi~{{ userInfo.nickName }}</span>
            <span>{{ userInfo.roleNames }}</span>
            <span>{{ userInfo.pgName || '未加入课题组' }}</span>
          </p>
        </div>
        <div class="btns">
          <p>安全积分：<span>100</span></p>
          <el-button size="medium"
                     round>个人设置</el-button>
        </div>
      </div>
    </div>
    <div class="common-container">
      <el-container>
        <div class="left-tabs">
          <h4>个人中心</h4>
          <ul>
            <li
              v-for="(item, index) in options"
              :key="index"
              :class="{ active: $route.path === item.path }"
              @click="tabSelect(item, index)"
            >
              {{ item.label }}
            </li>
          </ul>
        </div>
        <router-view></router-view>
      </el-container>
    </div>
    <AppointCreate
      ref="appointCreateRef"
      @refresh="
        searchForm.pageNum = 1;
        getAppointList();
      "
    ></AppointCreate>
     <PersonalInfoDialog ref="personalInfoDialogRef" />
  </div>
</template>

<script>
  import Banner from "../../components/Banner";
  import LeftTabs from "@/components/LeftTabs";
  import RightContent from "@/components/RightContent";
  import FullCalendar from "@fullcalendar/vue";
  import dayGridPlugin from "@fullcalendar/daygrid";
  import interactionPlugin from "@fullcalendar/interaction";
  import { getNoticeList } from "@/api/login";
  import {
    getInstrList,
    getInstrListByUser,
    userCancelAppoint,
  } from "@/api/instr";
  import { mapGetters } from "vuex";
  import moment from "moment";
  import to from "await-to-js";
  import { getToken } from "@/utils/auth";
  import AppointCreate from "../equipment/components/appoint-create.vue";
  import PersonalInfoDialog from "@/components/PersonalInfo";
  export default {
    name: "PersonalCenter",
    components: {
      Banner,
      LeftTabs,
      RightContent,
      FullCalendar,
      AppointCreate,
	  PersonalInfoDialog,
    },
    data() {
      return {
        active: -1,
        loading: true,
        selectTab: {},
        searchForm: {
          pageNum: 1,
          pageSize: 10,
        },
        total: 0,
        options: [
          {
            label: "工作台",
            path: '/personal-center/work'
          },
          {
            label: "预约信息",
            path: '/personal-center/appointment'
          },
        ],
        routeList: [
          {
            name: "首页",
            path: "/",
          },
          {
            name: "个人中心",
          },
        ],
        breadList: [],
        calendarOptions: {
          height: 300,
          plugins: [dayGridPlugin, interactionPlugin], // 需要用哪个插件引入后放到这个数组里
          initialDate: new Date(), // 日历第一次加载时显示的初始日期。可以解析为Date的任何职包括ISO8601日期字符串，例如"2014-02-01"。
          initialView: "dayGridMonth", // 日历加载时的初始视图，默认值为'dayGridMonth'，可以为任何可用视图的值，如例如'dayGridWeek'，'timeGridDay'，'listWeek'
          locale: "zh-cn", // 设置日历的语言，中文为 “zh-cn”
          firstDay: "1", // 设置每周的第一天，默认值取决于当前语言环境，该值为代表星期几的数字，且值必须为整数，星期日=0
          weekNumberCalculation: "ISO", // 指定"ISO"结果为ISO8601周数。指定"ISO"将firstDay的默认值更改为1（Monday）
          buttonText: {
            // 文本将显示在headerToolbar / footerToolbar的按钮上。不支持HTML注入。所有特殊字符将被转义。
            today: "今天",
            month: "月",
            week: "周",
            day: "天",
          },
          headerToolbar: {
            // 在日历顶部定义按钮和标题。将headerToolbar选项设置为false不会显示任何标题工具栏。可以为对象提供属性start/center/end或left/center/right。这些属性包含带有逗号/空格分隔值的字符串。用逗号分隔的值将相邻显示。用空格分隔的值之间会显示一个很小的间隙。
            right: "today prev,next",
            center: "title",
            left: "dayGridMonth,dayGridWeek,dayGridDay",
          },
          eventTimeFormat: {
            // 在每个事件上显示的时间的格式
            hour: "numeric",
            minute: "2-digit",
            hour12: false,
          },
          events: [],
          dateClick: this.handleDateClick, // 当用户单击日期或时间时,触发该回调，触发此回调，您必须加载interaction插件
        },
        instrList: [],
        noticeList: [],
        curSelectedDate: "w",
        curTime: "",
        appointData: [],
        WEEKS: [
          "星期日",
          "星期一",
          "星期二",
          "星期三",
          "星期四",
          "星期五",
          "星期六",
        ],
      };
    },
    computed: {
      ...mapGetters(["userInfo"]),
    },
    mounted() {
      // this.tabSelect(this.options[0], 0);
      this.curTime = this.getToday();
      this.getNotice();
      this.getInstr();
    },
    methods: {
      moment,
      // 獲取當前日期
      getToday() {
        return moment(moment().startOf("day").valueOf()).format("YYYY-MM-DD");
      },
      getYesterday() {
        this.curTime = moment(
          moment(this.curTime).add(-1, "days").startOf("day").valueOf()
        ).format("YYYY-MM-DD");
      },
      getTomorrow() {
        this.curTime = moment(
          moment(this.curTime).add(+1, "days").startOf("day").valueOf()
        ).format("YYYY-MM-DD");
      },
      getPrevWeekDays() {
        this.curTime = moment(this.curTime)
          .subtract(1, "week")
          .format("YYYY-MM-DD");
      },
      getNextWeekDays() {
        this.curTime = moment(this.curTime).add(1, "week").format("YYYY-MM-DD");
      },
      getPrevMonthDays() {
        this.curTime = moment(this.curTime)
          .subtract(1, "months")
          .format("YYYY-MM-DD");
      },
      getNextMonthDays() {
        this.curTime = moment(this.curTime)
          .add(1, "months")
          .format("YYYY-MM-DD");
      },
      getWeekDate() {
        // 获取当前周的周一0点
        var startOfWeek = moment(this.curTime)
          .startOf("isoWeek")
          .format("YYYY-MM-DD HH:mm:ss");

        // 获取下一周的周一0点
        var startOfNextWeek = moment(this.curTime)
          .startOf("isoWeek")
          .add(1, "weeks")
          .format("YYYY-MM-DD HH:mm:ss");
        return [startOfWeek, startOfNextWeek];
      },
      getMonthDate() {
        const date = moment(this.curTime);
        // 获取当前月份的最后一天
        return [
          date.startOf("month").format("YYYY-MM-DD HH:mm:ss"),
          date.endOf("month").add(1, "days").format("YYYY-MM-DD") + " 00:00:00",
        ];
      },
      // 上一周、天、月
      handlePrev() {
        if (this.curSelectedDate == "d") {
          this.getYesterday();
        } else if (this.curSelectedDate == "w") {
          this.getPrevWeekDays();
        } else if (this.curSelectedDate == "m") {
          this.getPrevMonthDays();
        }
        this.getAppointList();
      },
      // 下一周、天、月
      handleNext() {
        if (this.curSelectedDate == "d") {
          this.getTomorrow();
        } else if (this.curSelectedDate == "w") {
          this.getNextWeekDays();
        } else if (this.curSelectedDate == "m") {
          this.getNextMonthDays();
        }
        this.getAppointList();
      },
      selectDate(date) {
        this.curSelectedDate = date;
        this.getAppointList();
      },
      async getAppointList() {
        let startTimeStart = "";
        let startTimeEnd = "";
        if (this.curSelectedDate == "d") {
          startTimeStart = moment(this.curTime).format("YYYY-MM-DD HH:mm:ss");
          startTimeEnd = moment(this.curTime)
            .add(1, "days")
            .format("YYYY-MM-DD HH:mm:ss");
        } else if (this.curSelectedDate == "w") {
          startTimeStart = this.getWeekDate()[0];
          startTimeEnd = this.getWeekDate()[1];
        } else if (this.curSelectedDate == "m") {
          startTimeStart = moment(this.curTime)
            .startOf("month")
            .format("YYYY-MM-DD HH:mm:ss");
          startTimeEnd = this.getMonthDate()[1];
        }
        console.log(startTimeStart);
        const [err, res] = await to(
          getInstrListByUser({
            startTimeStart,
            startTimeEnd,
            ...this.searchForm,
          })
        );
        if (err) return;
        this.appointData = res.data.list;
        this.total = res.data.total;
      },
      setStatus(key) {
        let str = "";
        switch (key) {
          case "10":
            str = "待审核";
            break;
          case "11":
            str = "已退回";
            break;
          case "20":
            str = "已通过";
            break;
          case "30":
            str = "已驳回";
            break;
          case "40":
            str = "已取消";
            break;
          case "50":
            str = "已上机";
            break;
          case "60":
            str = "已完成";
            break;
          case "70":
            str = "审核超时";
            break;
          case "80":
            str = "超时取消";
            break;
          case "90":
            str = "超时未上机";
            break;
        }
        return str;
      },
      getBreachTypes(row) {
        let breachTypes = [];
        if (row.isLate) breachTypes.push("迟到");
        if (row.isOvertime) breachTypes.push("超时");
        if (row.isLeaveEarly) breachTypes.push("早退");
        if (row.isAbsence) breachTypes.push("爽约");
        return breachTypes.join("、") || "-";
      },
      // 取消预约
      cancelAppoint(row) {
        // 删除附件
        this.$confirm("确认取消预约?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const post = userCancelAppoint({ id: Number(row.id) });
            const [err] = await to(post);
            if (err) return;
            this.$message.success("取消成功");
            this.getAppointList();
          })
          .catch(() => {});
      },
      // 编辑预约
      handleEditAppoint(row) {
        const token = getToken();
        if (!token) {
          return this.$router.push("/login");
        }
        this.$refs.appointCreateRef.openDialog(row);
      },
      // 选择tab
      tabSelect(row, index) {
        this.active = index;
        this.selectTab = { ...row };
        this.breadList = [...this.routeList, { name: this.selectTab.label }];
        this.$router.push(row.path)
      },
      async getNotice() {
        const [err, res] = await to(getNoticeList());
        if (err) return;
        this.noticeList = res.data.list || [];
      },
      async getInstr() {
        const [err, res] = await to(getInstrList({ pageSize: 4, pageNum: 1 }));
        if (err) return;
        this.instrList = res.data.list || [];
      },
      handleDateClick(dateClickInfo) {
        console.log(dateClickInfo);
      },
      handleSizeChange(val) {
        this.searchForm.pageSize = val;
        this.getAppointList();
      },
      handleCurrentChange(val) {
        this.searchForm.pageNum = val;
        this.getAppointList();
      },
    },
  };
</script>

<style lang="scss" scoped>
.center-banner {
  background: url(../../assets/img/center-banner.png) top no-repeat;
  background-size: 100% 240px;
  height: 240px;
  display: flex;
  justify-content: center;
  align-items: center;
  .content {
    height: 180px;
    width: 1200px;
    border-radius: 16px;
    background-color: rgba($color: #fff, $alpha: 0.5);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 40px;
    .user {
      display: flex;
      align-items: center;
      img {
        height: 100px;
        width: 100px;
        border-radius: 50%;
      }
      p {
        height: 100px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        margin-left: 12px;
        span:nth-child(1) {
          font-weight: bold;
          font-size: 18px;
        }
        span:nth-child(3) {
          font-weight: bold;
        }
      }
    }
    .btns {
      display: flex;
      align-items: center;
      > p {
        display: flex;
        align-items: center;
        margin-right: 20px;
        line-height: 30px;
        font-weight: bold;
        span {
          font-size: 30px;
          font-weight: bold;
          color: #1d66dc;
          font-style: italic;
        }
      }
    }
  }
}
  .flex {
    width: 100%;
    flex-wrap: wrap;
    .el-card {
      flex: 0 0 calc(50% - 14px);
      height: 400px;
      ::v-deep .el-card__body {
        padding: 10px;
        height: calc(100% - 79px);
      }
      &.calendar {
        height: 500px;
        ul {
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          height: 130px;
          li {
            font-size: 14px;
            display: flex;
            align-items: center;
            &:before {
              content: "";
              display: inline-block;
              width: 6px;
              height: 6px;
              border-radius: 3px;
              background-color: #a30014;
              margin-right: 4px;
            }
          }
        }
      }
      &.cost {
        height: 300px;
      }
    }
    &.technical .el-card {
      height: auto;
      ::v-deep .el-card__body {
        height: auto;
      }
    }
  }
  .cage-list {
    display: flex;
    flex-wrap: wrap;
    list-style: none;
    li {
      height: 160px;
      width: 221px;
      font-size: 14px;
      border: 1px solid #ebeef5;
      border-radius: 6px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding: 10px;
      &:nth-child(2n) {
        margin-left: 4px;
      }
      &:nth-child(n + 3) {
        margin-top: 4px;
      }
      header {
        display: flex;
        justify-content: space-between;
        p {
          color: #1d66dc;
        }
      }
    }
  }
  .platform-list {
    height: 100%;
    display: flex;
    flex-direction: column;
    li {
      flex: 1;
      display: flex;
      align-items: center;
      margin: 12px;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #ebeef5;
      .text {
        flex: 1;
        height: 100%;
        padding: 12px;
      }
      .btn {
        width: 120px;
        height: 100%;
        color: #fff;
        font-size: 20px;
        background-color: #73b9b9;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-around;
        header {
          font-size: 14px;
        }
        .remain-time {
          color: #f56c6c;
        }
      }
    }
  }
  .chart-container {
    display: flex;
    .text {
      flex: 1;
      font-size: 14px;
      display: flex;
      flex-direction: column;
      header {
        color: #1d66dc;
      }
      ul {
        margin-top: 12px;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
      }
      li {
        background-color: #e4b5bb;
        border-radius: 4px;
        padding: 4px 8px;
      }
    }
    #chart {
      width: 233px;
      height: 220px;
    }
  }
  .technical {
    p {
      font-size: 16px;
      height: 24px;
      line-height: 24px;
    }
    ul {
      display: flex;
      height: 50px;
      line-height: 50px;
      border-radius: 4px;
      overflow: hidden;
      margin: 20px 0;
      li {
        flex: 1;
        text-align: center;
        background-color: #d9fba5;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        &:nth-child(2) {
          background-color: #98ca49;
        }
        &:nth-child(3) {
          background-color: #a4dffa;
        }
        &:nth-child(4) {
          background-color: #48bff4;
        }
        &:nth-child(5) {
          background-color: #b6b6f1;
        }
        &:nth-child(6) {
          background-color: #ebcda7;
        }
        &:nth-child(7) {
          background-color: #f2a4ad;
        }
      }
    }
  }
  .toolbar-wrap {
    height: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // margin-bottom: 20px;
    .switch-date {
      width: 108px;
      height: 28px;
      border-radius: 2px;
      border: 1px solid #b5c1d8;
      display: flex;
      padding: 4px 6px 0;
      .btn {
        cursor: pointer;
        flex: 1;
        font-size: 13px;
        color: #585858;
        display: flex;
        align-items: center;
        justify-content: center;
        &.actived {
          background: #eef3fe;
          font-weight: bold;
          color: #2c78ff;
        }
      }
    }
    .date-wrap {
      display: flex;
      align-items: center;
      :deep(.el-button--small.is-circle) {
        width: 26px;
        height: 26px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .date {
        margin: 0 10px;
        font-size: 14px;
        color: #585858;
        display: flex;
        align-items: center;
      }
      .week {
        color: #2c78ff;
        padding-left: 6px;
      }
    }
  }
  .table-wrap {
    flex: 1;
    margin: 20px 0 0;
    // overflow: hidden;
  }
  .pagination {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
</style>