#include "CPidEditor.h"
#include "resource.h"
#include "CMainEditor.h"
#include "CPidEditorGrid.h"
#include "CPidEditorLang.h"
#include "CPidEditorAniUsing.h"
IMPLEMENT_DYNAMIC(CPidEditor, CDialog)

BEGIN_MESSAGE_MAP(CPidEditor, CDialog)
	ON_COMMAND(IDOK, &CPidEditor::OnEnterKey)
	ON_WM_SIZE()
	ON_WM_MOVING()
	ON_WM_SHOWWINDOW()
	ON_COMMAND(ID_EDIT_PID, &CPidEditor::OnEditPid)
	ON_COMMAND(ID_EDIT_PNG, &CPidEditor::OnEditPng)
	ON_COMMAND(ID_OPEN_FOLDER, &CPidEditor::OnOpenFolder)
	ON_COMMAND(ID_UPDATE_LIST, &CPidEditor::OnUpdateList)
	ON_COMMAND(ID_OPEN_FILE, &CPidEditor::OnOpenFile)
	ON_COMMAND(ID_SAVE_FILE, &CPidEditor::OnSaveFile)
	ON_COMMAND(ID_CLOSE_FILE, &CPidEditor::OnCloseFile)
	ON_COMMAND(ID_UNDO, &CPidEditor::OnUndo)
	ON_COMMAND(ID_REDO, &CPidEditor::OnRedo)
	ON_COMMAND(ID_COPY, &CPidEditor::OnCopy)
	ON_COMMAND(ID_PASTE, &CPidEditor::OnPaste)
	ON_COMMAND(ID_CUT, &CPidEditor::OnCut)
	ON_COMMAND(ID_SHOW_BK, &CPidEditor::OnShowBk)
	ON_COMMAND(ID_SHOW_GRID, &CPidEditor::OnShowGrid)
	ON_COMMAND(ID_GRID_SETTING, &CPidEditor::OnGridSetting)
	ON_COMMAND(ID_SHOW_ID, &CPidEditor::OnShowId)
	ON_COMMAND(ID_BRUSH_WND, &CPidEditor::OnBrushWnd)
	ON_COMMAND(ID_ANI_EDITOR, &CPidEditor::OnAniEditor)
	ON_COMMAND(ID_RESET_WND_POS, &CPidEditor::OnResetWndPos)
	ON_LBN_DBLCLK(IDC_LIST_PNGLIST, &CPidEditor::OnLbnDblclkListPnglist)
	ON_COMMAND(ID_SWITCH_LANGUAGE, &CPidEditor::OnSwitchLanguage)
	ON_COMMAND(ID_PID_SHOW_USING, &CPidEditor::OnPidShowUsing)
	ON_COMMAND(ID_NEXTFRAME, &CPidEditor::OnNextframe)
	ON_COMMAND(ID_PREVFRAME, &CPidEditor::OnPrevframe)
END_MESSAGE_MAP()

CPidEditor::CPidEditor(CWnd* pParent)
	: CDialog(IDD_CPIDEDITOR, pParent)
{
}

CPidEditor::~CPidEditor()
{
}

void CPidEditor::Draw()
{
	pDrawWnd.Draw();
	pBrushWnd.Draw();
	pAniWnd.Draw();
}

