import React, {Component} from 'react';
import {
    View,
    Text,
    StyleSheet,
    ScrollView,
    Dimensions, DeviceEventEmitter,
} from 'react-native';
import {Tabs, Provider, Button, Modal, Toast, List, Picker} from '@ant-design/react-native';
import {createAction} from '../../utils';
import {connect} from 'react-redux';
import CallPhone from '../../components/CallPhone';
import ComponentsStyles from '../../components/ComponentsStyles';
import RefreshFlatList from 'react-native-refresh-flatlist';
import SyncStorage from 'sync-storage';

const tabs = [
    {title: '基本信息', id: 1},
    {title: '跟踪记录', id: 2},
];
const {width} = Dimensions.get('window');

@connect(customer => ({...customer}))
class ReviewDetail extends Component {
    //  潜客跟踪
    constructor(props) {
        super(props);
        this.state = {
            getParm: {
                page: 1,
                rows: 10,
                customer: this.props.navigation.state.params.id,
            },
            moreModelVisible: false,
            dispatchVisible: false,

            USERS: [],
            new_user: '',
        };

    };

    componentDidMount() {
        this._fetchReviewReoprt();
        this._fetchData();
        this.refeshReport = DeviceEventEmitter.addListener('refeshReport', (param) => {
            this._fetchReviewReoprt(1);
        });
        this.refeshCustomerDetail = DeviceEventEmitter.addListener('refeshCustomerDetail', (param) => {
            this._fetchData(1);
        });
    }

    componentWillUnmount() {
        this.refeshReport.remove();
        this.refeshCustomerDetail.remove();
    }

    _fetchData = () => {
        this.props.dispatch({
            type: 'customer/fetchCustomerDetail',
            payload: {id: this.state.getParm.customer},
        });
    };
    _fetchMore = () => {
        const {page, totalRecord} = this.props.customer;
        if (page * this.state.getParm.rows >= totalRecord) {
            return;
        }
        const currentPage = page + 1;
        this._fetchReviewReoprt(currentPage);
    };

    _keyExtractor = (item, index) => {
        return index.toString();
    };

    _fetchReviewReoprt = (page) => {
        if (page) {
            this.state.getParm.page = page;
        }
        this.props.dispatch(createAction('customer/fetchReviewRecord')(this.state.getParm));
    };

