import React, { useState, useMemo } from 'react';
import styles from "./index.less";
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
import { DatePicker, Button } from "antd";
import dayjs from 'dayjs';
import AutoTable from '@/components/AutoTable/mtable';
import ReactEcharts from 'echarts-for-react';
import TreeRender from '@/components/TreeRender';
import Statuschart from '@/components/Statuschart';
const { RangePicker } = DatePicker;
const statusColors = {
    1: {
        name: '工作',
        color: '#7ac143',
        startColor: '#64e8fe'
    },
    2: {
        name: '待机',
        color: '#f59a23',
        startColor: '#FCBB67'
    },
    3: {
        name: '关机',
        color: '#6a737b',
        startColor: '#ccc'
    },
    4: {
        name: '报警',
        color: '#F83636',
        startColor: '#a97fff'
    }
},
    format = 'YYYY-MM-DD HH:mm:ss';
const Devicestatus = ({ drawer }) => {
    const [dateTimeRange, cdate] = useState([dayjs().subtract(24, 'hours').format(format), dayjs().format(format)]),
        [deviceId, cdv] = useState('');
    const device = useRequest(async () => {
        let res = await doFetch({ url: "/lease/umLeaseLedger/querySelectbox", params: {} });
        cdv(res?.data?.dataList?.[0]?.value ?? '');
        return res?.data?.dataList?.map((it) => {
            return {
                title: it.label,
                key: it.value,
                children: []
            }
        }) ?? [];
    }),
        chartdata = useRequest(async () => {
            if (deviceId) {
                let res = await doFetch({ url: "/lease/umLeaseLedger/queryEquipmentStatus", params: { dateTimeRange, id: deviceId } });
                return res?.data ?? {};
            } else {
                return {}
            }

        }, {
            refreshDeps: [dateTimeRange, deviceId]
        });

    const onselecteTree = (selectedKeys, e, alldata) => {
        cdv(e.node.key);
    };
    const optionsa = useMemo(() => {
        const rateList = chartdata?.data?.data?.rateList ?? [];
        const typeList = rateList?.map(it => it.name)?.concat(['总时长']) ?? ['总时长']; // 类型
        const percentList = rateList?.map(it => it.rate)?.concat([chartdata?.data?.data?.timeRange]) ?? [chartdata?.data?.data?.timeRange];

        /* 数据处理 */
        let data = [], obj = {};
        // 空格数据
        const sum = percentList.reduce((per, cur) => per + cur, 0);
        const gap = (1 * sum) / 100;
        const gapData = {
            name: '空格',
            value: gap,
            itemStyle: {
                color: 'transparent',
            },
        };
        for (let i in statusColors) {
            data.push({
                name: statusColors[i].name,
                value: rateList?.filter(it => it.status == i)?.[0]?.rate,
                itemStyle: {
                    borderRadius: "50%",
                    color: {
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: statusColors[i].startColor // 0% 处的颜色
                        }, {
                            offset: 1,
                            color: statusColors[i].color // 100% 处的颜色
                        }],
                    }
                }
            })
        }
        if (rateList?.length == 0) {
            obj['value0'] = {
                fontSize: 16,
                fontWeight: 500,
                height: 16,
                align: 'left',
                verticalAlign: "top",
                padding: [5, 0, 0, 16],
                color: '#5471c7',
                fontFamily: 'PangMenZhengDao',
            }
        } else {
            rateList.forEach((it, i) => {
                obj['value' + i] = {
                    fontSize: 16,
                    fontWeight: 500,
                    height: 16,
                    align: 'left',
                    verticalAlign: "top",
                    padding: [5, 0, 0, 16],
                    color: statusColors[it.status].color,
                    fontFamily: 'PangMenZhengDao',
                }
            });
            obj['value4'] = {
                fontSize: 16,
                fontWeight: 500,
                height: 16,
                align: 'left',
                verticalAlign: "top",
                padding: [5, 0, 0, 16],
                color: '#5471c7',
                fontFamily: 'PangMenZhengDao',
            }
        }

        const option = {
            legend: {
                type: "scroll",
                orient: 'vertical',
                height: '80%',
                left: '65%',
                top: 'center',
                icon: "roundRect", //设置为圆，删除则为矩形
                itemWidth: 5,
                itemHeight: 16,
                itemGap: 25,
                data: typeList,
                formatter: function (name) {
                    for (let i = 0; i < typeList.length; i++) {
                        if (name == typeList[i]) {
                            if (name != '总时长') {
                                return `{name|${name}}{value${i}|${rateList[i]['time']}小时} {value${i}|${percentList[i]}%}`
                            } else {
                                return `{name|${name}}{value${i}|${percentList[i]}小时}`
                            }
                        }
                    }
                },
                textStyle: {
                    rich: {
                        name: {
                            fontSize: 14,
                            fontWeight: 400,
                            height: 16,
                            verticalAlign: "top",
                            padding: [4, 0, 0, 4],
                            color: '#000',
                            fontFamily: 'Source Han Sans CN-Regular',
                        },
                        ...obj
                    }
                }
            },
            series: [{
                type: 'pie',
                z: 2,
                radius: ['43%', '55%'],
                center: ["35%", "50%"],
                label: {
                    show: false
                },
                labelLine: {
                    show: false
                },
                data: data
            },
            {
                type: 'pie',
                z: 3,
                radius: ['63%', '75%'],
                center: ["35%", "50%"],
                label: {
                    show: false
                },
                labelLine: {
                    show: false
                },
                data: [{
                    value: 100, name: '总时长', itemStyle: {
                        borderRadius: "50%",
                        color: {
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#73a0fb' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#5470c6' // 100% 处的颜色
                            }],
                        }
                    }
                }]
            }]
        };
        return option;
    }, [chartdata?.data]);
    const optionbData = useMemo(() => {
        let colors = [], allData = chartdata?.data?.data?.datalist ?? [], tableData = [];
        let data = allData?.length > 0 ? [{
            name: '',
            value: allData?.map(it => {
                return {
                    name: it.status,
                    value: [it.start, it.end]
                }
            }) ?? []
        }] : [];
        tableData = allData?.sort(compareTimeDesc);
        tableData = tableData?.map((it, i) => {
            return {
                ...it,
                id: i
            }
        }) ?? [];
        for (let i in statusColors) {
            colors.push({
                type: i,
                color: statusColors[i].color,
                name: statusColors[i].name
            })
        };
        return {
            statusData: data,
            statusColorList: colors,
            tableData
        }
    }, [chartdata?.data]);
    function compareTimeDesc(a, b) {
        const timeA = dayjs(a.start).valueOf();
        const timeB = dayjs(b.start).valueOf();
        return timeB - timeA;
    }
    return <div className={styles.ledgerbox}>
        <div className={styles.ledgercontent}>
            <div className={`${styles.ledgerleft} boxcontianbox`}>
                <TreeRender dataSource={device?.data} onselected={onselecteTree} noaction={true} isSelectFirst={true} maxWidth={215} />
            </div>
            <div className={`${styles.ledgerright} boxcontianbox`} style={{ padding: 16, flex: 1, borderLeft: '1px solid #f0f0f0' }}>
                <div style={{ marginBottom: 30 }}>
                    <RangePicker
                        showTime={{
                            format: 'HH:mm:ss',
                        }}
                        format={format}
                        onChange={(val, dateString) => {
                            cdate(dateString)
                        }}
                        value={dateTimeRange?.length > 0 ? [dayjs(dateTimeRange?.[0]), dayjs(dateTimeRange?.[1])] : []}
                        allowClear={false}
                    />
                    <Button onClick={() => {
                        chartdata.run()
                    }} type="primary" style={{ marginLeft: 15 }}>查询</Button>
                </div>
                <div style={{ display: 'flex' }}>
                    <div className='statuspage' style={{ flex: 1, marginRight: 30 }}>
                        <AutoTable
                            columns={[
                                {
                                    title: '采集时间',
                                    dataIndex: 'start',
                                    key: 'start',
                                    search: false
                                },
                                {
                                    title: '采集状态',
                                    dataIndex: 'name',
                                    key: 'name',
                                    search: false,
                                    render: (_, row) => {
                                        return <span style={{ color: statusColors[row.status]?.color }}>{row.name}</span>
                                    }
                                },
                            ]}
                            dataSource={optionbData?.tableData}
                            resizeable={false}
                            pageextra="none"
                            options={false}
                        />
                    </div>
                    <div style={{ flex: 2 }}>
                        <ReactEcharts
                            style={{ height: 300, width: '100%' }}
                            option={optionsa}
                        />
                        <div style={{ height: 200, width: '100%' }}>
                            <Statuschart statusData={optionbData.statusData} statusColorList={optionbData.statusColorList} />
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
}
export default Devicestatus;