void CPidEditor::Load(CString filename)
{
	saved.clear();
	undoRedo.Clear();
	//读取数据文件
	pngfile = filename;
	CString str = filename;
	str = str.Left(filename.ReverseFind(L'.'));
	str.Append(L".pid");
	pidfile = str;
	//子窗口载入
	pDrawWnd.Load(pngfile);
	pBrushWnd.Load(pngfile);
	pAniWnd.Load(pngfile);
	//载入文件数据
	FILE* fp;
	_wfopen_s(&fp, pidfile.GetString(), L"rb");
	if (fp)
	{
		fseek(fp, 0, SEEK_END);
		size_t fileLen = ftell(fp);
		fseek(fp, 0, SEEK_SET);
		std::vector<BYTE> cbuff;
		cbuff.resize(fileLen);
		fread_s(cbuff.data(), fileLen, fileLen, 1, fp);
		fclose(fp);
		std::vector<BYTE> byte_buff;
		size_t len = 0;
		ZLibUncompressData(&byte_buff, &len, cbuff.data(), fileLen);
		CString xml = (wchar_t*)byte_buff.data();
		XMLLoad(xml);//读取pid数据
		pAniWnd.XMLLoad(xml);//读取ani数据
		pAniWnd.Load(pngfile);//读取png
		//赋值
		StepCopyToSaved();
	}
	UpdateMenuState();//更新撤销重做菜单状态
	UpdateWindowTitle();//更新窗口标题
	Draw();
}

void CPidEditor::Save()
{
	StepCopyToSaved();
	CString xml = XMLSaved();//写入pid数据
	xml.Append(pAniWnd.XMLSaved());//写入ani数据
	//数据压缩
	std::vector<BYTE> compressData;
	size_t compressData_len;
	ZLibCompressData(&compressData, &compressData_len, xml.GetString(), ((size_t)xml.GetLength() + 1) * sizeof(wchar_t));//加入\0符
	//文件数据写入
	FILE* fp = nullptr;
	_wfopen_s(&fp, pidfile.GetString(), L"wb+");
	if (!fp)
	{
		CString err;
		err.Format(L"写入%s失败\n文件可能正在被占用", pidfile.GetString());
		MessageBox(err.GetString(), L"文件写入失败", MB_ICONINFORMATION);
		return;
	}
	fwrite(compressData.data(), compressData_len, 1, fp);
	fclose(fp);
	//更新窗口标题
	UpdateWindowTitle();
}

bool CPidEditor::Close()
{
	if (!IsLoaded())
		return false;
	if (!CheckSaved())//如果未保存
	{
		switch (MessageBox(TEXT("想要保存已修改的数据吗？"), TEXT("修改的数据即将丢失"), MB_YESNOCANCEL | MB_ICONWARNING))
		{
		case IDYES:
			Save();
		case IDNO:
			break;
		case IDCANCEL:
			return true;
		}
	}
	ResetContext();
	pAniWnd.ResetContext();
	return false;
}

CPIDEDITOR_DATATYPE_PID* CPidEditor::GetStep()
{
	return (CPIDEDITOR_DATATYPE_PID*)undoRedo.GetStep(CPIDEDITOR_DATATYPE_PID_STR);
}

void CPidEditor::UpdateMenuState()
{
	if (undoRedo.UndoEmpty())
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_UNDO, MF_DISABLED);
	else
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_UNDO, MF_ENABLED);
	if (undoRedo.RedoEmpty())
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_REDO, MF_DISABLED);
	else
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_REDO, MF_ENABLED);
	if (IsLoaded())
	{
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_FILE)->EnableMenuItem(ID_SAVE_FILE, MF_ENABLED);
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_FILE)->EnableMenuItem(ID_CLOSE_FILE, MF_ENABLED);
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_COPY, MF_ENABLED);
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_PASTE, MF_ENABLED);
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_CUT, MF_ENABLED);
	}
	else
	{
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_FILE)->EnableMenuItem(ID_SAVE_FILE, MF_DISABLED);
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_FILE)->EnableMenuItem(ID_CLOSE_FILE, MF_DISABLED);
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_COPY, MF_DISABLED);
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_PASTE, MF_DISABLED);
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_CUT, MF_DISABLED);
	}
}