    baseInfo = (reviewDetailData) => {
        return <View style={{marginTop: 5}}>
            <List style={styles.listStyle}>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.name}</Text>} arrow="empty">
                    <Text style={ComponentsStyles.font15}>姓名</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.gender_text}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>性别</Text>
                </List.Item>
                <View style={styles.telItemView}>
                    <Text style={ComponentsStyles.font15}>电话</Text>
                    <View style={styles.telView}>
                        <Text style={ComponentsStyles.icon}>{'\ue61a'}</Text>
                        <Text
                            style={styles.telText}
                            onPress={() => CallPhone(reviewDetailData.tel, 1)}>
                            {reviewDetailData.tel}
                        </Text>
                    </View>
                </View>

                <List.Item extra={<Text style={ComponentsStyles.IDText}>{reviewDetailData.address}</Text>}
                           wrap
                           multipleLine arrow="empty">
                    <Text style={ComponentsStyles.font15}>地址</Text>
                </List.Item>

                <List.Item extra={<Text style={ComponentsStyles.IDText}>{reviewDetailData.village}</Text>}
                           wrap
                           multipleLine arrow="empty">
                    <Text style={ComponentsStyles.font15}>小区</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.source_text}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>来源</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.project_text}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>项目</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.stage_progress_text}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>阶段进度</Text>
                </List.Item>

                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.status_text}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>状态</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.track_user_text}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>跟踪人员</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.store_text}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>门店</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.next_time_f}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>下次跟踪</Text>
                </List.Item>

                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.enter_count}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>进店次数</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.last_enter_time}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>最后进店时间</Text>
                </List.Item>

                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.create_time_f}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>建档时间</Text>
                </List.Item>

                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.create_user_text}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>建档人</Text>
                </List.Item>
                <List.Item extra={<Text style={ComponentsStyles.font15}>{reviewDetailData.notes}</Text>}
                           arrow="empty">
                    <Text style={ComponentsStyles.font15}>备注</Text>
                </List.Item>
            </List>
        </View>;
    };

    renderItem = (data) => {
        const item = data.item;
        return <View style={styles.reportMain}>
            <View style={styles.row5}>
                <View style={ComponentsStyles.itemView}>
                    <Text style={ComponentsStyles.icon}>{'\ue619'} </Text>
                    <Text style={ComponentsStyles.font15}>{item.create_user_text}</Text>
                </View>
            </View>
            <View style={styles.row5}>
                <Text style={ComponentsStyles.icon}>{'\ue6ed'} </Text>
                <Text style={ComponentsStyles.font15}>{item.description}</Text>
            </View>
            <View style={styles.row5}>
                <Text style={ComponentsStyles.icon}>{'\ue6cc'} </Text>
                <Text style={{fontSize: 15}}>{item.create_time_f}</Text>
            </View>

            <View style={styles.row5}>
                <Text style={styles.red5}>支援或放弃：</Text>
                <Text style={ComponentsStyles.font15}>{item.instruction}</Text>
            </View>

            <View style={styles.row5}>
                <Text style={styles.red5}>审核：</Text>
                <Text style={ComponentsStyles.font15}>{item.check_status_text}--{item.check_comment}</Text>
            </View>
        </View>;
    };

    addProject = (ids, name) => {
        this.props.dispatch({
            type: 'customer/addCustomerProject',
            payload: {projects: ids, id: this.state.getParm.customer},
            callback: () => {
                Toast.info('添加成功！', 1, () => {
                    DeviceEventEmitter.emit('backRefesh');
                    this.props.navigation.goBack();
                });

            },
        });
    };

    getUsers = () => {
        this.setState({moreModelVisible: false, dispatchVisible: true});
        this.props.dispatch({
            type: 'customer/getUser',
            callback: (data) => {
                let USERS = [];
                data.map((item, index) => {
                    USERS.push({
                        value: item.value, label: item.lable,
                    });
                });
                this.setState({USERS});
            },
        });
    };

    againDispatch = (id) => {
        if (!this.state.new_user) {
            Toast.info('请选择人员', 1);
            return;
        }

        this.props.dispatch({
            type: 'customer/againDispatchUser',
            payload: {id: id, user: this.state.new_user},
            callback: () => {
                DeviceEventEmitter.emit('backRefesh');
                this.props.navigation.goBack();
            },
        });
    };

    render() {
        const {reviewRecordData, reviewRecordRState, customerDetail} = this.props.customer;
        const dispatchButtons = [
            {text: '取消', onPress: () => this.setState({dispatchVisible: false})},
            {text: '保存', onPress: () => this.againDispatch(customerDetail.id)},
        ];
        const premissions = SyncStorage.get('premissions');
        return (
            <Provider>
                <Tabs
                    tabs={tabs}
                    initialPage={0}
                    tabBarPosition="top"
                    styles={{
                        topTabBarSplitLine: {
                            borderBottomWidth: 0,
                        },
                    }}
                    tabBarUnderlineStyle={{
                        backgroundColor: '#03C762',
                        width: 40,
                        marginLeft: (width / 2 - 38) / 2,
                        height: 3,
                        borderRadius: 2,
                    }}
                    tabBarActiveTextColor="#000"
                >
                    {/*基本信息*/}
                    <ScrollView>
                        {this.baseInfo(customerDetail)}
                    </ScrollView>
                    {/*    跟踪记录*/}
                    <View>
                        <RefreshFlatList
                            data={reviewRecordData}
                            renderItem={(item) => this.renderItem(item)}
                            keyExtractor={this._keyExtractor}
                            themeColor="#5eafe4"
                            refreshState={reviewRecordRState}
                            footerRefreshingText="正在加载"
                            footerFailureText="加载失败"
                            onHeaderRefresh={() => this._fetchReviewReoprt(1)}
                            onFooterRefresh={() => this._fetchMore()}
                            ListHeaderComponent={() => <View style={{height: 0}}/>}
                            ItemSeparatorComponent={() => <View style={{height: 0}}/>}
                        />
                    </View>
                </Tabs>
                <View style={{flexDirection: 'row', justifyContent: 'center', backgroundColor: '#fff'}}>
                    <Button
                        type="primary"
                        onPress={() => this.props.navigation.navigate('WriteTrackReport',
                            {
                                item: customerDetail,
                            })}
                        style={{width: 200, margin: 5}}
                    >
                        <Text
                            style={{color: '#fff'}}>填写跟踪报告</Text></Button>
                    <Button
                        type="warning"
                        onPress={() => this.setState({moreModelVisible: true})}
                        style={{width: 100, margin: 5}}
                    >
                        <Text
                            style={{color: '#fff'}}>更多</Text></Button>
                </View>
                <Modal
                    popup
                    closable
                    maskClosable
                    animationType="slide-up"
                    visible={this.state.moreModelVisible}
                    onClose={() => this.setState({moreModelVisible: false})}
                >
                    <View style={{padding: 10}}>
                        <List>
                            {premissions.indexOf('customer.inner_review') > -1 &&
                            <List.Item>
                                <Text style={styles.modalText}
                                      onPress={() => {
                                          this.props.navigation.navigate('WriteInternalReport',
                                              {
                                                  item: customerDetail,
                                              });
                                          this.setState({moreModelVisible: false});
                                      }
                                      }
                                >内部跟踪</Text>
                            </List.Item>
                            }

                            <List.Item>
                                <Text
                                    style={styles.modalText}
                                    onPress={() => {
                                        this.props.navigation.navigate('EditCustomer',
                                            {
                                                item: customerDetail,
                                            });
                                        this.setState({moreModelVisible: false});
                                    }
                                    }
                                >修改信息</Text>
                            </List.Item>

                            <List.Item>
                                <Text
                                    style={styles.modalText}
                                    onPress={() => {
                                        this.props.navigation.navigate('SearchProject', {
                                            callback: this.addProject,
                                            disabled_ids: customerDetail.project,
                                        });
                                        this.setState({moreModelVisible: false});
                                    }
                                    }
                                >添加项目</Text>
                            </List.Item>
                            {premissions.indexOf('customer.again_dispatch') > -1 &&
                            <List.Item>
                                <Text
                                    style={styles.modalText}
                                    onPress={() => this.getUsers()
                                    }
                                >重新分配</Text>
                            </List.Item>
                            }
                            <List.Item>
                                <Text
                                    style={styles.modalText}
                                    onPress={() => {
                                        this.props.navigation.navigate('UpdateProcess', {
                                            customer: customerDetail.id,
                                        });
                                        this.setState({moreModelVisible: false});
                                    }
                                    }
                                >更新进度</Text>
                            </List.Item>
                            <List.Item onPress={() => this.setState({moreModelVisible: false})}>
                                <Text style={styles.modalText}>取消</Text>
                            </List.Item>
                        </List>
                    </View>
                </Modal>
                <Modal
                    transparent
                    maskClosable
                    visible={this.state.dispatchVisible}
                    footer={dispatchButtons}
                >
                    <Picker
                        data={this.state.USERS}
                        cols={1}
                        value={this.state.new_user}
                        onChange={(val) => this.setState({new_user: val})}
                    >
                        <List.Item arrow="horizontal">
                            选择人员
                        </List.Item>
                    </Picker>
                </Modal>
            </Provider>
        );
    }
}

