powerfun-unity/Assets/Scripts/UI/Prefab/Panel/EditUserController.cs
2022-05-31 16:51:07 +08:00

515 lines
20 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Assets.Scripts;
using Assets.Scripts.Apis;
using Assets.Scripts.Apis.Models;
using Assets.Scripts.Mobile.Interface;
using Assets.Scripts.UI.Control;
using Assets.Scripts.UI.UIEffect;
using DG.Tweening;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class EditUserController : PFUIPanel, INativeOnMobileImageSelect
{
private Button mSaveButton;
private PFUIDropdown mSexDropdown;
private PFUIDropdown mDayDropdown;
private PFUIDropdown mMonthDropdown;
private PFUIDropdown mYearDropdown;
private PFUIDropdown mConutryDropdown;
private PFUIDropdown mUnitDropdown;
private Text mID;
private PFUIInputField mNickName;
private PFUIInputField mFTP;
private PFUIInputField mWeight;
private PFUIInputField mHeight;
private PFUIInputField mMHR;
private PFUIInputField mBW;
private PFUIInputField mWD;
private PFUIInputField mName;
private PFUIInputField mPhone;
private PFUIInputField mAddr;
private RawImage mHeadImage;
private UserApi userApi;
private Button mCancelButton;
private Button mBackButton;
private Button mSwitchButton;
PfUIButton mChangeAvatar;
Transform linkContainer;
Dictionary<string, Selectable> dict;
Transform panel;
float? panelTop = null;
UIGradient g1, g2;
TKPanRecognizer pan;
protected override void Awake()
{
Debug.Log(Utils.GetIP(Utils.ADDRESSFAM.IPv4));
userApi = new UserApi();
#if !(UNITY_ANDROID || UNITY_IOS)
panel = this.transform.Find("Panel");
pan = new TKPanRecognizer();
#else
panel = this.transform.Find("Panel/MainPanel");
panelTop = null;
g1 = transform.Find("Panel/Btn1").GetComponent<UIGradient>();
g2 = transform.Find("Panel/Btn2").GetComponent<UIGradient>();
if (!panelTop.HasValue) panelTop = panel.localPosition.y;
UIManager.AddEvent(transform.Find("Panel/Btn1").gameObject, EventTriggerType.PointerClick, b =>
{
setMobilePanelPosition(true);
});
UIManager.AddEvent(transform.Find("Panel/Btn2").gameObject, EventTriggerType.PointerClick, b =>
{
setMobilePanelPosition(false);
});
Debug.Log(panel.localPosition);
pan = new TKPanRecognizer();
var delta = Vector3.zero;
var rect = this.transform.Find("Panel").GetComponent<RectTransform>();
var startLocation = Vector2.zero;
pan.gestureRecognizedEvent += (r) =>
{
//Debug.Log(UIManager.Instance.MainCanvas);
//Debug.Log(this.transform.Find("Panel").GetComponent<Collider>().bounds.size
startLocation = r.startTouchLocation();
if (rect.isPointInTransfrom(startLocation))
{
delta = pan.deltaTranslation;
delta.x = 0;
delta.z = 0;
panel.transform.position += delta;
}
//Debug.Log("pan recognizer fired: " + panel.transform.localPosition);
};
pan.gestureCompleteEvent += (r) =>
{
if (rect.isPointInTransfrom(startLocation))
{
Debug.Log("运行动画");
if (panel.localPosition.y < 185f + 370f / 2f)
{
setMobilePanelPosition(true);
}
else
{
setMobilePanelPosition(false);
}
}
//if (!panelTop.HasValue) panelTop = transform.localPosition.y + 185;
//Debug.Log($"{panel.localPosition.y},{panelTop}");
//Debug.Log(r.deltaTranslation);
};
//TouchKit.addGestureRecognizer(pan);
#endif
mID = panel.Find("IDNumber").Find("input").Find("Text").GetComponent<Text>();
mSexDropdown = panel.Find("SexDropdown").GetComponent<PFUIDropdown>();
mSexDropdown = panel.Find("SexDropdown").GetComponent<PFUIDropdown>();
mYearDropdown = panel.Find("YearDropdown").GetComponent<PFUIDropdown>();
mMonthDropdown = panel.Find("MonthDropdown").GetComponent<PFUIDropdown>();
mDayDropdown = panel.Find("DayDropdown").GetComponent<PFUIDropdown>();
mUnitDropdown = panel.Find("UnitDropdown").GetComponent<PFUIDropdown>();
mSaveButton = this.transform.Find("SaveButton").GetComponent<Button>();
mCancelButton = this.transform.Find("CancelButton").GetComponent<Button>();
mHeadImage = this.transform.Find("HeadImage").GetComponent<RawImage>();
mBackButton = this.transform.Find("BackButton").GetComponent<Button>();
mSwitchButton = this.transform.Find("SwitchAccountButton").GetComponent<Button>();
mChangeAvatar = this.transform.Find("ChangeAvatar").GetComponent<PfUIButton>();
mConutryDropdown = panel.Find("CountryDropdown").GetComponent<PFUIDropdown>();
mNickName = panel.Find("NickName").Find("input").GetComponent<PFUIInputField>();
mFTP = panel.Find("Ftp").Find("input").GetComponent<PFUIInputField>();
mWeight = panel.Find("Weight").Find("input").GetComponent<PFUIInputField>();
mHeight = panel.Find("Height").Find("input").GetComponent<PFUIInputField>();
mMHR = panel.Find("MHR").Find("input").GetComponent<PFUIInputField>();
mBW = panel.Find("BW").Find("input").GetComponent<PFUIInputField>();
mWD = panel.Find("WD").Find("input").GetComponent<PFUIInputField>();
mName = panel.Find("Name").Find("input").GetComponent<PFUIInputField>();
mPhone = panel.Find("PN").Find("input").GetComponent<PFUIInputField>();
mAddr = panel.Find("Addr").Find("input").GetComponent<PFUIInputField>();
UIManager.AddEvent(mBackButton.gameObject, EventTriggerType.PointerClick, Cancel);
UIManager.AddEvent(mChangeAvatar.gameObject, EventTriggerType.PointerClick, (e) =>
{
#if !(UNITY_ANDROID || UNITY_IOS)
OpenFileName ofn = new OpenFileName();
ofn.structSize = Marshal.SizeOf(ofn);
ofn.filter = "Image Files(*.jpg;*.jpeg;*.png;*.bmp)\0*.jpg;*.png;*.jpeg;*.bmp\0";
ofn.file = new string(new char[256]);
ofn.maxFile = ofn.file.Length;
ofn.fileTitle = new string(new char[64]);
ofn.maxFileTitle = ofn.fileTitle.Length;
ofn.initialDir = UnityEngine.Application.dataPath;//默认路径
ofn.title = "Open Project";
ofn.defExt = "JPG";//显示文件的类型
//注意 一下项目不一定要全选 但是0x00000008项不要缺少
ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR
if (Win32.GetOpenFileName(ofn))
{
ChangeAvatar(ofn.file);
}
#else
App.imageSelectorController.Select("EditUserPanel(Clone)");
#endif
});
linkContainer = transform.Find("LinkContainer");
mSexDropdown.ClearOptions();
mSexDropdown.AddOptions(new List<string>
{
App.GetLocalString("Male"),App.GetLocalString("Female")
});
mUnitDropdown.ClearOptions();
mUnitDropdown.AddOptions(UIManager.Instance.loginRegOptions.units);
mYearDropdown.ClearOptions();
var years = new List<string>();
for (int i = 1960; i < 2099; i++)
{
years.Add(i.ToString());
}
mYearDropdown.AddOptions(years);
mYearDropdown.OnValueChange = (index) =>
{
//Debug.Log(index);
SetDayDropdown();
};
mMonthDropdown.ClearOptions();
var months = new List<string>();
for (int i = 1; i < 13; i++)
{
months.Add(i.ToString());
}
mMonthDropdown.AddOptions(months);
//mMonthDropdown.SelectValue("9");
mMonthDropdown.OnValueChange = (index) =>
{
SetDayDropdown();
};
mDayDropdown.ClearOptions();
SetDayDropdown();
//mDayDropdown.AddOptions()
//mDayDropdown.AddOptions(new List<Dropdown.OptionData>
//{
// new Dropdown.OptionData()
//});
dict = new Dictionary<string, Selectable>
{
{"NickName",mNickName.GetComponent<InputField>() },
{"FTP",mFTP.GetComponent<InputField>() },
{"Weight",mWeight.GetComponent<InputField>() },
{"Height",mHeight.GetComponent<InputField>() },
{"WheelDiameter",mWD.GetComponent<InputField>() },
{"MaxHeartRate",mMHR.GetComponent<InputField>() },
{"BicycleWeight",mBW.GetComponent<InputField>() },
{"Contact",mName.GetComponent<InputField>() },
{"ContactPhone",mPhone.GetComponent<InputField>() },
{"ContactAddress",mAddr.GetComponent<InputField>() },
};
#region
if (App.IsRowerMode == true)
{
transform.Find("Panel/MainPanel/BW").gameObject.SetActive(false);
transform.Find("Panel/MainPanel/WD").gameObject.SetActive(false);
}
#endregion
}
async Task Login()
{
var result = await new UserApi().Login("13115011550", "laozhong", "");
App.CurrentUser = result.data;
}
void LoadDataSync()
{
//if (!App.FromLogin)
//{
// await Login();
//}
var currentUser = App.CurrentUser;
if (currentUser == null) return;
//mIdText.text = currentUser.Id.ToString();
//mNameText.text = currentUser.Nickname;
//Utils.DisplayImage(StartCoroutine, mHeadImage, currentUser.WxHeadImg);
Utils.DisplayHead(mHeadImage, currentUser.WxHeadImg);
if (currentUser.Sex == 1)
{
mSexDropdown.SelectIndex(0);
}
else
{
mSexDropdown.SelectIndex(1);
}
mUnitDropdown.SelectIndex(currentUser.Unit);
if (currentUser.Birthday.HasValue)
{
var birthday = currentUser.Birthday.Value;
mYearDropdown.SelectValue(birthday.Year.ToString());
mMonthDropdown.SelectValue(birthday.Month.ToString());
mDayDropdown.SelectValue(birthday.Day.ToString());
}
mID.text = currentUser.Id.ToString("000000");
mNickName.Text = currentUser.Nickname;
mFTP.Text = currentUser.FTP.ToString();
mWeight.Text = currentUser.Weight.ToString();
mHeight.Text = currentUser.Height.ToString();
mMHR.Text = currentUser.MaxHeartRate.ToString();
mBW.Text = currentUser.BicycleWeight.ToString();
mWD.Text = currentUser.WheelDiameter.ToString();
mName.Text = currentUser.Contact;
mPhone.Text = currentUser.ContactPhone;
mAddr.Text = currentUser.ContactAddress;
//string.IsNullOrEmpty(currentUser.Unionid)
linkContainer.Find("Wx").GetComponent<Image>().sprite =
string.IsNullOrEmpty(currentUser.Unionid)
? Resources.Load<Sprite>("Images/Wechat_person_0")
: Resources.Load<Sprite>("Images/Wechat_person_1");
linkContainer.Find("Fb").GetComponent<Image>().sprite =
string.IsNullOrEmpty(currentUser.FacebookUserId)
? Resources.Load<Sprite>("Images/link-facebook")
: Resources.Load<Sprite>("Images/Login_Facebook");
linkContainer.Find("Ap").GetComponent<Image>().sprite =
string.IsNullOrEmpty(currentUser.AppleUserId)
? Resources.Load<Sprite>("Images/link-apple")
: Resources.Load<Sprite>("Images/Login_Apple");
linkContainer.Find("Gg").GetComponent<Image>().sprite =
string.IsNullOrEmpty(currentUser.GoogleUserId)
? Resources.Load<Sprite>("Images/link-google")
: Resources.Load<Sprite>("Images/Login_Google");
}
// Start is called before the first frame update
protected override void Start()
{
base.Start();
mConutryDropdown.ClearOptions();
mConutryDropdown.AddOptions(UIManager.Instance.loginRegOptions.countrys);
mConutryDropdown.OnValueChange = (int index) =>
{
mConutryDropdown.transform.Find("RawImage").GetComponent<RawImage>().texture =
UIManager.Instance.loginRegOptions.GetCountryImage(index);
};
mConutryDropdown.SelectValue(App.CurrentUser.Country);
mConutryDropdown.transform.Find("RawImage").GetComponent<RawImage>().texture =
UIManager.Instance.loginRegOptions.GetCountryImageByName(App.CurrentUser.Country);
var rect = ((RectTransform)mHeadImage.transform).rect;
SetRounded(mHeadImage.transform, rect.height);
UIManager.AddEvent(mSaveButton.gameObject, EventTriggerType.PointerClick, Save);
UIManager.AddEvent(mCancelButton.gameObject, EventTriggerType.PointerClick, Cancel);
UIManager.AddEvent(mSwitchButton.gameObject, EventTriggerType.PointerClick, Switch);
}
public override void Show()
{
base.Show();
LoadDataSync();
App.isChanged = false;
}
private void Switch(BaseEventData arg0)
{
UIManager.SwitchAccount();
}
// Update is called once per frame
void Update()
{
}
void setMobilePanelPosition(bool flag)
{
if(flag)
{
if (!panelTop.HasValue) panelTop = panel.localPosition.y;
panel.DOLocalMoveY(panelTop.Value, 0.3f);
g1.color1 = Utils.HexToColorHtml("#F93086");
g1.color2 = Utils.HexToColorHtml("#ff7485");
g2.color1 = Utils.HexToColorHtml("#353543");
g2.color2 = Utils.HexToColorHtml("#474759");
//.color1 = Utils.HexToColorHtml()
}
else
{
if (!panelTop.HasValue) panelTop = panel.localPosition.y;
panel.DOLocalMoveY(panelTop.Value + 370, 0.3f);
g2.color1 = Utils.HexToColorHtml("#F93086");
g2.color2 = Utils.HexToColorHtml("#ff7485");
g1.color1 = Utils.HexToColorHtml("#353543");
g1.color2 = Utils.HexToColorHtml("#474759");
}
}
void SetDayDropdown()
{
//Debug.Log(mDayDropdown.SelectedItem);
mDayDropdown.ClearOptions();
var year = mYearDropdown.SelectedItem;
var month = mMonthDropdown.SelectedItem;
//var date = new DateTime(int.Parse(year), int.Parse(month), 1);
var days = DateTime.DaysInMonth(int.Parse(year), int.Parse(month));
var list = new List<string>();
for (int i = 1; i <= days; i++)
{
list.Add(i.ToString());
}
mDayDropdown.ClearOptions();
mDayDropdown.AddOptions(list);
mDayDropdown.SelectIndex(0);
}
void Save(BaseEventData e)
{
//UIManager.ShowConfirm("Confirm", "Are you sure to edit?", SaveFunc);
try
{
SaveFunc();
}
catch (Exception ex)
{
Utils.showToast(gameObject, ex.Message);
}
//App.CurrentUser = user;
//UIManager.ShowAlert("result.errMsg");
}
void SaveFunc()
{
var user = JsonConvert.DeserializeObject<UserResultModel>(JsonConvert.SerializeObject(App.CurrentUser));
user.Birthday = new DateTime(int.Parse(mYearDropdown.SelectedItem), int.Parse(mMonthDropdown.SelectedItem), int.Parse(mDayDropdown.SelectedItem));
user.Sex = mSexDropdown.SelectedIndex == 0 ? 1 : 2;
user.Nickname = mNickName.Text;
user.Country = UIManager.Instance.loginRegOptions.GetCountryName(mConutryDropdown.SelectedIndex);
var errorList = new List<object>();
if (string.IsNullOrEmpty(mNickName.Text)) errorList.Add(new { Field = "NickName", ErrMsg = "请填写昵称" });
if (string.IsNullOrEmpty(mFTP.Text)) errorList.Add(new { Field = "FTP", ErrMsg = "请填写FTP" });
if (string.IsNullOrEmpty(mHeight.Text)) errorList.Add(new { Field = "Height", ErrMsg = "请填写身高" });
if (string.IsNullOrEmpty(mWeight.Text)) errorList.Add(new { Field = "Weight", ErrMsg = "请填写体重" });
if (string.IsNullOrEmpty(mMHR.Text)) errorList.Add(new { Field = "MaxHeartRate", ErrMsg = "请填写最大心率" });
if (string.IsNullOrEmpty(mBW.Text)) errorList.Add(new { Field = "BicycleWeight", ErrMsg = "请填写车重" });
if (string.IsNullOrEmpty(mWD.Text)) errorList.Add(new { Field = "WheelDiameter", ErrMsg = "请填写轮径" });
if (errorList.Count > 0)
{
Utils.SetValidate(dict, JArray.FromObject(errorList));
Utils.showToast(gameObject, "Please fill in the information");//请填写相关信息
return;
}
user.FTP = Convert.ToInt32(mFTP.Text, CultureInfo.InstalledUICulture); //int.Parse(mFTP.Text);
user.Height = Convert.ToInt32(mHeight.Text, CultureInfo.InstalledUICulture); //int.Parse(mHeight.Text);
user.Weight = Convert.ToDouble(mWeight.Text, CultureInfo.InstalledUICulture); //double.Parse(mWeight.Text);
user.MaxHeartRate = Convert.ToInt32(mMHR.Text, CultureInfo.InstalledUICulture); //int.Parse(mMHR.Text);
user.BicycleWeight = Convert.ToDouble(mBW.Text, CultureInfo.InstalledUICulture); //double.Parse(mBW.Text);
user.WheelDiameter = Convert.ToInt32(mWD.Text, CultureInfo.InstalledUICulture); //int.Parse(mWD.Text);
user.Unit = mUnitDropdown.SelectedIndex;
user.Contact = mName.Text;
user.ContactPhone = mPhone.Text;
user.ContactAddress = mAddr.Text;
var result = userApi.Update(user, out string cookie,"");
App.isChanged = false;
if (result.result == false)
{
Utils.SetValidate(dict, JArray.FromObject(result.data));
Utils.showToast(gameObject, result.errMsg);
//UIManager.ShowAlert(result.errMsg);
}
else
{
App.CurrentUser = JObject.FromObject(result.data).ToObject<UserResultModel>();
App.CurrentUser.cookie = cookie;
if (App.CurrentUser.Birthday.HasValue)
{
App.CurrentUser.Birthday = App.CurrentUser.Birthday.Value.ToLocalTime();
}
var userinfos = UIManager.Instance.userInfos;
var i = userinfos.FindIndex(x => x.Id == App.CurrentUser.Id);
if (i != -1)
{
userinfos[i].NickName = user.Nickname;
UIManager.Instance.userInfos = userinfos;
}
Utils.showToast(gameObject, "Success", type: 1);
//UIManager.ShowAlert("Success");
}
LoadDataSync();
}
void ChangeAvatar(string path)
{
var r = userApi.Update(App.CurrentUser, out string cookie,path);
App.isChanged = false;
if (r.result)
{
var img = JObject.FromObject(r.data).Value<string>("WxHeadImg");
Utils.DisplayImage(mHeadImage, img, true);
var userinfos = UIManager.Instance.userInfos;
var i = userinfos.FindIndex(x => x.Id == App.CurrentUser.Id);
if (i != -1)
{
userinfos[i].Avatar = img;
UIManager.Instance.userInfos = userinfos;
}
Debug.Log(img);
App.CurrentUser.WxHeadImg = img;
App.CurrentUser.cookie = cookie;
Utils.showToast(gameObject, "Success", type: 1);
//UIManager.ShowAlert();
}
else
{
Utils.showToast(gameObject, r.errMsg);
//UIManager.ShowAlert();
}
}
void Cancel(BaseEventData e)
{
UIManager.ShowPrePanel();
//if (App.isChanged)
//{
// UIManager.ShowConfirm("Tips", "It is detected that you have modified, do you want to give up and return?", () =>
// {
// UIManager.ShowPrePanel();
// UIManager.CloseConfirm();
// });
//}
//else
//{
// UIManager.ShowPrePanel();
//}
}
public void OnMobileImageSelect(string res)
{
Debug.Log(res);
if (res.IndexOf("true,") == 0)
{
var path = res.Replace("true,", "");
ChangeAvatar(path);
}
}
}