void CPidEditor::UpdateWindowTitle()
{
	CString windowTitle, appendStr;
	bool sav = CheckSaved();
	auto& view = *pDrawWnd.GetMyView();

	appendStr.Format(TEXT("ID编辑窗口 - "));
	windowTitle.Append(appendStr);
	if (view.cursorX_selected == 0 && view.cursorY_selected == 0)
		appendStr.Format(TEXT("未选中任何ID - "));
	else
		appendStr.Format(TEXT("当前选中的ID：%d - "), view.cursorY_selected * view.count_w + view.cursorX_selected);
	windowTitle.Append(appendStr);
	if (IsLoaded())
	{
		appendStr.Format(TEXT("已载入文件：%s"), pidfile.GetString());
		windowTitle.Append(appendStr);
		if (!sav)
			windowTitle.Append(TEXT("(未保存)"));
		else
			windowTitle.Append(TEXT("(已保存)"));
	}
	else
	{
		windowTitle.Append(TEXT("(未载入文件)"));
	}
	SetWindowText(windowTitle);
}

bool CPidEditor::CheckSaved()
{
	auto &step = *GetStep();
	//排除无效矩形的改动
	CPIDEDITOR_DATATYPE_PID l, r;
	for (auto& p : saved)
	{
		if (p.first == 0)
			continue;
		auto& rc = p.second;
		if (rc.GetWidth() == 0 || rc.GetHeight() == 0)
			continue;
		l.insert(p);
	}
	for (auto& p : step)
	{
		if (p.first == 0)
			continue;
		auto& rc = p.second;
		if (rc.GetWidth() == 0 || rc.GetHeight() == 0)
			continue;
		r.insert(p);
	}
	//其他条件
	bool bPidTile = (pid_tile_w_saved == pid_tile_w &&
		pid_tile_h_saved == pid_tile_h &&
		bInterArea_saved == bInterArea &&
		lineShow_saved == lineShow);
	bool bAniData = pAniWnd.CheckSaved();
	return l == r && bPidTile && bAniData;
}

bool CPidEditor::IsLoaded()
{
	return pidfile.GetLength() > 0;
}

void CPidEditor::ResetContext()
{
	pidfile = L"";
	pngfile = L"";
	saved.clear();
	undoRedo.Clear();
	pDrawWnd.ResetContext();
	pBrushWnd.ResetContext();
	pAniWnd.ResetContext();
	//更新撤销重做菜单状态
	UpdateMenuState();
	//更新窗口标题
	UpdateWindowTitle();
}

CString CPidEditor::GetPngFile()
{
	return pngfile;
}

MyUndoRedo* CPidEditor::GetMyUndoRedo()
{
	return &undoRedo;
}

void CPidEditor::XMLLoad(CString xml)
{
	std::vector<char> utf8_buff;
	UTF16ToUTF8(xml.GetString(), &utf8_buff);
	tinyxml2::XMLDocument xmlDoc;
	xmlDoc.Parse(utf8_buff.data());
	tinyxml2::XMLElement* elem = nullptr;
	//寻找BrushSet元素
	for (tinyxml2::XMLElement* pElem = xmlDoc.FirstChildElement(); pElem; pElem = pElem->NextSiblingElement())
	{
		if (!strcmp(pElem->Name(), "BrushSet"))
		{
			elem = pElem;
			break;
		}
	}
	if (elem)
	{
		//读取BrushSet
		auto pView = pBrushWnd.GetMyView();
		pView->grid_w = elem->FloatAttribute("BrushW");
		pView->grid_h = elem->FloatAttribute("BrushH");
		pView->scale = elem->FloatAttribute("Scale");
		pBrushWnd.UpdateGrid();
	}
	//寻找TileSet元素
	elem = nullptr;
	for (tinyxml2::XMLElement* pElem = xmlDoc.FirstChildElement(); pElem; pElem = pElem->NextSiblingElement())
	{
		if (!strcmp(pElem->Name(), "TileSet"))
		{
			elem = pElem;
			break;
		}
	}
	if (elem)
	{
		//读取TileSet
		pid_tile_w = elem->IntAttribute("TileW");
		pid_tile_h = elem->IntAttribute("TileH");
		bInterArea = elem->BoolAttribute("InterArea");
		lineShow = elem->IntAttribute("LineShow", 16);
		auto drawView = pDrawWnd.GetMyView();
		drawView->count_w = lineShow;
	}
	//寻找Pid元素
	elem = nullptr;
	for (tinyxml2::XMLElement* pElem = xmlDoc.FirstChildElement(); pElem; pElem = pElem->NextSiblingElement())
	{
		if (!strcmp(pElem->Name(), "Pid"))
		{
			elem = pElem;
			break;
		}
	}
	if (elem == nullptr)
	{
		CString err;
		err.Format(L"文件%s找不到Pid元素", pidfile.GetString());
		MessageBox(err.GetString(), L"文件载入错误", MB_ICONWARNING);
		return;
	}
	int max_id = 0;
	//遍历所有的Rect元素
	for (elem = elem->FirstChildElement(); elem; elem = elem->NextSiblingElement())
	{
		//跳过不是Rect的元素
		if (strcmp(elem->Name(), "Rect"))
			continue;
		//给step赋值
		MyRect rc;
		auto& step = *((CPIDEDITOR_DATATYPE_PID*)undoRedo.GetStep(CPIDEDITOR_DATATYPE_PID_STR));
		rc.left = elem->FloatAttribute("left");
		rc.right = elem->FloatAttribute("right");
		rc.top = elem->FloatAttribute("top");
		rc.bottom = elem->FloatAttribute("bottom");
		int id = elem->IntAttribute("id");
		if (id > max_id)
			max_id = id;
		step[id] = rc;
	}
	pDrawWnd.GetMyView()->count_max = max_id + 1 + 4 * lineShow;
}

