import React from 'react';
import styles from './index.css';
import { Map, Polygon, Polyline, Circle, Marker } from 'react-amap';
import EditTpl from '../edit';
const getAMap = async (i = 0) => {
    if (window.AMap) {
        return window.AMap;
    } else if (i < 5) {
        return new Promise(r => {
            setTimeout(() => {
                r(getAMap(i++));
            }, 50);
        });
    }
}
//龙里geoJSON
class GeoJSON extends React.Component {
    state = {
        gJ: {}
    }
    componentWillMount() {
        const { __map__: map, geoJSON, config } = this.props;
        if (!map) {
            console.log('组件必须作为 Map 的子组件使用');
            return;
        }
        //清空地图覆盖
        typeof this.state.gJ.clearOverlays == "function" && this
            .state
            .gJ
            .clearOverlays();
        try {
            let gJ = new AMap.GeoJSON({
                geoJSON,
                ...config
            });
            gJ.setMap(map);
            this.setState({ gJ });
        } catch (error) { }
    }

    render() {
        return '';
    }

};
//自定义argis卫星图
const ArcGIS = (props) => {
    const map = props.__map__;
    if (!map) {
        console.log('组件必须作为 Map 的子组件使用');
        return;
    }
    new AMap.TileLayer({
        map,
        tileUrl: 'https://mt3.google.cn/vt/imgtp=png32&lyrs=y&hl=zh-CN&gl=cn&x=[x]&y=[y]&z=[z]&s=Galil',
        zIndex: 2 // 在默认层级之上
    });
    return "";
};
//工具
const ToolBar = (props) => {
    const map = props.__map__;
    if (!map) {
        console.log('组件必须作为 Map 的子组件使用');
        return;
    }
    AMap
        .plugin(['AMap.ToolBar'], function () {
            map.addControl(new AMap.ToolBar({ position: "RT" }));
        })
    return "";
};
//动态增加点
const CurrentPoint = props => {
    const map = props.__map__,
        { addPoint = () => { } } = props;
    if (!map) {
        console.log('组件必须作为 Map 的子组件使用');
        return;
    }
    let point = null, pointText = "";
    addPoint((e) => {
        point && map.remove(point);
        pointText && map.remove(pointText);
        const defPoint = [107.465407, 27.749055];
        // 创建一个 Marker 实例：
        point = new AMap.Marker({
            ...e,
            content: `<i class="iconfont icon-qipao" style="font-size: 25px;color:${e._legend.color};"></i>`,
            offset: new AMap.Pixel(-16, -52),
            position: e.lnglat.map((x, i) => {
                return x - 0 || defPoint[i];
            }),
            animation: "AMAP_ANIMATION_DROP"
        });
        // 设置label标签 label默认蓝框白底左上角显示，样式className为：amap-marker-label
        point.setLabel({
            content: `<p style="
                                background: #ffffff;
                                color: #000000;
                                display: block;
                                padding: .6em 1em;
                                border-radius: 0.5em;
                                overflow: hidden;
                                ">${e.name}</p>`, //设置文本标注内容            
            content: e.name, //设置文本标注内容
            direction: 'top',//设置文本标注方位
            style: {
                fontSize: '20px'
            }
        });
        //事件监听
        if (e.events) {
            Object.keys(e.events).map(x => {
                point.on(x, e.events[x]);
            });
        }
        // 将创建的点标记添加到已有的地图实例：
        map.add([point, pointText]);
    });
    return "";
}
//缩放地图到合适的视野
const FitVision = props => {
    const map = props.__map__;
    if (!map) {
        console.log('组件必须作为 Map 的子组件使用');
        return;
    }
    setTimeout(()=>{
        map.setFitView(null,true,[0,0,0,0],17);
    },800);
    return "";
}
//清理图层
const ClearMap = props => {
    const map = props.__map__;
    if (!map) {
        console.log('组件必须作为 Map 的子组件使用');
        return;
    }
    map.clearMap();
    return "";
}
//操作工具
const MyTool = props => {
    const map = props.__map__;
    if (!map) {
        console.log('组件必须作为 Map 的子组件使用');
        return;
    }
    const aBtn = i => {
        switch (i) {
            case 0:
                map.zoomIn();
                break;
            case 1:
                map.zoomOut();
                break;
            case 2:
                map.setZoom(10);
                break;
            default:
                break;
        }
    }
    return <ul className={styles.actionBtn}>
        <li onClick={e => aBtn(0)}>
            <i className={`iconfont icon-jia`}></i>
        </li>
        <li onClick={e => aBtn(1)}>
            <i className={`iconfont icon-jian`}></i>
        </li>
        {/* <li onClick={e => aBtn(2)}>
            <i className={`iconfont icon-NMStubiao-`}></i>
        </li> */}
    </ul>
}
//图例
const MapLegend = props => {
    const { legend = [] } = props;
    if (legend.length == 1 && !legend[0].name) {
        return "";
    }
    return !!legend.length && <ul className={styles.mapBoxLegend}>
        {legend.map((x, i) => {
            if (!x.name && !x.icon) {
                return "";
            }
            switch ((x.icon + "").slice(0, 4)) {
                case 'http':
                    return (
                        <li key={i}>
                            <img src={x.icon}></img>
                            {x.name}
                        </li>
                    )
                    break;
                case "icon":
                    return (
                        <li key={i}>
                            <i
                                className={`iconfont ${x.icon}`}
                                style={{
                                    color: x.color
                                }}></i>
                            {x.name}
                        </li>
                    )
                    break;
                default:
                    return (
                        <li key={i}>
                            <i style={{ background: x.color }}></i>
                            {x.name}
                        </li>
                    )
                    break;
            }
        })
        }</ul>
}

