/*
 * Creator:     ML
 * CreatDate:   2020-04-30
 * descripts：  居民健康管理 图表 echarts  体检满意度
 * */
import React from 'react';
import moment from 'moment';
import { dayFormat } from 'tools/index';
import { Form, Col, Select, Icon, Button, Card, Row, Table, Typography } from 'antd';
import { $http } from 'containers/config/https';
import { Chart, Geom, Axis, Coord, Label, Legend, Tooltip, } from 'bizcharts';
import store from 'store';
import DataSet from "@antv/data-set";
const { DataView } = DataSet;
const { Text } = Typography;
//组件const
const Option = Select.Option;
const padding = {
    padding: "0px"
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 3 },
    wrapperCol: { span: 20 }
}
const formItemLayouts = {
    labelCol: { span: 7 },
    wrapperCol: { span: 17 }
}
const columnsSeting = [
    {
        key: "0",
        title: "设置统计维度",
        dataIndex: 'condition',
        align: 'left',
        minWidth: 120
    }
]
const dataTableOne = [{
    condition: "希望拥有个性化健康管理团队人次（是)",
    key: "1",
}, {
    condition: "希望拥有个性化健康管理团队人次（不是)",
    key: "2",
}, {
    condition: "未评价人次",
    key: "3",
}]
const dataTableTwo = [{
    condition: "满意人次",
    key: "1",
}, {
    condition: "不满意人次",
    key: "2",
}, {
    condition: "未评价人次",
    key: "3",
}]
const columnsOne = [
    {
        key: "0",
        title: '责任医生',
        dataIndex: 'docDesc',
        align: "center",
        width: 300
    },
    {
        key: "1",
        title: '希望拥有个性化健康管理团队人次（是）',
        dataIndex: 'individuationNum',
        align: "center",
        width: 500
    },
    {
        key: "2",
        title: '希望拥有个性化健康管理团队人次（不是）',
        dataIndex: 'noIndividuationNum',
        align: "center",
        width: 500
    }, {
        key: "3",
        title: '未评价人次',
        dataIndex: 'noEvalIndNum',
        align: "center",
        width: 500
    },
];

const columnsTwo = [
    {
        key: "0",
        title: '责任医生',
        dataIndex: 'docDesc',
        align: "center",
        width: 300
    },
    {
        key: "1",
        title: '满意人次',
        dataIndex: 'satisfactNum',
        align: "center",
        width: 500
    },
    {
        key: "2",
        title: '不满意人次',
        dataIndex: 'noSatisfactNum',
        align: "center",
        width: 500
    }, {
        key: "3",
        title: '未评价人次',
        dataIndex: 'noEvalSatisfactNum',
        align: "center",
        width: 500
    },
];