CString CPidEditor::XMLSaved()
{
	//写入xml文件
	tinyxml2::XMLDocument xmlDoc;
	//写入BrushSet元素
	auto elem_brushSet = xmlDoc.NewElement("BrushSet");
	elem_brushSet->SetAttribute("BrushW", pBrushWnd.GetMyView()->grid_w);
	elem_brushSet->SetAttribute("BrushH", pBrushWnd.GetMyView()->grid_h);
	elem_brushSet->SetAttribute("Scale", pBrushWnd.GetMyView()->scale);
	xmlDoc.InsertEndChild(elem_brushSet);
	//写入TileSet元素
	auto elem_tileSet = xmlDoc.NewElement("TileSet");
	elem_tileSet->SetAttribute("TileW", pid_tile_w);
	elem_tileSet->SetAttribute("TileH", pid_tile_h);
	elem_tileSet->SetAttribute("InterArea", bInterArea);
	elem_tileSet->SetAttribute("LineShow", lineShow);
	xmlDoc.InsertEndChild(elem_tileSet);
	//写入Pid元素
	auto elem_pid = xmlDoc.NewElement("Pid");
	xmlDoc.InsertEndChild(elem_pid);
	//写入pid数据
	for (auto& p : saved)
	{
		if (p.first == 0)
			continue;
		MyRect& rc = p.second;
		if (rc.GetWidth() == 0 || rc.GetHeight() == 0)
			continue;
		auto elem_id = xmlDoc.NewElement("Rect");
		elem_id->SetAttribute("id", p.first);
		elem_id->SetAttribute("top", rc.top);
		elem_id->SetAttribute("bottom", rc.bottom);
		elem_id->SetAttribute("left", rc.left);
		elem_id->SetAttribute("right", rc.right);
		elem_pid->InsertEndChild(elem_id);
	}
	//写出到文件
	tinyxml2::XMLPrinter xmlPrinter;
	xmlDoc.Print(&xmlPrinter);
	std::vector<wchar_t> wchar_buff;
	UTF8ToUTF16(xmlPrinter.CStr(), &wchar_buff);
	return CString(wchar_buff.data());
}

CString CPidEditor::GetPidFile()
{
	return pidfile;
}

void CPidEditor::SetAni(int id)
{
	if (!IsLoaded())
		return;
	pAniWnd.SetAniID(id);
}

void CPidEditor::AniIDSetRect(int id, MyRect* rc)
{
	auto& step = *GetStep();
	*rc = step[id];
}