//颜色类型转换
/*[parserColor 颜色转换为rgba格式]
@param  {[String]} value [需要转换的颜色值]
@return {[String]}       [返回转换后的颜色值,rgb(255,255,255)形式]
*/
function parseColorRgb(value, t = .4) {
    var str = "",
        vlen = value.length,
        rgb1 = "",
        rgb2 = "",
        rgb3 = "",
        colorObj = {
            "black": `rgba(0,0,0,${t})`,
            "red": `rgba(255,0,0,${t})`,
            "blue": `rgba(0,0,255,${t})`,
            "white": `rgba(255,255,255,${t})`,
            "yellow": `rgba(255,255,0,${t})`,
            "orange": `rgba(255,165,0,${t})`
        };

    //输入的是rgb格式的 rgb(0,0,255)
    if (/rgba/.test(value)) {
        return value;
    } else if (/^#/.test(value)) { //输入的是#FFFFFF的格式
        //#00f
        if (vlen == 4) {
            //$&表示匹配到的本身,甚少看到这样的用法,这里可当做$0 str = value.replace(/[A-Za-z0-9]/g, "$&$&");
            str = value
                .replace(/[A-Za-z0-9]/g, "$0$0")
                .substr(1, 6); //substr(1,6)去掉#
            // alert(str);
        } else if (vlen == 7) {
            //#FF0000
            str = value.replace(/^#([A-Za-z0-9]*)/, "$1");
        } else {
            str = "FFFFFF";
        }
        //按长度划分后把三个数字取出来
        // alert(str.substr(0, 2));
        //alert(parseInt(str.charAt(0), 16));
        rgb1 = parseInt(str.substr(0, 2), 16);
        rgb2 = parseInt(str.substr(2, 2), 16);
        rgb3 = parseInt(str.substr(4, 2), 16);
        return `rgba(${rgb1},${rgb2},${rgb3},${t})`;
    } else {
        //red,orange
        value = value.toLowerCase();
        return colorObj[value]
            ? colorObj[value]
            : `rgba(255,255,255,${t})`; //不匹配默认为白色
    }
}
//颜色取反方法
function ColorReverse(OldColorValue) {
    var OldColorValue = `0x${OldColorValue.replace(/#/g, "")}`;
    var str = `000000${(0xFFFFFF - OldColorValue).toString(16)}`;
    return `#${str.substring(str.length - 6, str.length)}`;
}

//处理点显示
const showMarker = (l = {}, value) => {
    if (!!l && !!l.content) {
        const colorStyle = {
            border: `1px solid ${l.color}`,
            boxShadow: `0 0 5px 0 ${l.color},0 0 5px 0 ${l.color} inset`
        }
        return (<div className={styles[l.content]} style={{ background: l.color }}>
            <span className={styles.after} style={colorStyle}></span>
            <span className={styles.before} style={colorStyle}></span>
        </div>);
    } else if (!!l && !!l.icon) {
        //判断 图例内容
        switch ((l.icon + "").slice(0, 4)) {
            case "icon":
                return <i
                    className={`iconfont ${l.icon}`}
                    style={{
                        color: "#ffffff",
                        background: parseColorRgb(l.color, 1),
                        fontSize: "18px",
                        border: `2px solid`,
                        padding: "7px",
                        borderRadius: "50%"
                    }}></i>
                break;
            case "http":
                return <img src={l.icon} />
                break;
        }
    }
    return <span className={styles.textMarker} style={{
        // background:parseColorRgb(ColorReverse(l.color,0.6)),
        background: parseColorRgb(l.color + "", 0.8),
        color: "#fff"
    }}>{value}</span>
}

class Covers extends React.Component{
    state = {
        cover:[],
        legend:[]
    }
    componentDidMount(){
        this.update(this.props);
    }
    update = (cover = [],legend = []) =>{
        this.setState({cover,legend});
    }
    render(){
        const {updateCover} = this.props;
        if(typeof updateCover === "function"){
            updateCover(this.update);
        }
        const {cover,legend} = this.state;
        if (!cover.length) return [];
        let d = [];
        cover.map((x, i) => {
            //关联图例
            let l = legend && legend[x.legend - 1];
            if (l) {
                x.style = x.style || {};
                x.style.strokeColor = l.color;
                x.style.fillColor = parseColorRgb(l.color, 0.5);
            } else {
                l = {};
            }
            switch (x.type) {
                case "Polygon":
                    try {
                        x.style.strokeWeight = 5;
                    } catch (error) {
                        console.error(x);
                    }
                    d.push(<Polygon {...this.props} key={i} {...x} />);
                    break;
                case "Polyline":
                    d.push(<Polyline {...this.props} key={i} {...x} />);
                    break;
                case "Circle":
                    d.push(<Circle {...this.props} key={i} {...x} />);
                    break;
                case "Marker":
                    const defPoint = [106.630153,26.647661];
                    Array.isArray(x.lnglat) && (x.position = x.lnglat = x.lnglat.map((x, i) => {
                        return x - 0 || defPoint[i];
                    }));
                    d.push(
                        <Marker {...this.props} key={i} {...x}>{showMarker(l, x.value)}</Marker>
                    );
                    break;
                default:
                    break;
            }
        });
        return d;
    }
}

class Amap extends React.Component {
    state = {
        config: {
            mId: '',
            data: {
                amapkey: '',
                map: {
                    mapStyle: "",
                    center: [
                        107.465407, 27.749055
                    ],
                    zoom: 8
                },
                legend: [
                    // {     name: "31231",     icon: 'icon-shucai',     color: "#fff" }, { name:
                    // "31231",     color: "red" }, {     name: "31231",     icon: 'icon-shucai',
                    // color: "red" }
                ],
                covers: [
                    // {     type: "Polygon",     style: {         // strokeColor: "#acd9f1",
                    // strokeOpacity: "1",         // fillColor: "#fff",         fillOpacity: "0.1"
                    // },     path: [         // [         //     106.627819, 26.64756 // ],    //
                    // [         //     106.674511, 26.619019         // ], // [106.617519,
                    // 26.613801]     ] }
                ]
            }
        }

    }
    shouldComponentUpdate(props, state) {
        const {
            config: _config = {}
        } = this.state, {
            config = {}
        } = state;
        if (JSON.stringify(config) != "{}" && config != _config) {
            return true;
        }
        return false;
    }
    componentWillReceiveProps(props) {
        const {
            config: _config = {}
        } = this.props, {
            config = {}
        } = props;
        if (JSON.stringify(config) != "{}" && config != _config) {
            this.setState({ config });
        }
    }
    //点事件
    pointClick = e => {
        // console.log(8008,e);
    }
    
    //图层
    Layer = () => { }
    render() {
        let {
            config,
            config: {
                data: {
                    legend = [],
                    map,
                    map: {
                        mapStyle = '',
                        center = []
                    },
                    covers:coversList = [],
                    amapkey = ''
                }
            }
        } = this.state,
            { noTool, noLegend} = this.props;
        //处理中心点
        if (!center[0] || !center[1]) {
            map.center = [106.630153, 26.647661];
        }
        return (
            <div style={this.props.style} className={styles.mapBox}>
                <EditTpl
                    style={{
                        bottom: "50%"
                    }}
                    data={config}
                    upData={config => this.setState({ config })}></EditTpl>
                <Map
                    protocol="https"
                    version="1.4.15"
                    {...this.props}
                    key={Math.random(1, 10)}
                    expandZoomRange={true}
                    amapkey={amapkey || '388e4a971a8fb8d616e4a85d7deff144'}
                    {...map}
                    mapStyle={mapStyle || 'amap://styles/4b0dc026a923f329ed1f444b7abb6ac8'}
                >
                    <Covers cover={coversList} legend={legend} updateCover={this.props.updateCover}></Covers>
                    {noTool ? '' : <MyTool />}
                    <FitVision />
                    <CurrentPoint {...this.props} />
                    {this.props.children}
                    {/* <ToolBar></ToolBar> */}
                </Map>
                {noLegend ? '' : <MapLegend legend={legend} />}
            </div>
        )
    }
}
export { ArcGIS, Amap, GeoJSON, ToolBar, getAMap, ClearMap }
export default Amap;