import { Modal, Tabs } from 'antd';
import { proFormMaxModelWidth } from '../../../../../config/defaultForm';

import ProjectCard from '@/pages/Setting/components/ProjectCard';
import { ProCard, ProColumns, ProDescriptions, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import ReactEcharts from 'echarts-for-react';
import React, { useState } from 'react';
import { proTablePaginationOptions } from '../../../../../config/defaultTable';
import { format } from 'echarts';

// 各类别占比环形图
type DetailChartProps = {
  title: string;
  chartOptions: Record<string, any>[];
};
const DetailChart: React.FC<DetailChartProps> = (props) => {
  const { title, chartOptions } = props;
  const getOption = () => {
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{b} : {c} ({d}%)',
      },
      legend: {
        // icon: 'circle',
        // orient: 'vertical',
        orient: 'vertical', // 图例的布局方向，可以设置为 'horizontal' 水平布局
        // left: 'right',      // 图例在容器中的位置
        itemWidth: 8, // 图例标记的宽度
        itemHeight: 8, // 图例标记的高度
        // right: 15,
        // itemBorderRadius: 100,
        // borderRadius: 100,
        textStyle: {
          color: '#666', // 图例文字的颜色
          // label: '123''{a} <br/>{b} : {c} ({d}%)'
        },
        data: chartOptions.map((item) => item.name),
        formatter: function (name: string) {
          // let total = 0
          // let currCount = 0
          // chartOptions.forEach(item=>{
          //   total+=item.value
          //   if(item.name === name){
          //     currCount = item.value
          //   }
          // })

          // console.log('itemFormatter',currCount, total)

          // let currProgress = Math.round(currCount/total * 1000)
          // for(let i=0; i<chartOptions.length; i++) {
          //   total+=
          // }
          // 在图例中显示比例
          return `${name}`;
        },
        right: 15,
        top: 'center',
        // data: [chartOptions[0].name, chartOptions[1].name],
      },
      series: [
        {
          center: ['30%', '50%'],
          radius: '85%',
          // name: format(name),
          type: 'pie',
          color: [chartOptions[0].color, chartOptions[1].color],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'inside', // 将标签显示在饼图的内部
            formatter: '{d}%', // 在饼图块内显示标签内容，包括名称和百分比
            color: 'white'
        },
          emphasis: {
            label: {
              show: false,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: chartOptions,
        },
      ],
    };
  };
  return (
    <div style={{ background: '#F8FAFD', borderRadius: 4, width: 'calc(25% - 12px)', padding: 15 }}>
      <span style={{ fontWeight: 700, fontSize: 16 }}>{title}</span>
      <ReactEcharts style={{ width: 200, height: 119 }} option={getOption()} />
    </div>
  );
};

// 设备信息

const DeviceBaseInfo: React.FC = () => {
  const baseColumns: ProColumns<Record<string, any>[]> = [
    {
      title: '设备组',
      dataIndex: 'label1',
    },
    {
      title: '设备分类',
      dataIndex: 'label2',
    },
    {
      title: '设备名称',
      dataIndex: 'label3',
    },
    {
      title: '设备ID',
      dataIndex: 'label4',
    },
    {
      title: '设备IP',
      dataIndex: 'label5',
    },
    // TODO 这边根据对应状态使用不同颜色字体
    {
      title: '设备状态',
      dataIndex: 'label8',
      render(dom, entity, index, action, schema) {
        return <span className="gn text_green">{dom}</span>;
      },
    },
    {
      title: '备注',
      dataIndex: 'label7',
    },
  ];
  // 基本信息测试数据
  const testBaseData: Record<string, any> = {
    label1: '设备组001',
    label2: '区域监控',
    label3: '设备001',
    label4: '001001',
    label5: '192.168.192.168',
    label8: '在线',
    label7: '这是备注这是备注这是备注这是备注这是备注',
  };
  // 硬件信息测试数据
  const chartList: Record<string, any>[] = [
    {
      title: 'CPU',
      type: 0,
      chartOptions: [
        {
          name: '已占用',
          value: 123,
          color: '#FFAB00',
        },
        {
          name: '未占用',
          color: '#477BFF',
          value: 233,
        },
      ],
    },
    {
      title: '内存',
      type: 1,
      chartOptions: [
        {
          name: '已占用',
          value: 160,
          color: '#00C45A',
        },
        {
          name: '未占用',
          color: '#FF8110',
          value: 40,
        },
      ],
    },
    {
      title: '存储',
      type: 2,
      chartOptions: [
        {
          name: '已占用',
          value: 60,
          color: '#FF8110',
        },
        {
          name: '未占用',
          color: '#47A3FF',
          value: 140,
        },
      ],
    },
    {
      title: 'GPU',
      type: 3,
      chartOptions: [
        {
          name: '已占用',
          value: 60,
          color: '#FFAB00',
        },
        {
          name: '未占用',
          color: '#477BFF',
          value: 140,
        },
      ],
    },
  ];
  // 当前任务
  const taskList: Record<string, any>[] = [
    {
      id: '001',
      modelName: '模型名称1',
      version: '版本号1',
      updateTime: '2023-12-12 10:10:56',
    },
    {
      id: '001',
      modelName: '模型名称2',
      version: '版本号1',
      updateTime: '2023-12-12 10:10:56',
    },
    {
      id: '001',
      modelName: '模型名称3',
      version: '版本号1',
      updateTime: '2023-12-12 10:10:56',
    },
    {
      id: '001',
      modelName: '模型名称4',
      version: '版本号1',
      updateTime: '2023-12-12 10:10:56',
    },
  ];

  return (
    <ul>
      <li>
        <p className="gn text_0 fs14 fw7" style={{}}>
          基础信息
        </p>
        <ProDescriptions
          column={5}
          dataSource={testBaseData}
          columns={baseColumns}
        ></ProDescriptions>
      </li>
      <li style={{ paddingBottom: 16 }}>
        <p className="gn text_0 fs14 fw7" style={{}}>
          硬件信息
        </p>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          {chartList.map((item, index) => {
            return (
              <DetailChart
                key={index}
                title={item.title}
                chartOptions={item.chartOptions}
              ></DetailChart>
            );
          })}
        </div>
      </li>
      <li>
        <p className="gn text_0 fs14 fw7" style={{}}>
          当前任务
        </p>
        <div style={{ display: 'flex', flexWrap: 'wrap', maxHeight: '30vh', overflowY: 'scroll' }}>
          {taskList.map((item, index) => {
            return (
              <div key={index} style={{ paddingRight: 16, paddingBottom: 16 }}>
                <ProCard
                  style={{
                    backgroundColor: 'rgba(21, 91, 212, 0.03)',
                    width: 289,
                    border: '1px solid rgba(21, 77, 221, 0.10)',
                  }}
                  bodyStyle={{ margin: 0, padding: 0 }}
                >
                  <div
                    style={{
                      display: 'flex',
                      padding: 15,
                    }}
                  >
                    <div>
                      <img src="/images/icons/logo.svg" alt="" style={{ width: '64px' }} />
                    </div>
                  </div>
                  <ProjectCard info={item}></ProjectCard>
                </ProCard>
              </div>
            );
          })}
        </div>
      </li>
    </ul>
  );
};