bool CPidEditor::IsBrushWndShow()
{
	return pBrushWnd.IsWindowVisible();
}

bool CPidEditor::IsAniWndShow()
{
	return pAniWnd.IsWindowVisible();
}

BOOL CPidEditor::PreTranslateMessage(MSG* pMsg)
{
	HOTKEYPROC;
}

void CPidEditor::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	static_pngList = (CStatic*)GetDlgItem(IDC_STATIC_PNGLIST);
	DDX_Control(pDX, IDC_LIST_PNGLIST, listbox_pngList);
	static_idEditor = (CStatic*)GetDlgItem(IDC_STATIC_IDEDITOR);
}

void* CPidEditor_Pid_NewData()
{
	return new CPIDEDITOR_DATATYPE_PID();
}
void* CPidEditor_Pid_NewCopyOfData(void* data)
{
	CPIDEDITOR_DATATYPE_PID* pStep = (CPIDEDITOR_DATATYPE_PID*)data;
	CPIDEDITOR_DATATYPE_PID* pNewStep = new CPIDEDITOR_DATATYPE_PID();
	*pNewStep = *pStep;
	return pNewStep;
}
void CPidEditor_Pid_ReleaseData(void* data)
{
	CPIDEDITOR_DATATYPE_PID* pStep = (CPIDEDITOR_DATATYPE_PID*)data;
	delete pStep;
}

BOOL CPidEditor::OnInitDialog()
{
	CDialog::OnInitDialog();
	//载入快捷键
	LOADHOTKEY(IDR_ACC_PIDEDITOR);
	//设置应用程序图标
	auto hIcon = AfxGetApp()->LoadIcon(IDI_ICON_PID);
	SetIcon(hIcon, true);
	//设置撤销重做功能
	MyUndoRedoDataOp op_pid;
	op_pid.NewData = CPidEditor_Pid_NewData;
	op_pid.NewCopyOfData = CPidEditor_Pid_NewCopyOfData;
	op_pid.ReleaseData = CPidEditor_Pid_ReleaseData;
	undoRedo.AddDataType(CPIDEDITOR_DATATYPE_PID_STR, op_pid);
	//设置listbox_pngList
	listbox_pngList.SetMenu(IDR_CPIDEDITOR_RMENU, IDR_CPIDEDITOR_RMENU_NOSEL);
	//初始化子窗口
	pDrawWnd.pParentEditor = this;
	pDrawWnd.Create(IDD_CPIDEDITOR_DRAW, this);
	pDrawWnd.ShowWindow(SW_SHOW);
	pBrushWnd.pParentEditor = this;
	pBrushWnd.pDrawWndView = pDrawWnd.GetMyView();
	pBrushWnd.Create(IDD_CPIDEDITOR_BRUSH, this);
	pAniWnd.pParentEditor = this;
	pAniWnd.pPid_tile_w = &pid_tile_w;
	pAniWnd.pPid_tile_h = &pid_tile_h;
	pAniWnd.Create(IDD_CANIEDITOR, this);
	//设置初始化
	showGrid = false;
	OnShowGrid();//启用网格
	showBk = false;
	OnShowBk();//启用透明背景
	showID = false;
	//更新列表
	OnUpdateList();
	//重置窗口位置
	OnResetWndPos();
	//更新撤销重做菜单状态
	UpdateMenuState();
	//更新窗口标题
	UpdateWindowTitle();
	languageSel = L"默认";
	return 0;
}

void CPidEditor::OnCancel()
{
	if (Close())
		return;
	ShowWindow(SW_HIDE);
}

void CPidEditor::OnEnterKey()
{
}

