import { InfoCircleOutlined, ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import { PlusOutlined } from '@ant-design/icons';
import { Space, DatePicker, Statistic, Card, Row, Col, Tooltip } from 'antd';
import { Suspense, useState, useEffect } from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { Line } from '@ant-design/charts';
import { Radar } from '@ant-design/charts';
import { Area } from '@ant-design/charts';
import { Column } from '@ant-design/charts';
import { RadialBar } from '@ant-design/charts';
import { Pie } from '@ant-design/charts';
import moment from 'moment';
import {
  getTopGoods,
  getnewMember,
  getSalesVolume,
  getSalesTimePoint,
  GetRepurchasing,
  GetSaleSamountAnalysis,
  GetOrderAnalysis,
} from './service';

const key = 'message';
const topColResponsiveProps = {
  xs: 24,
  sm: 12,
  md: 12,
  lg: 12,
  xl: 6,
  style: { marginBottom: 24 },
};
const MemberAnalysis = () => {
  const [startTimeStr, setstartTimeStr] = useState('');
  const dateFormat = 'YYYY-MM-DD';
  const { RangePicker } = DatePicker;
  const [topGoods, setTopGoods] = useState([]);
  const [newMember, setNewMember] = useState([]);
  const [salesVolume, setsalesVolume] = useState({});
  const [saleSamountAnalysis, setsaleSamountAnalysis] = useState({});
  const [salesTimePoint, setSalesTimePoint] = useState([]);

  //复购率
  const [repurchase, setRepurchase] = useState([]);

  //订单分析
  const [orderAnalysis, setorderAnalysis] = useState([]);

  const [dates, setDates] = useState([]);
  const getDate = (dates) => {
    var dd = new Date();
    dd.setDate(dd.getDate() + dates);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    var d = dd.getDate();
    return y + '-' + m + '-' + d;
  };
  const disabledDate = (current) => {
    if (!dates || dates.length === 0) {
      return false;
    }
    const tooLate = dates[0] && current.diff(dates[0], 'days') > 15;
    const tooEarly = dates[1] && dates[1].diff(current, 'days') > 15;
    return tooEarly || tooLate;
  };

  //初始化数据
  useEffect(() => {
    var endday = new Date();
    const initLoad = async (value) => {
      getTopGoods(JSON.stringify({ startTime: getDate(-7), EndTime: endday, Top: 5 })).then((r) => {
        if (r.data) {
          setTopGoods(r.data.dataInfo);
        }
      });
      GetSaleSamountAnalysis().then((r) => {
        if (r.data) {
          setsaleSamountAnalysis(r.data);
        }
      });
      getnewMember(JSON.stringify({ startTime: getDate(-7), EndTime: endday, Top: 5 })).then(
        (r) => {
          if (r.data) {
            setNewMember(r.data.dataInfo);
          }
        },
      );
      getSalesVolume().then((r) => {
        if (r.data) {
          setsalesVolume(r.data);
        }
      });
      getSalesTimePoint(JSON.stringify({ startTime: getDate(-7), EndTime: endday, Top: 5 })).then(
        (r) => {
          if (r.data) {
            setSalesTimePoint(r.data.dataInfo);
          }
        },
      );
      GetRepurchasing(JSON.stringify({ startTime: getDate(-7), EndTime: endday, Top: 5 })).then(
        (r) => {
          if (r.data) {
            setRepurchase(r.data.dataInfo);
          }
        },
      );
      GetOrderAnalysis(JSON.stringify({ startTime: getDate(-15), EndTime: endday, Top: 5 })).then(
        (r) => {
          if (r.data) {
            setorderAnalysis(r.data);
          }
        },
      );
    };
    initLoad();
  }, []);

  //商品top
  const onChangeTopGoods = async (date, dateString) => {
    await getTopGoods(
      JSON.stringify({ startTime: dateString[0], EndTime: dateString[1], Top: 5 }),
    ).then((r) => {
      if (r.data) {
        setTopGoods(r.data.dataInfo);
      }
    });
  };

  //时段分析
  const onChangeSalesTimePoint = async (date, dateString) => {
    await getSalesTimePoint(
      JSON.stringify({ startTime: dateString[0], EndTime: dateString[1], Top: 5 }),
    ).then((r) => {
      if (r.data) {
        setSalesTimePoint(r.data.dataInfo);
      }
    });
  };

  //复购率
  const onChangeRepurchasing = async (date, dateString) => {
    await GetRepurchasing(
      JSON.stringify({ startTime: dateString[0], EndTime: dateString[1], Top: 5 }),
    ).then((r) => {
      if (r.data) {
        setRepurchase(r.data.dataInfo);
      }
    });
  };
  //订单
  const onChangeOrderAnalysis = async (date, dateString) => {
    await GetOrderAnalysis(
      JSON.stringify({ startTime: dateString[0], EndTime: dateString[1], Top: 5 }),
    ).then((r) => {
      if (r.data) {
        setorderAnalysis(r.data);
      }
    });
  };

  const TopGoodsTB = {
    data: topGoods,
    xField: 'name',
    yField: 'star',
    height: 110,
    meta: { star: { alias: '销售份数', min: 0 } },
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: false,
      },
    },
    minColumnWidth: 20,
    maxColumnWidth: 20,
  };

  //新增用户
  const newMemberTB = {
    data: newMember,
    height: 118,
    xField: 'name',
    yField: 'star',
    meta: { star: { alias: '新增用户', min: 0 } },
    xAxis: {
      range: [0, 1],
    },
  };

  //销售时间点
  var SalesTimePointTB = {
    height: 300,
    data: salesTimePoint,
    xField: 'name',
    yField: 'star',
    label: {},
    meta: { star: { alias: '下单量' } },
    point: {
      size: 5,
      shape: 'diamond',
      style: {
        fill: 'white',
        stroke: '#5B8FF9',
        lineWidth: 2,
      },
    },
    tooltip: { showMarkers: false },
    state: {
      active: {
        style: {
          shadowBlur: 4,
          stroke: '#000',
          fill: 'red',
        },
      },
    },
    interactions: [{ type: 'marker-active' }],
  };

  //复购率
  var RepurchaseTB = {
    height: 300,
    appendPadding: 10,
    data: repurchase,
    angleField: 'star',
    colorField: 'name',
    radius: 0.9,
    label: {
      type: 'inner',
      offset: '-30%',
      content: function content(_ref) {
        var percent = _ref.percent;
        return ''.concat((percent * 100).toFixed(0), '%');
      },
      style: {
        fontSize: 14,
        textAlign: 'center',
      },
    },
    interactions: [{ type: 'element-active' }],
  };

  var OrderAnalysisTB = {
    data: orderAnalysis,
    xField: 'time',
    yField: 'count',
    yAxis: {
      label: {
        formatter: function formatter(v) {
          return ''.concat(v).replace(/\d{1,3}(?=(\d{3})+$)/g, function (s) {
            return ''.concat(s, ',');
          });
        },
      },
    },
    seriesField: 'name',
    color: function color(_ref) {
      var type = _ref.name;
      return type === '总订单数'
        ? '#5B8FF9'
        : type === '已支付单'
        ? '#5AD8A6'
        : type === '未付款单'
        ? '#F6BD16'
        : '#657798';
    },
    lineStyle: function lineStyle(_ref2) {
      var type = _ref2.type;
      if (type === 'register') {
        return {
          lineDash: [4, 4],
          opacity: 1,
        };
      }
      return { opacity: 0.5 };
    },
  };

  return (
    <GridContent>
      <Suspense>
        <Row gutter={16}>
          <Col {...topColResponsiveProps}>
            <Card
              title="销售额"
              actions={[
                <span style={{ float: 'left' }}>
                  &nbsp;&nbsp;今日销售额：{salesVolume.sumTodayDay}
                </span>,
              ]}
              bordered={false}
            >
              <div style={{ height: 70 }}>
                <div style={{ float: 'left' }}>
                  总销售额:
                  <Statistic title="" value={salesVolume.sum} />
                </div>
                <div style={{ float: 'right' }}>
                  {' '}
                  <Statistic
                    title="_"
                    value={
                      salesVolume.sumYesterDay == 0
                        ? 0
                        : ((salesVolume.sumTodayDay - salesVolume.sumYesterDay) /
                            salesVolume.sumYesterDay) *
                          100
                    }
                    precision={2}
                    valueStyle={{
                      color:
                        salesVolume.sumTodayDay > salesVolume.sumYesterDay ? '#3f8600' : '#cf1322',
                    }}
                    prefix={
                      salesVolume.sumTodayDay > salesVolume.sumYesterDay ? (
                        <ArrowUpOutlined />
                      ) : (
                        <ArrowDownOutlined />
                      )
                    }
                    suffix="%"
                  />
                </div>
                <div style={{ float: 'right' }}>&nbsp;&nbsp;</div>
                <div style={{ float: 'right' }}>
                  {' '}
                  <Statistic
                    title="同比昨日"
                    value={salesVolume.sumTodayDay - salesVolume.sumYesterDay}
                    precision={2}
                    valueStyle={{
                      color:
                        salesVolume.sumTodayDay > salesVolume.sumYesterDay ? '#3f8600' : '#cf1322 ',
                    }}
                    prefix={
                      salesVolume.sumTodayDay > salesVolume.sumYesterDay ? (
                        <ArrowUpOutlined />
                      ) : (
                        <ArrowDownOutlined />
                      )
                    }
                  />
                </div>
              </div>
            </Card>
          </Col>
          <Col {...topColResponsiveProps}>
            <Card
              title="销量"
              actions={[
                <span style={{ float: 'left' }}>
                  &nbsp;&nbsp;今日订单数：{saleSamountAnalysis.sumTodayDay}
                </span>,
              ]}
              bordered={false}
            >
              <Space size="large">
                <Statistic
                  title="用户总数"
                  value={saleSamountAnalysis.count}
                  style={{ float: 'left' }}
                  xl={18}
                />

                <Statistic
                  title="订单总数"
                  value={saleSamountAnalysis.sum}
                  style={{ float: 'left' }}
                />
                <Statistic
                  title="同比昨日"
                  value={
                    saleSamountAnalysis.sumYesterDay == 0
                      ? 0
                      : ((saleSamountAnalysis.sumTodayDay - saleSamountAnalysis.sumYesterDay) /
                          saleSamountAnalysis.sumYesterDay) *
                        100
                  }
                  precision={2}
                  valueStyle={{
                    color:
                      saleSamountAnalysis.sumTodayDay > saleSamountAnalysis.sumYesterDay
                        ? '#3f8600'
                        : '#cf1322',
                  }}
                  prefix={
                    salesVolume.sumTodayDay > salesVolume.sumYesterDay ? (
                      <ArrowUpOutlined />
                    ) : (
                      <ArrowDownOutlined />
                    )
                  }
                  suffix="%"
                />
              </Space>
            </Card>
          </Col>
          <Col {...topColResponsiveProps}>
            <Card
              title="热销商品Top"
              extra={
                <RangePicker
                  size="Small"
                  style={{ width: 230 }}
                  defaultValue={[moment(getDate(-7), dateFormat), moment(new Date(), dateFormat)]}
                  onChange={onChangeTopGoods}
                  format={dateFormat}
                />
              }
              bordered={false}
            >
              <Column {...TopGoodsTB} />
            </Card>
          </Col>
          <Col {...topColResponsiveProps}>
            <Card title="新增用户" bordered={false}>
              <Area {...newMemberTB} />
            </Card>
          </Col>
        </Row>
      </Suspense>
      <Suspense>
        <Row gutter={24}>
          <Col xl={18} lg={24} md={24} sm={24} xs={24}>
            <Card
              title="销售时间点分析"
              extra={
                <RangePicker
                  defaultValue={[moment(getDate(-7), dateFormat), moment(new Date(), dateFormat)]}
                  onChange={onChangeSalesTimePoint}
                  format={dateFormat}
                />
              }
              bordered={false}
            >
              <Line {...SalesTimePointTB} />
            </Card>
          </Col>
          <Col {...topColResponsiveProps}>
            <Card
              title="复购率"
              extra={
                <RangePicker
                  defaultValue={[moment(getDate(-7), dateFormat), moment(new Date(), dateFormat)]}
                  onChange={onChangeRepurchasing}
                  format={dateFormat}
                />
              }
              bordered={false}
            >
              <Pie {...RepurchaseTB} />
            </Card>
          </Col>
        </Row>
      </Suspense>
      <Suspense>
        <Row gutter={24}>
          <Col xl={24} lg={24} md={24} sm={24} xs={24}>
            <Card
              title="订单分析"
              extra={
                <RangePicker
                  defaultValue={[moment(getDate(-7), dateFormat), moment(new Date(), dateFormat)]}
                  onChange={onChangeOrderAnalysis}
                  onCalendarChange={(val) => setDates(val)}
                  disabledDate={disabledDate}
                  format={dateFormat}
                />
              }
              bordered={false}
            >
              <Line {...OrderAnalysisTB} />
            </Card>
          </Col>
        </Row>
      </Suspense>
    </GridContent>
  );
};

export default MemberAnalysis;
