From ff6fbf644d361c37bd3d17954dd4bab1341d7279 Mon Sep 17 00:00:00 2001
From: nguyenthuy <thuynt@dcv.vn>
Date: Wed, 19 May 2021 13:39:13 +0700
Subject: [PATCH] integrate convert unit api

---
 src/RootView.js                                                   |  14 ++++++++++++--
 src/Screens/Tool/CaculatedStopLoss.js                             |   2 +-
 src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLoss.js     |   2 +-
 src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLossView.js |   2 +-
 src/Screens/Tool/ConvertUnit.js                                   | 350 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------------------------------------------------------------------
 src/Screens/Tool/ExchangeRate.js                                  |   2 +-
 src/apis/Functions/Transaction.js                                 |   5 +++++
 src/apis/url.js                                                   |   2 ++
 src/routers/TabNavigation.js                                      |   3 ++-
 9 files changed, 227 insertions(+), 155 deletions(-)

diff --git a/src/RootView.js b/src/RootView.js
index 356242d..0fa5079 100644
--- a/src/RootView.js
+++ b/src/RootView.js
@@ -14,6 +14,11 @@ import DeviceInfo from 'react-native-device-info';
 import R from './assets/R';
 import {WIDTHXD, HEIGHTXD} from './Config/Functions';
 import DropdownManager from './components/DropdownAlert/DropdownManager';
+import AsyncStorage from '@react-native-community/async-storage';
+import KEY from './assets/AsynStorage';
+import I18n, {setLocation} from './helper/i18/i18n';
+import {changeLanguage} from './actions/language';
+
 
 enableScreens();
 
@@ -23,11 +28,16 @@ const RootView = (props) => {
             dropDownAlertRef.current,
             dropDownAlertLongTimeRef.current,
         );
+        setInitLanguage()
     }, []);
 
     const dropDownAlertRef = useRef(null);
     const dropDownAlertLongTimeRef = useRef(null);
-
+    const setInitLanguage = async () => {
+        const laguage = await AsyncStorage.getItem(KEY.LANGUAGE);
+        if (laguage) props.changeLanguage(laguage);
+        setLocation(I18n, laguage);
+    };
     return (
         <>
             <View style={{flex: 1}}>
@@ -85,4 +95,4 @@ const mapStateToProps = (state) => {
     };
 };
 
-export default connect(mapStateToProps, {})(RootView);
+export default connect(mapStateToProps, {changeLanguage})(RootView);
diff --git a/src/Screens/Tool/CaculatedStopLoss.js b/src/Screens/Tool/CaculatedStopLoss.js
index 24cd7d6..87a5e05 100644
--- a/src/Screens/Tool/CaculatedStopLoss.js
+++ b/src/Screens/Tool/CaculatedStopLoss.js
@@ -79,7 +79,7 @@ const CaculatedStopLoss = (props) => {
     if (res.status == 200 && res.data.code == 200) {
       setDataProduct(res.data.data);
     } else {
-      showAlert(TYPE.ERROR, I18n.t('Notification', I18n.t('Can_not_get_data')));
+      showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
     }
   };
 