void CPidEditor::OnSize(UINT nType, int cx, int cy)
{
	CDialog::OnSize(nType, cx, cy);
	if (!static_pngList)
		return;
	auto dpi = MyGetDPI();
	//贴图列表
	int x, y, w, h;
	x = DPISCALE(10);
	y = DPISCALE(10);
	w = DPISCALE(200);
	h = cy - DPISCALE(20);
	static_pngList->MoveWindow(x, y, w, h);
	y += DPISCALE(20);
	h -= DPISCALE(20);
	listbox_pngList.MoveWindow(x, y, w, h);
	//ID编辑器
	x = DPISCALE(220);
	y = DPISCALE(10);
	w = cx - DPISCALE(230);
	h = cy - DPISCALE(20);
	static_idEditor->MoveWindow(x, y, w, h);
	y += DPISCALE(20);
	h -= DPISCALE(20);
	w -= DPISCALE(1);
	pDrawWnd.MoveWindow(x, y, w, h);
}

void CPidEditor::OnMoving(UINT fwSide, LPRECT pRect)
{
	CDialog::OnMoving(fwSide, pRect);
	OnResetWndPos();
}

void CPidEditor::OnShowWindow(BOOL bShow, UINT nStatus)
{
	CDialog::OnShowWindow(bShow, nStatus);
	auto mainEditor = (CMainEditor*)pMainEditor;
	if (bShow)
		mainEditor->GetMenu()->GetSubMenu(CMAINEDITOR_MENUINDEX_GAMEEDITOR)->CheckMenuItem(ID_PID_EDITOR, MF_BYCOMMAND | MF_CHECKED);
	else
	{
		mainEditor->GetMenu()->GetSubMenu(CMAINEDITOR_MENUINDEX_GAMEEDITOR)->CheckMenuItem(ID_PID_EDITOR, MF_BYCOMMAND | MF_UNCHECKED);
		pBrushWnd.ShowWindow(SW_HIDE);
	}
}

void CPidEditor::OnEditPid()
{
	if (Close())
		return;
	int sel = listbox_pngList.GetCurSel();
	CString name;
	listbox_pngList.GetText(sel, name);
	CString filename;
	if (languageSel.GetLength() == 0 || languageSel == L"默认")
		filename.Format(L"./data/pid/%s", name.GetString());
	else
		filename.Format(L"./data/language/%s/pid/%s",languageSel.GetString(), name.GetString());
	Load(filename);
}


void CPidEditor::OnEditPng()
{
	int selIndex = listbox_pngList.GetCurSel();
	if (selIndex < 0)
		return;
	wchar_t buff[MAX_PATH];
	CString filepath;
	GetModuleFileNameW(nullptr, buff, _countof(buff));
	filepath = buff;
	auto index = filepath.ReverseFind(L'\\');
	filepath.Delete(index, filepath.GetLength() - index);
	if (languageSel.GetLength() == 0 || languageSel == L"默认")
	{
		filepath.Append(L"\\data\\pid\\");
	}
	else
	{
		CString buff;
		buff.Format(L"\\data\\language\\%s\\pid\\", languageSel.GetString());
		filepath.Append(buff.GetString());
	}
	CString pngfile;

	listbox_pngList.GetText(selIndex, pngfile);
	filepath.Append(pngfile);

	CString cmd;
	cmd.Format(L"explorer \"%s\"", filepath.GetString());
	MyWinExec(cmd.GetString());
}


void CPidEditor::OnOpenFolder()
{
	std::vector<char> utf8_buff;
	wchar_t buff[MAX_PATH];
	CString filepath;
	GetModuleFileNameW(nullptr, buff, _countof(buff));
	filepath = buff;
	auto index = filepath.ReverseFind(L'\\');
	filepath.Delete(index, filepath.GetLength() - index);
	if (languageSel.GetLength() == 0 || languageSel == L"默认")
	{
		filepath.Append(L"\\data\\pid\\");
	}
	else
	{
		CString buff;
		buff.Format(L"\\data\\language\\%s\\pid\\", languageSel.GetString());
		filepath.Append(buff.GetString());
	}

	CString cmd;
	index = listbox_pngList.GetCurSel();
	if (index >= 0)
	{
		CString pngfile;
		listbox_pngList.GetText(index, pngfile);
		filepath.Append(pngfile);
		cmd.Format(L"explorer /select,%s", filepath.GetString());
	}
	else
	{
		cmd.Format(L"explorer %s", filepath.GetString());
	}
	MyWinExec(cmd.GetString());
}

