using Assets.Scripts.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class WorkerController : MonoBehaviour { public static Dictionary> Workers = new Dictionary>(); public static List TestStructures = new List(); public GameObject WorkersList; // scroll content public Dropdown DropdownLocation; public Dropdown DropdownData; public GameObject inputField_date; public InputField inputField_location; public GameObject TimeStart; public GameObject TimeEnd; public GameObject StartHour; public GameObject StartMin; public GameObject StartSec; public GameObject EndHour; public GameObject EndMin; public GameObject EndSec; public GameObject StartStopButton; public GameObject ErrorDialog; public GameObject ButtonPlay; public Dropdown DropdownMode; public Toggle ToggleLine; public Toggle ToggleDisappearance; public GameObject DatePicker; public Camera camera; public Toggle projection; InputField inputField_date_text; enum Mode { RealTime = 0, History = 1, Stop = 2 }; Mode active_mode = Mode.Stop; int mode = 0; //public GameObject Time; static Client client = new Client(); Dropdown Year; Dropdown Month; Dropdown Day; //DateTime Date //{ // get // { // var date = new DateTime(int.Parse(Year.options[Year.value].text), int.Parse(Month.options[Month.value].text), int.Parse(Day.options[Day.value].text)); // return date; // } //} DateTimePicker Date; public List maps; static List starting = new List(); // флаги остановок public static Dictionary end_send = new Dictionary(); // флаги завершения загрузки Dictionary moving = new Dictionary(); // флаги начала движения //bool real_time = false; //bool history_start = false; float interpolationPeriod = 0.1f; float next_time = 0; float time = 0; //List StartStop = new List(); // Start is called before the first frame update void Start() { DebugHelper.ActivateConsole(); WorkerMarker(4, Color.red); WorkerMarker(356, Color.green); inputField_date_text = inputField_date.transform.GetComponent(); //Year = DatePicker.transform.GetChild(0).GetComponent(); //Month = DatePicker.transform.GetChild(1).GetComponent(); //Day = DatePicker.transform.GetChild(2).GetComponent(); Date = DatePicker.GetComponent(); //foreach (var s in structures.Select(s => s.acc_id).Distinct()) // WorkerMarker(s, UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f)); //foreach (var s in structures.Select(s => s.ts.Date).Distinct()) //{ // dates.Add(s); // DropdownData.options.Add(new Dropdown.OptionData(s.ToString("dd.MM.yyyy"))); //} //foreach (var s in structures.Select(s => s.location_id).Distinct()) //{ // locations.Add(s); DropdownLocation.options.Add(new Dropdown.OptionData("1 Братск")); DropdownLocation.options.Add(new Dropdown.OptionData("22 Офис Ижевск")); DropdownLocation.options.Add(new Dropdown.OptionData("25")); inputField_date_text.text = DateTime.Now.ToString("yyyy.MM.dd"); //} } int active_location = 0; // Update is called once per frame void Update() { if (DropdownMode.value != mode) { StopProgress(); active_mode = Mode.Stop; mode = DropdownMode.value; switch (DropdownMode.value) { case 0: //history_start = false; //////inputField_date.gameObject.SetActive(false); DatePicker.SetActive(false); TimeStart.SetActive(false); TimeEnd.SetActive(false); break; case 1: //real_time = false; //////inputField_date.gameObject.SetActive(true); DatePicker.SetActive(true); TimeStart.SetActive(true); TimeEnd.SetActive(true); break; } } if (active_location != DropdownLocation.value) { maps.ElementAt(active_location).SetActive(false); maps.ElementAt(DropdownLocation.value).SetActive(true); active_location = DropdownLocation.value; switch (DropdownLocation.value) { case 0: inputField_location.text = "1"; break; case 1: inputField_location.text = "22"; break; case 2: inputField_location.text = "25"; break; } } foreach (var m in markers) { m.marker.SetActive(m.toggle.isOn); if (m.toggle.isOn && Workers.ContainsKey(m.acc_id) && starting.Last() && end_send[m.acc_id]) { //end_send[m.value.acc_id] = false; // moving.Add(true); //if (markers.Count - 1 == m.i) time += Time.deltaTime; if (time >= interpolationPeriod) { time -= interpolationPeriod; StartingAccPositiong(m); } } } if (active_mode == Mode.RealTime && !inputField_location.text.Equals("") && Time.time >= next_time) { //var dateNow = DateTime.UtcNow.AddHours(3); //Time.GetComponent().text = dateNow.ToString(); starting.Add(true); var location_id = uint.Parse(inputField_location.text); foreach (var m in markers) { if (m.toggle.isOn) { client.CoordinatesRequest(0, 0, 1, location_id, m.acc_id); //history_start = true; end_send[m.acc_id] = false; } } next_time++; } if (ToggleLine.isOn) { foreach (var m in markers) m.marker_line.gameObject.SetActive(true); ToggleDisappearance.interactable = true; } else { foreach (var m in markers) { m.marker_line.gameObject.SetActive(false); m.marker_line.positionCount = 0; } ToggleDisappearance.interactable = false; } if (projection.isOn) { //camera_2d.SetActive(true); //camera_2_5D.SetActive(false); camera.orthographic = true; } else { //camera_2d.SetActive(false); //camera_2_5D.SetActive(true); camera.orthographic = false; } } public static List markers = new List(); /// /// Создание маркера для сотрудника /// /// void WorkerMarker(uint acc_id, Color color) { var toggle = Instantiate(Resources.Load("GameObjects/Toggle", typeof(Toggle))) as Toggle; toggle.name = acc_id.ToString(); toggle.transform.GetChild(1).gameObject.GetComponent().text = acc_id.ToString(); toggle.transform.SetParent(WorkersList.transform); var marker = Instantiate(Resources.Load("GameObjects/Capsule", typeof(GameObject))) as GameObject; marker.name = "marker_" + acc_id.ToString(); marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent().text = $"{acc_id}"; marker.GetComponent().material.color = color; // UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); var marker_line = Instantiate(Resources.Load("GameObjects/Line", typeof(LineRenderer))) as LineRenderer; marker_line.name = "marker_line_" + acc_id.ToString(); marker_line.startColor = color; marker_line.endColor = Color.white; marker_line.material.color = color; markers.Add(new Marker { acc_id = acc_id, marker = marker, toggle = toggle, marker_line = marker_line }); } /// /// Смена положения маркера /// /// Задержка /// Шаг до нового положения /// Начальное положение /// Финальное положение /// Маркер сотрудника /// Данные из БД /// Номер процесса/запуска /// Номер записи из БД /// Всего записей из БД /// //static IEnumerator MarkerPostion(float pause, float step, Vector3 start_pos, Vector3 end_pos, GameObject worker_marker, Toggle toggle, Structure w, int count, int progress, int all) //{ // yield return new WaitForSeconds(pause); // if (worker_marker.activeSelf == true && history_start && starting[count]) // { // var x_position = Mathf.Lerp(start_pos.x, end_pos.x, step); // var y_position = Mathf.Lerp(start_pos.z, end_pos.z, step); // //Debug.Log($"marker name={worker_marker.name} time={pause} step={step} sec x={x_position} y={y_position} x0={start_pos.x} y0={start_pos.z} x1={end_pos.x} y1={end_pos.z}"); // worker_marker.transform.position = new Vector3(x_position, 0.5f, y_position); // worker_marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent().text = $"{w.acc_id} x={end_pos.x} y={end_pos.z}"; // toggle.transform.GetChild(1).gameObject.GetComponent().text = $"{w.acc_id} {w.ts:hh:mm:ss}\n{progress + 1} из {all}"; // if (progress + 1 == all) // { // sStartStopButton.transform.GetChild(0).GetComponent().text = "Отобразить"; // starting[count] = false; // history_start = false; // } // } //} void Position(float step, Vector3 start_pos, Vector3 end_pos, Marker marker, Structure w, int count, string progress) { if (marker.marker.activeSelf == true && starting[count]) { var x_position = Mathf.Lerp(start_pos.x, end_pos.x, step); var y_position = Mathf.Lerp(start_pos.z, end_pos.z, step); //Debug.Log($"marker name={worker_marker.name} time={pause} step={step} sec x={x_position} y={y_position} x0={start_pos.x} y0={start_pos.z} x1={end_pos.x} y1={end_pos.z}"); var new_position = new Vector3(x_position, 0.5f, y_position); if (marker.marker.transform.position != new_position) { marker.marker.transform.position = new Vector3(x_position, 0.5f, y_position); marker.marker_line.SetPosition(marker.marker_line.positionCount++, new Vector3(x_position, 0, y_position)); if(ToggleDisappearance.isOn)marker.marker_line = LineDisappearance(marker.marker_line); } marker.marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent().text = $"{w.acc_id} x={end_pos.x} y={end_pos.z}"; marker.toggle.transform.GetChild(1).gameObject.GetComponent().text = $"{w.acc_id} {w.ts.ToString("hh:mm:ss")}{progress}"; } } //static IEnumerator RequestPostion(long ts, long te, uint loc, uint account_id) //{ // client.CoordinatesRequest(ts, te, 1, loc); // yield return new WaitForSeconds(5); // foreach (var t in TestStructures) // Debug.Log(t); //} /// /// Запуск отрисовки /// public void ButtonStart() { if (active_mode == Mode.Stop) foreach (var m in markers) m.marker_line.positionCount = 0; var button_text = StartStopButton.transform.GetChild(0); switch (DropdownMode.value) { case 0: //real_time = !real_time; if (active_mode == Mode.Stop/*real_time*/) { active_mode = Mode.RealTime; button_text.GetComponent().text = "Остановить"; } else { active_mode = Mode.Stop; button_text.GetComponent().text = "Отобразить"; } break; case 1: if (int.Parse(StartHour.GetComponent().text) == 99) SceneManager.LoadScene("Editor3D"); else { if (active_mode == Mode.Stop/*real_time*/) active_mode = Mode.History; else active_mode = Mode.Stop; }//history_start = !history_start; if (active_mode == Mode.History/*history_start*/) { starting.Add(true); var date = DateTime.Now; var error_date = false; ////////try ////////{ //date = DateTime.Parse(inputField_date_text.text); date = Date.Date; //////} //////catch (Exception e) //////{ ////// ErrorDialog.SetActive(true); ////// error_date = true; ////// var text = ErrorDialog.transform.GetChild(0).GetComponent().text = "Некорректный формат даты"; ////// //history_start = false; ////// active_mode = Mode.Stop; //////} var time_start = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks); time_start = time_start.AddHours(int.Parse(StartHour.GetComponent().text)); time_start = time_start.AddMinutes(int.Parse(StartMin.GetComponent().text)); time_start = time_start.AddSeconds(int.Parse(StartSec.GetComponent().text)); Debug.Log(time_start); //var time_start = new DateTime(1, 1, 1, int.Parse(StartHour.GetComponent().text), int.Parse(StartMin.GetComponent().text), int.Parse(StartSec.GetComponent().text)); //var time_end = new DateTime(1, 1, 1, int.Parse(EndHour.GetComponent().text), int.Parse(EndMin.GetComponent().text), int.Parse(EndSec.GetComponent().text)); var time_end = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks); time_end = time_end.AddHours(int.Parse(EndHour.GetComponent().text)); time_end = time_end.AddMinutes(int.Parse(EndMin.GetComponent().text)); time_end = time_end.AddSeconds(int.Parse(EndSec.GetComponent().text)); // client.account_id = 356; //StartCoroutine(RequestPostion(time_start.Ticks, time_end.Ticks, 22, 356)); if (!error_date) { try { var location_id = uint.Parse(inputField_location.text); foreach (var m in markers) { if (m.toggle.isOn) { client.CoordinatesRequest(time_start.Ticks, time_end.Ticks, 1, location_id, m.acc_id); end_send[m.acc_id] = false; } } button_text.GetComponent().text = "Остановить"; } catch (Exception e) { ErrorDialog.SetActive(true); ErrorDialog.transform.GetChild(0).GetComponent().text = "Введите идентификатор локации"; //history_start = false; active_mode = Mode.Stop; } } // var workers = structures.Where(w => w.ts >= time_start && w.ts <= time_end && w.location_id == int.Parse(DropdownLocation.options[DropdownLocation.value].text.ToString())).ToList(); //foreach (var m in markers) // if (m.toggle.isOn) // StartingAccPositiong(m); } else { StopProgress(); } break; } } public void ErrorDialogClose() { ErrorDialog.SetActive(false); } void StopProgress() { if (starting.Any()) starting[starting.Count - 1] = false; StartStopButton.transform.GetChild(0).GetComponent().text = "Отобразить"; foreach (var m in markers) { end_send[m.acc_id] = false; moving.Remove(m.acc_id); } } /// /// Затухание траектории /// /// Траектория /// LineRenderer LineDisappearance(LineRenderer lineRenderer) { //LineRenderer lineRenderer = GetComponent(); int newPositionCount = lineRenderer.positionCount - 1; Vector3[] newPositions = new Vector3[newPositionCount]; for (int i = 0; i < newPositionCount; i++) { newPositions[i] = lineRenderer.GetPosition(i + 1); } lineRenderer.SetPositions(newPositions); return lineRenderer; } //void StartingAccPositiong(Marker m, float time) //{ // var worker = Workers[m.acc_id].OrderBy(wr => wr.ts).ToList(); // if (worker.Any()) // { // var offset = 0.1f; // for (int i = 0; i < worker.Count; i++) // { // var w = worker.ElementAt(i); // var start_pos = m.marker.transform.position; // if (i != 0) start_pos = new Vector3(worker.ElementAt(i - 1).coord_x / 100f, 0.5f, worker.ElementAt(i - 1).coord_y / 100f); // var end_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f); // //if (real_time) // Position(time, start_pos, end_pos, m, w, starting.Count - 1, ""); // //if (history_start) // //{ // // for (float j = 0; j <= 1.1f; j += 0.1f) // 1.1f из-за округления float // // { // // StartCoroutine(MarkerPostion(i + offset + j, j, start_pos, end_pos, m.marker, m.toggle, w, starting.Count - 1, i, worker.Count)); // // } // // offset += 0.1f; // //} // } // } //} /// /// Смена положения по интервалу /// Шаги для плавного перемещения /// /// Данные о маркере void StartingAccPositiong(Marker m) { int i = 0; float step = 0.1f; if (moving.ContainsKey(m.acc_id)) { if (moving[m.acc_id].index < Workers[m.acc_id].Count) i = moving[m.acc_id].index; { if (moving[m.acc_id].step < 1.1f) step = moving[m.acc_id].step; } } else moving[m.acc_id] = new MarkerMoving(); var worker = Workers[m.acc_id].OrderBy(wr => wr.ts).ToList(); if (worker.Any()) { var w = worker.ElementAt(i); var start_pos = m.marker.transform.position; if (i != 0) start_pos = new Vector3(worker.ElementAt(i - 1).coord_x / 100f, 0.5f, worker.ElementAt(i - 1).coord_y / 100f); if (active_mode == Mode.History && i == 0) start_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f); var end_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f); var progress = ""; if (active_mode == Mode.History) progress = $"\n{i + 1} из {Workers[m.acc_id].Count}"; Position(step, start_pos, end_pos, m, w, starting.Count - 1, progress); // StartingAccPositiong(m.value, time_step); } if (step >= 1) i++; step += interpolationPeriod; // 0.1f; moving[m.acc_id].index = i; moving[m.acc_id].step = step; } public void OpenEditor() { SceneManager.LoadScene("Scenes/Editor2D"); } void OnGUI() { //if (Input.GetKeyDown(KeyCode.BackQuote)) DebugHelper.DrawConsole(); } }