import React, { useEffect, useState } from 'react';
import { Avatar, Button, Card, Col, List, Space, Tag } from 'antd';
import { useModel } from '@umijs/max';
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { ArrowDownOutlined, ArrowUpOutlined, MoreOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import ECharts from '@/pages/example/components/ECharts';
import { getDataList } from '@/services/rwa/Welcome';

const Welcome: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const menuList = initialState?.menuList;
  const cols: React.ReactElement[] = [];
  menuList?.forEach((item) => {
    cols.push(
      <Col key={item.key} span={6}>
        <Card bordered={false}>
          <Button href={item.path}>{item.name}</Button>
        </Card>
      </Col>,
    );
  });

  /**
   * 顶部任务卡片数据
   * 存储8个数据
   * 0：今日任务总数
   * 1：昨日任务总数
   * 2：今日完成总数
   * 3：昨日完成总数
   * 4：今日未完成总数
   * 5：昨日未完成总数
   * 6：今日废弃总数
   * 7：昨日废弃总数
   */
  const [taskDataCount, setTaskDataCount] = useState<number[]>([0, 0, 0, 0, 0, 0, 0, 0]);
  const [contUuCount, setContUuCount] = useState<any[]>([]);

  // 表内业务风险暴露（一级）风险加权资产占比
  const [ withinTableAssetType,setWithinTableAssetType]  = useState<any[]>([]);
  // 表外业务风险暴露（一级）风险加权资产占比
  const [ outTableAssetType,setOutTableAssetType]  = useState<any[]>([]);
  // 前十大机构信用风险加权资产合计
  const [top10OrgAssetAccountName,setTop10OrgAssetAccountName] = useState<any[]>([]);
  const [top10OrgAssetAccountValue,setTop10OrgAssetAccountValue] = useState<any[]>([]);
  // 风险暴露（一级）风险加权资产占比
  const [riskExposeAssetRatio,setRiskExposeAssetRatio] = useState<any[]>([]);
  // 风险暴露（一级）缓释前风险暴露占比
  const [preReleaseRiskExposeAssetRatio,setPreReleaseRiskExposeAssetRatio] = useState<any[]>([]);
  // 信用风险缓释工具当期缓释覆盖金额占比
  const [creditRiskReleaseTool,setCreditRiskReleaseTool] = useState<any[]>([]);
  // 风险暴露分类（一级）当期缓释情况
  const [riskExposeClass,setRiskExposeClass] = useState<any[]>([]);

  // 存放x轴标签值
  const [xLableList,setXLableList] = useState<any[]>([]);
  // 缓释数据存放list
  const [releaseDataList,setReleaseDataList]  = useState<any[]>([]);
  // 未缓释数据存放list
  const [unReleaseDataList,setUnReleaseDataList] = useState<any[]>([]);
  // 缓释比例存放list
  const [releaseRatioDataList,setReleaseRatioDataList] = useState<any[]>([]);


  /**
   * 模拟造数方法，正是环境删掉
   * @param minValue
   * @param maxValue
   * @returns
   */
  const selectFrom = (minValue: number, maxValue: number) => {
    // 通过最大值减去最小值然后加1得到取值的范围可能值的总数
    // 例如取2到10之间的整数，10-2 = 8
    const choices = maxValue - minValue;
    // 然后通过随机数乘以刚才的到的值，
    // 例如：Math.random() * 8，由于得到的是小于1的随机数，所以随机最大值0.99*8得到的数始终小于8
    // 然后使用floor方法向下取正得到的数最大值就是7，然后再加上最小值
    return Math.floor(Math.random() * choices + minValue);
  };

  const chartSetOption = (
    id: string,
    title: string,
    optionPropss: { seriesName: string; type: 'pie'; data: any[] }[],
    color?: string[],
  ) => {
    const titleProps = {
      text: title,
      left: 'left',
      textStyle: {
        fontSize: '20',
      },
    };
    const seriesProps: any[] = [];
    optionPropss.forEach((optionProps: { seriesName: string; type: 'pie'; data: any[] }) => {
      if (optionProps.type === 'pie') {
        seriesProps.push({
          name: optionProps.seriesName,
          type: optionProps.type,
          data: optionProps.data,
          radius: '70%',
          label: {
            show: false,
          },
          labelLine: {
            show: false,
          },
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          center: ['30%', '50%'],
        });
      }
    });
    const option: Record<string, any> = {
      title: titleProps,
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        left: 'right',
      },
      series: seriesProps,
    };
    if (color) {
      option!.color = color;
    }
    const dom = document.getElementById(id);
    if (dom) {
      let chart = echarts.init(dom);
      //销毁图表，否则图表无法重新创建
      if (chart) {
        try {
          chart.dispose();
        } catch (e) {}
      }
      chart = echarts.init(dom);
      chart.setOption(option);
    }
  };

  const init = () => {
    setTaskDataCount([
      selectFrom(1000, 4000),
      selectFrom(1000, 4000),
      selectFrom(800, 1000),
      selectFrom(800, 1000),
      selectFrom(800, 1000),
      selectFrom(800, 1000),
      selectFrom(800, 1000),
      selectFrom(800, 1000),
    ]);
    chartSetOption(
      'contCard-prodUseCount',
      '产品使用统计',
      [
        {
          seriesName: '使用数量',
          type: 'pie',
          data: [
            { value: selectFrom(1000, 4000), name: '产品配置标准版本管理' },
            { value: selectFrom(1000, 4000), name: '系统管理' },
            { value: selectFrom(1000, 4000), name: '平台管理' },
            { value: selectFrom(1000, 4000), name: '财务引擎' },
            { value: selectFrom(1000, 4000), name: '规则引擎' },
            { value: selectFrom(1000, 4000), name: '交易引擎' },
            { value: selectFrom(1000, 4000), name: '模型引擎' },
            { value: selectFrom(1000, 4000), name: '流程引擎' },
            { value: selectFrom(1000, 4000), name: '权限管理' },
            { value: selectFrom(1000, 4000), name: '公共机制管理' },
            { value: selectFrom(1000, 4000), name: '数据补录' },
            { value: selectFrom(1000, 4000), name: '批次配置管理' },
          ],
        },
      ],
      [
        '#9ED4E8',
        '#F49495',
        '#FBD88B',
        '#B2DC9C',
        '#879BD6',
        '#FDC537',
        '#F833A1',
        '#718EF4',
        '#49C6FF',
        '#72EBCC',
        '#B6B7E9',
        '#FEDEE0',
      ],
    );
    setContUuCount([
      {
        title: '超级管理员',
        avatar: '/avatar.png',
        description: '系统管理：203 | 平台管理：23 | 权限管理：18',
        tags: [
          { color: '#F53E27', title: '系统管理' },
          { color: '#FA7921', title: '平台管理' },
        ],
      },
      {
        title: '测试管理员',
      },
      {
        title: '业务管理员',
      },
      {
        title: '维护管理员',
      },
    ]);
  };

  useEffect(() => {
    init();
    //十分钟请求一次后台获取数据
    setInterval(init, 1000 * 60 * 3);
    getChartData();
  }, []);


  const getChartData = async () => {
       const resData = await getDataList()
         // 表内业务风险暴露（一级）风险加权资产占比
         setWithinTableAssetType(resData.WithinTableAssetType?.pieData);
         // 表外业务风险暴露（一级）风险加权资产占比
         setOutTableAssetType(resData.OutTableAssetType?.pieData);
         // 前十大机构信用风险加权资产合计
         if (resData.Top10OrgAssetAccount?.pieData && resData.Top10OrgAssetAccount?.pieData.length > 0) {
          resData.Top10OrgAssetAccount?.pieData.forEach((item,index)=>{
            if (item?.name) {
              top10OrgAssetAccountName.push(item?.name);
            }
            if (item.value) {
              top10OrgAssetAccountValue.push(item.value);
            }
          });
          setTop10OrgAssetAccountName(...[top10OrgAssetAccountName]);
          setTop10OrgAssetAccountValue(...[top10OrgAssetAccountValue]);
         } else {
          setTop10OrgAssetAccountName([]);
          setTop10OrgAssetAccountValue([]);
         }
         
         // 风险暴露（一级）风险加权资产占比
         setRiskExposeAssetRatio(resData.RiskExposeAssetRatio?.pieData);
         // 风险暴露（一级）缓释前风险暴露占比
        setPreReleaseRiskExposeAssetRatio(resData.PreReleaseRiskExposeAssetRatio?.pieData);
        // 信用风险缓释工具当期缓释覆盖金额占比
        setCreditRiskReleaseTool(resData.CreditRiskReleaseTool?.pieData);
        // 风险暴露分类（一级）当期缓释情况
        if (resData.RiskExposeClass) {
          if (resData.RiskExposeClass.xLabels) {
            setXLableList(resData.RiskExposeClass.xLabels);
          }
          if (resData.RiskExposeClass.xData) {
            setReleaseDataList(resData.RiskExposeClass.xData);
          }
          if (resData.RiskExposeClass.yData) {
            setUnReleaseDataList(resData.RiskExposeClass.yData);
          }
          if (resData.RiskExposeClass.zData) {
            setReleaseRatioDataList(resData.RiskExposeClass.zData);
          }
        }
        setRiskExposeClass(resData.RiskExposeClass?.pieData);
  }

  /**
   * 任务卡片生成
   * @param title 卡片标题
   * @param taskIndex 卡片数据索引
   * @returns
   */
  const drawTaskCard = (title: string, taskIndex: number) => {
    const today = taskDataCount[taskIndex];
    const yesterday = taskDataCount[taskIndex + 1];
    return (
      <div className="taskCard-content">
        <div className="taskCard-title">
          {title}
          <div className="taskCard-button">
            <Button type="text">
              <MoreOutlined style={{ fontSize: '20px', fontWeight: 'bold' }} />
            </Button>
          </div>
        </div>
        <div className="taskCard-show">
          {today >= yesterday ? (
            <ArrowUpOutlined className="taskCard-sign taskCard-sign-green" />
          ) : (
            <ArrowDownOutlined className="taskCard-sign taskCard-sign-red" />
          )}
          <div className="taskCard-data">{today}</div>
          <div className="taskCard-compare">
            较昨日
            {today >= yesterday ? (
              <span className="taskCard-sign-green">上涨</span>
            ) : (
              <span className="taskCard-sign-red">下降</span>
            )}
            {Math.abs(today - yesterday)}个
          </div>
        </div>
      </div>
    );
  };

