using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class PuzzleManager : MonoBehaviour
{
  public static PuzzleManager Instance;

  [SerializeField] private List<GameObject> puzzleItems;

  private List<List<int>> puzzleOrders = new List<List<int>>()
  {
    // new List<int>() { 0, 1, 2, 3, 4, 5, 6, 8, 7 },
    new List<int>() { 8, 0, 1, 4, 5, 2, 3, 6, 7 },
    new List<int>() { 8, 4, 1, 0, 7, 2, 3, 6, 5 },
    new List<int>() { 0, 2, 8, 4, 1, 5, 3, 6, 7 }
  };

  // ==================================================

  private void Awake() => Instance = this;
  private void Start() => Init();

  // ==================================================

  private void Init()
  {
    InitItems();
    Shuffle();
    return;
  }

  // ==================================================
  #region Game相关

  private void Shuffle()
  {
    // 全随机
    // for (int i = 0; i < puzzleItems.Count; i++)
    // {
    //   int randomIndex = UnityEngine.Random.Range(0, puzzleItems.Count);
    //   puzzleItems[i].gameObject.transform.SetSiblingIndex(randomIndex);
    // }

    List<int> currentOrder = puzzleOrders[UnityEngine.Random.Range(0, puzzleOrders.Count)];
    for (int i = 0; i < currentOrder.Count; i++)
    {
      puzzleItems[currentOrder[i]].transform.SetAsLastSibling(); // 把指定序号安排到最底层
    }

    UpdateAllPositions();
    return;
  }

  private void DetectWin()
  {
    if (!CanGameWin()) // 还没赢
    {
      return;
    }

    FindEmptyItem().GetComponent<CanvasGroup>().DOFade(1f, ANIMTIME * 10f);
    GameManager.Instance.GameFinished();
    return;
  }

  private bool CanGameWin()
  {
    for (int i = 0; i < puzzleItems.Count; i++)
    {
      if (puzzleItems[i].transform.GetSiblingIndex() != i)
      {
        return false;
      }
    }
    return true;
  }

  #endregion
  // ==================================================
  #region Item移动

  public void MoveAction(int id)
  {
    if (CanItemMove(id)) // 查询是否可移动
    {
      // Debug.Log($"{id} can move");
      Move(id);
    }
    return;
  }

  private bool CanItemMove(int id)
  {
    ItemHandler moverIH = FindItem(id).GetComponent<ItemHandler>();
    ItemHandler emptyIH = FindEmptyItem().GetComponent<ItemHandler>();

    if (
      (moverIH.Row == emptyIH.Row && (moverIH.Column == emptyIH.Column - 1 || moverIH.Column == emptyIH.Column + 1)) // 同一行的左右互邻
      || // 或
      (moverIH.Column == emptyIH.Column && (moverIH.Row == emptyIH.Row - 1 || moverIH.Row == emptyIH.Row + 1)) // 同一列的上下互邻
    )
    {
      return true;
    }
    else
    {
      return false;
    }
  }

  /// <summary>
  /// 移动
  /// </summary>
  private bool isMoveLock = false;
  private const float ANIMTIME = .33f;
  private void Move(int id)
  {
    if (isMoveLock)
    {
      return;
    }
    isMoveLock = true;

    GameObject mover = FindItem(id);
    GameObject empty = FindEmptyItem();

    // 自己和空白位置交换
    Vector3 moverPosition = mover.transform.position;
    Vector3 emptyPosition = empty.transform.position;
    mover.transform.DOMove(emptyPosition, ANIMTIME);
    empty.transform.DOMove(moverPosition, ANIMTIME).OnComplete(() =>
    {
      // 序号对调
      int moverSiblingIndex = mover.transform.GetSiblingIndex();
      int emptySiblingIndex = empty.transform.GetSiblingIndex();
      mover.transform.SetSiblingIndex(emptySiblingIndex);
      empty.transform.SetSiblingIndex(moverSiblingIndex);

      UpdateAllPositions();
      DetectWin(); // 检查是否完成

      isMoveLock = false;
    });
    return;
  }

  #endregion
  // ==================================================
  #region Item检索

  /// <summary>
  /// 搜索空白Item
  /// </summary>
  /// <returns></returns>
  public GameObject FindEmptyItem()
  {
    return FindItem(8);
  }

  /// <summary>
  /// 搜索Item
  /// </summary>
  /// <returns></returns>
  public GameObject FindItem(int id)
  {
    foreach (var item in puzzleItems)
    {
      if (item.GetComponent<ItemHandler>().ID == id)
      {
        // Debug.Log($"Find Item in {item.GetComponent<ItemHandler>().row}.{item.GetComponent<ItemHandler>().column}");
        return item;
      }
    }
    return null;
  }

  #endregion
  // ==================================================
  #region Item初始化

  /// <summary>
  /// 初始化
  /// </summary>
  private void InitItems()
  {
    UpdateAllIDs();
    UpdateAllPositions();
    return;
  }

  /// <summary>
  /// 更新id
  /// 仅一次
  /// </summary>
  private void UpdateAllIDs()
  {
    foreach (var item in puzzleItems)
    {
      item.GetComponent<ItemHandler>().ID = item.transform.GetSiblingIndex();
    }
    return;
  }

  /// <summary>
  /// 更新坐标
  /// </summary>
  private void UpdateAllPositions()
  {
    foreach (var item in puzzleItems)
    {
      item.GetComponent<ItemHandler>().Row = item.transform.GetSiblingIndex() / 3;
      item.GetComponent<ItemHandler>().Column = item.transform.GetSiblingIndex() % 3;
    }
    return;
  }

  #endregion
}