import React, {Component} from 'react';
import {StyleSheet, View, Text, DeviceEventEmitter, ScrollView, TouchableOpacity, Dimensions} from 'react-native';
import {Button} from '@ant-design/react-native';
import ReadUHF from '../../utils/ReadUHF';
import Barcode from 'react-native-barcode-builder';
// import SyncStorage from "sync-storage";
import {SyncStorage} from '../../utils';

let screenW = Dimensions.get('window').width;
let lastBackPressed = 0;

class DesktopHome2 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            userData: [],
            no_begin: '8',
            no_length: '14',
            zuhe_temp: '1',
            error: 0,
            isStart: true,
            timerID: [],
        };
    }

    static navigationOptions = {
        headerRight: () => (
            <Text
                onPress={() => DeviceEventEmitter.emit('onSet')}
                style={{
                    fontSize: 18,
                    color: '#fff',
                    // marginRight: 5,
                }}>设置</Text>
        ),
    };

    async componentDidMount() {
        // ReadUHF.changeFlag(0)
        DeviceEventEmitter.addListener('onSet', (param) => {
            this.props.navigation.navigate("SetPower")
        });
        DeviceEventEmitter.addListener('MsgFromAndroid', this._addCode);
        DeviceEventEmitter.addListener('onKeyDown', this.onKeyDown);
        const show_type = await SyncStorage.get('show_type');
        if (show_type === undefined) {
            SyncStorage.set('show_type', '1');
        }
        const zuhe_temp = await SyncStorage.get('zuhe_temp');
        this.setState({zuhe_temp});
    }

    _addCode = async (item) => {
        const str = JSON.parse(item);
        // 防止重复扫描
        const show_type = await SyncStorage.get('show_type') ?? '1';
        let {data, userData, error} = this.state;
        const product_index = userData.indexOf(str['userData']);
        console.log(66666666, product_index, show_type, str['error'], str['error_msg'])
        if (product_index < 0) {
            // 只显示本类别 不显示错误信息
            if (show_type == '1') {
                // 且没有错误
                console.log('000kkk')
                if (str['error'] == '0') {
                    userData.push(str['userData']);
                    data.unshift(str);
                }
            } else {
                // 全部都显示
                console.log('eeerrr')
                if (str['error']) {
                    error += 1;
                }
                userData.push(str['userData']);
                data.unshift(str);
            }
            console.log(7777777, data)
            console.log(8888888, error)
            console.log(8888888, userData)
            this.setState({data, userData, error});
        }
    };

    _start = async () => {
        const no_begin = await SyncStorage.get('no_begin');
        const no_length = await SyncStorage.get('no_length');
        if (no_begin && no_begin) {
            this.setState({no_begin, no_length});
        }
        let {isStart} = this.state;
        ReadUHF.doRead();
        this.setState({isStart: !isStart});
    };
    _clear = () => {
        this.setState({userData: [], data: [], error: 0});
    };
    onKeyDown = async () => {
        const no_begin = await SyncStorage.get('no_begin');
        const no_length = await SyncStorage.get('no_length');
        if (no_begin && no_begin) {
            this.setState({no_begin, no_length});
        }
        let {isStart} = this.state;
        this.setState({isStart: !isStart});
    };

    dianYaRender = (item, index) => {
        const assetID = item.assetID.slice(parseInt(this.state.no_begin) - 1, parseInt(this.state.no_begin) + parseInt(this.state.no_length) - 1);
        const releaseDates = item.releaseDate.split('-');
        const releaseDate = releaseDates[0] + '年' + releaseDates[1] + '月';
        let districtText = '';
        if (parseInt(item.district) > 10000) {
            districtText = item.districtText;
        } else {
            const len1 = item.districtText.split('-')[1].length;
            districtText = '国网' + item.districtText.split('-')[1].slice(0, len1 - 1) + '电力';
        }
        return (
            <View
                key={index}
                style={styles.mainView}
            >
                <Text style={styles.textColor}>计量{item.kind}</Text>
                <View style={styles.betweenView}>
                    <Text style={styles.textColor3}>型号：{item.model}</Text>
                    <View style={styles.centerWidth}>
                        <Text style={styles.textColor3}>电压等级：{item.voltageLevel}kV</Text>
                    </View>
                    <Text style={styles.textColor3}>绕组数量：{item.secondWindingCount}</Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={styles.textColor4}>二次电压</Text>
                    <View style={styles.centerWidth}>
                        <Text style={styles.textColor4}>准确等级</Text>
                    </View>
                    <View style={styles.rightWidth}>
                        <Text style={styles.textColor4}>功率因数</Text>
                    </View>
                    <Text style={styles.textColor4}>生产日期</Text>
                </View>
                <View style={styles.betweenView}>
                    <View style={styles.centerView}>
                        <Text style={styles.textColor4}>{item.secondVoltage}kV</Text>
                    </View>
                    <View style={styles.centerWidth}>
                        <Text style={styles.textColor4}>{item.accuracy}</Text>
                    </View>
                    <View style={styles.rightWidth}>
                        <Text style={styles.textColor4}>{item.powerFactor}</Text>
                    </View>
                    <View style={styles.centerView}>
                        <Text style={styles.textColor4}>{releaseDate}</Text>
                    </View>
                </View>
                <View style={styles.betweenView}>
                    <Text style={styles.textColor3}>安装场所：{item.place}</Text>
                    <View style={styles.centerWidth}>
                        <Text style={styles.textColor3}>额定负荷：{item.ratedLoad}VA</Text>
                    </View>
                    <Text style={styles.textColor3}>电压因数：{item.voltageFactor}</Text>
                </View>
                <View style={styles.betweenView}>
                    <View style={styles.centerView}>
                        <Text style={styles.textColor3}>{item.manufacturer}</Text>
                    </View>
                    <View style={{
                        width: (screenW - 10) / 3 * 2,
                        borderLeftWidth: 0.5,
                        borderLeftColor: '#7b7b7b',
                    }}>
                        <View style={{
                            flexDirection: 'row',
                            marginHorizontal: 3,
                        }}>
                            <View style={{
                                flex: 1,
                            }}>
                                <Text style={[styles.textColor, {textAlign: 'left'}]}>{districtText}</Text>
                            </View>
                            <Text style={[styles.textColor, {textAlign: 'right', paddingRight: 5}]}>NO.{assetID}</Text>
                        </View>
                        <View style={{
                            marginHorizontal: 5,
                        }}>
                            <Barcode value={item.assetID} format="CODE128" height={35} width={1.1}/>
                            <Text style={styles.textColor}>{item.assetID}</Text>
                        </View>
                    </View>
                </View>

            </View>
        );
    };

    dianLiuRender = (item, index) => {
        const assetID = item.assetID.slice(parseInt(this.state.no_begin) - 1, parseInt(this.state.no_begin) + parseInt(this.state.no_length) - 1);
        const releaseDates = item.releaseDate.split('-');
        const releaseDate = releaseDates[0] + '年' + releaseDates[1] + '月';
        let districtText = '';
        if (parseInt(item.district) > 10000) {
            districtText = item.districtText;
        } else {
            const len1 = item.districtText.split('-')[1].length;
            districtText = '国网' + item.districtText.split('-')[1].slice(0, len1 - 1) + '电力';
        }
        return (
            <View
                key={index}
                style={styles.mainView}
            >
                <Text style={styles.textColor}>计量{item.kind}</Text>
                <View style={styles.betweenView}>
                    <Text style={styles.textColor3}>型号：{item.model}</Text>
                    <View style={styles.centerWidth}>
                        <Text style={styles.textColor3}>电压等级：{item.voltageLevel}kV</Text>
                    </View>
                    <Text style={styles.textColor3}>绕组数量：{item.secondWindingCount}</Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={styles.textColor4}>一次电流</Text>
                    <View style={styles.centerWidth}>
                        <Text style={styles.textColor4}>二次电流</Text>
                    </View>
                    <View style={styles.rightWidth}>
                        <Text style={styles.textColor4}>功率因数</Text>
                    </View>
                    <Text style={styles.textColor4}>生产日期</Text>
                </View>
                <View style={styles.betweenView}>
                    <View style={styles.centerView}>
                        <Text style={styles.textColor4}>{item.firstCurrent}A</Text>
                    </View>
                    <View style={styles.centerWidth}>
                        <Text style={styles.textColor4}>{item.senondCurrent}A</Text>
                    </View>
                    <View style={styles.rightWidth}>
                        <Text style={styles.textColor4}>{item.powerFactor}</Text>
                    </View>
                    <View style={styles.centerView}>
                        <Text style={styles.textColor4}>{releaseDate}</Text>
                    </View>
                </View>
                <View style={styles.betweenView}>
                    <Text style={styles.textColor3}>安装场所：{item.place}</Text>
                    <View style={styles.centerWidth}>
                        <Text style={styles.textColor3}>额定负荷：{item.ratedLoad}VA</Text>
                    </View>
                    <Text style={styles.textColor3}>准确等级：{item.accuracy}</Text>
                </View>
                <View style={styles.betweenView}>
                    <View style={styles.centerView}>
                        <Text style={styles.textColor3}>{item.manufacturer}</Text>
                    </View>
                    <View style={{
                        width: (screenW - 10) / 3 * 2,
                        borderLeftWidth: 0.5,
                        borderLeftColor: '#7b7b7b',
                    }}>
                        <View style={{
                            flexDirection: 'row',
                            marginHorizontal: 3,
                        }}>
                            <View style={{
                                flex: 1,
                            }}>
                                <Text style={[styles.textColor, {textAlign: 'left'}]}>{districtText}</Text>
                            </View>
                            <Text style={[styles.textColor, {textAlign: 'right', paddingRight: 5}]}>NO.{assetID}</Text>
                        </View>
                        <View style={{
                            marginHorizontal: 5,
                        }}>
                            <Barcode value={item.assetID} format="CODE128" height={35} width={1.1}/>
                            <Text style={styles.textColor}>{item.assetID}</Text>
                        </View>
                    </View>
                </View>

            </View>
        );
    };

    errorRender = (item, index) => {
        return (
            <View
                key={index}
                style={[styles.mainView, {padding: 10}]}
            >
                <Text style={{color: 'red'}}>{item.error_msg}</Text>
            </View>
        );
    };

    render() {
        let {isStart, zuhe_temp} = this.state;
        const start_text = isStart ? '开始识别' : '停止识别';
        return (
            <View style={styles.container}>
                <ScrollView style={styles.container}>
                    {
                        this.state.data.map((item, index) => {
                            if (item.error) {
                                return this.errorRender(item, index);
                            }
                            else if (item.kind.indexOf('电压') > -1) {
                                return this.dianYaRender(item, index);
                            }
                            else if (item.kind.indexOf('电流') > -1) {
                                return this.dianLiuRender(item, index);
                            }
                            else {
                                // 组合互感器，没有设置，默认用电压模板
                                if (zuhe_temp === '2') {
                                    return this.dianLiuRender(item, index);
                                } else {
                                    return this.dianYaRender(item, index);
                                }
                            }

                        })
                    }
                </ScrollView>
                <Text
                    style={{marginLeft: 10, color: '#f77b22'}}>合计：{this.state.data.length} 失败：{this.state.error}</Text>
                <View style={{flexDirection: 'row'}}>
                    <Button onPress={() => this._start()}
                            type="primary"
                            style={[styles.button, {
                                backgroundColor: isStart ? '#0099FF' : 'red',
                                width: '65%',
                            }]}
                    >
                        <Text style={{color: '#fff'}}>
                            {start_text}
                        </Text>
                    </Button>
                    <Button onPress={() => this._clear()}
                            type="warning"
                            style={{
                                width: '25%',
                                borderRadius: 5,
                                marginHorizontal: 10,
                                marginTop: 5,
                                marginBottom: 2,
                                borderWidth: 0,
                                backgroundColor: '#de7642',
                            }}
                    >
                        <Text style={{color: '#fff'}}>
                            清除
                        </Text>
                    </Button>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    button: {
        borderRadius: 5,
        marginHorizontal: 10,
        marginBottom: 2,
        marginTop: 5,
        borderWidth: 0,
        backgroundColor: '#2b90ea',
    },
    textColor: {
        color: '#333',
        textAlign: 'center',
    },
    textColor3: {
        color: '#333',
        textAlign: 'center',
        width: (screenW - 9) / 3,

    },
    textColor4: {
        color: '#333',
        textAlign: 'center',
        width: (screenW - 8) / 4,

    },
    textColor2: {
        color: '#333',
        textAlign: 'center',
        width: (screenW - 10) / 2,
    },
    mainView: {
        margin: 5,
        borderWidth: 0.5,
        borderColor: '#7b7b7b',
    },
    betweenView: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        borderTopWidth: 0.5,
        borderTopColor: '#7b7b7b',
    },
    centerWidth: {
        borderLeftWidth: 0.5,
        borderRightWidth: 0.5,
        borderLeftColor: '#7b7b7b',
        borderRightColor: '#7b7b7b',
        alignItems: 'center',
        flexDirection: 'row',
    },
    centerView: {
        alignItems: 'center',
        flexDirection: 'row',
    },
    rightWidth: {
        borderRightWidth: 0.5,
        borderRightColor: '#7b7b7b',
        alignItems: 'center',
        flexDirection: 'row',
    },
});

export default DesktopHome2;
