/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * Special Declaration: These technical material reserved as the technical secrets by AGREE 
 * TECHNOLOGY have been protected by the "Copyright Law" "ordinances on Protection of Computer 
 * Software" and other relevant administrative regulations and international treaties. Without 
 * the written permission of the Company, no person may use (including but not limited to the 
 * illegal copy, distribute, display, image, upload, and download) and disclose the above 
 * technical documents to any third party. Otherwise, any infringer shall afford the legal 
 * liability to the company.
 */
import {Composite} from "Composite";
import {Widget} from "Widget";
import {EChart} from "widget/echart/EChart";

export class BranchChart extends EChart {
    private netPointList: Array<NetPoint> = new Array<NetPoint>();
    private title: string = "unset";
    private subTitle: string = "";

    setData(args: { netPointList: Array<NetPoint> }) {
        this.netPointList = new Array<NetPoint>();
        this.netPointList.push({ pointName: "当前网点", distance: 0, walkTime: 0 });
        this.netPointList = this.netPointList.concat(args.netPointList);
    }

    setTitle(args: { titles: { title: string, subTitle: string } }) {
        this.title = args.titles.title;
        this.subTitle = args.titles.subTitle;
    }

    postLayout() {
        if (this.netPointList.length > 0) {
            this.redrawChart();
        }
        super.postLayout();
    }

    //根据netPoint数据创建将要生成的<div>并转换成string字符串...echart的蛋疼接口不接受JQuery
    private getFormat(netPoint: NetPoint) {
        let $assistNode: JQuery = $("<div>");
        let tableBlock: JQuery = $("<div></div>").addClass("branchChart-table responsive-table");

        //--表格--
        let table: JQuery = $("<table class='centered'></table>");

        //--表格标题处理--
        let tableTheadTemplate: string = `
        <thead>
            <tr>
                <th data-field="name" style="width:50%">项目名称</th>
                <th data-field="name" style="width:50%">描述/值</th>
            </tr>
        </thead>
        `;
        let tableThead: JQuery = $(tableTheadTemplate);


        //--表格body即内容部分处理--
        let tableBody: JQuery = $("<tbody></tbody>");

        //组建tableRow的方法,到时候插入tableBody即可
        let createRow = function (name: string, content: string): JQuery {
            let row: JQuery = $("<tr>");
            let nameEntry: JQuery = $("<td style='padding:5px 5px;width:50%'></td>").html(name);
            let contentEntry: JQuery = $(`<td style="padding:5px 5px;width:50%;overflow:auto"></td>`).html(content);
            row.append(nameEntry).append(contentEntry);
            return row;
        };

        //将对应数据插入表格
        tableBody.append(createRow("网点名称", netPoint.pointName));
        tableBody.append(createRow("和当前网点距离", netPoint.distance + "米"));
        tableBody.append(createRow("步行需要时间", netPoint.walkTime + "分钟"));
        if (netPoint.description && netPoint.description.length > 0) {
            for (let d of netPoint.description) {
                tableBody.append(createRow(d.descriptionName, d.descriptionContent));
            }
        }
        table.append(tableThead);
        table.append(tableBody);
        tableBlock.append(table);

        let showNumberTable: JQuery = $(`
        <table class="centered" style="width:70%;margin-left:15%;">
            <thead>
                <tr>
                    <th data-field="name" style="width:50%">网点窗口数量</th>
                    <th data-field="name" style="width:50%">当前等待人数</th>
                </tr>
            </thead>
            <tbody>
                <tr></tr>
            </tbody>
        </table>
        `);
        if (netPoint.windowNumber && netPoint.waitInLineNumber) {
            let showNumberRow: JQuery = showNumberTable.find("tbody").find("tr");
            showNumberRow.append(createRow(netPoint.windowNumber + "", netPoint.waitInLineNumber + ""));
            tableBlock.append(showNumberTable);
        }


        let othersTable: JQuery = $(`
        <table class="centered">
            <thead>
                <tr>
                    <th data-field="name" style="width:50%">其他数据名称</th>
                    <th data-field="name" style="width:50%">其他数据数值</th>
                </tr>
            </thead>
            <tbody>
                <tr></tr>
            </tbody>
        </table>
        `);

        if (netPoint.othersInfo && netPoint.othersInfo.length > 0) {
            let othersRow: JQuery = othersTable.find("tbody").find("tr");
            let othersList = netPoint.othersInfo;
            for (let other of othersList) {
                othersRow.append(createRow(other.otherName, other.otherContent));
            }
            tableBlock.append(othersTable);
        }



        //$assistNode是为了获取html()字符串才使用的,使用因为已不可再访问被进行回收
        $assistNode.append(tableBlock);
        return $assistNode.html();
    }

    //获取长度最大值的方法
    private getMaxLength(): number {
        let distanceList: Array<number> = new Array<number>();
        for (let netPoint of this.netPointList) {
            distanceList.push(netPoint.distance);
        }
        //将获取到的长度列表按从小到大排列获取最大值
        distanceList.sort(function (a: number, b: number) {
            return a - b;
        });
        return distanceList[distanceList.length - 1];
    }

