WorkerController.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. using Assets.Scripts.Models;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading;
  7. using UnityEngine;
  8. using UnityEngine.SceneManagement;
  9. using UnityEngine.UI;
  10. public class WorkerController : MonoBehaviour
  11. {
  12. public static Dictionary<uint, List<Structure>> Workers = new Dictionary<uint, List<Structure>>();
  13. public static List<Structure> TestStructures = new List<Structure>();
  14. public GameObject WorkersList; // scroll content
  15. public Dropdown DropdownLocation;
  16. public Dropdown DropdownData;
  17. public GameObject inputField_date;
  18. public InputField inputField_location;
  19. public GameObject TimeStart;
  20. public GameObject TimeEnd;
  21. public GameObject StartHour;
  22. public GameObject StartMin;
  23. public GameObject StartSec;
  24. public GameObject EndHour;
  25. public GameObject EndMin;
  26. public GameObject EndSec;
  27. public GameObject StartStopButton;
  28. public GameObject ErrorDialog;
  29. public GameObject ButtonPlay;
  30. public Dropdown DropdownMode;
  31. public Toggle ToggleLine;
  32. public Toggle ToggleDisappearance;
  33. public GameObject DatePicker;
  34. public Camera camera;
  35. public Toggle projection;
  36. InputField inputField_date_text;
  37. enum Mode { RealTime = 0, History = 1, Stop = 2 };
  38. Mode active_mode = Mode.Stop;
  39. int mode = 0;
  40. //public GameObject Time;
  41. static Client client = new Client();
  42. Dropdown Year;
  43. Dropdown Month;
  44. Dropdown Day;
  45. //DateTime Date
  46. //{
  47. // get
  48. // {
  49. // 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));
  50. // return date;
  51. // }
  52. //}
  53. DateTimePicker Date;
  54. public List<GameObject> maps;
  55. static List<bool> starting = new List<bool>(); // флаги остановок
  56. public static Dictionary<uint, bool> end_send = new Dictionary<uint, bool>(); // флаги завершения загрузки
  57. Dictionary<uint, MarkerMoving> moving = new Dictionary<uint, MarkerMoving>(); // флаги начала движения
  58. //bool real_time = false;
  59. //bool history_start = false;
  60. float interpolationPeriod = 0.1f;
  61. float next_time = 0;
  62. float time = 0;
  63. //List<bool> StartStop = new List<bool>();
  64. // Start is called before the first frame update
  65. void Start()
  66. {
  67. DebugHelper.ActivateConsole();
  68. WorkerMarker(4, Color.red);
  69. WorkerMarker(356, Color.green);
  70. inputField_date_text = inputField_date.transform.GetComponent<InputField>();
  71. //Year = DatePicker.transform.GetChild(0).GetComponent<Dropdown>();
  72. //Month = DatePicker.transform.GetChild(1).GetComponent<Dropdown>();
  73. //Day = DatePicker.transform.GetChild(2).GetComponent<Dropdown>();
  74. Date = DatePicker.GetComponent<DateTimePicker>();
  75. //foreach (var s in structures.Select(s => s.acc_id).Distinct())
  76. // WorkerMarker(s, UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f));
  77. //foreach (var s in structures.Select(s => s.ts.Date).Distinct())
  78. //{
  79. // dates.Add(s);
  80. // DropdownData.options.Add(new Dropdown.OptionData(s.ToString("dd.MM.yyyy")));
  81. //}
  82. //foreach (var s in structures.Select(s => s.location_id).Distinct())
  83. //{
  84. // locations.Add(s);
  85. DropdownLocation.options.Add(new Dropdown.OptionData("1 Братск"));
  86. DropdownLocation.options.Add(new Dropdown.OptionData("22 Офис Ижевск"));
  87. DropdownLocation.options.Add(new Dropdown.OptionData("25"));
  88. inputField_date_text.text = DateTime.Now.ToString("yyyy.MM.dd");
  89. //}
  90. }
  91. int active_location = 0;
  92. // Update is called once per frame
  93. void Update()
  94. {
  95. if (DropdownMode.value != mode)
  96. {
  97. StopProgress();
  98. active_mode = Mode.Stop;
  99. mode = DropdownMode.value;
  100. switch (DropdownMode.value)
  101. {
  102. case 0:
  103. //history_start = false;
  104. //////inputField_date.gameObject.SetActive(false);
  105. DatePicker.SetActive(false);
  106. TimeStart.SetActive(false);
  107. TimeEnd.SetActive(false);
  108. break;
  109. case 1:
  110. //real_time = false;
  111. //////inputField_date.gameObject.SetActive(true);
  112. DatePicker.SetActive(true);
  113. TimeStart.SetActive(true);
  114. TimeEnd.SetActive(true);
  115. break;
  116. }
  117. }
  118. if (active_location != DropdownLocation.value)
  119. {
  120. maps.ElementAt(active_location).SetActive(false);
  121. maps.ElementAt(DropdownLocation.value).SetActive(true);
  122. active_location = DropdownLocation.value;
  123. switch (DropdownLocation.value)
  124. {
  125. case 0:
  126. inputField_location.text = "1";
  127. break;
  128. case 1:
  129. inputField_location.text = "22";
  130. break;
  131. case 2:
  132. inputField_location.text = "25";
  133. break;
  134. }
  135. }
  136. foreach (var m in markers)
  137. {
  138. m.marker.SetActive(m.toggle.isOn);
  139. if (m.toggle.isOn && Workers.ContainsKey(m.acc_id) && starting.Last() && end_send[m.acc_id])
  140. {
  141. //end_send[m.value.acc_id] = false;
  142. // moving.Add(true);
  143. //if (markers.Count - 1 == m.i)
  144. time += Time.deltaTime;
  145. if (time >= interpolationPeriod)
  146. {
  147. time -= interpolationPeriod;
  148. StartingAccPositiong(m);
  149. }
  150. }
  151. }
  152. if (active_mode == Mode.RealTime && !inputField_location.text.Equals("") && Time.time >= next_time)
  153. {
  154. //var dateNow = DateTime.UtcNow.AddHours(3);
  155. //Time.GetComponent<Text>().text = dateNow.ToString();
  156. starting.Add(true);
  157. var location_id = uint.Parse(inputField_location.text);
  158. foreach (var m in markers)
  159. {
  160. if (m.toggle.isOn)
  161. {
  162. client.CoordinatesRequest(0, 0, 1, location_id, m.acc_id);
  163. //history_start = true;
  164. end_send[m.acc_id] = false;
  165. }
  166. }
  167. next_time++;
  168. }
  169. if (ToggleLine.isOn)
  170. {
  171. foreach (var m in markers)
  172. m.marker_line.gameObject.SetActive(true);
  173. ToggleDisappearance.interactable = true;
  174. }
  175. else
  176. {
  177. foreach (var m in markers)
  178. {
  179. m.marker_line.gameObject.SetActive(false);
  180. m.marker_line.positionCount = 0;
  181. }
  182. ToggleDisappearance.interactable = false;
  183. }
  184. if (projection.isOn)
  185. {
  186. //camera_2d.SetActive(true);
  187. //camera_2_5D.SetActive(false);
  188. camera.orthographic = true;
  189. }
  190. else
  191. {
  192. //camera_2d.SetActive(false);
  193. //camera_2_5D.SetActive(true);
  194. camera.orthographic = false;
  195. }
  196. }
  197. public static List<Marker> markers = new List<Marker>();
  198. /// <summary>
  199. /// Создание маркера для сотрудника
  200. /// </summary>
  201. /// <param name="acc_id"></param>
  202. void WorkerMarker(uint acc_id, Color color)
  203. {
  204. var toggle = Instantiate(Resources.Load("GameObjects/Toggle", typeof(Toggle))) as Toggle;
  205. toggle.name = acc_id.ToString();
  206. toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = acc_id.ToString();
  207. toggle.transform.SetParent(WorkersList.transform);
  208. var marker = Instantiate(Resources.Load("GameObjects/Capsule", typeof(GameObject))) as GameObject;
  209. marker.name = "marker_" + acc_id.ToString();
  210. marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{acc_id}";
  211. marker.GetComponent<Renderer>().material.color = color; // UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
  212. var marker_line = Instantiate(Resources.Load("GameObjects/Line", typeof(LineRenderer))) as LineRenderer;
  213. marker_line.name = "marker_line_" + acc_id.ToString();
  214. marker_line.startColor = color;
  215. marker_line.endColor = Color.white;
  216. marker_line.material.color = color;
  217. markers.Add(new Marker { acc_id = acc_id, marker = marker, toggle = toggle, marker_line = marker_line });
  218. }
  219. /// <summary>
  220. /// Смена положения маркера
  221. /// </summary>
  222. /// <param name="pause">Задержка</param>
  223. /// <param name="step">Шаг до нового положения</param>
  224. /// <param name="start_pos">Начальное положение</param>
  225. /// <param name="end_pos">Финальное положение</param>
  226. /// <param name="worker_marker">Маркер сотрудника</param>
  227. /// <param name="w">Данные из БД</param>
  228. /// <param name="count">Номер процесса/запуска</param>
  229. /// <param name="progress">Номер записи из БД</param>
  230. /// <param name="all">Всего записей из БД</param>
  231. /// <returns></returns>
  232. //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)
  233. //{
  234. // yield return new WaitForSeconds(pause);
  235. // if (worker_marker.activeSelf == true && history_start && starting[count])
  236. // {
  237. // var x_position = Mathf.Lerp(start_pos.x, end_pos.x, step);
  238. // var y_position = Mathf.Lerp(start_pos.z, end_pos.z, step);
  239. // //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}");
  240. // worker_marker.transform.position = new Vector3(x_position, 0.5f, y_position);
  241. // worker_marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{w.acc_id} x={end_pos.x} y={end_pos.z}";
  242. // toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{w.acc_id} {w.ts:hh:mm:ss}\n{progress + 1} из {all}";
  243. // if (progress + 1 == all)
  244. // {
  245. // sStartStopButton.transform.GetChild(0).GetComponent<Text>().text = "Отобразить";
  246. // starting[count] = false;
  247. // history_start = false;
  248. // }
  249. // }
  250. //}
  251. void Position(float step, Vector3 start_pos, Vector3 end_pos, Marker marker, Structure w, int count, string progress)
  252. {
  253. if (marker.marker.activeSelf == true && starting[count])
  254. {
  255. var x_position = Mathf.Lerp(start_pos.x, end_pos.x, step);
  256. var y_position = Mathf.Lerp(start_pos.z, end_pos.z, step);
  257. //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}");
  258. var new_position = new Vector3(x_position, 0.5f, y_position);
  259. if (marker.marker.transform.position != new_position)
  260. {
  261. marker.marker.transform.position = new Vector3(x_position, 0.5f, y_position);
  262. marker.marker_line.SetPosition(marker.marker_line.positionCount++, new Vector3(x_position, 0, y_position));
  263. if(ToggleDisappearance.isOn)marker.marker_line = LineDisappearance(marker.marker_line);
  264. }
  265. marker.marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{w.acc_id} x={end_pos.x} y={end_pos.z}";
  266. marker.toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{w.acc_id} {w.ts.ToString("hh:mm:ss")}{progress}";
  267. }
  268. }
  269. //static IEnumerator RequestPostion(long ts, long te, uint loc, uint account_id)
  270. //{
  271. // client.CoordinatesRequest(ts, te, 1, loc);
  272. // yield return new WaitForSeconds(5);
  273. // foreach (var t in TestStructures)
  274. // Debug.Log(t);
  275. //}
  276. /// <summary>
  277. /// Запуск отрисовки
  278. /// </summary>
  279. public void ButtonStart()
  280. {
  281. if (active_mode == Mode.Stop)
  282. foreach (var m in markers)
  283. m.marker_line.positionCount = 0;
  284. var button_text = StartStopButton.transform.GetChild(0);
  285. switch (DropdownMode.value)
  286. {
  287. case 0:
  288. //real_time = !real_time;
  289. if (active_mode == Mode.Stop/*real_time*/) {
  290. active_mode = Mode.RealTime;
  291. button_text.GetComponent<Text>().text = "Остановить";
  292. }
  293. else {
  294. active_mode = Mode.Stop;
  295. button_text.GetComponent<Text>().text = "Отобразить";
  296. }
  297. break;
  298. case 1:
  299. if (int.Parse(StartHour.GetComponent<InputField>().text) == 99) SceneManager.LoadScene("Editor3D");
  300. else {
  301. if (active_mode == Mode.Stop/*real_time*/) active_mode = Mode.History;
  302. else active_mode = Mode.Stop;
  303. }//history_start = !history_start;
  304. if (active_mode == Mode.History/*history_start*/)
  305. {
  306. starting.Add(true);
  307. var date = DateTime.Now; var error_date = false;
  308. ////////try
  309. ////////{
  310. //date = DateTime.Parse(inputField_date_text.text);
  311. date = Date.Date;
  312. //////}
  313. //////catch (Exception e)
  314. //////{
  315. ////// ErrorDialog.SetActive(true);
  316. ////// error_date = true;
  317. ////// var text = ErrorDialog.transform.GetChild(0).GetComponent<Text>().text = "Некорректный формат даты";
  318. ////// //history_start = false;
  319. ////// active_mode = Mode.Stop;
  320. //////}
  321. var time_start = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
  322. time_start = time_start.AddHours(int.Parse(StartHour.GetComponent<InputField>().text));
  323. time_start = time_start.AddMinutes(int.Parse(StartMin.GetComponent<InputField>().text));
  324. time_start = time_start.AddSeconds(int.Parse(StartSec.GetComponent<InputField>().text));
  325. Debug.Log(time_start);
  326. //var time_start = new DateTime(1, 1, 1, int.Parse(StartHour.GetComponent<InputField>().text), int.Parse(StartMin.GetComponent<InputField>().text), int.Parse(StartSec.GetComponent<InputField>().text));
  327. //var time_end = new DateTime(1, 1, 1, int.Parse(EndHour.GetComponent<InputField>().text), int.Parse(EndMin.GetComponent<InputField>().text), int.Parse(EndSec.GetComponent<InputField>().text));
  328. var time_end = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
  329. time_end = time_end.AddHours(int.Parse(EndHour.GetComponent<InputField>().text));
  330. time_end = time_end.AddMinutes(int.Parse(EndMin.GetComponent<InputField>().text));
  331. time_end = time_end.AddSeconds(int.Parse(EndSec.GetComponent<InputField>().text));
  332. // client.account_id = 356;
  333. //StartCoroutine(RequestPostion(time_start.Ticks, time_end.Ticks, 22, 356));
  334. if (!error_date)
  335. {
  336. try
  337. {
  338. var location_id = uint.Parse(inputField_location.text);
  339. foreach (var m in markers)
  340. {
  341. if (m.toggle.isOn)
  342. {
  343. client.CoordinatesRequest(time_start.Ticks, time_end.Ticks, 1, location_id, m.acc_id);
  344. end_send[m.acc_id] = false;
  345. }
  346. }
  347. button_text.GetComponent<Text>().text = "Остановить";
  348. }
  349. catch (Exception e)
  350. {
  351. ErrorDialog.SetActive(true);
  352. ErrorDialog.transform.GetChild(0).GetComponent<Text>().text = "Введите идентификатор локации";
  353. //history_start = false;
  354. active_mode = Mode.Stop;
  355. }
  356. }
  357. // 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();
  358. //foreach (var m in markers)
  359. // if (m.toggle.isOn)
  360. // StartingAccPositiong(m);
  361. }
  362. else
  363. {
  364. StopProgress();
  365. }
  366. break;
  367. }
  368. }
  369. public void ErrorDialogClose()
  370. {
  371. ErrorDialog.SetActive(false);
  372. }
  373. void StopProgress()
  374. {
  375. if (starting.Any()) starting[starting.Count - 1] = false;
  376. StartStopButton.transform.GetChild(0).GetComponent<Text>().text = "Отобразить";
  377. foreach (var m in markers)
  378. {
  379. end_send[m.acc_id] = false;
  380. moving.Remove(m.acc_id);
  381. }
  382. }
  383. /// <summary>
  384. /// Затухание траектории
  385. /// </summary>
  386. /// <param name="lineRenderer">Траектория</param>
  387. /// <returns></returns>
  388. LineRenderer LineDisappearance(LineRenderer lineRenderer)
  389. {
  390. //LineRenderer lineRenderer = GetComponent<LineRenderer>();
  391. int newPositionCount = lineRenderer.positionCount - 1;
  392. Vector3[] newPositions = new Vector3[newPositionCount];
  393. for (int i = 0; i < newPositionCount; i++)
  394. {
  395. newPositions[i] = lineRenderer.GetPosition(i + 1);
  396. }
  397. lineRenderer.SetPositions(newPositions);
  398. return lineRenderer;
  399. }
  400. //void StartingAccPositiong(Marker m, float time)
  401. //{
  402. // var worker = Workers[m.acc_id].OrderBy(wr => wr.ts).ToList();
  403. // if (worker.Any())
  404. // {
  405. // var offset = 0.1f;
  406. // for (int i = 0; i < worker.Count; i++)
  407. // {
  408. // var w = worker.ElementAt(i);
  409. // var start_pos = m.marker.transform.position;
  410. // if (i != 0) start_pos = new Vector3(worker.ElementAt(i - 1).coord_x / 100f, 0.5f, worker.ElementAt(i - 1).coord_y / 100f);
  411. // var end_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);
  412. // //if (real_time)
  413. // Position(time, start_pos, end_pos, m, w, starting.Count - 1, "");
  414. // //if (history_start)
  415. // //{
  416. // // for (float j = 0; j <= 1.1f; j += 0.1f) // 1.1f из-за округления float
  417. // // {
  418. // // StartCoroutine(MarkerPostion(i + offset + j, j, start_pos, end_pos, m.marker, m.toggle, w, starting.Count - 1, i, worker.Count));
  419. // // }
  420. // // offset += 0.1f;
  421. // //}
  422. // }
  423. // }
  424. //}
  425. /// <summary>
  426. /// Смена положения по интервалу
  427. /// Шаги для плавного перемещения
  428. /// </summary>
  429. /// <param name="m">Данные о маркере</param>
  430. void StartingAccPositiong(Marker m)
  431. {
  432. int i = 0;
  433. float step = 0.1f;
  434. if (moving.ContainsKey(m.acc_id))
  435. {
  436. if (moving[m.acc_id].index < Workers[m.acc_id].Count) i = moving[m.acc_id].index;
  437. {
  438. if (moving[m.acc_id].step < 1.1f) step = moving[m.acc_id].step;
  439. }
  440. }
  441. else moving[m.acc_id] = new MarkerMoving();
  442. var worker = Workers[m.acc_id].OrderBy(wr => wr.ts).ToList();
  443. if (worker.Any())
  444. {
  445. var w = worker.ElementAt(i);
  446. var start_pos = m.marker.transform.position;
  447. if (i != 0) start_pos = new Vector3(worker.ElementAt(i - 1).coord_x / 100f, 0.5f, worker.ElementAt(i - 1).coord_y / 100f);
  448. if (active_mode == Mode.History && i == 0) start_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);
  449. var end_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);
  450. var progress = "";
  451. if (active_mode == Mode.History) progress = $"\n{i + 1} из {Workers[m.acc_id].Count}";
  452. Position(step, start_pos, end_pos, m, w, starting.Count - 1, progress);
  453. // StartingAccPositiong(m.value, time_step);
  454. }
  455. if (step >= 1) i++;
  456. step += interpolationPeriod; // 0.1f;
  457. moving[m.acc_id].index = i;
  458. moving[m.acc_id].step = step;
  459. }
  460. public void OpenEditor()
  461. {
  462. SceneManager.LoadScene("Scenes/Editor2D");
  463. }
  464. void OnGUI()
  465. {
  466. //if (Input.GetKeyDown(KeyCode.BackQuote))
  467. DebugHelper.DrawConsole();
  468. }
  469. }