// 设备信息

const DeviceLogInfo: React.FC = () => {
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(10);
  const columns: ProColumns<Record<string, any>[]> = [
    {
      title: (
        <FormattedMessage
          id="DCSDeviceList.deviceStatus.detailModel.logTable.deviceName"
          defaultMessage="$$$"
        />
      ),
      dataIndex: 'deviceName',
      //   width: 120,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="DCSDeviceList.deviceStatus.detailModel.logTable.deviceID"
          defaultMessage="$$$"
        />
      ),
      dataIndex: 'deviceID',
      //   width: 120,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="DCSDeviceList.deviceStatus.detailModel.logTable.deviceCat"
          defaultMessage="$$$"
        />
      ),
      dataIndex: 'deviceCat',
      //   width: 120,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="DCSDeviceList.deviceStatus.detailModel.logTable.deviceIP"
          defaultMessage="$$$"
        />
      ),
      dataIndex: 'deviceIP',
      //   width: 120,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="DCSDeviceList.deviceStatus.detailModel.logTable.deviceTime"
          defaultMessage="$$$"
        />
      ),
      dataIndex: 'deviceTime',
      //   width: 120,
      hideInSearch: true,
    },
  ];

  let testData: Record<string, any>[] = [];
  for (let i = 0; i < 8; i++) {
    testData.push({
      deviceName: '设备' + (i + 1),
      deviceID: '123456',
      deviceCat: '外围监控',
      deviceIP: '192.168.1.10',
      deviceTime: '22:00:00',
    });
  }
  return (
    <ProTable
      cardProps={{
        bodyStyle: { padding: 0, margin: 0 },
      }}
      search={false}
      options={{ fullScreen: false, setting: false, density: false, reload: false }}
      rowKey="key"
      request={async (params = {}, sort) => {
        const { current, ...rest } = params;
        const reqParams = {
          page: current,
          desc: false,
          orderKey: '',
          ...rest,
        };
        if (sort && Object.keys(sort).length) {
          reqParams.orderKey = Object.keys(sort)[0];
          let sort_select = sort[reqParams.orderKey];
          reqParams.desc = sort_select === 'descend';
        }
        // TODO 联调查询设备日志接口
        // let resps = await postDeviceGroupGetDeviceGroupList({ ...reqParams });
        let resp = {
          success: true,
          data: {
            list: testData,
            total: 8,
            page: 1,
            pageSize: 8,
          },
        };
        return {
          data: resp.data.list,
          success: resp.success,
          total: resp.data.total,
          current: resp.data.page,
          pageSize: resp.data.pageSize,
        };
      }}
      pagination={{
        ...proTablePaginationOptions,
        pageSize: currentPageSize,
        onChange: (page, pageSize) => setCurrentPageSize(pageSize),
      }}
      columns={columns}
    ></ProTable>
  );
};

export type DetailInfoCardProps = {
  detailModalOpen: boolean;
  handleDetailModal: () => void;
};

const DetailInfoCard: React.FC<DetailInfoCardProps> = (props) => {
  const intl = useIntl();

  const [type, setType] = useState<string>('deviceInfo');

  return (
    <Modal
      width={proFormMaxModelWidth}
      title={intl.formatMessage({
        id: 'DCSDeviceList.deviceStatus.detailModel.name',
        defaultMessage: '$$$',
      })}
      open={props.detailModalOpen}
      footer={null}
      onCancel={props.handleDetailModal}
      destroyOnClose
    >
      <Tabs
        activeKey={type}
        onChange={(activeKey: string) => setType(activeKey)}
        items={[
          {
            key: 'deviceInfo',
            label: intl.formatMessage({
              id: 'DCSDeviceList.deviceStatus.detailModel.baseInfo',
              defaultMessage: '设备信息',
            }),
          },
          {
            key: 'deviceLog',
            label: intl.formatMessage({
              id: 'DCSDeviceList.deviceStatus.detailModel.log',
              defaultMessage: '设备日志',
            }),
          },
        ]}
      ></Tabs>
      {type === 'deviceInfo' && <DeviceBaseInfo></DeviceBaseInfo>}
      {type === 'deviceLog' && <DeviceLogInfo></DeviceLogInfo>}
    </Modal>
  );
};

export default DetailInfoCard;