    //调用此方法进行数据同步完毕后的绘图,addOption方法在此方法后执行,不然会被覆盖掉对应信息
    private redrawChart() {
        let own = this;

        //-- 网点在图表上的定位逻辑 start --//
        let maxLength: number = 1.1 * this.getMaxLength();
        let indicatorContent: Array<any> = new Array<any>();


        for (let i = 0; i < this.netPointList.length; i++) {
            let indicatorEntry = {
                name: i > 0 ? `${this.netPointList[i].pointName} 步行距离:${this.netPointList[i].distance}米` : "",
                max: maxLength
            };
            indicatorContent.push(indicatorEntry);
        }


        //length为对应图表的节点数目,包括原点
        let createDataEntry = function (index: number, value: number, length: number): any {
            let valueList: Array<string> = new Array<string>();
            for (let i = 0; i < length; i++) {
                valueList.push("");
            }
            valueList[index] = value.toString();
            let dataEntryTemplate: any = {
                value: valueList,
                name: index.toString(),
                symbol: "circle",
                symbolSize: 8
            };
            return dataEntryTemplate;
        };

        let dataContent: Array<any> = new Array<any>();
        for (let i = 0; i < this.netPointList.length; i++) {
            dataContent.push(createDataEntry(
                i, this.netPointList[i].distance, this.netPointList.length
            ));
        }


        //-- 网点在图表上的定位逻辑 end --//

        let branchOption = {
            title: {
                text: this.title,
                subtext: this.subTitle,
                x: "center"
            },
            legend: {
            },
            tooltip: {
                formatter: function (params: Params, ticket: any, callback: any) {
                    let netPoint: NetPoint = own.netPointList[params.dataIndex];
                    return own.getFormat(netPoint);
                },
                enterable: true,
                backgroundColor: "transparent",
                transitionDuration: 0.4,
                textStyle: {
                    color: "black"
                },
                hideDelay: 50,
                //设置居中
                position: function (point: Array<number>, params: any, dom: any): any {
                    //css设定的弹出对话框大小为300,400
                    let x: number = point[0];
                    let y: number = point[1];
                    let width: number = own.$thisNode.get(0).clientWidth;
                    let height: number = own.$thisNode.get(0).clientHeight;

                    let rX: number = x;
                    let rY: number = y;

                    if (x + 150 > width && x - 150 < 0) {
                        return "inside";
                    } else if (x + 150 > width) {
                        rX = width - 150;
                    } else if (x - 150 < 0) {
                        rX = 150;
                    }

                    if (y + 200 > height && y - 200 < 0) {
                        return "inside";
                    } else if (y + 200 > height) {
                        rY = height - 200;
                    } else if (y - 200 < 0) {
                        rY = 200;
                    }

                    return [rX - 150, rY - 200];
                }
            },
            radar: [
                {
                    indicator: indicatorContent,
                    center: ["50%", "50%"],
                    radius: "70%",
                    startAngle: 90,
                    splitNumber: 5,
                    shape: "circle",
                    name: {
                        textStyle: {
                            color: "#003D79",
                            fontSize: "13"
                        }
                    },
                    splitArea: {
                        areaStyle: {
                            color: ["rgba(114, 172, 209, 1)",
                                "rgba(114, 172, 209, 0.8)", "rgba(114, 172, 209, 0.6)",
                                "rgba(114, 172, 209, 0.4)", "rgba(114, 172, 209, 0.2)"],
                            shadowColor: "rgba(0, 0, 0, 0.3)",
                            shadowBlur: 10
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: "rgba(114, 172, 209, 0.1)"
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: "rgba(114, 172, 209, 0.5)"
                        }
                    }
                }
            ],
            series: [
                {
                    name: "雷达图",
                    type: "radar",
                    itemStyle: {
                        normal: {
                            shadowColor: "black",
                            shadowBlur: 10,
                            color: "white"
                        }

                    },
                    data: dataContent
                }
            ]
        };
        this.option = branchOption;
        if (this.echart) {
            this.echart.setOption(this.option);
        }
    }
}

//NetPoint 单个网点信息的抽象成的interface
interface NetPoint {
    pointName: string;
    distance: number;
    walkTime: number;
    windowNumber?: number;
    waitInLineNumber?: number;
    description?: Array<{ descriptionName: string, descriptionContent: string }>;
    othersInfo?: Array<{ otherName: string, otherContent: string }>;
}

interface Params {
    componentType: 'series';
    // 系列类型
    seriesType: string;
    // 系列在传入的 option.series 中的 index
    seriesIndex: number;
    // 系列名称
    seriesName: string;
    // 数据名，类目名
    name: string;
    // 数据在传入的 data 数组中的 index
    dataIndex: number;
    // 传入的原始数据项
    data: Object;
    // 传入的数据值
    value: number | Array<number>;
    // 数据图形的颜色
    color: string;

    // 饼图的百分比
    percent: number;

}