<template>
  <view class="mypage">
    <view class="myTop">
      <view class="goWork" @click="GoWork()">
        <view class="goWork_btn_E">
          <view class="goWork_btn_W" v-show="userData.online"> 下班 </view>
          <view class="goWork_btn_X" v-show="!userData.online"> 上班 </view>
        </view>
      </view>
      <view class="topText">
        <view class="topTextHeader">
          <text>您好,{{ userData.name }}</text>
          <button v-show="!userData.online" class="changeHospital" size="mini" type="default"
            @click="changeHospital">切换院区</button>
        </view>
        <view>当前积分 : {{ tabNum.score }}</view>
      </view>
    </view>
    <view class="myCont">
      <view class="myCont_cont">
        <view class="myCont_cont_tab">
          <view style="border-right: 1px solid rgb(229, 233, 237)" @click="tab('day', '今日')"
            :class="{ acts: tabType == 'day' }">
            今日 ({{ tabNum.day || 0 }})
          </view>
          <view style="border-right: 1px solid rgb(229, 233, 237)" @click="tab('week', '本周')"
            :class="{ acts: tabType == 'week' }">
            本周 ({{ tabNum.week || 0 }})
          </view>
          <view @click="tab('month', '本月')" :class="{ acts: tabType == 'month' }">
            本月 ({{ tabNum.month || 0 }})
          </view>
        </view>
        <view class="TB" v-show="tabNums > 0 && !TBLoading">
          <view class="TB_inner" style="
              display: flex;
              align-items: center;
              justify-content: space-between;
            ">
            <view class="tbTitle"> {{ types }}已完成工单{{ tabNums }}单，未评价工单{{tabEvaluate}}单，共计得分{{tabScores}}分 </view>
            <view class="tbText" @click="my_list(tabType)"> 查看明细>> </view>
          </view>
          <view class="canvasRing_wrap">
            <canvas ref="canvasRef" canvas-id="canvasRing" id="canvasRing" class="charts"
              @touchstart="touchRing"></canvas>
          </view>
        </view>
        <view class="TB1" v-show="tabNums == 0 && !TBLoading">
          <view class="title"> {{ types }}已完成工单{{ tabComplete }}单，未评价工单{{tabEvaluate}}单，共计得分{{tabScores}}分 </view>
          <view class="cont"> 暂无数据 </view>
        </view>
        <view class="TB_list" v-show="!TBLoading">
          <view v-for="(data, i) of BtData" :key="i">
            <view class="TB_list_L">
              {{ data.name }}
            </view>
            <view class="TB_list_R">
              {{ data.value }}单
              <text :style="{ color: data.itemStyle.color }">{{
                data.percent
              }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 弹窗 -->
    <showModel :title="models.title" :icon="models.icon" :disjunctor="models.disjunctor" :content="models.content"
      @ok="ok" @cancel="cancel" :operate="models.operate"></showModel>
    <!-- 切换院区弹窗 -->
    <changeHospital v-if="hosModels.disjunctor" :title="hosModels.title" :disjunctor="hosModels.disjunctor" @ok="hosOk"
      @cancel="hosCancel">
    </changeHospital>
  </view>
</template>
<script>
  import showModel from "../../components/showModel/showModel.vue";
  import changeHospital from "../../components/changeHospital/changeHospital.vue";
  // http://doc.ucharts.cn/1172177
  import uCharts from "../../js_sdk/u-charts/u-charts/u-charts.js";
  import {
    get,
    post,
    webHandle
  } from "../../http/http.js";
  export default {
    data() {
      return {
        // 弹窗model
        models: {
          disjunctor: false,
        },
        // 切换院区弹窗model
        hosModels: {
          disjunctor: false,
        },
        type: '',
        tabType: "day",
        tabNum: {},
        BtData: [],
        types: "今日",
        tabNums: "", //总数量
        tabComplete: "", //已完成工单数量
        tabEvaluate: "", //未评价工单数量
        tabScores: "", //积分
        sxbType: false,
        userData: {},
        // 图表数据
        cWidth: "",
        cHeight: "",
        pixelRatio: 1,
        serverData: "",
        canvaRing: null,
        TBLoading: false,
      };
    },
    components: {
      showModel,
      changeHospital,
    },
    methods: {
      // 切换院区-确认
      hosOk(hosId) {
        this.hosModels.disjunctor = false;
        uni.showLoading({
          title: '正在加载中',
          mask: true
        });
        let type = '';
        // #ifdef APP-PLUS
        type = 'APP';
        // #endif
        // #ifdef H5
        type = 'Wechat';
        // #endif
        post("/auth/changeHospital", {
          "currentHosId": hosId,
          loginType: type
        }).then(result => {
          uni.hideLoading()
          if (result.status == 200) {
            uni.showToast({
              icon: 'success',
              title: '切换院区成功'
            });
            let userData = uni.getStorageSync('userData');
            console.log(userData)
            userData.user.currentHospital = result.user.user.currentHospital;
            uni.setStorageSync('userData', userData);
            this.tab("day", "今日");
          } else {
            uni.showToast({
              icon: 'none',
              title: '切换院区失败'
            });
          }
        })
      },
      // 切换院区-取消
      hosCancel() {
        this.hosModels.disjunctor = false;
      },
      // 切换院区
      changeHospital() {
        this.hosModels = {
          title: '切换院区',
          disjunctor: true,
        }
      },
      // 绘图
      showRing(canvasId, chartData) {
        this.canvaRing = new uCharts({
          $this: this,
          canvasId: canvasId,
          type: "ring",
          fontSize: 11,
          padding: [5, 5, 5, 5],
          legend: {
            show: false, //右侧描述
            position: "right",
            float: "center",
            itemGap: 10,
            padding: 5,
            lineHeight: 26,
            margin: 5,
            borderWidth: 1,
          },
          background: "#FFFFFF",
          pixelRatio: this.pixelRatio,
          series: chartData.series,
          animation: true,
          width: this.cWidth * this.pixelRatio,
          height: this.cHeight * this.pixelRatio,
          disablePieStroke: true,
          dataLabel: false, //折线描述
          subtitle: {
            name: "",
            color: "#7cb5ec",
            fontSize: 25 * this.pixelRatio,
          },
          title: {
            name: "",
            color: "#666666",
            fontSize: 15 * this.pixelRatio,
          },
          extra: {
            pie: {
              offsetAngle: 0,
              ringWidth: 28 * this.pixelRatio,
              labelWidth: 15,
            },
          },
        });
        this.TBLoading = false;
        uni.hideLoading();
      },
      touchRing(e) {
        this.canvaRing.touchLegend(e, {
          animation: false,
        });
        this.canvaRing.showToolTip(e, {
          format: function(item) {
            return item.name + ":" + item.data;
          },
        });
      },
      // 查看明细
      my_list(type) {
        uni.navigateTo({
          url: `../my_list/my_list?type=${type}`,
        });
      },
      // 获取启动中的工作分配方案
      getWorkSchemeAndRule() {
        return post("/auth/getUserWorkDept", {});
      },
      // 获取执行中列表
      getWorkingNum() {
        return post("/workerOrder/executingOrders", {
          "idx": 0,
          "sum": 1
        });
      },
      //上下班弹窗确定
      ok() {
        this.models.disjunctor = false;
        let setDeptConfg = uni.getStorageSync("setDeptConfg");
        if (this.type == "on") {
          uni.redirectTo({
            url: `../homePage/homePage`,
          });
        } else if (this.type == "off") {
          uni.showLoading({
            title: "加载中",
            mask: true,
          });
          // 判断当前启用的工作方案是自主还是综合排班
          this.getWorkSchemeAndRule().then((ress) => {
            if (ress.status == 200) {
              let workType = ress.settings ? ress.settings.workType : -1; //1是综合，2是自主
              let ruleType = ress.settings ? ress.settings.ruleType : -1; //3是科室绑定人员
              // 自主下班,并且是科室绑定人员
              if (workType == 2 && ruleType == 3) {
                post("/auth/onOrOffLine", {
                  type: "off",
                  customWorking: "off",
                  classId:uni.getStorageSync("setDeptConfg").classesId
                }).then((res) => {
                  uni.hideLoading();
                  if (res.status == 200) {
                    let obj = uni.getStorageSync("userData");
                    obj.user.online = false;
                    if (uni.getStorageSync("setDeptConfg")) {
                      uni.removeStorageSync("setDeptConfg"); //清空选择的科室配置,初始化
                    }
                    if (uni.getStorageSync("setDepts")) {
                      uni.removeStorageSync("setDepts"); //清空选择的科室,初始化
                    }
                    uni.setStorageSync("userData", obj);
                    this.getCurrentUser();
                    this.getTabData();
                  } else {
                    uni.showToast({
                      icon: "none",
                      title: "请求失败！",
                    });
                  }
                });
              } else {
                post("/auth/onOrOffLine", {
                  type: "off",
                  classId:uni.getStorageSync("setDeptConfg").classesId
                }).then((res) => {
                  uni.hideLoading();
                  if (res.status == 200) {
                    if (uni.getStorageSync("setDeptConfg")) {
                      uni.removeStorageSync("setDeptConfg"); //清空选择的科室配置,初始化
                    }
                    if (uni.getStorageSync("setDepts")) {
                      uni.removeStorageSync("setDepts"); //清空选择的科室,初始化
                    }
                    let obj = uni.getStorageSync("userData");
                    obj.user.online = false;
                    uni.setStorageSync("userData", obj);
                    this.getCurrentUser();
                    this.getTabData();
                  } else {
                    uni.showToast({
                      icon: "none",
                      title: "请求失败！",
                    });
                  }
                });
              }
            } else {
              uni.hideLoading();
              uni.showToast({
                icon: "none",
                title: "请求失败！",
              });
            }
          });
        }
      },
      //上下班弹窗取消
      cancel() {
        this.models.disjunctor = false;
      },
      // 上下班
      async GoWork() {
        let types = "";
        let workingNum = 0;
        if (this.userData.online) {
          //有online为上班 传off
          this.type = "off";
          uni.showLoading({
            title: '加载中',
            mask: true
          });
          let workingNumResult = await this.getWorkingNum();
          uni.hideLoading();
          if (workingNumResult.status == 200) {
            workingNum = workingNumResult.data.data.length;
          }
          if (workingNum) {
            types = "您还<b style='color:red'>有未完成的工单</b>，确定下班后，<b style='color:red'>未完成工单将不计算积分。</b>";
          } else {
            types = "确定是否下班 ?";
          }
        } else {
          this.type = "on";
          types = "确定是否上班 ?";
        }
        this.models = {
          disjunctor: true,
          title: this.type == 'off' ? '下班提醒' : "上班提醒",
          content: types,
          icon: "warn",
          operate: {
            ok: "确定",
            cancel: "取消",
          },
        };
      },
      //环形图数据
      getBtData() {
        get("/api/countOrderTypesByDate/" + this.tabType).then((res) => {
          if (res.status == 200) {
            this.BtData = [];
            let color = [
              "#39B199",
              "#56BAB6",
              "#A4C4C1",
              "#48717F",
              "#07863C",
              "#BEE1A7",
            ];
            for (var i = 0; i < res.data.length; i++) {
              let data = {
                value: Number,
                name: "",
                itemStyle: {
                  color: "",
                },
              };
              data.value = Number(res.data[i].num);
              data.percent = res.data[i].percent;
              data.name = res.data[i].name;
              data.itemStyle.color = color[i];
              this.BtData.push(data);
            }
            let Ring = {
              series: [],
            };
            let dataRing = res.data.map((item) => {
              return {
                name: item.name,
                data: item.num - 0,
              };
            });
            //这里我后台返回的是数组，所以用等于，如果您后台返回的是单条数据，需要push进去
            Ring.series = dataRing;
            console.log(this.tabNums);
            if (this.tabNums > 0) {
              this.showRing("canvasRing", Ring);
            } else {
              this.TBLoading = false;
              uni.hideLoading();
            }
          } else {
            this.TBLoading = false;
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: "请求失败！",
            });
          }
        });
      },
      //tab数据
      getTabData() {
        this.TBLoading = true;
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        get("/api/countOrderByDate").then((res) => {
          this.tabNum = res;
          if (this.tabType == "day") {
            this.tabNums = this.tabNum.day;
            this.tabComplete = this.tabNum.dayComplete;
            this.tabEvaluate = this.tabNum.dayEvaluate;
            this.tabScores = this.tabNum.dayTotal;
          }
          if (this.tabType == "week") {
            this.tabNums = this.tabNum.week;
            this.tabComplete = this.tabNum.weekComplete;
            this.tabEvaluate = this.tabNum.weekEvaluate;
            this.tabScores = this.tabNum.weekTotal;
          }
          if (this.tabType == "month") {
            this.tabNums = this.tabNum.month;
            this.tabComplete = this.tabNum.monthComplete;
            this.tabEvaluate = this.tabNum.monthEvaluate;
            this.tabScores = this.tabNum.monthTotal;
          }
          this.getBtData();
        });
      },
      // 本日,本周,本月
      tab(type, types) {
        this.types = types;
        this.tabType = type;
        this.getTabData();
      },
      // 获取当前用户信息
      getCurrentUser() {
        if (uni.getStorageSync("userData")) {
          this.userData = uni.getStorageSync("userData").user;
        } else {
          this.userData = {};
        }
      },
    },
    onLoad(options) {
      this.getCurrentUser();
      //#ifdef H5
      if (options.login == 1) {
        uni.redirectTo({
          url: "../homePage/homePage?type=mypage",
        });
      }
      //#endif
      if (options.login != 1) {
        this.tab("day", "今日");
      }

      //图表
      this.cWidth = uni.upx2px(500);
      this.cHeight = uni.upx2px(500);
      // #ifdef APP-PLUS
      webHandle("no", "app");
      // #endif
      // #ifdef H5
      webHandle("no", "wx");
      // #endif
    },
  };
