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;

class DesktopHome extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            data2: [
                {
                    userData: "453534",
                    barcode: "4330012800000003232126",
                    orgType: "国网公司",
                    model: "YJLSZ-JF-10-630",
                    connection: "三相三线",
                    windingCount: "1",
                    transformer: "线性反应原理",
                    insulation: "油浸式",
                    ratedVoltage: "1000kV/√3",
                    ratedFrequencyAndPlace: "100,户外",
                    powerFactor: "0.8",
                    ratedCurrent1: "1000000/5",
                    ratedCurrent2: "1000000/5",
                    ratedCurrent3: "1000000/5",
                    ratedSecondLoadTA: "17.5",
                    overlightLoadTA: "18.5",
                    precisionTA: "0.5SS",
                    voltageChangeRate: "10000/√3/100/√3",
                    ratedSecondLoadTV: "17.5",
                    overlightLoadTV: "18.5",
                    precisionTV: "0.5SS",
                    flagAndRight: "新，局属",
                    encodeType: "国标",
                    securityAndExpansionFactor: "10,1.2",
                    releaseDate: "2023-07",
                    assetProperty: "供电企业资产，营销",
                    manufacturer: "武汉高压研究所新技术公司华电电气技术有限公司",
                    assetAttribution: "国网天府新区供电公司客户服务中心",
                }
            ],
            userData: [], //防止重复扫描
            no_begin: '8',
            no_length: '14',
            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 === null) {
            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'])
        if (product_index < 0) {
            // 只显示本类别，不显示错误信息
            if (show_type == '1') {
                // 且没有错误
                if (str['error'] == 0) {
                    userData.push(str['userData'])
                    data.unshift(str)
                }
            } else {
                // 全部都显示
                if (str['error']) {
                    error += 1
                }
                userData.push(str['userData'])
                data.unshift(str)
            }
            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})
    }

    dianLiuRender = (item, index) => {
        return (
            <View
                key={item.userData}
                style={styles.mainView}
            >
                <View style={{
                    // marginHorizontal: 5,
                }}>
                    <Barcode value={item.barcode} format="CODE128" height={35} width={1.1}/>
                    <Text style={styles.textColor}>{item.barcode}</Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={styles.textLeft50}>单位类别 <Text style={styles.textRed}>{item.orgType}</Text></Text>
                    <Text style={styles.textLeft50}>产品名称 <Text style={styles.textRed}>电流电压组合互感器</Text></Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={styles.textLeft50}>产品型号 <Text style={styles.textRed}>{item.model}</Text></Text>
                    <Text style={styles.textLeft50}>接线方式 <Text style={styles.textRed}>{item.connection}</Text></Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={[styles.textColor, {borderRightWidth: 0.5,textAlign: 'left',  width: '30%'}]}>绕组配置 <Text
                        style={styles.textRed}>{item.windingCount}</Text></Text>
                    <Text style={[styles.textColor, {borderRightWidth: 0.5,textAlign: 'left',  width: '46%'}]}>互感器原理 <Text
                        style={styles.textRed}>{item.transformer}</Text></Text>
                    <Text style={[styles.textColor, {textAlign: 'left', width: '24%'}]}>绝缘方式 <Text
                        style={styles.textRed}>{item.insulation}</Text></Text>
                    {/*<Text style={{borderRightColor}}>绝缘方式 <Text style={styles.textRed}>{item.insulation}</Text></Text>*/}
                </View>
                <View style={styles.betweenView}>
                    <Text style={[styles.textColor, {borderRightWidth: 0.5,textAlign: 'left',  width: '30%'}]}>额定电压 <Text
                        style={styles.textRed}>{item.ratedVoltage}</Text></Text>
                    <Text style={[styles.textColor, {borderRightWidth: 0.5,textAlign: 'left',  width: '46%'}]}>额定频率(Hz),安装场所 <Text
                        style={styles.textRed}>{item.ratedFrequencyAndPlace}</Text></Text>
                    <Text style={[styles.textColor, {textAlign: 'left', width: '24%'}]}>功率因数 <Text
                        style={styles.textRed}>{item.powerFactor}</Text></Text>
                </View>
                <View style={[styles.betweenView, {paddingHorizontal:0}]}>
                    <Text style={styles.textColor1}>额定电流变比(A)</Text>
                    <Text style={styles.textColor2}>TA额定二次负荷(VA)</Text>
                    <Text style={styles.textColor3}>TA轻载负荷(VA)</Text>
                    <Text style={styles.textColor4}>TA精度</Text>
                </View>
                <View style={[styles.betweenView, {paddingHorizontal:0}]}>
                    <Text style={styles.textColor1}>电流变比1 <Text
                        style={styles.textRed}>{item.ratedCurrent1}</Text></Text>
                    <Text style={{borderRightWidth: 0.5, width: '31%'}}/>
                    <Text style={{borderRightWidth: 0.5, width: '26%'}}/>
                    <Text style={{width: '16%'}}/>
                </View>
                <View style={[styles.betweenView, {borderTopWidth: 0, paddingHorizontal:0}]}>
                    <Text style={[styles.textColor1, {
                        borderTopWidth: 0.5,
                    }]}>电流变比2 <Text style={styles.textRed}>{item.ratedCurrent2}</Text></Text>
                    <Text style={styles.textColor2}><Text
                        style={styles.textRed}>{item.ratedSecondLoadTA}</Text></Text>
                    <Text style={styles.textColor3}><Text
                        style={styles.textRed}>{item.overlightLoadTA}</Text></Text>
                    <Text style={styles.textColor4}><Text
                        style={styles.textRed}>{item.precisionTA}</Text></Text>
                </View>
                <View style={[styles.betweenView, {borderTopWidth: 0, paddingHorizontal:0}]}>
                    <Text style={[styles.textColor1, {
                        borderTopWidth: 0.5,
                    }]}>电流变比3 <Text style={styles.textRed}>{item.ratedCurrent3}</Text></Text>
                    <Text style={{borderRightWidth: 0.5, width: '31%'}}/>
                    <Text style={{borderRightWidth: 0.5, width: '26%'}}/>
                    <Text style={{width: '16%'}}/>
                </View>
                <View style={[styles.betweenView, {paddingHorizontal:0}]}>
                    <Text style={styles.textColor1}>电压比</Text>
                    <Text style={styles.textColor2}>TV额定二次负荷(VA)</Text>
                    <Text style={styles.textColor3}>TV轻载负荷(VA)</Text>
                    <Text style={styles.textColor4}>TV精度</Text>
                </View>
                <View style={[styles.betweenView, {paddingHorizontal:0}]}>
                    <Text style={styles.textColor1}><Text style={styles.textRed}>{item.voltageChangeRate}</Text></Text>
                    <Text style={styles.textColor2}><Text
                        style={styles.textRed}>{item.ratedSecondLoadTV}</Text></Text>
                    <Text style={styles.textColor3}><Text
                        style={styles.textRed}>{item.overlightLoadTV}</Text></Text>
                    <Text style={styles.textColor4}><Text
                        style={styles.textRed}>{item.precisionTV}</Text></Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={[styles.textColor, {
                        borderRightWidth: 0.5,
                        textAlign: 'left',
                        width: '70%'
                    }]}>新旧标志,电能设备计量产权 <Text style={styles.textRed}>{item.flagAndRight}</Text></Text>

                    <Text style={[styles.textColor, {textAlign: 'left', width: '30%'}]}> 加密方式 <Text
                        style={styles.textRed}>{item.encodeType}</Text></Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={[styles.textColor, {
                        borderRightWidth: 0.5,
                        textAlign: 'left',
                        width: '70%'
                    }]}>仪表保安系数,额定一次电流扩大倍数 <Text style={styles.textRed}>{item.securityAndExpansionFactor}</Text></Text>

                    <Text style={[styles.textColor, {textAlign: 'left', width: '30%'}]}> 出厂日期 <Text
                        style={styles.textRed}>{item.releaseDate}</Text></Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={[styles.textColor,]}>资产属性，资产归属  <Text style={styles.textRed}>{item.assetProperty}</Text></Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={[styles.textColor,]}>生产厂家  <Text style={styles.textRed}>{item.manufacturer}</Text></Text>
                </View>
                <View style={styles.betweenView}>
                    <Text style={[styles.textColor,]}>资产归属地  <Text style={styles.textRed}>{item.assetAttribution}</Text></Text>
                </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 {
                                return this.dianLiuRender(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,
        backgroundColor: '#fff'
    },
    button: {
        borderRadius: 5,
        marginHorizontal: 10,
        marginBottom: 2,
        marginTop: 5,
        borderWidth: 0,
        backgroundColor: "#2b90ea"
    },
    textLeft50: {
        color: '#333',
        fontSize: 11,
        width: '50%',
        textAlign: 'left',
    },
    textColor: {
        color: '#333',
        fontSize: 11,
        textAlign: 'center',
    },
    textColor1: {
        color: '#333',
        fontSize: 11,
        textAlign: 'center',
        borderRightWidth: 0.5,
        width: '27%'
    },
    textColor2: {
        color: '#333',
        fontSize: 11,
        textAlign: 'center',
        borderRightWidth: 0.5,
        width: '31%'
    },
    textColor3: {
        color: '#333',
        fontSize: 11,
        textAlign: 'center',
        borderRightWidth: 0.5,
        width: '26%'
    },
    textColor4: {
        color: '#333',
        fontSize: 11,
        textAlign: 'center',
        width: '16%'
    },
    textRed: {
        color: 'red',
    },
    mainView: {
        margin: 5,
        borderWidth: 0.5,
        borderColor: '#7b7b7b',
    },
    betweenView: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        borderTopWidth: 0.5,
        borderTopColor: '#7b7b7b',
        paddingHorizontal: 5,
    },
    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 DesktopHome;
