/**
 * 车辆列表V2
 * @邠心vbe on 2024/01/30
 */
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet, Pressable, FlatList, RefreshControl } from 'react-native';
import apiUser from '../../api/apiUser';
import Button, { ElevationObject } from '../../components/Button';
import Dialog from '../../components/Dialog';
import TextView from '../../components/TextView';
import { PageList } from '../Router';
import { MyRefreshProps } from '../../components/ThemesConfig';
import utils from '../../utils/utils';

export default class VehicleListV2 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      vehicleList: [],
      refreshing: false
    };
  }

  componentDidMount() {
    //this.getVehicleList();
    this.props.navigation.addListener('focus', () => {
      this.getVehicleList();
    })
  }

  onRefresh() {
    this.setState({
      refreshing: true
    })
    this.getVehicleList();
  }

  getVehicleList() {
    apiUser.getVehicles().then(res => {
      if (res.data) {
        this.setState({
          vehicleList: res.data,
          refreshing: false
        });
        if (this.props.onResult) {
          this.props.onResult(res.data.length)
        }
      }
    }).catch(err => {
      this.setState({
        vehicleList: [],
        refreshing: false
      });
      if (this.props.onResult) {
        this.props.onResult(0)
      }
    });
  }

  removeVehicle(id) {
    Dialog.showDialog({
      title: $t('profile.removeVehicle'),
      message: $t('profile.tipRemoveVehicle'),
      callback: btn => {
        if (btn == 'ok') {
          Dialog.dismissLoading();
          this.deleteVehicle(id);
        }
      }
    })
  }

  deleteVehicle(id) {
    Dialog.showProgressDialog();
    apiUser.deleteVehicle({
      vehiclePk: id
    }).then(res => {
      Dialog.dismissLoading();
      toastShort($t('common.deleteSuccess'));
      this.getVehicleList();
    }).catch(err => {
      Dialog.dismissLoading();
      toastShort(err);
    });
  }

  showTypeCapacity(item) {
    let str = "";
    if (item.connectorType) {
      str += item.connectorType;
    }
    if (item.batteryCapacity) {
      if (str) {
        str += ", ";
      }
      str += item.batteryCapacity + "KWH";
    }
    return str;
  }

  listItem = ({item, index, separators}) => {
    return (
      <Pressable
        style={styles.vehicleView}
        android_ripple={ripple}
        onPress={() => {
          startPage(PageList.editVehicleV2, {id: item.vehiclePk});
        }}
        onLongPress={() => {
          this.removeVehicle(item.vehiclePk)
        }}>
        <View style={styles.vehicleRow}>
          <TextView style={styles.vehicleName}>{item.brand} {item.model}</TextView>
        </View>
        <TextView style={styles.vehicleModle}>{item.licensePlate}</TextView>
        <View style={styles.vehicleRow}>
          <TextView style={styles.vehicleType}>{this.showTypeCapacity(item)}</TextView>
          {/* <View style={styles.vehicleTypeRow}>
            <View style={styles.vehicleTypeIcon}>
              <VehicleType size={10}/>
            </View>
            
          </View> */}
        </View>
        {/* <Pressable
          style={styles.closeIcon}
          android_ripple={rippleLess}
          onPress={() => this.removeVehicle(item.vehiclePk)}>
          <MaterialCommunityIcons
            name="close"
            size={20}
            color={textCancel}
          />
        </Pressable> */}
        { utils.isNotEmpty(item.vehiclePhoto) &&
          <Image
            resizeMode="contain"
            style={styles.vehicleViewBg}
            source={{uri: utils.getImageUrl(item.vehiclePhoto)}}/>
        }
      </Pressable>
    )
  }

  listHeader = () => {
    return (
      <View style={$padding(8, 16)}>
        <TextView style={styles.titleText}>{$t('profile.titleVehicles')}</TextView>
        <Button
          style={styles.addButton}
          onClick={() => startPage(PageList.addVehicleV2)}>
          <MaterialIcons
            name="add-circle"
            size={18}
            color={colorPrimary}
          />
          <TextView style={styles.addBtnText}>{$t('profile.btnAdd')}</TextView>
        </Button>
      </View>
    )
  }

  render() {
    return (
      <FlatList
        style={ui.flex1}
        data={this.state.vehicleList}
        contentContainerStyle={$padding(8, 0)}
        renderItem={this.listItem}
        keyExtractor={item => item?.vehiclePk}
        //onEndReached={() => this.getVehicleListPage()}
        refreshControl={
          <RefreshControl
            {...MyRefreshProps()}
            refreshing={this.state.refreshing}
            onRefresh={() => this.onRefresh()}
          />
        }
        ListHeaderComponent={this.listHeader}
        ListEmptyComponent={<Text style={ui.noData}>{$t('profile.noVehicles')}</Text>}
      />
    );
  }
}

const styles = StyleSheet.create({
  titleText: {
    fontSize: 14,
    color: textPrimary,
    fontWeight: 'bold'
  },
  vehicleView: {
    borderWidth: 1,
    borderRadius: 4,
    borderStyle: 'solid',
    borderColor: '#EAEAEA',
    overflow: 'hidden',
    //...ElevationObject(5),
    ...$margin(8, 16),
    ...$padding(12, 16, 12),
    backgroundColor: colorLight
  },
  vehicleViewBg: {
    top: 16,
    right: 16,
    width: 40,
    height: 40,
    position: 'absolute'
  },
  vehicleRow: {
    alignItems: 'center',
    flexDirection: 'row',
  },
  vehicleIcon: {
    width: 32,
    height: 32,
  },
  vehicleName: {
    color: textDark,
    fontSize: 14,
    fontWeight: 'bold'
  },
  vehicleModle: {
    color: textPrimary,
    fontSize: 14,
    paddingTop: 4,
    paddingBottom: 4
  },
  vehicleTypeRow: {
    height: 20,
    marginLeft: 44,
    borderRadius: 4,
    overflow: 'hidden',
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: '#E5EFDE'
  },
  vehicleTypeIcon: {
    width: 20,
    height: 20,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colorAccent
  },
  vehicleType: {
    color: colorAccent,
    fontSize: 14
  },
  closeIcon: {
    top: 0,
    right: 0,
    padding: 12,
    position: 'absolute'
  },
  addButton: {
    marginTop: 16,
    borderWidth: 1,
    borderRadius: 4,
    borderStyle: 'solid',
    borderColor: colorPrimary,
    backgroundColor: 'transparent'
  },
  addBtnText: {
    fontSize: 15,
    color: colorPrimary,
    fontWeight: 'bold',
    paddingLeft: 8
  }
});