</script>
<style lang="less">
  .mypage {
    .charts {
      width: 625upx;
      height: 500upx;
      background-color: #ffffff;
    }

    .canvasRing_wrap {
      background-color: #ffffff;
    }

    #canvasRing {
      left: 50%;
      margin-left: -250rpx;
    }

    .myTop {
      height: 390rpx;
      background-image: url(../../static/img/BG_xiaban.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;

      .goWork {
        margin: 0 auto 20rpx auto;
        padding-top: 30rpx;
        width: 240rpx;
        height: 240rpx;

        .goWork_btn_E {
          width: 100%;
          height: 100%;
          background: #bee1a7;
          border-radius: 30%;
          text-align: center;

          .goWork_btn_W {
            width: 75%;
            height: 75%;
            background-image: linear-gradient(to right, #72c172, #3bb197);
            border-radius: 30%;
            margin: 0 auto;
            /*水平居中*/
            position: relative;
            /*脱离文档流*/
            top: 12.5%;
            /*偏移*/
            line-height: 180rpx;
            color: #fff;
            font-size: 36rpx;
          }

          .goWork_btn_X {
            width: 75%;
            height: 75%;
            background-image: linear-gradient(to left, #72c172, #3bb197);
            border-radius: 30%;
            margin: 0 auto;
            /*水平居中*/
            position: relative;
            /*脱离文档流*/
            top: 12.5%;
            /*偏移*/
            line-height: 180rpx;
            color: #fff;
            font-size: 36rpx;
          }
        }
      }

      .topText {
        font-size: 36rpx;
        text-align: center;

        .topTextHeader {
          display: flex;
          justify-content: center;
          align-items: center;

          .changeHospital {
            margin-left: 16rpx;
            margin-right: 0;
          }
        }
      }
    }

    .myCont {
      .myCont_top {
        text-align: left;
        line-height: 90rpx;
        height: 90rpx;
        background: rgb(229, 233, 237);
        padding-left: 10rpx;
        padding-right: 10rpx;

        .myCont_topL {
          float: left;
          width: 60%;
          height: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .myCont_topR {
          width: 35%;
          height: 100%;
          float: right;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .myCont_cont {
        .myCont_cont_tab {
          height: 90rpx;
          line-height: 90rpx;
          font-size: 32rpx;
          border-bottom: 4rpx solid rgb(229, 233, 237);

          view {
            float: left;
            width: 33%;
            height: 100%;
            text-align: center;
          }
        }

        .TB {
          position: relative;

          .TB_inner {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
            margin-top: 26rpx;

            .tbTitle {
              width: 70%;
              font-size: 32rpx;
              color: rgb(72, 113, 127);
              font-weight: 500;
              margin-left: 10rpx;
            }

            .tbText {
              font-size: 32rpx;
              color: rgb(72, 113, 127);
              margin-right: 10rpx;
            }
          }
        }

        .TB1 {
          height: 200rpx;

          .title {
            text-align: left;
            font-size: 32rpx;
            color: rgb(72, 113, 127);
            font-weight: 500;
            margin-top: 26rpx;
            padding-left: 10rpx;
          }

          .cont {
            font-size: 36rpx;
            margin-top: 30rpx;
            text-align: center;
          }
        }

        .acts {
          color: rgb(73, 184, 86);
          border-bottom: 2rpx solid rgb(73, 184, 86);
        }

        .TB_list {
          width: 100%;
          text-align: left;

          view {
            height: 84rpx;
            line-height: 84rpx;
            border-bottom: 2rpx solid rgb(229, 233, 237);
            padding: 0 10rpx;
            font-size: 32rpx;

            .TB_list_L {
              float: left;
            }

            .TB_list_R {
              float: right;

              text {
                font-size: 28rpx;
              }
            }
          }
        }
      }
    }
  }
</style>
