/**
*  选择项
*/

import React, { useMemo, useState } from 'react';
import { Text, TextInput, TextStyle, TouchableOpacity, View, ViewStyle } from 'react-native';
import Picker from 'react-native-picker';
import { FormProps } from '../../kit';
import request from '../../util/request';
import Icon from '../icon';



interface Props extends FormProps {

    /**
    *  类型 area:省市区  address: 省市区和详细地址 street：只需要填写详细地址
    */
    type?: 'address' | 'area' | 'street'

    /**
    *  样式
    */
    style?: ViewStyle,

    /**
    *  左侧文字
    */
    labelText: string,
    /**
    *  左侧文字样式
    */
    labelTextStyle?: TextStyle,

	/**
	*  显示文本的样式
	*/
    valueStyle?: TextStyle;

	/**
	*  省市区 数据 
	*/
    areaValue?: string[];

    /**
    *  街道地址 数据
    */
    streetValue?: string

    /**
    *  选择事件
    */
    onSelect?: (value: { area?: string[], street?: string }) => void;
}

let areaDatasource: any

export default function AddressSelectItem(props: Readonly<Props>) {
    let { type = 'address' } = props

    const [area, setArea] = useState(props.areaValue)
    const [street, setStreet] = useState(props.streetValue)
    const [empty, setEmpty] = useState(false)
    const [datasource, setDatasource] = useState([])


    useMemo(() => {
        setArea(props.areaValue)
        setEmpty(false)
    }, [props.areaValue])

    useMemo(() => {
        setStreet(props.streetValue)
        setEmpty(false)
    }, [props.streetValue])

    useMemo(() => {
        if (areaDatasource) {
            setDatasource(areaDatasource)
        } else {
            request.get('http://resource.bm001.com/js/queryContry').then((res: any) => {
                areaDatasource = res.dataList.map((p: any) => {
                    let cities = p.children.map((city: any) => {
                        let areas = city.children.map((area: any) => {
                            return area.name
                        })
                        let cityData: any = {}
                        cityData[city.name] = areas
                        return cityData
                    })

                    let pri: any = {}
                    pri[p.name] = cities
                    return pri
                })
                console.log('数据源', areaDatasource)
                setDatasource(areaDatasource)
            })
        }
    }, [props.labelText])

    props.getFormRef && props.getFormRef((action) => {
        switch (action) {
            case 'data':
                return (area || street) ? { area, street } : undefined;

            case 'enpty':
                setEmpty(true)
                break;
        }
    })


    // 点击事件 
    let selectClick = () => {

        // 如果有数据源 弹出pick选择器
        Picker.init({
            pickerTitleText: props.labelText || '选择',
            pickerCancelBtnText: '取消',
            pickerConfirmBtnText: '确认',
            pickerData: datasource,
            selectedValue: area,
            pickerConfirmBtnColor: [90, 169, 250, 1],
            pickerCancelBtnColor: [153, 153, 153, 1],
            pickerTitleColor: [51, 51, 51, 1],
            pickerToolBarBg: [255, 255, 255, 1],
            pickerBg: [255, 255, 255, 1],
            onPickerConfirm: data => {
                props.onSelect && props.onSelect({ area: data, street });
                setArea(data)
                setEmpty(false)
            },
            onPickerCancel: data => { },
            onPickerSelect: data => { }
        });
        Picker.show();
    }

    let streetChange = (text: string) => {
        props.onSelect && props.onSelect({ area, street: text });
        setStreet(text)
        setEmpty(false)
    }

    return (
        <View>
            {
                (type == 'area' || type == 'address') && (
                    <TouchableOpacity style={{ height: 55, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 15, ...props.style }} activeOpacity={1} onPress={selectClick}>
                        <View style={{ width: 80, overflow: 'hidden', flexDirection: 'row', alignItems: 'center' }}>
                            {
                                props.labelText && <Text style={{ color: 'rgba(0,0,0,0.6)', fontSize: 16, ...props.labelTextStyle }}>{props.labelText} <Text style={{ color: '#D5544F' }}>{props.require ? ' *' : ''}</Text></Text>
                            }
                        </View>
                        <Text style={{ flex: 1, textAlign: 'right', fontSize: 16, marginRight: 10, color: empty ? '#D5544F' : (area ? '#000' : 'rgba(0,0,0,0.3)'), ...props.valueStyle }} >{area ? area.join(' ') : '请选择省市区'}</Text>

                        <Icon iconCode={0xe649} style={{ fontSize: 10, color: 'rgba(0,0,0,0.3)' }} />
                    </TouchableOpacity >
                )
            }

            {
                (type == 'address' || type == 'street') && (
                    <View style={{ height: type == 'street' ? 55 : 42, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 15 }}>

                        {
                            type == 'street' && (
                                <View style={{ width: 80, overflow: 'hidden', flexDirection: 'row', alignItems: 'center' }}>
                                    {
                                        props.labelText && <Text style={{ color: 'rgba(0,0,0,0.6)', fontSize: 16, ...props.labelTextStyle }}>{props.labelText} <Text style={{ color: '#D5544F' }}>{props.require ? ' *' : ''}</Text></Text>
                                    }
                                </View>
                            )
                        }
                        <TextInput
                            autoCapitalize='none'
                            style={{ fontSize: 16, marginLeft: 15, color: '#000', textAlign: 'right', textAlignVertical: 'center', padding: 0, flex: 1, ...props.valueStyle }}
                            underlineColorAndroid="transparent"
                            value={street}
                            placeholder={'请输入详细地址'}
                            placeholderTextColor={empty ? '#D5544F' : '#aaa'}
                            autoCorrect={false}
                            clearButtonMode='while-editing'
                            disableFullscreenUI={true}
                            onChangeText={streetChange}
                        />
                    </View >
                )
            }

        </View>
    )

}
