/**
 * 设置页面
 * @邠心vbe on 2022/12/9
 */
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import apiUser from '../api/apiUser';
import Button from '../components/Button';
import Dropdown from '../components/Dropdown';
import Switch from '../components/Switch';
import { i18nUtil } from '../i18n';
import routeUtil from '../utils/routeUtil';
import storage, { getStorage, setStorage } from '../utils/storage';
import app from '../../app.json';

export const SETTINGS_KEY = 'CHARGE_SETTINGS_V2'
export const SettingUtil = {
  getSettings: (back) => {
    if (!global.settingsInfo) {
      storage.getStorage(SETTINGS_KEY).then(sto => {
        if (sto) {
          const res = JSON.parse(sto);
          global.settingsInfo = res;
          back(global.settingsInfo)
        } else {
          back({
            alwaysLocation: true,
            moveMyLocation: true,
            refreshInterval: 10
          })
        }
      })
    } else {
      back(global.settingsInfo)
    }
  }
}

export default class Settings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      settings: {
        alwaysLocation: true,
        moveMyLocation: true,
        refreshInterval: undefined
      },
      userInfo: {
        notifyLowBalance: false,
        notifyChargingComplete: false,
        notifyPromotionsOffers: false
      },
      localeList: [],
      currentLocale: "",
      intervalList: [10, 15, 20, 30, 60, 90, 120],
      //switchStyle: isIOS ? { false: "#B2B2B2", true: colorAccent } : null,
    };
    this.changed = false;
    //global.colorAccent = "#00A9FF"
    //global.colorPrimary = "#00A9FF"
  }

  componentDidMount() {
    this.props.navigation.addListener('blur', () => {
      //console.log("保存设置");
      this.saveSettings();
    });
    this.props.navigation.addListener('focus', () => {
      getUserInfo(info => {
        this.setState({
          userInfo: info
        });
      }, true);
    });
    this.getLocaleValues();
    SettingUtil.getSettings(res => {
      const info = this.state.settings;
      for (let item in info) {
        if (res[item] !== undefined) {
          info[item] = res[item]
        }
      }
      this.setState({
        settings: info
      })
    })
  }

  getLocaleValues() {
    const locales = [{
      name: $t("default"),
      value: ""//i18nUtil.getDefaultLocale()
    }];
    for (let item of i18nUtil.locales) {
      if (item.enable) {
        locales.push({
          name: item.name,
          value: item.value
        })
      }
    }
    this.setState({
      localeList: locales
    });
    getStorage(i18nUtil.SETTING_KEY).then(res => {
      if (res) {
        this.setState({
          currentLocale: res
        })
      }
    })
    console.log("getLocaleValues", locales);
  }

  changeSwitch(key, value) {
    this.state.settings[key] = value
    //console.log('changeSwitch', item);
    this.setState({
      settings: this.state.settings
    })
  }

  changeNotifySwitch(key, value) {
    userInfo[key] = value;
    this.setState({
      userInfo: userInfo
    });
    this.changed = true;
  }

  changeSettings(key, value) {
    this.state.settings[key] = value
    this.setState({
      settings: this.state.settings
    })
    console.log("设置数据", this.state.settings);
  }

  saveSettings() {
    global.settingsInfo = this.state.settings
    storage.setStorageJson(SETTINGS_KEY, this.state.settings)
    if (this.changed) {
      apiUser.setNotifySwitch(this.state.userInfo);
    }
  }

  changeLocale(locale) {
    if (locale !== this.state.currentLocale) {
      /*this.setState({
        currentLocale: locale
      })*/
      if (locale == "") {
        i18nUtil.setlocale(i18nUtil.getDefaultLocale());
      } else {
        i18nUtil.setlocale(locale);
      }
      setStorage(i18nUtil.SETTING_KEY, locale);
      routeUtil.resetToHome(this.props);
    }
  }

  render() {
    return (
      <View style={ui.flex1}>
        { app.modules.i18n &&
          <View style={styles.menuView}>
            <Text style={styles.buttonText}>{$t('settings.language')}</Text>
            <Dropdown
              list={this.state.localeList}
              //title={$t('settings.language')}
              nameKey="name"
              valueKey="value"
              value={this.state.currentLocale}
              onChange={l => this.changeLocale(l)}
              style={styles.localeSelect}
              showIcon={false}
              textStyle={styles.settingText}
            />
          </View>
        }
        <Text style={styles.title}>{$t('settings.notification')}</Text>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => this.changeNotifySwitch("notifyChargingComplete", !userInfo.notifyChargingComplete)}>
          <Text style={styles.buttonText}>{$t('settings.notifyChargingComplete')}</Text>
          <Switch
            value={this.state.userInfo.notifyChargingComplete}
            onValueChange={v => this.changeNotifySwitch("notifyChargingComplete", v)}/>
        </Button>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => this.changeNotifySwitch("notifyLowBalance", !userInfo.notifyLowBalance)}>
          <Text style={styles.buttonText}>{$t('settings.notifyLowBalance')}</Text>
          <Switch 
            value={this.state.userInfo.notifyLowBalance}
            onValueChange={v => this.changeNotifySwitch("notifyLowBalance", v)}/>
        </Button>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => this.changeNotifySwitch("notifyPromotionsOffers", !userInfo.notifyPromotionsOffers)}>
          <Text style={styles.buttonText}>{$t('settings.notifyPromotionsOffers')}</Text>
          <Switch
            value={this.state.userInfo.notifyPromotionsOffers}
            onValueChange={v => this.changeNotifySwitch("notifyPromotionsOffers", v)}/>
        </Button>
        <Text style={styles.title}>{$t('settings.maps')}</Text>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => this.changeSwitch('alwaysLocation', !this.state.settings.alwaysLocation)}>
          <Text style={styles.buttonText}>{$t('settings.showMyLocations')}</Text>
          <Switch
            value={this.state.settings.alwaysLocation}
            onValueChange={v => this.changeSwitch('alwaysLocation', v)}/>
        </Button>
        <View style={styles.menuView}>
          <Text style={styles.buttonText}>{$t('settings.refreshInterval')}</Text>
          <Dropdown
            style={styles.localeSelect}
            list={this.state.intervalList}
            title={$t('settings.refreshInterval')}
            suffixList={$t('settings.seconds')}
            suffixText={$t('settings.seconds')}
            showIcon={false}
            autoSelect={false}
            value={this.state.settings.refreshInterval}
            textStyle={styles.settingText}
            onChange={v => this.changeSettings("refreshInterval", v)}
          />
        </View>
        <Button
          style={styles.itemButton}
          viewStyle={styles.itemView}
          onClick={() => this.changeSwitch('moveMyLocation', !this.state.settings.moveMyLocation)}>
          <Text style={styles.buttonText}>{$t('settings.moveMyLocations')}</Text>
          <Switch
            value={this.state.settings.moveMyLocation}
            onValueChange={v => this.changeSwitch('moveMyLocation', v)}/>
        </Button>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  title: {
    color: '#888',
    fontSize: 10,
    marginTop: 1,
    ...$padding(8, 16, 4),
    backgroundColor: colorLight
  },
  itemButton: {
    borderRadius: 0,
    backgroundColor: colorLight
  },
  itemView: {
    flex: 1,
    height: 56,
    paddingLeft: 16,
    paddingRight: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  menuView: {
    height: 56,
    paddingLeft: 16,
    paddingRight: 16,
    overflow: 'hidden',
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: colorLight
  },
  buttonText: {
    flex: 1,
    color: textPrimary,
    fontSize: 16
  },
  settingText: {
    color: '#888',
    fontSize: 14,
    textAlign: 'right'
  },
  localeSelect: {
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    paddingLeft: 16,
    paddingRight: 16,
    position: "absolute",
    alignItems: "center",
    flexDirection: "row",
    justifyContent: 'flex-end'
  }
})