diff --git a/src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLoss.js b/src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLoss.js
index a0e21af..684977b 100644
--- a/src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLoss.js
+++ b/src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLoss.js
@@ -67,7 +67,7 @@ const CalculatorProfitLoss = (props) => {
       });
       props.hideLoading();
       if (res.status == 200 && res.data.code == 200) {
-        const newList = [res.data.data].concat(dataCalculator);
+        const newList = [res.data.data].concat([...dataCalculator]);
         setDataCalculator(newList);
         setLotTransactionNumber(null);
         setOpenPrice(null);
diff --git a/src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLossView.js b/src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLossView.js
index 6b5f4a7..255dc8a 100644
--- a/src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLossView.js
+++ b/src/Screens/Tool/CalculatorProfitLoss/CalculatorProfitLossView.js
@@ -112,7 +112,7 @@ const CalculatorProfitLossView = (props) => {
         </View>
         <FlatList
           style={{paddingBottom: HEIGHTXD(15), backgroundColor: R.colors.white}}
-          keyExtractor={(item) => item.id}
+          keyExtractor={(item) => item}
           data={props.dataCalculator}
           renderItem={({item, index}) => (
             <ItemCalculator
diff --git a/src/Screens/Tool/ConvertUnit.js b/src/Screens/Tool/ConvertUnit.js
index b0e7d85..31292aa 100644
--- a/src/Screens/Tool/ConvertUnit.js
+++ b/src/Screens/Tool/ConvertUnit.js
@@ -1,165 +1,219 @@
-import React, {Component, useState} from 'react';
-import {
-  View,
-  Text,
-  StyleSheet,
-  TextInput,
-  TouchableOpacity,
-} from 'react-native';
+import React, {useEffect, useState} from 'react';
+import {Platform, StyleSheet, Text, TextInput, View} from 'react-native';
 import HeaderBack from '../../components/Header/HeaderBack';
 
 import PickerItem from '../../components/Picker/PickerItem';
 import I18n from '../../helper/i18/i18n';
 import AppText from '../../components/AppText';
-import TextField from '../../components/Input/TextField';
-import {getFontXD, HEIGHTXD, WIDTHXD} from '../../Config/Functions';
+import {getFontXD, HEIGHTXD, toPriceVnd, WIDTHXD} from '../../Config/Functions';
 import R from '../../assets/R';
-import Icon from 'react-native-vector-icons/FontAwesome';
-
-const dataType = [
-  {
-    value: '0',
-    name: 'KG',
-  },
-  {
-    value: '1',
-    name: 'Pound',
-  },
-];
+import {getUnitList} from '../../apis/Functions/Transaction';
+import {showAlert, TYPE} from '../../components/DropdownAlert';
+import {hideLoading, showLoading} from '../../actions/loadingAction';
+import {connect} from 'react-redux';
+
 
 const ConvertUnit = (props) => {
-  const [typeOne, setTypeOne] = useState();
-  const [typeTwo, setTypeTwo] = useState();
-  const [valueOne, setValueOne] = useState();
-  const [valueTwo, setValueTwo] = useState();
-  const [result, setResult] = useState();
-
-  const onClick = () => {
-    console.log('Heloo', typeOne, typeTwo, valueOne, valueTwo);
-  };
-
-  return (
-    <View style={{flex: 1}}>
-      <HeaderBack title={'ConvertUnit'} />
-      <View style={{flex: 1, paddingTop: 20, paddingHorizontal: 20}}>
-        <AppText style={styles.txtTitle} i18nKey={'Count'} />
-        <View style={styles.Item}>
-          <View style={styles.wrap}>
-            <TextInput
-              onChangeText={(val) => setValueOne(val)}
-              keyboardType={'number-pad'}
-              style={styles.wrapInput}
-              maxLength={12}
-            />
-          </View>
-        </View>
+    const [fromUnitList, setFromUnitList] = useState([]);
+    const [toUnitList, setToUnitList] = useState([]);
+    const [toUnit, setToUnit] = useState();
+    const [fromUnit, setFromUnit] = useState();
+    const [number, setNumber] = useState(null);
+    const [rateItem, setRateItem] = useState({
+        value_one: 0.025000000373,
+        value_two: 0,
+        name: 'Kg,',
+    });
+    const [result, setResult] = useState();
+    useEffect(() => {
+        getDataUnit();
+    }, []);
 
-        <View style={styles.Item}>
-          <View style={styles.wrap}>
-            <PickerItem
-              width={WIDTHXD(400)}
-              data={dataType}
-              onValueChange={(value, items) => {
-                setTypeTwo(items);
-              }}
-            />
-            <TouchableOpacity>
-              <Icon name={'exchange'} size={30} color={R.colors.black} />
-            </TouchableOpacity>
-
-            <PickerItem
-              width={WIDTHXD(400)}
-              data={dataType}
-              onValueChange={(value, items) => {
-                setTypeOne(items);
-              }}
-            />
-          </View>
-        </View>
+    useEffect(() => {
+        calcultorResult();
+    }, [number, fromUnit, toUnit]);
+
+    const getDataUnit = async () => {
+        props.showLoading();
+        const res = await getUnitList({
+            platform: Platform.OS,
+        });
+        if (res.status == 200 && res.data.code == 200) {
+            setFromUnitList(res.data.data);
+            setFromUnit(res.data.data[0]);
+            onChangeFromUnit('', res.data.data[0])
+        } else {
+            showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
+        }
+        props.hideLoading();
+    };
+
+    const onChangeNumber = (string) => {
+        let number = string.toString().split(',').join('');
+        setNumber(number);
+
+    };
 
-        <Text style={styles.txtResult}>Kết quả: {result}</Text>
+    const onChangeFromUnit = (value, item) => {
+        setFromUnit(item);
+        let toUnit = [];
+        item.rates.map((rateItem) => {
+            toUnit.push({
+                id: rateItem.to_unit_id,
+                value: rateItem.to_unit.name,
+                name: rateItem.to_unit.name,
+                rate: rateItem.value_one > 0 ? rateItem.value_one : rateItem.value_two,
+            });
+        });
+        setToUnitList(toUnit);
+        setToUnit(toUnit[0]);
+    };
 
-        <View style={styles.footer}>
-          <TouchableOpacity onPress={onClick} style={styles.btnContainer}>
-            <AppText style={styles.txtBtn} i18nKey={'Caculate'} />
-          </TouchableOpacity>
+    const onChangeToUnit = (value, item) => {
+        setToUnit(item);
+        if (number && number != '' && parseFloat(number) > 0) {
+            let result = parseFloat(number) * item.rate;
+            setResult(`${parseFloat(number)} ${fromUnit.name} = ${result} ${item.name}`);
+        }
+    };
+
+    const calcultorResult = () => {
+        if (number && number != '' && parseFloat(number) > 0) {
+            let result = parseFloat(number) * toUnit.rate;
+            setResult(`${parseFloat(number)} ${fromUnit.name} = ${result} ${toUnit.name}`);
+        } else {
+            setResult('')
+        }
+    };
+
+    return (
+        <View style={{flex: 1}}>
+            <HeaderBack title={'ConvertUnit'}/>
+            <View style={{flex: 1, paddingTop: 20, paddingHorizontal: 20}}>
+                <AppText style={styles.txtTitle} i18nKey={'Count'}/>
+                <View style={styles.Item}>
+                    <View style={styles.wrap}>
+                        <TextInput
+                            onChangeText={(val) => onChangeNumber(val)}
+                            keyboardType={'number-pad'}
+                            style={styles.wrapInput}
+                            maxLength={12}
+                            value={toPriceVnd(number)}
+                        />
+                    </View>
+                </View>
+
+                <View style={styles.Item}>
+                    <View style={styles.wrap}>
+                        <PickerItem
+                            width={WIDTHXD(480)}
+                            data={fromUnitList}
+                            defaultValue={fromUnit?.name}
+                            value={fromUnit?.name}
+                            onValueChange={(value, item) => {
+                                onChangeFromUnit(value, item);
+                            }}
+                        />
+                        {/*<TouchableOpacity>*/}
+                        {/*  <Icon name={'exchange'} size={30} color={R.colors.black} />*/}
+                        {/*</TouchableOpacity>*/}
+
+                        <PickerItem
+                            width={WIDTHXD(480)}
+                            data={toUnitList}
+                            defaultValue={toUnit?.name}
+                            value={toUnit?.name}
+                            onValueChange={(value, item) => {
+                                onChangeToUnit(value, item);
+                            }}
+                        />
+                    </View>
+                </View>
+
+                <Text style={styles.txtResult}>{result}</Text>
+            </View>
         </View>
-      </View>
-    </View>
-  );
+    );
 };
 
 const styles = StyleSheet.create({
-  txtTitle: {
-    fontSize: getFontXD(42),
-    color: R.colors.color777,
-    marginBottom: 5,
-  },
-  note: {
-    fontSize: getFontXD(36),
-    fontStyle: 'italic',
-    marginTop: 10,
-  },
-  row: {
-    height: HEIGHTXD(109),
-    width: '80%',
-    justifyContent: 'space-between',
-    marginVertical: 5,
-    paddingHorizontal: 10,
-  },
-  footer: {
-    alignItems: 'center',
-    justifyContent: 'center',
-    marginTop: 40,
-  },
-  btnContainer: {
-    width: WIDTHXD(428),
-    height: HEIGHTXD(120),
-    justifyContent: 'center',
-    alignItems: 'center',
-    backgroundColor: R.colors.main,
-    borderRadius: 10,
-  },
-  txtBtn: {
-    fontSize: getFontXD(48),
-    color: R.colors.white,
-    fontWeight: '600',
-  },
-  wrapInput: {
-    width: '100%',
-    backgroundColor: R.colors.white,
-    height: HEIGHTXD(109),
-    fontSize: getFontXD(42),
-    borderRadius: 5,
-    paddingHorizontal: 10,
-    shadowColor: '#000',
-    shadowOffset: {
-      width: 0,
-      height: 1,
+    txtTitle: {
+        fontSize: getFontXD(42),
+        color: R.colors.color777,
+        marginBottom: 5,
+    },
+    note: {
+        fontSize: getFontXD(36),
+        fontStyle: 'italic',
+        marginTop: 10,
+    },
+    row: {
+        height: HEIGHTXD(109),
+        width: '80%',
+        justifyContent: 'space-between',
+        marginVertical: 5,
+        paddingHorizontal: 10,
+    },
+    footer: {
+        alignItems: 'center',
+        justifyContent: 'center',
+        marginTop: 40,
+    },
+    btnContainer: {
+        width: WIDTHXD(428),
+        height: HEIGHTXD(120),
+        justifyContent: 'center',
+        alignItems: 'center',
+        backgroundColor: R.colors.main,
+        borderRadius: 10,
+    },
+    txtBtn: {
+        fontSize: getFontXD(48),
+        color: R.colors.white,
+        fontWeight: '600',
+    },
+    wrapInput: {
+        width: '100%',
+        backgroundColor: R.colors.white,
+        height: HEIGHTXD(109),
+        fontSize: getFontXD(42),
+        borderRadius: 5,
+        paddingHorizontal: 10,
+        shadowColor: '#000',
+        shadowOffset: {
+            width: 0,
+            height: 1,
+        },
+        shadowOpacity: 0.2,
+        shadowRadius: 1.41,
+        elevation: 2,
+    },
+    wrap: {
+        flexDirection: 'row',
+        alignItems: 'center',
+        justifyContent: 'space-between',
+    },
+    Item: {
+        marginBottom: 20,
+    },
+    txtNote: {
+        fontSize: getFontXD(36),
+        textAlign: 'right',
+        marginTop: 10,
+    },
+    txtResult: {
+        fontSize: getFontXD(52),
+        color: R.colors.black,
+        fontWeight: '600',
+        textAlign: 'center',
+        marginTop: 20,
     },
-    shadowOpacity: 0.2,
-    shadowRadius: 1.41,
-    elevation: 2,
-  },
-  wrap: {
-    flexDirection: 'row',
-    alignItems: 'center',
-    justifyContent: 'space-between',
-  },
-  Item: {
-    marginBottom: 20,
-  },
-  txtNote: {
-    fontSize: getFontXD(36),
-    textAlign: 'right',
-    marginTop: 10,
-  },
-  txtResult: {
-    fontSize: getFontXD(52),
-    color: R.colors.black,
-    fontWeight: '600',
-    textAlign: 'center',
-    marginTop: 20,
-  },
 });
-export default ConvertUnit;
+const mapStateToProps = (state) => {
+    return {};
+};
+export default connect(mapStateToProps, {
+    showLoading,
+    hideLoading,
+})(ConvertUnit);
+
diff --git a/src/Screens/Tool/ExchangeRate.js b/src/Screens/Tool/ExchangeRate.js
index fde9dae..8d6f117 100644
--- a/src/Screens/Tool/ExchangeRate.js
+++ b/src/Screens/Tool/ExchangeRate.js
@@ -41,7 +41,7 @@ const ExchangeRate = (props) => {
     if (res.status == 200 && res.data.code == 200) {
       setDataProduct(res.data.data);
     } else {
-      showAlert(TYPE.ERROR, I18n.t('Notification', I18n.t('Can_not_get_data')));
+      showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
     }
   };
 
diff --git a/src/apis/Functions/Transaction.js b/src/apis/Functions/Transaction.js
index ccc1af6..d2d6e30 100644
--- a/src/apis/Functions/Transaction.js
+++ b/src/apis/Functions/Transaction.js
@@ -26,3 +26,8 @@ export const getListExchangeRate = async (body) =>
   GetData(url.urlGetListExchangeRate, body)
     .then((res) => res)
     .catch((err) => err);
+
+export const getUnitList = async (body) =>
+  GetData(url.urlGetUnitList, body)
+    .then((res) => res)
+    .catch((err) => err);
diff --git a/src/apis/url.js b/src/apis/url.js
index 5429aa7..485fb84 100644
--- a/src/apis/url.js
+++ b/src/apis/url.js
@@ -57,4 +57,6 @@ export default {
   urlProfitLost: root + 'api/v1/customers/calculate-profit',
 
   urlGetListExchangeRate: root + 'api/v1/customers/get-list-exchange-rate',
+  urlGetUnitList: `${root}api/v1/customers/get-list-unit`,
+
 };
diff --git a/src/routers/TabNavigation.js b/src/routers/TabNavigation.js
index 8a38ddb..b61efd2 100644
--- a/src/routers/TabNavigation.js
+++ b/src/routers/TabNavigation.js
@@ -18,7 +18,7 @@ import Test from '../Screens/NewFeed/Test';
 import {useNavigation} from '@react-navigation/native';
 import Transaction from '../Screens/Transaction/Transaction';
 import {AccountVerification, PACKETCQG} from '../routers/ScreenNames';
-import I18n from '../helper/i18/i18n';
+import I18n, {setLocation} from '../helper/i18/i18n';
 import {changeLanguage} from '../actions/language';
 import KEY from '../assets/AsynStorage';
 import AsyncStorage from '@react-native-community/async-storage';
@@ -77,6 +77,7 @@ const TabNavigator = (props) => {
   const setInitLanguage = async () => {
     const laguage = await AsyncStorage.getItem(KEY.LANGUAGE);
     if (laguage) props.changeLanguage(laguage);
+    setLocation(I18n, laguage);
   };
 
   const showPopUp = () => {
--
libgit2 0.27.0