void CPidEditor::OnUpdateList()
{
	listbox_pngList.ResetContent();
	if (languageSel.GetLength() == 0 || languageSel == L"默认")
	{
		CFileFind finder;
		bool rs = finder.FindFile(L"./data/pid/*.png");
		while (rs)
		{
			rs = finder.FindNextFile();
			CString str = finder.GetFileName();
			listbox_pngList.AddString(str);
		}
	}
	else
	{
		CString path;
		path.Format(L"./data/language/%s/pid/*.png", languageSel.GetString());
		CFileFind finder;
		bool rs = finder.FindFile(path.GetString());
		while (rs)
		{
			rs = finder.FindNextFile();
			CString str = finder.GetFileName();
			listbox_pngList.AddString(str);
		}
	}
}

void CPidEditor::OnOpenFile()
{
	if (Close())
		return;
	wchar_t buff[MAX_PATH];
	CString filepath;
	GetModuleFileNameW(nullptr, buff, _countof(buff));
	filepath = buff;
	auto index = filepath.ReverseFind(L'\\');
	filepath.Delete(index, filepath.GetLength() - index);
	filepath.Append(L"\\data\\pid\\");
	CFileDialog fd(TRUE, TEXT(""), TEXT(""), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, TEXT("图像文件(*.png)|*.png|所有文件(*.*)|*.*||"), this);
	fd.m_ofn.lpstrInitialDir = filepath.GetString();
	if (fd.DoModal() != IDOK)
		return;
	Load(fd.GetPathName());
	UpdateMenuState();
	UpdateWindowTitle();
}


void CPidEditor::OnSaveFile()
{
	if (!IsLoaded())
		return;
	Save();
}


void CPidEditor::OnCloseFile()
{
	Close();
}


void CPidEditor::OnUndo()
{
	undoRedo.Undo();
	UpdateMenuState();
	UpdateWindowTitle();
	Draw();
}


void CPidEditor::OnRedo()
{
	undoRedo.Redo();
	UpdateMenuState();
	UpdateWindowTitle();
	Draw();
}

void CPidEditor::OnCopy()
{
	if (!IsLoaded())
		return;
	rcCopy = pDrawWnd.GetCopyRect();
}


void CPidEditor::OnPaste()
{
	if (!IsLoaded())
		return;
	pDrawWnd.SetCopyRect(rcCopy);
	UpdateMenuState();
	UpdateWindowTitle();
	Draw();
}


void CPidEditor::OnCut()
{
	if (!IsLoaded())
		return;
	rcCopy = pDrawWnd.GetCopyRect();
	MyRect rc;
	pDrawWnd.SetCopyRect(rc);
	UpdateMenuState();
	UpdateWindowTitle();
	Draw();
}

void CPidEditor::OnShowBk()
{
	if (showBk)
	{
		showBk = false;
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_BK, MF_BYCOMMAND | MF_UNCHECKED);
	}
	else
	{
		showBk = true;
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_BK, MF_BYCOMMAND | MF_CHECKED);
	}
	Draw();
}


void CPidEditor::OnShowGrid()
{
	if (showGrid)
	{
		showGrid = false;
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_GRID, MF_BYCOMMAND | MF_UNCHECKED);
	}
	else
	{
		showGrid = true;
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_GRID, MF_BYCOMMAND | MF_CHECKED);
	}
	Draw();
}


