import React from 'react';
import ReactDOM from 'react-dom';
import 'antd-mobile/dist/antd-mobile.css';
import { Card, WingBlank, WhiteSpace, Switch, InputItem, Tag, Modal, List, Button, Flex, Radio, Checkbox } from 'antd-mobile';
import './less/list.less';
import { Http } from '../../Utils/help'

const RadioItem = Radio.RadioItem;
const CheckboxItem = Checkbox.CheckboxItem;

export default class subscription extends React.Component {
    constructor(props) {
        super(props);
        //const { subdata } = this.props.location.state;
        this.saveSubscription = this.saveSubscription.bind(this);
        this.onTagClose = this.onTagClose.bind(this);
        this.getTagAndValue = this.getTagAndValue.bind(this);
        this.onClose = this.onClose.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
        this.state = {
            subdata: [],
            checked: false,
            topicid: null,
            tag: {},
            tags: [],//标签
            filter: [],//标签值
            res: [],
            showvisible: false,//modal是否显示处理
            radioval: "",
            initData: [],//所有标签对应的标签值
        };
    }

    componentWillMount() {
        console.log("componentWillMount--")
        this.dataAjax = Http.getJSON2("subscription/getSubscription");
        // this.dataAjax = Http.getJSON2("subscription",{page:1});
    }
    componentDidUpdate() {
        console.log("componentDidUpdate--")
    }

    componentDidMount() {
        console.log("componentDidMount--");
        this.dataAjax.done((result) => {
            this.setState({
                subdata: result,
            })
        })
    }

    onTagClose(v, topicid) {
        console.log("onTagClose")
        this.dataAjax = Http.postJSON2("subscription/removetag", { "topicid": topicid, "filtertags": v }, this.succeed)
    }

    //关闭model
    onClose = () => {
        console.log("onClose")
        this.setState({
            showvisible: false,
            topicid: null,
            tags: [],//标签
            filter: [],//标签值
            res: [],
            radioval: "",
            initData: [],
        });
    }

    // afterClose=()=>{
    //     const {subdata} = this.state
    //     console.log("afterClose")
    //     console.log(subdata)
    //     this.setState({
    //         subdata:subdata,
    //     })
    // }
    //确定 提交更改
    onSubmit = key => () => {
        console.log("onSubmit")
        const { tags, filter, topicid } = this.state
        this.dataAjax = Http.postJSON2("subscription/addtag", { "topicid": topicid, "filtertags": filter.join(",") }, this.succeed, this.error)
    }
    //点击标签值为“+”的事件
    getTagAndValue = (tags, filtertags, topicid) => {
        console.log("getTagAndValue")
        let tagarr = tags.split(",")
        let tagstr = ''
        for (let i = 0; i < tagarr.length; i++) {
            tagstr += "'" + tagarr[i] + "',"
        }
        // console.log(tagstr.substring(0, tagstr.length - 1))
        this.dataAjax = Http.getJSON2("ds/data/message/subscription_tagvalue", { "tag": tagstr.substring(0, tagstr.length - 1) }).done((result) => {
            try {
                // console.log(tagarr, filtertags, result)
                let delval = tagarr[0]
                let children = []
                let index = 0
                for (let z = 0; z < result.length; z++) {
                    if (result[z].tag === delval) {
                        if (filtertags.includes(result[z].datas)) {
                            children[index] = JSON.parse('{"label":"' + result[z].datas + '","value":"' + result[z].datas + '","checked":true}')
                        } else {
                            children[index] = JSON.parse('{"label":"' + result[z].datas + '","value":"' + result[z].datas + '"}')
                        }
                        index++
                    }
                }

                this.setState({
                    showvisible: true,//是否显示modal
                    topicid: topicid,
                    radioval: delval,
                    initData: children,
                    tags: tagarr,
                    filter: filtertags,
                    res: result,
                })
            } catch (error) {
                console.error(error.message);
                console.error(error.stack);
            }
        })
    }
    //切换标签事件
    onChange = (value) => {
        console.log("onChange")
        const { res, filter } = this.state
        // console.log(filter, res)
        let delval = value
        let children = []
        let index = 0

        for (let z = 0; z < res.length; z++) {
            if (res[z].tag === delval) {
                if (filter.includes(res[z].datas)) {
                    children[index] = JSON.parse('{"label":"' + res[z].datas + '","value":"' + res[z].datas + '","checked":true}')
                } else {
                    children[index] = JSON.parse('{"label":"' + res[z].datas + '","value":"' + res[z].datas + '"}')
                }
                index++
            }
        }
        this.setState({
            radioval: value,
            initData: children,
        });
    }
    //复选框点击事件
    onChangeCheck = (val) => {
        console.log("onChangeCheck")
        let filters = this.state.filter
        if (filters.includes(val.value)) {
            // console.log("del:" + val.value)
            var index = filters.indexOf(val.value);
            // console.log(index)
            if (index > -1) {
                filters.splice(index, 1)
            }
            // this.setState({
            //     filter: filters,
            // })
        } else {
            filters.push(val.value)
            // this.setState({
            //     filter: filters,
            // })
        }
    }

