<!--我的收益首页-->
<template>
  <div>
    <div class="MyMomeny">
      <div>
        <p>可提现</p>
        <p>{{ UserData.withdrawablePrice | getPrice }}</p>
      </div>

      <div class="MomenyInfo">
        <div>
          <p>累计</p>
          <p>{{ UserData.cumulativePrice | getPrice }}</p>
        </div>
        <div>
          <p>待入账</p>
          <p>{{ UserData.toBeRecordedPrice | getPrice }}</p>
        </div>
        <div>
          <p>提现中</p>
          <p>{{ UserData.withdrawingPrice | getPrice }}</p>
        </div>
      </div>
    </div>
    <div class="container">
      <div style="text-align: left; font-size: .32rem; margin-left: .2rem; margin-bottom: .2rem">
        当月合计：{{MonthTotalEarnings | getPrice}}</div>
      <div>
        <div>
          <div class="btn" @click="layOut">
            <span>{{ this.nowdate }}</span>
            <img :src="require('@/assets/images/profit/jiantou.png')" ref="jiantou" />
          </div>
          <div id="sum_earnings"></div>
        </div>
        <div>
          <div class="incometable">
            <dl ref="incometable">
              <li>
                <dt>日期</dt>
                <dt>收入</dt>
              </li>
              <li v-for="(item, index) in ProfitList" :key="index">
                <dd>{{ item.time | getTime }}</dd>
                <dd>{{ item.totalProfitPrice | getPrice }}</dd>
              </li>
            </dl>

            <div class="tableinfo" @click="openinfo(UserData.dailyProfitList.length,revenueNumber)" ref="tableinfo">
              {{ this.showinfo.ys1 == true ? "展开" : "收缩" }}
              <img :src="require('@/assets/images/profit/jt1.png')" ref="jiantou" />
            </div>
          </div>
        </div>

        <div class="bingtu">
          <div id="pie_chat"></div>
        </div>
        <div class="recentincome">
          <div class="rec_header">
            <p>最近收入</p>
            <div @click="jumpToList(nowdate)">查看更多&nbsp;></div>
          </div>
          <div class="ifNoData" v-if="UserData.recentProfitList!==undefined && UserData.recentProfitList.length<=0">
            最近暂无收入~~</div>
          <div class="rec_body">
            <ul>
              <li v-for="(item, index) in UserData.recentProfitList" :key="index" v-if="index<5"
                @click="jumpToDetail(item.id, item.type)">
                <img :src="item.sceneIcon" />
                <div>
                  <p>{{ typeTips[item.type] }}</p>
                  <p>{{ item.orderCode| ellipsis}}</p>
                  <p>{{ item.createTime |compatibleDate}}</p>
                </div>
                <div>
                  <p class="price_red">+{{ item.price | getPrice }}</p>
                  <p>{{ statusTips[item.status] }}</p>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <ChooseDateAlert @confirm="getdateData" @cancel="onshow = false" :onshow="onshow"></ChooseDateAlert>
  </div>