void CPidEditor::OnGridSetting()
{
	CPidEditorGrid dlg;
	auto drawView = pDrawWnd.GetMyView();
	dlg.outGridW = (int)drawView->grid_w;
	dlg.outGridH = (int)drawView->grid_h;
	dlg.outCountW = lineShow = drawView->count_w;
	dlg.outMaxID = drawView->count_max - 1;
	dlg.outTileW = pid_tile_w;
	dlg.outTileH = pid_tile_h;
	dlg.outInterArea = bInterArea;
	if (dlg.DoModal() != IDOK)
		return;
	drawView->grid_w = (float)dlg.outGridW;
	drawView->grid_h = (float)dlg.outGridH;
	lineShow = drawView->count_w = dlg.outCountW;
	drawView->count_max = dlg.outMaxID + 1;
	pid_tile_w = dlg.outTileW;
	pid_tile_h = dlg.outTileH;
	bInterArea = dlg.outInterArea;
	Draw();
	UpdateWindowTitle();
}

void CPidEditor::OnShowId()
{
	if (showID)
	{
		showID = false;
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_ID, MF_BYCOMMAND | MF_UNCHECKED);
	}
	else
	{
		showID = true;
		GetMenu()->GetSubMenu(CPIDEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_ID, MF_BYCOMMAND | MF_CHECKED);
	}
	Draw();
}


void CPidEditor::OnBrushWnd()
{
	pBrushWnd.ShowWindow(pBrushWnd.IsWindowVisible() ? SW_HIDE : SW_SHOW);
}

void CPidEditor::OnAniEditor()
{
	pAniWnd.ShowWindow(pAniWnd.IsWindowVisible() ? SW_HIDE : SW_SHOW);
}


void CPidEditor::OnResetWndPos()
{
	CRect rcDst, rcSrc;
	GetWindowRect(rcDst);
	pBrushWnd.GetWindowRect(rcSrc);
	MoveToNeighborRect(rcDst, rcSrc, 1, 0);
	::MoveWindow(&pBrushWnd, rcSrc.left, rcSrc.top);
}

void CPidEditor::OnLbnDblclkListPnglist()
{
	int selIndex = listbox_pngList.GetCurSel();
	if (selIndex < 0)
		return;
	OnEditPid();
}

void CPidEditor::OnSwitchLanguage()
{
	CPidEditorLang dlg;
	dlg.languageSel = languageSel;
	if (dlg.DoModal() != IDOK)
		return;
	if (languageSel == dlg.languageSel)
		return;
	languageSel = dlg.languageSel;
	//刷新目录
	OnUpdateList();
}

void CPidEditor_OnPidShowUsing_Foreach(std::vector<std::wstring>* addList, std::wstring aniNameNow, std::vector<MyAniLayer>* aniLayer, int dstID)
{
	for (auto& layer : *aniLayer)
	{
		for (auto& frame : layer.rcList)
		{
			if (frame.id == dstID)
			{
				addList->push_back(aniNameNow);
				return;
			}
		}
	}
}

void CPidEditor::OnPidShowUsing()
{
	auto pView = pDrawWnd.GetMyView();
	int id = pView->cursorY * pView->count_w + pView->cursorX;
	CPidEditorAniUsing dlg;
	//寻找正在使用该id的动画
	auto& aniList = *pAniWnd.GetAniList();
	dlg.inID = id;
	for (auto& ani : aniList)
	{
		auto& step = *ani.second.GetStep();
		CPidEditor_OnPidShowUsing_Foreach(&dlg.inAniList, ani.first, &step, id);
	}
	dlg.DoModal();
}

void CPidEditor::OnNextframe()
{
	pAniWnd.OnNextframe();
}

void CPidEditor::OnPrevframe()
{
	pAniWnd.OnPrevframe();
}

void CPidEditor::StepCopyToSaved()
{
	saved = *((CPIDEDITOR_DATATYPE_PID*)undoRedo.GetStep(CPIDEDITOR_DATATYPE_PID_STR));
	pid_tile_w_saved = pid_tile_w;
	pid_tile_h_saved = pid_tile_h;
	bInterArea_saved = bInterArea;
	lineShow_saved = lineShow;
	pAniWnd.StepCopyToSaved();
}

