/**
 * 互联网医院数据监测中心
 *  * Creator:     ML
 * CreatDate:   2020-05-26
 * descripts：  互联网医院数据监测中心 用户统计  实时下单情况 右 
 */
import React from 'react';
import { Form, Row, Col, Input, Button, message, Table, Select, Popconfirm, Modal, Steps, DatePicker, Switch, Icon, Upload, Spin, Radio } from 'antd';
import { Util, } from 'tools/index';
import '../style/index.less';
import DataSet from "@antv/data-set";
import store from '../../../store';
import { $http } from '../../../containers/config/https';
import { Chart, Geom, Axis, Coord, Label, Legend, Tooltip, Guide, Shape, G2, Facet, Interval, Line, Point } from 'bizcharts';
const { Html, Arc } = Guide;
let updateCharts;
class ShowUserStatisitcsBIPage extends React.Component {

  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData: userData,
      registeredValue: "month",
      visitUserValue: "month",
      visitUserData: [],
      avgGrade: [],
      avgDateTime: [],
      showVisitLoading: false,
      showRegisterLoading: false,
      showGradLoading: false,
      registeredUsersData: [
        { "docDesc": "5月21日", "clinic": "新增用户数", "flag": 1, "value": 1 },
        { "docDesc": "5月21日", "clinic": "下单用户数", "flag": 1, "value": 2 },
        { "docDesc": "5月22日", "clinic": "新增用户数", "flag": 1, "value": 3 },
        { "docDesc": "5月22日", "clinic": "下单用户数", "flag": 1, "value": 4 },
        { "docDesc": "5月23日", "clinic": "下单用户数", "flag": 1, "value": 5 },
        { "docDesc": "5月23日", "clinic": "新增用户数", "flag": 1, "value": 5 },
        { "docDesc": "5月24日", "clinic": "下单用户数", "flag": 1, "value": 15 },
        { "docDesc": "5月24日", "clinic": "新增用户数", "flag": 1, "value": 17 },
        { "docDesc": "5月25日", "clinic": "下单用户数", "flag": 1, "value": 21 },
        { "docDesc": "5月25日", "clinic": "新增用户数", "flag": 1, "value": 24 },
        { "docDesc": "5月26日", "clinic": "新增用户数", "flag": 1, "value": 23 },
        { "docDesc": "5月26日", "clinic": "下单用户数", "flag": 1, "value": 33 },
      ],
      tableOneData: [
        { docDesc: "唐文昌", admNum: "xys", admEffectNum: "图文咨询", admIneffectNum: "2020-05-11 19:08" },
        { docDesc: "唐文昌", admNum: "xys", admEffectNum: "视频问诊", admIneffectNum: "2020-05-12 19:02" },
        { docDesc: "李信安", admNum: "xys", admEffectNum: "图文咨询", admIneffectNum: "2020-05-13 17:20" },
        { docDesc: "郗粉丽", admNum: "新元素（全科医生）", admEffectNum: "视频问诊", admIneffectNum: "2020-05-14 16:00" },
        { docDesc: "黄江海", admNum: "刘晓意", admEffectNum: "视频问诊", admIneffectNum: "2020-05-11 10:10" },
        { docDesc: "yx", admNum: "张晨(专科医生)", admEffectNum: "图文咨询", admIneffectNum: "2020-05-18 09:32" },
        { docDesc: "王传", admNum: "李宏", admEffectNum: "视频问诊", admIneffectNum: "2020-05-14 19:00" },
        { docDesc: "张扬", admNum: "陈奕辰", admEffectNum: "图文咨询", admIneffectNum: "2020-05-16 19:00" },
        { docDesc: "罗叶辉", admNum: "张文", admEffectNum: "视频问诊", admIneffectNum: "2020-05-15 19:00" },
        { docDesc: "罗艺轩", admNum: "王红(专科)", admEffectNum: "视频问诊", admIneffectNum: "2020-05-11 19:00" },
      ]
    }
  }
  componentDidMount() {
    this.getGrade()
    this.getVisitUsers()
    // this.getRegisteredUsers()
    updateCharts = setInterval(() => {
      this.getGrade()
      this.getVisitUsers(this.state.visitUserValue)
      // this.getRegisteredUsers(this.state.registeredValue)
    }, 12 * 60 * 60 * 1000)
  }
  componentWillUnmount() {
    clearInterval(updateCharts)
  }

  //查询医院评价平均分,平均就诊时长
  getGrade = () => {
    const { userData, } = this.state
    this.setState({
      showGradLoading: true
    })
    let data = {}
    data = {
      params: [{
        hospID: userData && userData.hospID || "",
      }],
    };
    $http.post('urlS', this, {
      code: "03100133",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = []
          let arrs = []
          res.result.gradeData && res.result.gradeData.map((item, i) => {
            item.clinic = "患者评价"
            item.avgGrade = Number(item.avgGrade)
            arr.push(item)
          })
          res.result.avgDateTimeData && res.result.avgDateTimeData.map((items, index) => {
            items.clinic = "接诊时长"
            items.avgDateTime = Number(items.avgDateTime)
            arrs.push(items)
          })
          this.setState({
            avgGrade: arr,
            avgDateTime: arrs
          }, () => {
            this.setState({
              showGradLoading: false
            })
          })
        } else {
          this.setState({
            showGradLoading: false
          })
        }
      }, error: function () {
        this.setState({
          showGradLoading: false
        })
      }
    });
  }

  //就诊用户趋势
  getVisitUsers = (time) => {
    // 03100122
    const { userData, } = this.state
    this.setState({
      visitUserData: [],
      showVisitLoading: true
    }, () => {
      let data = {}
      data = {
        params: [{
          hospID: userData && userData.hospID || "",
          userID: userData && userData.userID || "",
          locID: userData && userData.locID || "",
          type: time || "month"
        }],
      };
      $http.post('urlS', this, {
        code: "03100132",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            let arr = []
            res.result.cumulativeList && res.result.cumulativeList.map((item, i) => {
              item.clinic = "新增注册用户"
              arr.push(item)
            })
            res.result.newlyList && res.result.newlyList.map((items, index) => {
              items.clinic = "新增就诊人次"
              arr.push(items)
            })
            // console.log("arr", arr)
            this.setState({
              visitUserData: arr
            }, () => {
              this.setState({
                showVisitLoading: false
              })
            })
          } else {
            this.setState({
              showVisitLoading: false
            })
          }
        }, error: function () {
          this.setState({
            showVisitLoading: false
          })
        }
      });
    })
  }
  handleTo = (name, time) => {
    let obj = {
      // "registered": () => this.getRegisteredUsers(time),
      "visitUser": () => this.getVisitUsers(time)
      //  "re":()=>this.getRegisteredUsers(name),
    }
    if (obj[name]) {
      obj[name]()
    }
  }
  handleChange = (e, name) => {
    if (e.target) {
      this.setState({
        [name + "Value"]: e.target.value
      }, () => {
        this.handleTo(name, e.target.value)
      })
    }
  }
  render() {
    let chartIns = null;
    const scale = {
      call: {
        min: 0
      },
      people: {
        min: 0
      },
      waiting: {
        min: 0
      }
    };
    Shape.registerShape('point', 'pointer', {
      drawShape(cfg, group) {
        let point = cfg.points[0]; // 获取第一个标记点
        point = this.parsePoint(point);
        const center = this.parsePoint({ // 获取极坐标系下画布中心点
          x: 0,
          y: 0,
        });
        // 绘制指针
        group.addShape('line', {
          attrs: {
            x1: center.x,
            y1: center.y,
            x2: point.x,
            y2: point.y,
            stroke: cfg.color,
            lineWidth: 5,
            lineCap: 'round',
          },
        });
        return group.addShape('circle', {
          attrs: {
            x: center.x,
            y: center.y,
            r: 12,
            stroke: cfg.color,
            lineWidth: 4.5,
            fill: '#fff',
          },
        });
      },
    });
    // const data = [
    //   { value: this.state.avgGrade && Number(this.state.avgGrade)},
    // ];
    const cols = {
      value: {
        min: 0,
        max: 5,
        tickInterval: 1,
        nice: false,
      },
    };

    const colsPointOne = {
      docDesc: {
        range: [0, 1]
      }
    };
    const colsPointGrad = {
      avgGrade: {
        min: 4,
        max: 5,
      },
      avgGradez: {
        min: 4,
        max: 5
      }
    };
    const dsRegistered = new DataSet();
    const dvRegistered = dsRegistered
      .createView()
      .source(this.state.registeredUsersData)
      .transform({
        type: "percent",
        field: "ordinate",
        // 统计销量
        dimension: "clinic",
        // 每年的占比
        groupBy: ["abscissa"],
        // 以不同产品类别为分组
        as: "percent"
      });

    const dsVisitUser = new DataSet();
    const dvVisitUser = dsVisitUser
      .createView()
      .source(this.state.visitUserData)
      .transform({
        type: "percent",
        field: "ordinate",
        // 统计销量
        dimension: "clinic",
        // 每年的占比
        groupBy: ["abscissa"],
        // 以不同产品类别为分组
        as: "percent"
      });
    const dsGrad = new DataSet();
    const dvGrad = dsGrad
      .createView()
      .source(this.state.avgGrade)
      .transform({
        // type: "percent",
        field: "avgGrade",
        // // 统计销量
        dimension: "clinic",
        // 每年的占比
        groupBy: ["abscissa"],
        // 以不同产品类别为分组
        as: "percent",
        type: "percent",

      });

    const dsGradTime = new DataSet();
    const dvGradTime = dsGradTime
      .createView()
      .source(this.state.avgDateTime)
      .transform({
        type: "percent",
        field: "avgDateTime",
        // 统计销量
        dimension: "clinic",
        // 每年的占比
        groupBy: ["abscissa"],
        // 以不同产品类别为分组
        as: "percent"
      });
    return <div className="orderLisiBI-dom">
      <div>
        <Row style={{ margin: "0px 0 12px 20px", backgroundColor: "rgb(0, 31, 95)", padding: "12px 6px" }}>
          <div style={{ color: "#fff", textAlign: "left" }}>
            用户趋势图
            {/* <p style={{ position: 'absolute',top:"10px",left:"6px",fontSize:"12px",top:"34px",left:"25px" }}>就诊人次</p> */}
            <div style={{ float: 'right' }}>
              <Radio.Group defaultValue='1' buttonStyle="solid" size='small' onChange={(e) => this.handleChange(e, "visitUser")} value={this.state.visitUserValue}>
                <Radio.Button value='month'>近6个月</Radio.Button>
                <Radio.Button value='day'>近7日</Radio.Button>
              </Radio.Group>
            </div>
          </div>
          <Spin spinning={this.state.showVisitLoading} style={{ background: "rgb(0, 31, 95)", marginTop: "10px" }}>
            <Chart height={240} data={dvVisitUser} scale={colsPointOne} forceFit className="order-charts"
              padding={[30, 30, 30, 60]}
            >
              <Legend
                position="top"
                // marker={(x, y, r) => {
                //   return [
                //     ['M', x - r, y],
                //     ['L', x + r, y]
                //   ];
                // }}
                marker="square"
                textStyle={{
                  fill: "#fff"
                }}
              />
              <Axis name="abscissa"
                label={{
                  textStyle: {
                    fill: '#fff', // 文本的颜色
                  }
                }}
                grid={null}
              />
              <Axis
                name="ordinate"
                label={{
                  formatter: val => `${val}`,
                  textStyle: {
                    fill: '#fff', // 文本的颜色
                  }
                }}
                grid={null}
              />
              <Tooltip
                crosshairs={{
                  type: "y"
                }}
              />
              <Geom
                type="line"
                position="abscissa*ordinate"
                size={2}
                color={"clinic"}
                shape={"smooth"}
              />
              <Geom
                type="point"
                position="abscissa*ordinate"
                size={4}
                shape={"circle"}
                color={"clinic"}
                style={{
                  stroke: "#fff",
                  lineWidth: 1
                }}
              />
            </Chart>
          </Spin>
        </Row>
        <Row style={{ margin: "0px 0 12px 20px", backgroundColor: "rgb(0, 31, 95)", padding: "12px 6px", }}>
          <div style={{ color: "#fff", textAlign: "left" }}>
            患者评价趋势
            {/* <p style={{ position: 'absolute',top:"10px",left:"6px",fontSize:"12px",top:"34px",left:"25px" }}>注册用户</p> */}
            <div style={{ float: 'right' }}>
              <Radio.Group buttonStyle="solid" size='small' value={"month"}>
                <Radio.Button value='month'>近6个月</Radio.Button>
              </Radio.Group>
            </div>
          </div>
          <Spin spinning={this.state.showGradLoading} style={{ background: "rgb(0, 31, 95)", marginTop: "10px" }}>
            <Chart
              width={600}
              height={(this.props.allHeight == true ? 350 : 240)} data={dvGrad}
              scale={colsPointGrad}
              forceFit className="order-charts"
              padding={[30, 30, 30, 60]}
              onGetG2Instance={chart => {
                chartIns = chart;
                chartIns.on('interval:mouseenter', e => {
                  chartIns.get('geoms').forEach(g => {
                    if (g.get('type') === 'interval') {
                      (g.getShapes() || []).forEach(s => {
                        s.set('origin_fill', s.get('attrs').fill);
                        s.attr('fill', '#3181bd');
                      });
                    }
                  });
                });
                chartIns.on('interval:mouseleave', e => {
                  chartIns.get('geoms').forEach(g => {
                    if (g.get('type') === 'interval') {
                      (g.getShapes() || []).forEach(s => {
                        s.attr('fill', s.get('origin_fill'));
                      });
                    }
                  });
                });
              }}
            >
              <Axis
                name="avgGrade"
                label={{
                  formatter: val => `${val}`,
                  textStyle: {
                    fill: '#fff', // 文本的颜色
                  }
                }}
                grid={null}
                visible={true}
              />
              <Axis name="abscissa"
                label={{
                  textStyle: {
                    fill: '#fff', // 文本的颜色
                  }
                }}
                grid={null}
                visible={true}
              />
              <Axis
                name="avgGradez"
                // grid={null}
                // label={{
                //   textStyle: {
                //     fill: "#fdae6b"
                //   }
                // }}
                visible={false}
              />
              <Tooltip
                shared={false}
                itemTpl='<li>
                <span style="margin-right:"2px">
                评分:{value}
                </span>
                </li>'
              />
              <Geom type="interval" position="abscissa*avgGrade" color="#3182bd">
                <Label
                  content="avgGrade"
                  offset={10} // 设置坐标轴文本 label 距离坐标轴线的距离
                  textStyle={{
                    textAlign: 'center', // 文本对齐方向，可取值为： start middle end
                    fill: '#ffffff', // 文本的颜色
                    fontSize: '12', // 文本大小
                    fontWeight: 'bold', // 文本粗细
                    textBaseline: 'middle' // 文本基准线，可取 top middle bottom，默认为middle
                  }}
                  //textStyle={()=>{}}// 支持回调 
                  position="middle"
                  autoRotate={false} // 是否需要自动旋转，默认为 true
                //     formatter={(val, item) => {
                //      if(val>4){
                //       return val
                //      }
                //   }
                // }
                />
              </Geom>
              <Geom
                type="line"
                position="abscissa*avgGradez"
                color="#fdae6b"
                size={3}
                shape="smooth"
              />
              <Geom
                type="point"
                position="abscissa*avgGradez"
                color="#fdae6b"
                size={3}
                shape="circle"
                style={{
                  lineWidth: 1,
                  stroke: "#fff"
                }}
              >
              </Geom>
            </Chart>

          </Spin>
        </Row>
        <Row style={{ margin: "0px 0 12px 20px", backgroundColor: "rgb(0, 31, 95)", padding: "12px 6px", }}>
          <div style={{ color: "#fff", textAlign: "left" }}>
            平均接诊时长（分钟）
             {/* <p style={{ position: 'absolute',top:"10px",left:"6px",fontSize:"12px",top:"34px",left:"25px" }}>注册用户</p>  */}
            <div style={{ float: 'right' }}>
              <Radio.Group buttonStyle="solid" size='small' value={"month"}>
                <Radio.Button value='month'>近6个月</Radio.Button>
              </Radio.Group>
            </div>
          </div>
          <Spin spinning={this.state.showGradLoading} style={{ background: "rgb(0, 31, 95)", marginTop: "10px" }}>
            <Chart height={(this.props.allHeight == true ? 260 : 192)} data={dvGradTime} scale={colsPointOne} forceFit className="order-charts"
              padding={[30, 30, 30, 60]}
            >
              {/* <Legend
              position="top"
              marker="square"
              textStyle={{
                fill: "#fff"
              }}
            /> */}
              <Axis name="abscissa"
                label={{
                  textStyle: {
                    fill: '#fff', // 文本的颜色
                  }
                }}
                grid={null}
              />
              <Axis
                name="avgDateTime"
                label={{
                  formatter: val => `${val}`,
                  textStyle: {
                    fill: '#fff', // 文本的颜色
                  }
                }}
                grid={null}
              />
              <Tooltip
                crosshairs={{
                  type: "y"
                }}
              />
              <Geom
                type="line"
                position="abscissa*avgDateTime"
                size={2}
                color={"clinic"}
                shape={"smooth"}
              />
              <Geom
                type="point"
                position="abscissa*avgDateTime"
                size={4}
                shape={"circle"}
                color={"clinic"}
                style={{
                  stroke: "#fff",
                  lineWidth: 1
                }}
              />
            </Chart>
          </Spin>
        </Row>
        {/* <Row style={{ margin: "12px 0 12px 20px", backgroundColor: "rgb(4,78,181)", }}>
          <Col span={11} style={{ padding: "12px 6px", backgroundColor: "rgb(0, 31, 95)", marginRight: "25px" }}>
            <p style={{ color: "#fff", textAlign: "left" }}>
              患者评价（平均分）
        </p>
            <Chart height={ (this.props.allHeight == true?247: 186)} data={data} style={{ borderRadius: "4px" }} scale={cols} padding={[0, 0, 20, 0]} forceFit>
              <Coord type="polar" startAngle={-9 / 8 * Math.PI} endAngle={1 / 8 * Math.PI} radius={0.75} />
              <Axis
                name="value"
                zIndex={2}
                line={null}
                label={{
                  offset: -16,
                  textStyle: {
                    fontSize: 18,
                    textAlign: 'center',
                    textBaseline: 'middle',
                    fill:"#fff",
                  },
                }}
                subTickCount={4}
                subTickLine={{
                  length: -8,
                  stroke: '#fff',
                  strokeOpacity: 1,
                }}
                tickLine={{
                  length: -18,
                  stroke: '#fff',
                  strokeOpacity: 1,
                }}
              />
              <Axis name="1" visible={false} />
              <Guide>
                <Arc
                  zIndex={0}
                  start={[0, 0.965]}
                  end={[5, 0.965]}
                  style={{ // 底灰色
                    stroke: '#CBCBCB',
                    lineWidth: 18,
                  }}
                />
                <Arc
                  zIndex={1}
                  start={[0, 0.965]}
                  end={[data[0].value, 0.965]}
                  style={{
                    stroke: '#1890FF',
                    lineWidth: 18,
                  }}
                />
                <Html
                  position={['50%', '95%']}
                  html={() => (`<div style="width: 300px;text-align: center;font-size: 
                  12px!important;"><p style="font-size: 1.1em; color: #fff;
                  margin: 0;
                  position: absolute;
                  top: -82px;
                  left: 130px;
                  ">
                  平均分</p><p style="font-size: 1.6em;color: #fff;margin: 0;position: absolute;
                  top: -9px;
                  left: 126px;
                  font-weight: 600">
                  ${this.state.avgGrade && this.state.avgGrade || "0"}分</p></div>`)}
                />
              </Guide>
              <Geom
                type="point"
                position="value*1"
                shape="pointer"
                color="#1890FF"
                active={false}
                style={{ stroke: '#fff', lineWidth: 1 }}
              />
            </Chart>
          </Col>

          <Col span={12} style={{ padding: "12px 6px", backgroundColor: "rgb(0, 31, 95)", height: (this.props.allHeight == true?'300px': '239px'), position: "relative" }}>
            <p style={{ color: "#fff", textAlign: "left" }}>
              平均接诊时长
             </p>
            <span style={{ color: "rgb(255,154,0)", position: "absolute", top: "50%", left: "0", right: "0", bottom: "0", margin: "auto", fontSize: "36px" }}>
              {this.state.avgDateTime && this.state.avgDateTime + "分钟" || "--"}
            </span>
          </Col>

        </Row> */}

      </div>
    </div>
  }
}

export default ShowUserStatisitcsBIPage;