</template>
<script>
  import ChooseDateAlert from "./../doctorComponents/ChooseDateAlert"; //选择日期弹窗
  export default {
    components: {
      ChooseDateAlert
    },
    name: "MyProfitIndex",
    filters: {
      ellipsis (value) {
        if (!value) return ''
        if (value.length > 20) {
          return value.slice(0,20) + '...'
        }
        return value
      },
      getTime(value) {
          return value.split(" ")[0];
      }
    },
    data() {
      return {
        MonthTotalEarnings: 0, // 当月合计收益
        UserData: {},
        revenueNumber: 5, //每日收入 为展开条数
        ProfitList: {},
        typeImg: [
          require("@/assets/images/profit/type_2.png"),
          require("@/assets/images/profit/type_1.png"),
          require("@/assets/images/profit/type_3.png")
        ],
        symbolSize: 5,
        maxValue: null,
        minValue: 0,
        points: [],
        lay_type: 1, //切换箭头图标
        nowdate: `${new Date().getFullYear()}年${new Date().getMonth() + 1}月`,
        onshow: false, //弹窗显示
        showinfo: {
          ys1: true,
          ys2: false
        },
        indexDate: {
          time: `${new Date().getFullYear()}-${new Date().getMonth() +
          1}-${new Date().getDay()}`
        },
        bingtuColor: [],
        //状态
        statusTips: {
          1: "已入账",
          2: "待入账",
          3: "已取消",
          4: "已提现",
          5: "提现中",
          6: "已扣除"
        },
        //类型
        typeTips: {
          1: "在线问诊",
          2: "处方购药",
          3: "下级利润",
          4: "销售额达标利润"
        }
      };
    },
    created() {
      this.GetDoctorProfit(this.nowdate);
      // this.getdatamax(this.ProfitList);
    },
    mounted() {
      let Pie_chat = this.$echarts.init(document.getElementById("pie_chat"));
      // let date = this.getnowdate(this.nowdate);
      // Pie_chat.on("click", this.jumpToList(date, 2));
    },
    methods: {
      drawLine: function (name, zxData) {
        const interval = this.getLeftData(this.minValue, this.maxValue);
        var faultByHourIndex = zxData.length; //播放所在下标
        var faultByHourTime = setTimeout(function () {
          name.dispatchAction({
            type: "showTip", // 根据 tooltip 的配置项显示提示框。
            seriesIndex: 0,
            dataIndex: faultByHourIndex - 1
          });
        }, 1000);
        // name.getZr().on("click", function(params) {
        //   let point = [params.offsetX, params.offsetY];
        //   console.log(point);
        //   if (name.containPixel("gird", point)) {
        //     // let xIndex = myChart.convertFromPixel({ seriesIndex: 0 }, point)[1];
        //     // let op = myChart.getOption();
        //     // let name = op.xAxis[0].data[xIndex];
        //     console.log("sdasd");
        //   }
        // });
        name.setOption({
          color: ["#478bfb"],
          title: {
            text: "每日收入"
          },
          tooltip: {
            trigger: "item", //触发类型；轴触发，axis则鼠标hover到一条柱状图显示全部数据，item则鼠标hover到折线点显示相应数据，
            backgroundColor: "transparent",
            formatter: function (params) {
              var data = params.data || [1, 1];
              var html =
                `<div class="tip" id="tip"><div class="san"></div><div>${params.data[2]}月${params.data[0]}号</div><div>+${params.data[1]}</div></div> `;
              return html;
            },
            position: function (point, params, dom, rect, size) {
              //其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
              var x = point[0]; //
              var y = point[1];
              var viewWidth = size.viewSize[0];
              var viewHeight = size.viewSize[1];
              var boxWidth = size.contentSize[0];
              var boxHeight = size.contentSize[1];
              var posX = 0; //x坐标位置
              var posY = 0; //y坐标位置

              if (x < boxWidth) {
                //左边放不开
                posX = x - boxWidth;
              } else {
                //左边放的下
                posX = x - boxWidth;
              }

              if (y < boxHeight) {
                //上边放不开
                posY = 5;
              } else {
                //上边放得下
                posY = y - boxHeight;
              }

              return [posX, posY];
            }
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true
          },
          xAxis: {
            min: 1,
            max: 30,
            type: "value",
            axisTick: {
              show: false
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: "#000", //更改坐标轴文字颜色
                fontSize: 14 //更改坐标轴文字大小
              }
            },
            axisLine: {
              lineStyle: {
                color: "#90b5f0" //更改坐标轴颜色
              }
            },
            splitLine: {
              show: false,
              lineStyle: {
                color: "#e4e4e4"
              }
            } //去除网格线
          },
          yAxis: {
            min: interval.min,
            max: interval.max,
            interval: interval.interval,
            scale: true,
            axisTick: {
              show: false
            },
            axisLabel: {
              show: false
            },
            splitLine: {
              show: true
            }, //去除网格线
            axisLine: {
              onZero: false,
              lineStyle: {
                color: "transparent"
              }
            }
          },
          series: [{
            id: "a",
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: this.symbolSize,
            data: zxData
          }]
        });
      },

      drawLine_2: function (name, classData) {
        var bingtuColor = [];
        //有无数据添加颜色
        if (classData.length == 0) {
          bingtuColor = ["#e4e4e4"];
          classData = [{
            value: 0,
            name: "全部收入"
          }];
        } else {
          bingtuColor = ["#66f7ef", "#1e89f4", "#ffbe08", "#07c160"];
        }
        name.setOption({
          title: {
            text: "收入分类",
            left: "left"
          },
          series: [{
            name: "访问来源",
            type: "pie",
            radius: ["30%", "60%"],
            avoidLabelOverlap: true,    // 防止标签重复堆叠
            hoverAnimation: false, //选中饼图该区域放大
            minAngle: 35,
            label: {
              normal: {
                formatter: "+{c}\n{b}",
                textStyle: {
                  fontWeight: "normal",
                  fontSize: 12,
                  borderWidth: 20,
                  borderRadius: 4,
                  padding: [0, -50],
                  color: "#000"
                },
                lineHeight: 20
              }
            },
            //点击文字放大
            // emphasis: {
            //   label: {
            //     show: true,
            //     fontSize: "10",
            //     fontWeight: "bold"
            //   }
            // },
            labelLine: {
              show: false
            },
            data: classData,
            itemStyle: {
              normal: {
                show: true,
                // position: "inner", //标签的位置
                textStyle: {
                  fontWeight: 200,
                  fontSize: 10 //文字的字体大小
                },
                color: function (params) {
                  //自定义颜色
                  var colorList = bingtuColor;
                  return colorList[params.dataIndex];
                },
                labelLine: {
                  //指示线状态
                  show: true,
                  length: 10,
                  length2: 50
                }
              },
              show: false,
              borderColor: "#000",
              borderWidth: 1
            }
          }]
        });
      },
      // 获取最大值和最小值 这个函数只是自己处理最大值最小值的方案，只作为参考
      getNumber(data) {
        this.maxValue = Math.ceil(Math.max.apply(null, data));
        const minData = Math.min.apply(null, data);
        const minfloor = Math.floor(Math.min.apply(null, data));
        this.minValue = minfloor === minData ? minData - 1 : minfloor;
      },
      // 计算间隔，返回最大值，最小值 ，间隔
      getLeftData(min, max) {
        // 控制分割条数，
        const distance = parseInt(((max - min) / 3).toString(), 10);
        return {
          max: 3 * distance + min + 3,
          min,
          interval: distance + 1
        };
      },
      //切换箭头图标
      layOut() {
        this.onshow = !this.onshow;
        if (this.lay_type == 0) {
          this.lay_type = 1;
        } else {
          this.lay_type = 0;
        }

        // let self = this
        // self.$refs["openAlert"].openAlert(this.onshow)
      },
      openinfo(length, number) {
        this.showinfo.ys1 = !this.showinfo.ys1;
        this.showinfo.ys2 = !this.showinfo.ys2;
        if (this.showinfo.ys1) {
          this.$refs.incometable.style.height = 1.09 + 1.09 * number + "rem";
        } else {
          this.$refs.incometable.style.height = 1.09 + 1.09 * length + "rem";
        }
      },
      getdateData(data) {
        var {
          currentDate,
          show
        } = data;
        this.nowdate = `${currentDate.getFullYear()}年${currentDate.getMonth() +
        1}月`;
        this.onshow = show;
      },
      getPrice(val) {
        let valout = isNaN(val)|| isNaN(Number(val)) || val ==0 ? 0: (val / 100).toFixed(2);
        return valout;
      },
      getCaption(obj) {
        var index = obj.lastIndexOf("年");
        obj = obj.substring(index + 1, obj.length);
        console.log(obj);
        // return obj;
      },
      jumpToDetail(id, type) {
        this.$router.push({
          path: "/profitInfo",
          query: {
            id,
            type
          }
        });
      },
      //跳转列表
      jumpToList(nowdate, Type) {
        var date = this.getnowdate(nowdate);
        this.$router.push({
          path: "/bill",
          query: {
            date,
            Type
          }
        });
      },
      dataProcessing(data) {
        var classData = [];
        var zxData = [];
        let sum_earnings = this.$echarts.init(
          document.getElementById("sum_earnings")
        );
        let Pie_chat = this.$echarts.init(document.getElementById("pie_chat"));
        //折线图数据处理
        data.dailyProfitList.map((item, index) => {
          var price = this.getPrice(item.totalProfitPrice);
          zxData.push([index + 1, price, this.getTimeMonth(item.time)]);
        });
        //饼图数据处理
        data.monthlyProfitList.map((item, index) => {
          var name = this.typeTips[item.type];
          var price = this.getPrice(item.profitPrice);
          classData.push({
            value: price,
            name: name,
            Type: item.type
          });
        });

        this.drawLine(sum_earnings, zxData);
        this.drawLine_2(Pie_chat, classData);
        let date = this.getnowdate(this.nowdate);
        // Pie_chat.on("click", this.jumpToList(date, 2));
        // Pie_chat.on("click", param => {
        //   this.jumpToList(date, param.data.Type);
        // });

        //初始展开收缩特效
        if (data.dailyProfitList.length > this.revenueNumber) {
          this.$refs.tableinfo.style.display = "block";
          this.$refs.incometable.style.height =
            1.09 + 1.09 * this.revenueNumber + "rem";
        }
      },
      GetDoctorProfit(nowdate) {
        var date = this.getnowdate(nowdate);
        var obj = {
          time: date
        };
        this.LJ_LOADING();
        this.$http.GetDoctorProfit(obj).then(res => {
          console.log(res);
          this.$toast.clear();
          this.UserData = {
            cumulativePrice: 0,
            withdrawablePrice: 0,
            toBeRecordedPrice: 0,
            withdrawingPrice: 0,
            recentProfitList: []
          };
          if (res.data.success) {
            let sum = 0;
            this.UserData = res.data.result;
            res.data.result.dailyProfitList.forEach((item, index) => {
              return sum += item.totalProfitPrice;
            })
            this.MonthTotalEarnings = sum.toFixed(2);
            this.maxValue = this.getdatamax(this.UserData.dailyProfitList);
            this.dataProcessing(res.data.result);
            this.ProfitList = this.UserData.dailyProfitList.reverse();
            //数据处理
          } else {
            this.$toast(res.data.message);
          }
          // console.log(this.UserData);
        });
      },
      //过滤时间选取月份
      getTimeMonth(value) {
        var month = value.substring(5, 7);
        if (month.substr(0, 1).indexOf("0") != -1) {
          return month.slice(1, 2);
        } else {
          return month;
        }
      },
      //过滤当前时间
      getnowdate(value) {
        if (value) {
          return value.replace("年", "-").replace("月", "");
        } else {
          return;
        }
      },
      getdatamax(arr) {
        // var max = arr.sort((a, b) => {
        //   return b - a;
        // })[0].TotalProfitPrice;
        var maxi = 0;
        for (var i = 0; i < arr.length; i++) {
          if (arr[maxi].totalProfitPrice <= arr[i].totalProfitPrice) {
            maxi = i;
          }
        }
        return this.getPrice(arr[maxi].totalProfitPrice + 10000);
        // console.log(max);
        // arr.map((i,item)=>{
        //   if(item.TotalProfitPrice<)
        // })
      }
    },
    watch: {
      nowdate(newValue) {
        this.GetDoctorProfit(newValue);
      }
    }
  };