const chartOne = {
  title: {
    text: '表内业务风险暴露（一级）风险加权资产占比',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '90%',
    left: 'center'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        position: 'outer',
        alignTo: 'none',
        bleedMargin: 5
      },
      // emphasis: {
      //   label: {
      //     show: true,
      //     fontSize: 10,
      //     fontWeight: 'bold'
      //   }
      // },
      emphasis: {
        label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
          },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      labelLine: {
        show: true
      },
      data: withinTableAssetType
    }
  ]
};



const chartTwo = {
  title: {
    text: '表外业务风险暴露（一级）风险加权资产占比',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '90%',
    left: 'center'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        position: 'outer',
        alignTo: 'none',
        bleedMargin: 5
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: true
      },
      data:outTableAssetType
    }
  ]
};


const chartThree = {
  title: {
    text: '前十大机构信用风险加权资产合计',
    left: 'center'
  },
  xAxis: {
    type: 'category',
    data: top10OrgAssetAccountName
  },
  yAxis: {
    min:0,
    max: 250000,
    interval: 50000,
    type: 'value',
  },
  series: [
    {
      data: top10OrgAssetAccountValue,
      type: 'bar',
    }
  ]
};


const chartFour =  {
  title: {
    text: '风险暴露（一级）风险加权资产占比',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '90%',
    left: 'center'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        position: 'outer',
        alignTo: 'none',
        bleedMargin: 5
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: true
      },
      data: riskExposeAssetRatio
    }
  ]
};

