<template>
  <div class="w100">
    <el-row class="flex mt12"
            :gutter="12">
      <el-col :span="12">
        <el-card>
          <div slot="header"
               class="header">
            <h4>科研仪器</h4>
            <el-button @click="openUploadDialog">上传</el-button>
          </div>
          <ul class="cage-list">
            <li v-for="v in instrList"
                :key="v.id">
              <header>
                <p>{{ v.instName }}</p>
                <el-tag v-if="v.instStatus == '10'"
                        type="primary"
                        size="mini">
                  正常
                </el-tag>
                <el-tag v-else-if="v.instStatus == '20'"
                        type="warning"
                        size="mini">
                  故障
                </el-tag>
                <el-tag v-else-if="v.instStatus == '30'"
                        type="danger"
                        size="mini">
                  报废
                </el-tag>
              </header>
              <p>型号：{{ v.instNameEn }}</p>
              <p>仪器负责人：{{ v.instHeadName }}</p>
            </li>
          </ul>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card header="通知公告">
          <div slot="header"
               class="header">
            <h4>通知公告</h4>
          </div>
          <div class="link-list">
            <ul>
              <li v-for="item in noticeList"
                  :key="item.id">
                <div>
                  {{ item.noticeTitle }}
                </div>
                <span>{{ item.noticeTime.split(" ")[0] }}</span>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row class="flex mt12"
            :gutter="12">
      <el-col :span="12">
        <el-card>
          <div slot="header"
               class="header">
            <h4>科研平台</h4>
          </div>
          <ul class="platform-list">
            <li>
              <div class="text">
                <header>
                  <p>分子生物平台</p>
                  <span>单价：¥100/小时</span>
                </header>
                <p>位置：7栋6层-分子生物平台中心-12号终端</p>
                <p>有效时间：1月1日 12：00 -- 1月15日 12:00</p>
              </div>
              <div class="btn">
                <header>
                  <p>剩余时长</p>
                  <p class="remain-time">2天18小时</p>
                </header>
                小计：¥300
              </div>
            </li>
            <li>
              <div class="text">
                <header>
                  <p>分子生物平台</p>
                  <span>单价：¥100/小时</span>
                </header>
                <p>位置：7栋6层-分子生物平台中心-12号终端</p>
                <p>有效时间：1月1日 12：00 -- 1月15日 12:00</p>
              </div>
              <div class="btn">
                <header>
                  <p>剩余时长</p>
                  <p class="remain-time">2天18小时</p>
                </header>
                小计：¥300
              </div>
            </li>
          </ul>
        </el-card>
        <el-card class="mt12">
          <div slot="header"
               class="header">
            <h4>笼位管理(共3个)</h4>
          </div>
          <ul class="cage-list">
            <li>
              <header>
                <p>实验用小鼠-3只</p>
                <el-tag type="primary"
                        size="mini">正常</el-tag>
              </header>
              <p>位置：7栋6层-602室 4区12号架 8号笼</p>
              <p>到期时间：2月1日（剩余10天）</p>
            </li>
            <li>
              <header>
                <p>实验用小鼠-3只-笼位申请</p>
                <el-tag type="warning"
                        size="mini">待分配</el-tag>
              </header>
              <p>位置：待分配</p>
              <p>申请时间：2月1日</p>
            </li>
            <li>
              <header>
                <p>实验用小鼠-3只</p>
                <el-tag type="primary"
                        size="mini">正常</el-tag>
              </header>
              <p>位置：7栋6层-602室 4区12号架 8号笼</p>
              <p>到期时间：2月1日（剩余10天）</p>
            </li>
          </ul>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="calendar">
          <div slot="header"
               class="header">
            <h4>日程安排</h4>
          </div>
          <FullCalendar class="fullCalendar"
                        ref="fullCalendar"
                        :options="calendarOptions" />
          <ul>
            <li>仪器：需要进行第二期临床实验使用仪器</li>
            <li>平台：需要使用平台查找相应的案例</li>
            <li>笼位：进行第二次动物实验</li>
            <li>技术：约李老师进行第三次技术咨询</li>
          </ul>
        </el-card>
        <el-card class="mt12 cost">
          <div slot="header"
               class="header">
            <h4>费用统计</h4>
          </div>
          <div class="chart-container">
            <div class="text">
              <header>课题组：人血球免疫蛋白应用研究课题组</header>
              <ul>
                <li>费用账单：6条待确认</li>
                <li>本月支出：¥567.89</li>
                <li>累计支出：¥1234.56</li>
              </ul>
            </div>
            <div id="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row class="flex mt12 technical"
            :gutter="12">
      <el-col :span="24">
        <el-card>
          <div slot="header"
               class="header">
            <h4>技术服务</h4>
          </div>
          <p>技术服务 - No.123456 - 李老师</p>
          <ul>
            <li>11-20：委托发起</li>
            <li>11-21：项目确定</li>
            <li>11-23：项目开始</li>
            <li>11-23：阶段性结果</li>
            <li>当前：结尾验收</li>
            <li>费用结算</li>
            <li>结果上传</li>
          </ul>
          <p>技术服务 - No.123456 - 李老师</p>
          <ul>
            <li>11-20：委托发起</li>
            <li>11-21：项目确定</li>
            <li>11-23：项目开始</li>
            <li>11-23：阶段性结果</li>
            <li>当前：结尾验收</li>
            <li>费用结算</li>
            <li>结果上传</li>
          </ul>
        </el-card>
      </el-col>
    </el-row>
    <FileUploadDialog ref="fileUploadDialogRef"></FileUploadDialog>
  </div>