const styles = StyleSheet.create({
    modalText: {
        color: '#333',
        fontSize: 16,
        textAlign: 'center',
        textAlignVertical: 'center',
    },
    textInput: {
        width: '80%',
        textAlign: 'left',
        paddingHorizontal: 10,
    },
    modalContainer: {
        flexDirection: 'row',
        paddingHorizontal: 10,
        paddingLeft: 13,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    textStyle: {
        fontSize: 16,
        paddingVertical: 10,
    },
    telItemView: {
        flex: 1,
        flexDirection: 'row',
        marginLeft: 15,
        paddingRight: 18,
        paddingVertical: 8,
        borderBottomWidth: 0.5,
        borderBottomColor: '#eaeaea',
    },
    telName: {
        color: '#333',
        fontSize: 18,
    },
    telView: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
    },
    telText: {
        color: '#2b90ea',
        fontSize: 15,
    },
    listStyle: {
        borderBottomWidth: 10,
        borderBottomColor: '#f6f7f8',
    },
    reportMain: {
        marginTop: 5,
        // marginBottom: 5,
        backgroundColor: '#fff',
        paddingHorizontal: 10,
        // borderWidth:1,
    },
    customerText: {
        color: '#333',
        fontSize: 16,
    },
    row5: {
        flexDirection: 'row',
        paddingVertical: 5,
    },
    red5: {
        fontSize: 15,
        color: 'red',
        padding: 2,
    },
});

export default ReviewDetail;