const chartFive =  {
  title: {
    text: '风险暴露（一级）缓释前风险暴露占比',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '90%',
    left: 'center'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        position: 'outer',
        alignTo: 'none',
        bleedMargin: 5
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: true
      },
      data: preReleaseRiskExposeAssetRatio
    }
  ]
};


const chartSix =  {
  title: {
    text: '信用风险缓释工具当期缓释覆盖金额占比',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '90%',
    left: 'center'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        position: 'outer',
        alignTo: 'none',
        bleedMargin: 5
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: true
      },
      data: creditRiskReleaseTool
    }
  ]
};



const chartSeven ={
  title: {
    text: '风险暴露分类（一级）当期缓释情况',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  toolbox: {
    feature: {
      dataView: { show: true, readOnly: true },
      magicType: { show: true, type: ['line', 'bar'] },
      restore: { show: true },
      saveAsImage: { show: true }
    }
  },
  legend: {
    top:'90%',
    data: ['缓释', '未缓释', '缓释比例']
  },
  xAxis: [
    {
      type: 'category',
      data: xLableList,
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      min: 0,
      max: 5000000,
      interval: 1000000,
      axisLabel: {
        formatter: '{value}'
      }
    },
    {
      type: 'value',
      min: 0,
      max: 125,
      interval: 25,
      axisLabel: {
        formatter: '{value}'
      }
    }
  ],
  series: [
    {
      name: '缓释',
      type: 'bar',
      tooltip: {
        valueFormatter: function (value: number) {
          return (value as number) + ' 万元';
        }
      },
      stack: 'total',
      data:releaseDataList
    },
    {
      name: '未缓释',
      type: 'bar',
      tooltip: {
        valueFormatter: function (value: number) {
          return (value as number) + ' 万元';
        }
      },
      stack: 'total',
      data: unReleaseDataList
    },
    {
      name: '缓释比例',
      type: 'line',
      yAxisIndex: 1,
      tooltip: {
        valueFormatter: function (value: number) {
          return (value as number) + ' %';
        }
      },
      data: releaseRatioDataList
    }
  ]
};


  return (
    <PageContainer>
    <div style={{ display: 'flex', justifyContent: 'space-between' }}><div style={{ flex: 1 }}>
<ECharts
  elementId={"chartOne"} height={'400px'} option={chartOne} width={'100%'}></ECharts>
   </div>
   <div style={{ flex: 1 }}> <ECharts
  elementId={"chartTwo"} height={'400px'} option={chartTwo} width={'100%'}></ECharts>
   </div>
   </div>
<ECharts
  elementId={"chartThree"} height={'400px'} option={chartThree} width={'100%'}></ECharts>
 <div style={{ display: 'flex', justifyContent: 'space-between' }}><div style={{ flex: 1 }}>
<ECharts
  elementId={"chartFour"} height={'400px'} option={chartFour} width={'100%'}></ECharts>
  </div>
  <div style={{ flex: 1 }}> <ECharts
  elementId={"chartFive"} height={'400px'} option={chartFive} width={'100%'}></ECharts>
   </div>
   </div>
  <ECharts
  elementId={"chartSix"} height={'400px'} option={chartSix} width={'100%'}></ECharts>
<ECharts
  elementId={"chartSeven"} height={'400px'} option={chartSeven} width={'100%'}></ECharts>
</PageContainer>
  );
};
export default Welcome;