    //主题 开关按钮事件
    saveSubscription = (e, topicid, tags) => {
        console.log("saveSubscription")
        var uptags
        if (JSON.stringify(tags) == "[]") {
            uptags = ""
        } else {
            uptags = tags.join(",")
        }
        var status
        if (e) {
            status = "New";
        } else {
            status = "Deleted";
        }
        this.dataAjax = Http.postJSON2("subscription/setSubscription", { "status": status, "topicid": topicid, "filtertags": uptags }, this.succeed, this.error);
    }
    //提交成功
    succeed = (result) => {
        console.log("提交成功");

        this.dataAjax = Http.getJSON2("subscription/getSubscription").done((result) => {
            // console.log(result);
            try {
                this.setState({
                    subdata: result,
                    showvisible: false,
                    topicid: null,
                    tags: [],//标签
                    filter: [],//标签值
                    res: [],
                    radioval: "",
                    initData: [],
                })
                this.forceUpdate();
            } catch (error) {
                console.error(error.message);
                console.error(error.stack);
            }
        })
    }
    //提交失败
    error = (result) => {
        // Toast.fail("提交失败", 1);
    }

    render() {
        let card;

        (this.state.subdata.length > 0) ? card =
            <div>
                <WingBlank size="lg">
                    <WhiteSpace size="lg" />
                    {
                        (this.state.subdata.length > 0) ?
                            this.state.subdata.map((ind, val) => {
                                return (
                                    <div key={val} style={{ padding: '0 0 5px 0' }}>
                                        <Card key={ind.topicid}>
                                            <Card.Header
                                                title={ind.topname}
                                                extra={<span><Switch
                                                    platform="android"
                                                    checked={ind.status}
                                                    onChange={(e) => {
                                                        this.saveSubscription(e, ind.topicid, ind.filtertags)
                                                    }}
                                                /></span>}
                                            />
                                            <Card.Body style={{ padding: '0 0 0 3px' }}>
                                                <div style={{ padding: '0 0 0 0', margin: '0 0 0 0' }}>
                                                    <InputItem editable={false} style={{ width: 'auto', fontSize: '90%', padding: '0 0 0 0', margin: '0 0 0 0', color: '#778899' }}
                                                        defaultValue={"标签:" + (ind.tags == null ? "无" : ind.tags)} /></div>
                                                <div style={{ width: '100%', fontSize: '90%', padding: '0 0 0 0', margin: '0 0 0 0' }}>
                                                    {/* {console.log("标签值:" + (ind.filtertags == null ? "" : ind.filtertags),val)} */}
                                                    {ind.filtertags ? ind.filtertags.map((v, i) =>
                                                        <Tag key={ind.topname + v + i} style={{ margin: '10px 0 0 10px' }} closable={this.state.tag[ind.topname + v + i]}
                                                            onChange={(checked) => {
                                                                let tag = this.state.tag
                                                                tag[ind.topname + v + i] = checked
                                                                this.setState({ tag: tag })
                                                            }
                                                            }
                                                            afterClose={() => this.onTagClose(v, ind.topicid)}>{v}</Tag>) : ""}
                                                    {ind.tags != null && ind.status ? <Tag style={{ margin: '10px 0 0 10px' }} onChange={() => this.getTagAndValue(ind.tags, ind.filtertags, ind.topicid)}>+</Tag> : ""}
                                                </div>
                                            </Card.Body>
                                        </Card>
                                    </div>
                                )
                            })
                            : ""
                    }

                </WingBlank>
            </div>
            : card = null;
        return (
            <div>
                {card}
                {
                    <Modal
                        popup
                        visible={this.state.showvisible}
                        // onClose={this.onClose}
                        onClose={this.succeed}
                        animationType="slide-up"
                    // afterClose={this.afterClose}
                    >
                        {/* <Flex>
                            <Flex.Item style={{ align: 'center' }} >Test</Flex.Item> */}
                        <WingBlank size="sm">
                            <WhiteSpace size="sm" />
                            <Flex>
                                <Flex.Item style={{ flex: '0.5' }}>
                                    <Card style={{ width: '100%', height: '300px', margin: '5px 2px 0 5px' }}>
                                        <Card.Body style={{ height: '100%', overflowY: 'auto' }}>

                                            <List>
                                                {this.state.tags.map(i => (
                                                    <RadioItem key={i} style={{ height: '40px' }} checked={this.state.radioval === i} onChange={() => this.onChange(i)}>
                                                        {i}
                                                    </RadioItem>
                                                ))}
                                            </List>
                                        </Card.Body>
                                    </Card>
                                </Flex.Item>
                                <Flex.Item>
                                    <Card style={{ width: '95%', height: '300px', margin: '5px 5px 0 2px' }}>
                                        <Card.Body style={{ height: '100%', overflowY: 'auto' }}>
                                            <List>
                                                {this.state.initData.map(i => (
                                                    <CheckboxItem
                                                        key={i.value}
                                                        style={{ height: '40px' }}
                                                        defaultChecked={i.checked}
                                                        onChange={() => this.onChangeCheck(i)}
                                                    >
                                                        {i.label}
                                                    </CheckboxItem>
                                                ))}
                                            </List>
                                        </Card.Body>
                                    </Card>
                                </Flex.Item>
                            </Flex>
                            <WhiteSpace size="sm"/>
                        </WingBlank>
                        {<List style={{ padding: '0 0 8px 0',margin:'0 12px 0 6px' }}>
                            <List.Item>
                                <Button type="primary" onClick={this.onSubmit('showvisible')}>确定</Button>
                            </List.Item>
                        </List>}
                    </Modal>
                }
            </div>
        )
    }


}