</script>
<style scoped lang="less">
  /deep/.van-picker__toolbar {
    display: none;
  }

  /deep/ .van-picker-column__item--selected {
    color: @baseBlue;
  }

  .flex-col {
    display: flex;
    flex-flow: column nowrap;
    justify-content: space-between;
  }

  .blueborder {
    width: 6rem;
    height: 0.94rem;
    border-top: 0.01rem solid @bordercolor;
    border-bottom: 0.01rem solid @bordercolor;
    position: absolute;
    top: 50%;
    margin-top: -0.475rem;
    left: 50%;
    margin-left: -3rem;
  }

  .flex {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
  }

  @baseBlue: #478bfb;
  @boxShadow: 0rem 0.01rem 0.1rem 0rem #00000026;
  @graycolor: #999999;
  @xiancolor: #f1f1f1;
  @bordercolor: #c7dbfd;
  @qiangray: #e4e4e4;

  // .yangshi1 {
  //   height: 5.5rem;
  // }
  // .yangshi2 {
  //   height: 7.7rem;
  // }
  .MyMomeny {
    overflow: hidden;
    box-shadow: @boxShadow;

    >div:first-child {
      width: 100%;
      height: 3.4rem;
      background-color: @baseBlue;
      display: flex;
      flex-flow: column nowrap;
      justify-content: center;
      align-items: center;
      color: #fff;

      >p:first-child {
        font-size: 0.35rem;
        margin: 0.3rem;
      }

      >p:nth-child(2) {
        font-size: 1rem;
      }
    }

    .MomenyInfo {
      margin: 0.25rem 0;
      .flex();

      >div {
        width: 32%;
        height: 0.83rem;
        border-right: 0.01rem solid #ddd;
        .flex-col();
        justify-content: center;
        align-items: center;

        p {
          font-size: 0.25rem;
          margin: 0.05rem;
        }
      }
    }
  }

  .container {
    >div {
      width: 7rem;
      margin: 0 auto;
    }

    margin-top: 1rem;
    box-shadow: 0rem -0.05rem 0.05rem 0rem #00000014;
    position: relative;
    padding-top: 0.5rem;

    .btn {
      width: 2.5rem;
      height: 0.73rem;
      line-height: 0.73rem;
      font-size: 0.3rem;
      color: #fff;
      background-color: @baseBlue;
      margin: 0 auto;
      border-radius: 0.35rem;
      position: absolute;
      top: -0.4rem;
      left: 50%;
      margin-left: -1.25rem;
      letter-spacing: 0.02rem;

      img {
        width: 0.28rem;
        height: 0.14rem;
      }
    }

    #sum_earnings {
      width: 100%;
      height: 4.3rem;
    }

    .incometable {
      width: 5.8rem;
      margin: 0.5rem auto;
      box-shadow: 0rem 0rem 0.1rem 0.01rem #97bdfd;
      font-size: 0.35rem;

      dl {
        width: 100%;
        overflow: hidden;
        transition: all 1s;

        >li {
          width: 100%;
          border-bottom: 0.01rem solid #e4e4e4;
          height: 1.09rem;
          line-height: 1.09rem;
          .flex();
        }

        dt,
        dd {
          width: 50%;
          text-align: center;
        }

        dd {
          font-size: 0.3rem;
        }

        dt {
          font-size: 0.32rem;
          font-weight: bold;
        }

        dt:first-child {
          position: relative;
        }

        dt:first-child::after {
          content: "";
          width: 0.01rem;
          height: 0.5rem;
          border-left: 0.01rem solid #e4e4e4;
          position: absolute;
          top: 50%;
          margin-top: -0.25rem;
          right: 0;
        }
      }

      .tableinfo {
        font-size: 0.25rem;
        height: 1rem;
        line-height: 1rem;
        display: none;

        img {
          width: 0.28rem;
          height: 0.14rem;
        }
      }
    }

    #pie_chat {
      width: 100%;
      height: 6.5rem;
      // pointer-events: none;
    }

    .recentincome {
      width: 6.5rem;
      margin: 0 auto;

      .ifNoData {
        width: 100%;
        height: 2rem;
        line-height: 2.5rem;
        color: @qiangray;
        font-size: 0.28rem;
        text-align: center;
      }

      .rec_header {
        height: 0.5rem;
        line-height: 0.5rem;
        border-bottom: 0.01rem solid #e4e4e4;
        .flex();

        p {
          font-size: 0.32rem;
        }

        div {
          color: @graycolor;
          font-size: 0.25rem;
        }
      }

      .rec_body {
        ul {
          .flex-col();

          li {
            display: flex;
            flex-flow: row nowrap;
            justify-content: space-between;
            align-items: center;
            padding: 0.25rem 0;
            border-bottom: 0.01rem solid @xiancolor;

            img {
              width: 100%;
              height: 100%;
              object-fit: contain;
              width: 1.14rem;
              height: 1.12rem;
              border-radius: 0.25rem;
            }

            >div:nth-child(2) {
              width: 2.8rem;
              .flex-col();

              p {
                color: @graycolor;
                text-align: left;
                margin: 0.1rem 0;
              }

              p:first-child {
                font-size: 0.35rem;
                color: #000;
              }
            }

            >div:nth-child(3) {
              width: 1.35rem;
              display: flex;
              flex-flow: column nowrap;
              align-items: center;
              justify-content: center;

              p {
                font-size: 0.28rem;
                margin: 0.1rem 0;
                color: @graycolor;
              }

              .price_red {
                color: red;
                font-size: 0.35rem;
              }
            }
          }
        }
      }
    }
  }

  /deep/.tip {
    width: 1.2rem;
    height: 0.7rem;
    line-height: 0.35rem;
    border-radius: 0.15rem;
    background: linear-gradient(45deg, #70a4fa, #478bfb);
    color: #fff;
    position: relative;
    top: -0.2rem;
    left: 53%;
    font-size: 0.2rem;

    &::after {
      position: absolute;
      bottom: -0.08rem;
      right: 0.45rem;
      border: 0.1rem solid;
      border-color: transparent transparent currentColor currentColor;
      -webkit-transform: rotate(-45deg);
      transform: rotate(-45deg);
      opacity: 0.8;
      color: #478bfb;
      content: "";
    }
  }

  /deep/ .tip2 {
    width: 1.2rem;
    height: 1rem;
    text-align: right;
  }

  /deep/ #sum_earnings {
    >div {
      z-index: 10 !important;
    }
  }
</style>