class AnalysisChartsConful extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            chartsData: [], //饼、柱图的详情数据
            doctorData: [],
            originDoctor: [],
            sexData: [],
            originSex: [],
            MBIData: [],
            originBMI: [],
            ageData: [],
            originAge: [],
            doctorCs: [],
            doctorCsOrigin: [],
            doctorCsTwo: [],
            doctorCsTwoOrigin: [],
            showOne: false,
            showTwo: false,
            dataTableOne: [],
            dataTableTwo: [],
            selectedRowKeys_right: [],
            selectedRowKeys_rightOne: [],
            columns: columnsOne,
            columnsT: columnsTwo,
            doctortoTalCount: 0,
            sexTalCount: 0
        };
    }

    componentWillReceiveProps(nextProps) {
    }



    componentDidMount = () => {
        this.getAllData()
        this.props.onRefConful(this)
    }



    //获取数据
    getAllData = (activeID) => {
        const arr = [
            {
                title: "个性化健康管理团队情况",
                key: 0,
                des: "zeren",
                type: "tabge",
                pie: [
                    {
                        descripts: "表格",
                        id: 1,
                        type: "tabge",
                        activeID: activeID || 1
                    },
                    {
                        descripts: "柱形",
                        id: 2,
                        type: "pi",
                        activeID: activeID || 1
                    },
                    {
                        descripts: "折线图",
                        id: 3,
                        type: "point",
                        activeID: activeID || 1
                    }, {
                        descripts: "饼状图",
                        id: 4,
                        type: "pie",
                        activeID: activeID || 1
                    }
                ]
            }, {
                title: "服务满意度",
                key: 1,
                des: "BMI",
                type: "tabge",
                pie: [
                    {
                        descripts: "表格",
                        id: 1,
                        type: "tabge",
                        activeID: 1
                    },
                    {
                        descripts: "柱形",
                        id: 2,
                        type: "pi",
                        activeID: 1
                    },
                    {
                        descripts: "折线图",
                        id: 3,
                        type: "point",
                        activeID: 1
                    }, {
                        descripts: "饼状图",
                        id: 4,
                        type: "pie",
                        activeID: 1
                    },
                ]
            },
        ]
        this.setState({
            arr,
        })
    }
    getData = (
        doctorData,
        // doctorDataTotal, 
        sexData, ) => {
        let arr = [...doctorData.data, { docDesc: "总计", individuationNum: doctorData.individuationCount, noIndividuationNum: doctorData.noIndividuationCount, noEvalIndNum: doctorData.noEvalIndCount }]
        let arr1 = [...sexData.data, { docDesc: "总计", satisfactNum: sexData.satisfactCount, noSatisfactNum: sexData.noSatisfactCount, noEvalSatisfactNum: sexData.noEvalSatisfactCount }]
        this.setState({
            doctorData: arr,
            originDoctor: doctorData.data,
            doctorCs: doctorData.staData,
            doctorCsOrigin: doctorData.staData,
            doctortoTalCount: doctorData.totalCount,
            oneCount: doctorData.totalCount,
            // // doctorDataTotal,
            sexData: arr1,
            originSex: sexData.data,
            doctorCsTwo: sexData.staData,
            doctorCsTwoOrigin: sexData.staData,
            sexTalCount: sexData.totalCount,
            twoCount: sexData.totalCount
        })
        // console.log("ppppppppp", doctorData, sexData)
    }
    //选择图形样式
    handleType = (subItem, name) => {
        const { arr } = this.state
        let newArr = arr
        newArr && newArr.map((item, index) => {
            if (name == item.des) {
                item.pie.map((i, s) => {
                    i.activeID = ""
                    // item.type=""
                    if (subItem.id == i.id) {
                        i.activeID = i.id
                        item.type = i.type
                    }
                })
            }
        })
        this.setState({
            arr: newArr,
            showOne: false
        }, () => {
            // console.log(this.state.arr)
        })
    }

    //设置table最后一行
    setClassName = (record, index) => {
        return (record.docDesc === "总计" || record.BMIDesc === "总计" || record.ageDesc === "总计" || record.sexDesc === "总计" ? "rowFont" : '')
    }
    //设置统计维度
    handleSetting = (e, show, columns, dataTable, selectedRowKeys) => {
        //设置初始选中
        dataTable && dataTable.map((item, index) => {
            columns && columns.map((i, s) => {
                if (i.key == item.key) {
                    selectedRowKeys.push(i.key)
                }
            })
        })
        this.setState({
            [selectedRowKeys]: selectedRowKeys
        }, () => {
            this.setState({
                ["show" + show]: !this.state["show" + show]
            })
        })
    }
    //确认筛选
    handleOk = (name, selectedRowKeys_right, columns, columnsShow, OriginData, originName) => {
        //选中条件 进行筛选
        if (selectedRowKeys_right.length > 0) {
            let arr = columns
            let newArr = [
                arr[0]
            ]
            let newArr1 = []
            arr && arr.map((item, index) => {
                selectedRowKeys_right && selectedRowKeys_right.map((i, s) => {
                    if (item.key == i) {
                        newArr.push(item)
                    }
                })
                OriginData && OriginData.map((j, jIndex) => {
                    selectedRowKeys_right && selectedRowKeys_right.map((i, s) => {
                        if (j.flag == i) {
                            newArr1.push(j)
                        }
                    })
                })
            })
            this.setState({
                [columnsShow]: Array.from(new Set(newArr)),
                [originName]: newArr1
            }, () => {
                this.setState({
                    ["show" + name]: false
                })
            })
        } else {
            //直接关闭
            this.setState({
                ["show" + name]: false
            })
        }
    }
    render() {
        const { zerentabgeID, zerenzhuID, zerencrealID, zerenpieID, arr, columns, columnsT } = this.state;
        const { DataView } = DataSet;
        const { chartsData, show } = this.state

        const rowSelection_right = {
            selectedRowKeys: this.state.selectedRowKeys_right,
            onChange: (selectedRowKeys, selectedRows) => {
                let btnStatus = false;
                let canSaveStatus = false;
                let selectrow = "";
                if (selectedRowKeys.length === 0) {
                    btnStatus = true;
                    canSaveStatus = true;
                } else {
                    selectrow = selectedRowKeys[selectedRowKeys.length - 1];
                }
                this.setState({ btnStatus: btnStatus, canSaveStatus: canSaveStatus, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_right: selectedRowKeys });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                // console.log("selected, selectedRows, changeRows",selected, selectedRows, changeRows)
                if (selectedRows.length > 0) {
                    this.setState({
                        btnStatus: false,
                        canSaveStatus: false,
                    })
                } else {
                    this.setState({
                        btnStatus: true,
                        canSaveStatus: true,
                    })
                }
                this.setState({ selectedRow_right: selectedRows, });
            }
        };

        const rowSelection_rightOne = {
            selectedRowKeys: this.state.selectedRowKeys_rightOne,
            onChange: (selectedRowKeys, selectedRows) => {
                let btnStatus = false;
                let canSaveStatus = false;
                let selectrow = "";
                if (selectedRowKeys.length === 0) {
                    btnStatus = true;
                    canSaveStatus = true;
                } else {
                    selectrow = selectedRowKeys[selectedRowKeys.length - 1];
                }
                this.setState({ selectrow1: selectrow, selectedRow_right1: selectedRows, selectedRowKeys_rightOne: selectedRowKeys });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                // console.log("selected, selectedRows, changeRows",selected, selectedRows, changeRows)
                if (selectedRows.length > 0) {
                    this.setState({
                        btnStatus: false,
                        canSaveStatus: false,
                    })
                } else {
                    this.setState({
                        btnStatus: true,
                        canSaveStatus: true,
                    })
                }
                this.setState({ selectedRow_right1: selectedRows, });
            }
        };
        //饼 
        const dv = new DataView();
        dv.source(this.state.originDoctor).transform({
            type: "percent",
            field: "duationNum",
            dimension: "docDesc",
            as: "percent"
        });
        //柱 折
        const ds = new DataSet();
        const dvOne = ds
            .createView()
            .source(this.state.doctorCs)
            .transform({
                type: "percent",
                field: "value",
                // 统计销量
                dimension: "individuation",
                // 每年的占比
                groupBy: ["docDesc"],
                // 以不同产品类别为分组
                as: "percent"
            });
        const colsOne = {
            percent: {
                min: 0,
                formatter(val) {
                    return val;
                }
            }
        };
        const colsPointOne = {
            docDesc: {
                range: [0, 1]
            }
        };


        const dvTwo = new DataView();
        dvTwo.source(this.state.originSex).transform({
            type: "percent",
            field: "healthNum",
            dimension: "docDesc",
            as: "percent"
        });
        // const widthMax = this.state.doctortoTalCount * 50 
        const dsOne = new DataSet();
        const dvTwot = dsOne
            .createView()
            .source(this.state.doctorCsTwo)
            .transform({
                type: "percent",
                field: "value",
                // 统计
                dimension: "satisfact",
                // 占比
                groupBy: ["docDesc"],
                // 以不同产品类别为分组
                as: "percent"
            });



        const chartStyle = {
            position: "absolute",
            margin: "auto",
            left: "0",
            top: "0",
            right: "0",
            bottom: "0",
            display: "flex",
            alignItems: "center"
        }
        const cols = {
            percent: {
                formatter: val => {
                    val = val * 100 + "%";
                    return val;
                }
            }
        };
        const colss = {
            docDesc: {
                range: [0, 1]
            }
        };
        const colsPi = {
            sales: {
                tickInterval: 20
            }
        };
        const colsPoint = {
            value: {
                min: 0,
                range: [0, 0.93],
                alias: ''
            },
            year: {
                range: [0, 0.9],
                alias: ''
            }
        };
        //数据
        let chartsList = []
        arr && arr.map((item, i) => {
            if (item.key == "0") {
                chartsList.push(
                    <Col span={12}>
                        <Card span={12} key={item.id} title={item.title}>
                            <div className="button-dom" style={{ position: "relative" }}>
                                {
                                    item.pie && item.pie.map((i, s) => {
                                        return (
                                            <Button onClick={() => this.handleType(i, item.des)} style={{ background: (i.activeID == i.id ? "rgb(0, 153, 255)" : "#fff"), color: (i.activeID == i.id ? "#fff" : "#333") }} >{i.descripts}</Button>
                                        )
                                    })
                                }
                                <Button style={{ float: "right" ,display:(dv&&dv.length>0?"block":"none")}} onClick={(e) => this.handleSetting(e, "One", this.state.columns, dataTableOne, this.state.selectedRowKeys_right)}>设置统计维度</Button>
                                <div className={this.state.showOne ? "setting-table-dom" : ""}
                                    style={{ display: (this.state.showOne ? "inline-block" : "none"), }}>
                                    <Table
                                        columns={columnsSeting}
                                        dataSource={dataTableOne}
                                        pagination={false}
                                        bordered
                                        rowKey={record => record.key}
                                        rowClassName={this.setClassName}
                                        rowSelection={rowSelection_right}
                                    />
                                    <Row>
                                        <Button onClick={() => this.handleOk("One", this.state.selectedRowKeys_right, columnsOne, "columns", this.state.doctorCsOrigin, "doctorCs")}>确定</Button>
                                    </Row>
                                </div>
                            </div>
                            <div className="charts-item" style={{ width: item.type == "pi" || item.type == "point" ? this.state.oneCount * 150 + "px" : "", height: "320px", position: "relative" }}>
                                {
                                    item.type == "pie"&&dv&&dv.length>0  ?
                                        <Chart
                                            height={246}
                                            width={600}
                                            data={dv}
                                            scale={cols}
                                            padding={[60, 240, 12, 12]}
                                            forceFit
                                            style={chartStyle}
                                        >
                                            <Coord type="theta" radius={0.75} />
                                            <Axis name="duationNum" />
                                            {/* <Legend
                                        position="bottom"
                                        layout="horizontal"
                                        itemWidth={120}
                                        itemGap={12}
                                        offsetY={-20}

                                        // offsetX={-50}
                                        // top={12}
                                    /> */}
                                            <Legend
                                                position="right"
                                                offsetY={-20}
                                                offsetX={-50}
                                            />
                                            <Tooltip
                                                showTitle={false}
                                            //    itemTpl='<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
                                            />
                                            <Geom
                                                type="intervalStack"
                                                position="duationNum"
                                                color="docDesc"
                                                tooltip={[
                                                    "docDesc*duationNum",
                                                    (docDesc, duationNum) => {
                                                        duationNum = duationNum.toFixed(2) + "%";
                                                        return {
                                                            name: docDesc,
                                                            value: duationNum
                                                        };
                                                    }
                                                ]}
                                                style={{
                                                    lineWidth: 1,
                                                    stroke: "#fff",
                                                    // bottom:20
                                                }}
                                            >
                                                <Label
                                                    content="duationNum"
                                                    formatter={(val, item) => {
                                                        var str = val;
                                                        var a = str.split("%").join("");
                                                        // let b = a.toFixed(2)
                                                        // let b = a&&a.map((i,s)=>{
                                                        //    i = i.toFixed(2)
                                                        // })

                                                        // console.log("b------------", b)
                                                        return item.point.docDesc;
                                                    }}
                                                />
                                            </Geom>
                                        </Chart>
                                        : item.type == "pi" && dvOne&&dvOne.length>0?
                                        <Chart height={310} data={dvOne} scale={colsOne} forceFit
                                        padding={[20, 20, 20, 30]}
                                    >
                                        <Legend
                                            visible={false}
                                            marker={(x, y, r) => {
                                                return [
                                                    ['M', x - r, y],
                                                    ['L', x + r, y]
                                                ];
                                            }}
                                        />
                                        <Axis name="docDesc" />
                                        <Axis name="value" />
                                        <Tooltip />
                                        <Geom
                                            type="intervalStack"
                                            position="docDesc*value"
                                            color={"individuation"}
                                        />
                                    </Chart>: item.type == "point"&&dvOne&&dvOne.length>0 ?
                                                <Chart height={310} data={dvOne} scale={colsPointOne} forceFit
                                                    padding={[20, 20, 20, 30]}

                                                >
                                                    <Legend
                                                        visible={false}
                                                        marker={(x, y, r) => {
                                                            return [
                                                                ['M', x - r, y],
                                                                ['L', x + r, y]
                                                            ];
                                                        }}
                                                    />
                                                    <Axis name="docDesc" />
                                                    <Axis
                                                        name="value"
                                                        label={{
                                                            formatter: val => `${val}`
                                                        }}
                                                    />
                                                    <Tooltip
                                                        crosshairs={{
                                                            type: "y"
                                                        }}
                                                    />
                                                    <Geom
                                                        type="line"
                                                        position="docDesc*value"
                                                        size={2}
                                                        color={"individuation"}
                                                        shape={"smooth"}
                                                    />
                                                    <Geom
                                                        type="point"
                                                        position="docDesc*value"
                                                        size={4}
                                                        shape={"circle"}
                                                        color={"individuation"}
                                                        style={{
                                                            stroke: "#fff",
                                                            lineWidth: 1
                                                        }}
                                                    />
                                                </Chart>
                                                :item.type=="tabge"?
                                                <div>
                                                    <Table
                                                        columns={columns}
                                                        dataSource={this.state.doctorData}
                                                        pagination={false}
                                                        bordered
                                                        rowClassName={this.setClassName}

                                                    />
                                                </div>:<div style={{width:"100px"}}>
                                                    <p>暂无数据</p>
                                                </div>
                                }
                            </div>
                        </Card>
                    </Col>
                )
            } if (item.key == "1") {
                chartsList.push(
                    <Col span={12}>
                        <Card span={12} key={item.id} title={item.title}>
                            <div className="button-dom" style={{ position: "relative" }}>
                                {
                                    item.pie && item.pie.map((i, s) => {
                                        return (
                                            <Button onClick={() => this.handleType(i, item.des)} style={{ background: (i.activeID == i.id ? "rgb(0, 153, 255)" : "#fff"), color: (i.activeID == i.id ? "#fff" : "#333") }} >{i.descripts}</Button>
                                        )
                                    })
                                }
                                <Button style={{ float: "right",display:(dvTwo&&dvTwo.length>0?"block":"none") }} onClick={(e) => this.handleSetting(e, "Two", this.state.columnsT, dataTableTwo, this.state.selectedRowKeys_rightOne)}>设置统计维度</Button>
                                <div className={this.state.showTwo ? "setting-table-dom" : ""}
                                    style={{ display: (this.state.showTwo ? "inline-block" : "none"), }}>
                                    <Table
                                        columns={columnsSeting}
                                        dataSource={dataTableTwo}
                                        pagination={false}
                                        bordered
                                        rowKey={record => record.key}
                                        rowClassName={this.setClassName}
                                        rowSelection={rowSelection_rightOne}
                                    />
                                    <Row>
                                        <Button onClick={() => this.handleOk("Two", this.state.selectedRowKeys_rightOne, columnsTwo, "columnsT", this.state.doctorCsTwoOrigin, "doctorCsTwo")}>确定</Button>
                                    </Row>
                                </div>
                            </div>
                            <div className="charts-item" style={{ width: item.type == "pi" || item.type == "point" ? this.state.twoCount * 150 + "px" : "", height: "320px", position: "relative" }}>
                                {
                                    item.type == "pie"&&dvTwo&&dvTwo.length>0  ?
                                        //  <Chart
                                        //     height={600}
                                        //     width={600}
                                        //     data={dvTwo}
                                        //     // scale={cols}
                                        //     // padding={[10, 0, 220, 0]}
                                        //     forceFit
                                        //     style={chartStyle}
                                        // >
                                        <Chart
                                            height={246}
                                            width={600}
                                            data={dvTwo}
                                            scale={cols}
                                            padding={[60, 240, 12, 12]}
                                            forceFit
                                            style={chartStyle}
                                        >
                                            <Coord type="theta" radius={0.75} />
                                            <Axis name="healthNum" />
                                            {/* <Legend
                                            position="bottom"
                                            layout="horizontal"
                                            itemWidth={120}
                                            itemGap={12}
                                            offsetY={-20}

                                            // offsetX={-50}
                                            // top={12}
                                        /> */}
                                            <Legend
                                                position="right"
                                                offsetY={-20}
                                                offsetX={-50}
                                            />
                                            <Tooltip
                                                showTitle={false}
                                            //    itemTpl='<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
                                            />
                                            <Geom
                                                type="intervalStack"
                                                position="healthNum"
                                                color="docDesc"
                                                tooltip={[
                                                    "docDesc*healthNum",
                                                    (docDesc, healthNum) => {
                                                        healthNum = healthNum.toFixed(2) + "%";
                                                        return {
                                                            name: docDesc,
                                                            value: healthNum
                                                        };
                                                    }
                                                ]}
                                                style={{
                                                    lineWidth: 1,
                                                    stroke: "#fff",
                                                    // bottom:20
                                                }}
                                            >
                                                <Label
                                                    content="healthNum"
                                                    formatter={(val, item) => {
                                                        var str = val;
                                                        var a = str.split("%").join("");
                                                        // let b = a.toFixed(2)
                                                        // let b = a&&a.map((i,s)=>{
                                                        //    i = i.toFixed(2)
                                                        // })

                                                        // console.log("b------------", b)
                                                        return item.point.docDesc;
                                                    }}
                                                />
                                            </Geom>
                                        </Chart> : item.type == "pi"&&dvTwot&&dvTwot.length>0 ?
                                            <Chart height={310} data={dvTwot} scale={colsOne} forceFit
                                                padding={[20, 20, 40, 30]}
                                            >
                                                <Legend
                                                    visible={false}
                                                />
                                                <Axis name="docDesc" />
                                                <Axis name="percent" />
                                                <Tooltip />
                                                <Geom
                                                    type="intervalStack"
                                                    position="docDesc*percent"
                                                    color={"satisfact"}
                                                />
                                            </Chart>
                                            : item.type == "point"&&dvTwot&&dvTwot.length>0 ?
                                                <Chart height={310} data={dvTwot} scale={colsPointOne} forceFit
                                                    padding={[20, 20, 20, 30]}
                                                >
                                                    <Legend
                                                        visible={false}
                                                        marker={(x, y, r) => {
                                                            return [
                                                                ['M', x - r, y],
                                                                ['L', x + r, y]
                                                            ];
                                                        }}
                                                    />
                                                    <Axis name="docDesc" />
                                                    <Axis
                                                        name="value"
                                                        label={{
                                                            formatter: val => `${val}`
                                                        }}
                                                    />
                                                    <Tooltip
                                                        crosshairs={{
                                                            type: "y"
                                                        }}
                                                    />
                                                    <Geom
                                                        type="line"
                                                        position="docDesc*value"
                                                        size={2}
                                                        color={"satisfact"}
                                                        shape={"smooth"}
                                                    />
                                                    <Geom
                                                        type="point"
                                                        position="docDesc*value"
                                                        size={4}
                                                        shape={"circle"}
                                                        color={"satisfact"}
                                                        style={{
                                                            stroke: "#fff",
                                                            lineWidth: 1
                                                        }}
                                                    />
                                                </Chart> :item.type=="tabge"?
                                                <div>
                                                    <Table
                                                        columns={columnsT}
                                                        dataSource={this.state.sexData}
                                                        pagination={false}
                                                        bordered
                                                        rowClassName={this.setClassName}
                                                    />
                                                </div>:<div style={{width:"100px"}}>
                                                    <p style={{textAlign:"center"}}>暂无数据</p>
                                                </div>
                                }
                            </div>
                        </Card>
                    </Col>
                )
            }
        })
        return (
            <div className="charts-dom">
                <Row>
                    {
                        chartsList
                    }
                </Row>
            </div>
        );
    }
}
export default AnalysisChartsConful 