</template>

<script>
import Banner from "../../components/Banner";
import LeftTabs from "@/components/LeftTabs";
import RightContent from "@/components/RightContent";
import * as echarts from "echarts";
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 PersonalInfoDialog from "@/components/PersonalInfo";
import FileUploadDialog from "@/views/PersonalCenter/file-upload.vue";
export default {
  name: "PersonalCenter",
  components: {
    Banner,
    LeftTabs,
    RightContent,
    FullCalendar,
    PersonalInfoDialog,
    FileUploadDialog,
  },
  data() {
    return {
      active: -1,
      loading: true,
      selectTab: {},
      searchForm: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      options: [
        {
          label: "工作台",
        },
        {
          label: "预约信息",
        },
      ],
      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.curTime = this.getToday();
    this.initChart();
    this.getNotice();
    this.getInstr();
  },
  beforeDestroy() {
    this.chart && this.chart.dispose()
  },
  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];
      }
      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 }];
      if (index == 1) {
        this.getAppointList();
      }
    },
    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 || [];
    },
    initChart() {
      let chart = echarts.init(document.getElementById("chart"));
      const options = {
        series: [
          {
            type: "gauge",
            startAngle: 180,
            endAngle: 0,
            center: ["50%", "75%"],
            radius: "90%",
            min: 0,
            max: 1,
            splitNumber: 8,
            axisLine: {
              lineStyle: {
                width: 6,
                color: [
                  [0.25, "#FF6E76"],
                  [0.5, "#FDDD60"],
                  [0.75, "#58D9F9"],
                  [1, "#7CFFB2"],
                ],
              },
            },
            pointer: {
              icon: "path://M12.8,0.7l12,40.1H0.7L12.8,0.7z",
              length: "12%",
              width: 20,
              offsetCenter: [0, "-60%"],
              itemStyle: {
                color: "auto",
              },
            },
            axisTick: {
              length: 12,
              lineStyle: {
                color: "auto",
                width: 2,
              },
            },
            splitLine: {
              length: 20,
              lineStyle: {
                color: "auto",
                width: 5,
              },
            },
            axisLabel: {
              color: "#464646",
              fontSize: 14,
              distance: -40,
              rotate: "tangential",
              formatter: function (value) {
                if (value === 0.875) {
                  return "充足";
                } else if (value === 0.625) {
                  return "可控";
                } else if (value === 0.375) {
                  return "紧张";
                } else if (value === 0.125) {
                  return "危险";
                }
                return "";
              },
            },
            title: {
              offsetCenter: [0, "-10%"],
              fontSize: 14,
            },
            detail: {
              fontSize: 20,
              offsetCenter: [0, "-35%"],
              valueAnimation: true,
              formatter: function (value) {
                return Math.round(value * 100) + "";
              },
              color: "inherit",
            },
            data: [
              {
                value: 0.7,
                name: "危险预算余额",
              },
            ],
          },
        ],
      };
      chart.setOption(options);
    },
    handleDateClick(dateClickInfo) {
      console.log(dateClickInfo);
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.getAppointList();
    },
    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.getAppointList();
    },
    openUploadDialog() {
      console.log('传递参数:id为申请单id')
      this.$refs.fileUploadDialogRef.openDialog(1);
    }
  },
};
</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>
