//---------------------------------------------------------------------------
#include <vcl.h>
#include <Vcl.Imaging.pngimage.hpp>
#include <stdio.h>

#pragma hdrstop

#include "GlobalUnit.h"
#include "AudStylePanel.h"
#include "MessageFormUnit.h"
#include "FavorTextureUnit.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)

#define LIST_RECOMMAND	0
#define LIST_ORIGIN		1
#define LIST_SHARE		2
#define LIST_LOCAL		3
#define LIST_COLLECTION	4


__fastcall TAudStylePanel::TAudStylePanel(TComponent* AOwner)
	: TStylePanel(AOwner)
{
	m_strTitle = "风格库";
	AddToolBtn( 3, "imgTabSelect", CMClick, "筛选与排序" );
	m_nBtnCount = 1;

	AddToolBtn( 3, "imgTabLocal", ListTypeClick, "本地自定义风格" );
	m_lstBtnTools[m_nBtnCount++]->Tag = LIST_LOCAL;

	AddToolBtn( 3, "imgTabCollect", ListTypeClick, "收藏的风格" );
	m_lstBtnTools[m_nBtnCount++]->Tag = LIST_COLLECTION;

	if( SOFTWARE_ID!=e_Pro_Lite ){
		AddToolBtn( 3, "imgTabShare", ListTypeClick, "网友分享的组合风格" );
		m_lstBtnTools[m_nBtnCount++]->Tag = LIST_SHARE;
	}

	AddToolBtn( 3, "imgTabRelease", ListTypeClick, "在线发布的原创风格" );
	m_lstBtnTools[m_nBtnCount++]->Tag = LIST_ORIGIN;

	AddToolBtn( 3, "imgTabRecom", ListTypeClick, "官方推荐风格" );
	m_lstBtnTools[m_nBtnCount++]->Tag = LIST_RECOMMAND;

	m_SearchPanel = new TStyleSelPanel(this);           //搜索面板
	m_SearchPanel->Parent = this;
	m_SearchPanel->Visible = false;
	m_SearchPanel->Left = 1;
	m_SearchPanel->Top = 25;

	m_editName = new TEdit(this);
	m_editName->Parent = this;
	m_editName->HideSelection = false;
	m_editName->BorderStyle = bsNone;
	m_editName->MaxLength = 39;

	m_editName->Font->Name = g_strTxtFontName;
	m_editName->Font->Quality = TFontQuality::fqClearTypeNatural;
	m_editName->Font->Size = g_szFont9;

	m_editName->OnMouseDown = EditMouseDown;
	m_editName->OnMouseUp = EditMouseUp;
	m_editName->OnMouseMove = EditMouseMove;
	m_editName->OnKeyDown = EditKeyDown;
	m_editName->OnChange = EditChange;

	m_iListType = 0;

	m_bDoubleClick = false;
	m_RenameTimer = NULL;
}
//---------------------------------------------------------------------------

__fastcall TAudStylePanel::~TAudStylePanel()
{
	ClearFavorTextures( true );
}
//---------------------------------------------------------------------------

void TAudStylePanel::Init()
{
//	InsColGet();
	if( g_aOriginStyles.empty() ){
		SelectStyle();
	}

	if( m_SearchPanel ){
		m_SearchPanel->Reset();
		if( ((TPNGButton*)m_lstBtnTools[0])->Down ){
			CMClick( NULL );
		}
	}

	m_iListType = LIST_RECOMMAND;
	for( int i=0; i<m_nBtnCount-1; i++ ){
		m_lstBtnTools[i]->Down = false;
	}
	m_lstBtnTools[m_nBtnCount-1]->Down = true;

	GetFavorTextures();
	RefreshList();
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::UMSearchStyle(TMessage &msg)
{
	Stop( STOP_SELF );
	ClearAllItems();

	RefreshList();

	CalcViewArea();
	ResetScrollBar();
	InvalidateRgn( Handle, NULL, false );
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::DoubleClick(TObject* sender)
{
	if( m_pSelItem && m_iFocCol==COL_TEXT ){
		int iOnline = m_pSelItem->GetOnlineState();
		if( iOnline==e_Downloaded ){
			PlayDemo( m_pSelItem, -1 );
		}
		else if( iOnline==e_UnDownload ){
			DoDownload( sender );
		}

		m_bDoubleClick = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::DoCollect(TObject* Sender)
{
	if( m_pFocItem->iType==SEGTYPE_STYLE )
		SetCollect(m_pFocItem);
	else if( m_pFocItem->iType==SEGTYPE_TRACK ){
		TTrackItem *pTrk = (TTrackItem*)m_pFocItem;
		bool bSet = !pTrk->IsCollected();
//		InsColSet( (TTrackItem*)m_pFocItem, bCollected);
//		pTrk->SetCollect( bSet );

		SetFavorTexture( pTrk->pStyle->idLoc, pTrk->pStyle->idStyle, pTrk->GetSegType(),
													pTrk->GetSegNo(), pTrk->pTrack->iChanNo, bSet );
	}

	DrawItem( m_pFocItem, m_iFocLine, -1 );
}
// ---------------------------------------------------------------------------

void TAudStylePanel::PlayDemo( TCommonItem *pItem, int tempo )
{
	TStylePanel::PlayDemo( pItem, g_iMelodyKey<0 ? -1 : g_nMelodyTempo );
}
//---------------------------------------------------------------------------

bool TAudStylePanel::StartDrag()
{
	bool bCanDrag = m_pFocItem->GetOnlineState()==e_Downloaded; //可选风格已下载

	if( m_SearchPanel->DInStr.Length>0 && m_pFocItem->iType!=SEGTYPE_TRACK )
		bCanDrag = false;

	return bCanDrag;
}
//---------------------------------------------------------------------------

void TAudStylePanel::SetDownload( TCommonItem *pItem )
{
	TStyleItem* pStyItem = pItem->GetStyleItem() ;
	pStyItem->SetDownload();

	//查找当前行号
	TCommonItem *pFind = m_pTopItem;
	for( int i=0; i<m_nItemShow && pFind; i++ ){
		if( pFind->GetStyleItem()==pStyItem ){
			DrawItem( pFind, i, COL_TEXT );
		}

		pFind = GetNextItem( pFind );
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::OnNetworkMessage(TMessage &msg)
{
	WORD eMessage = HIWORD(msg.WParam);
	WORD eExtra = LOWORD(msg.WParam);

	switch (eMessage) {
	case e_styleInfoResponse:
		{
			if( 0!=eExtra && eExtra!=e_ShareStyle )
				break;

			int iStyleId = msg.LParam;
			int idLoc = eExtra==e_ShareStyle ? 1 : 0;

			TPROSTYLE infoStyle;
			if( idLoc==0 )
				infoStyle.pOrigin = new TSTYLEORIGIN;
			else
				infoStyle.pShare = new TSTYLESHARE;

			int ret = f_CM_GetStyleInfo( idLoc, iStyleId, &infoStyle );

			if( ret==0 ){
				if( idLoc==0 && infoStyle.pOrigin->detail.iTimesignature!=g_iMelodyTimeSignature )
					break;

				if( idLoc==1 && infoStyle.pShare->iTimesignature!=g_iMelodyTimeSignature )
					break;

				bool bNew = false;
				TPROSTYLE* pInfo = GetStyleInfo( idLoc, iStyleId );

				if( !pInfo ){
					pInfo = new TPROSTYLE;
					if( idLoc==0 )
						pInfo->pOrigin = new TSTYLEORIGIN;
					else
						pInfo->pShare = new TSTYLESHARE;

					bNew = true;
				}

				pInfo->idLoc = infoStyle.idLoc;
				pInfo->idStyle = infoStyle.idStyle;
				if( idLoc==0 )
					memcpy( pInfo->pOrigin, infoStyle.pOrigin, sizeof(TSTYLEORIGIN) );
				else
					memcpy( pInfo->pShare, infoStyle.pShare, sizeof(TSTYLESHARE) );

				if( bNew ){
					STYLELIST& aStyles = idLoc==0 ? g_aOriginStyles : g_aShareStyles;

					int index = 0;
					for( int i=aStyles.size()-1; i>=0; i-- ){
						if( pInfo->idStyle > aStyles[i]->idStyle ){
							index = i+1;
							break;
						}
					}

					if( index>=aStyles.size() )
						aStyles.push_back( pInfo );
					else
						aStyles.insert( aStyles.begin()+index, pInfo );

					if( idLoc==0 && m_iListType==LIST_ORIGIN ||
								idLoc==1 && m_iListType==LIST_SHARE ){
						int iLine = m_nTotalLine - m_iTopLine;

						TStyleItem* pStyItem = AddStyleItem( pInfo,
													IsCollected( pInfo->idLoc, pInfo->idStyle ) );

						ResetScrollBar();

						if( iLine<m_nItemShow )
							DrawItem( pStyItem, iLine, -1 );
					}
				}
			}
			else{
				TPROSTYLE* pInfo = GetStyleInfo( idLoc, iStyleId );

				if( pInfo ){
/*					pInfo->pOrigin->cost = -1;

					TStyleItem * pStyItem = NULL;
					for( int i=0; i<m_aItems->Count; i++ ){
						TStyleItem *pItem = (TStyleItem*)m_aItems->Items[i];
						if( pItem->pStyle->idLoc==0 && pItem->pStyle->idStyle==iStyleId ){
							pStyItem = pItem;
							break;
						}
					}

					//从列表中删除
					if( pStyItem ){
						DeleteItem( pStyItem, iLine );
					}
*/
					DeleteStyleInfo( idLoc, iStyleId );
				}
			}
		}
		break;

	case e_styleDataResponse: // download the style data
		{
			if( 0!=eExtra )
				break;

			int iRet = 0;
			int iStyleId = msg.LParam;

			TPROSTYLE* pInfo = GetStyleInfo( 0, iStyleId );

			if( pInfo && pInfo->pOrigin->state!=e_Downloaded ){
				pInfo->pOrigin->state = e_Downloaded;

				if( m_iListType==LIST_ORIGIN || m_iListType==LIST_RECOMMAND ){
					for( int i=0; i<m_aItems->Count; i++ ){
						TStyleItem* pItem = (TStyleItem*)m_aItems->Items[i];
						if( pItem->pStyle && pItem->pStyle==pInfo ){
							//刷新显示
							SetDownload( pItem );
							break;
						}
					}
				}
				else if( m_iListType==LIST_SHARE ){
					for( int i=0; i<m_aItems->Count; i++ ){
						TStyleItem* pStyItem = (TStyleItem*)m_aItems->Items[i];
						bool bSet = false;
						for( int j=0; !bSet && j<pStyItem->aItems->Count; j++ ){
							TSegmentItem* pSeg = (TSegmentItem*)pStyItem->aItems->Items[j];
							for( int k=0; k<pSeg->aItems->Count; k++ ){
								TTrackItem* pTrk = (TTrackItem*)pSeg->aItems->Items[k];
								if( pTrk->pStyle==pInfo ){
									SetDownload( pStyItem );
									bSet = true;
									break;
								}
							}
						}
					}
				}
			}
		}
		break;

	case e_styleRecomResponse:
		{
			if( 0!=eExtra )
				break;

			//获取推荐列表
			int nRecomNum = 50;
			DWORD idRecoms[50];

			f_CM_GetStyleRecomIDs( g_iMelodyTimeSignature, idRecoms, &nRecomNum );

			if( nRecomNum==0 )
				break;

			g_aRecomStyles.clear();
			for( int i=0; i<g_aOriginStyles.size(); i++ ){
				TPROSTYLE* pInfo = g_aOriginStyles[i];

				for( int j=0; j<nRecomNum; j++ ){
					if( idRecoms[j]==pInfo->idStyle ){
						g_aRecomStyles.push_back( pInfo );
						break;
					}
				}
			}

			if( m_iListType==LIST_RECOMMAND && m_aItems->Count==0 ){
				PostMessage( Handle, UM_SEARCH, 0, 0 );
			}
		}
		break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::OnNetworkError(TMessage &msg)
{
	WORD eMessage = HIWORD(msg.WParam);
	WORD eExtra = LOWORD(msg.WParam);

	DebugPrint("网络访问错误，消息号：%d，错误号：0x%X\n", eMessage, eExtra);
}
// ---------------------------------------------------------------------------

void __fastcall TAudStylePanel::CMClick(System::TObject* Sender)         //add ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{
	m_SearchPanel->Visible = !m_SearchPanel->Visible;
	((TPNGButton*)m_lstBtnTools[0])->Down = m_SearchPanel->Visible;	//按钮

	Winapi::Messages::TWMSize Message;
	Message.Width = Width;
	Message.Height = Height;
	WMSize(Message);

	InvalidateRgn( Handle, NULL, false );
}

void __fastcall TAudStylePanel::WMSize(Winapi::Messages::TWMSize &Message)
{
	if( m_SearchPanel && m_SearchPanel->Width != Width-2 )
		m_SearchPanel->Width = Width-2;

	if( m_SearchPanel && m_SearchPanel->Visible ){
		m_nTitleHeight = 25 + m_SearchPanel->Height;
	}
	else{
		m_nTitleHeight = 25;
	}

	TStylePanel::WMSize(Message);
}

bool TAudStylePanel::IsCollected( UINT idLoc, UINT idStyle )
{
	for( int i=0; i<g_aCollectStyles.size(); i++ ){
		if( g_aCollectStyles[i]->idLoc==idLoc && g_aCollectStyles[i]->idStyle==idStyle ){
			return true;
		}
	}

	return false;
}
//---------------------------------------------------------------------------

DWORD TAudStylePanel::GetStyleOptions( TPROSTYLE* info )
{
	DWORD dwOpts = 0;

	if( info->idLoc==0 ){
		dwOpts |= OPT_SCORE;

		if( info->pOrigin->state!=e_Downloaded )
			dwOpts |= OPT_DOWNLOAD;
		else
			dwOpts |= OPT_COLLECT;

		if( info->pOrigin->cost>0 )
			dwOpts |= OPT_CHARGE;
	}
	else if( info->idLoc==1 ){
		dwOpts |= OPT_SCORE;

		bool bDownloaded = true,
			bCharge = false;
		for( int s=0; s<4; s++ ){
			int rep = s<2 ? 1 : 2;
			for( int r=0; r<rep; r++ ){
				int nSegNum = info->pShare->nSegNum[s];
				int iStart = r * 4,
					iEnd = iStart + ( r==0 ? ( nSegNum & 0x0F ) : ( nSegNum>>4 ));

				for( int n=iStart; n<iEnd; n++ ){
					for( int t=0; t<16 && info->pShare->trkRef[s][n][t].idStyle>0; t++ ){
						TPROSTYLE* pTrkInfo = GetStyleInfo( 0, info->pShare->trkRef[s][n][t].idStyle );
						if(!pTrkInfo){
							bDownloaded = false;
							goto LINE_BREAK;
						}

						if( bDownloaded && pTrkInfo->pOrigin->state!=e_Downloaded ){
							bDownloaded = false;
							if( bCharge )
								goto LINE_BREAK;
						}

						if( !bCharge && pTrkInfo->pOrigin->cost>0 ){
							bCharge = true;
							if( !bDownloaded )
								goto LINE_BREAK;
						}
					}
				}
			}
		}
LINE_BREAK:
		if( !bDownloaded )
			dwOpts |= OPT_DOWNLOAD;
		else
			dwOpts |= OPT_COLLECT;

		if( bCharge )
			dwOpts |= OPT_CHARGE;
	}
	else{
		dwOpts = OPT_DEL | OPT_UPLOAD;
	}

	return dwOpts;
}
//---------------------------------------------------------------------------

String TAudStylePanel::ChargeTip( TStyleItem* pItem )
{
	String strTip;

	if( pItem->pStyle->idLoc==0 ){
		strTip = "收费：";
		strTip += IntToStr( ((TStyleItem*)pItem)->pStyle->pOrigin->cost );
		strTip += "唱作音符";
	}
	else if( pItem->pStyle->idLoc==1 ){
		strTip = "    包含收费风格\n\n  风格   唱作音符\n";
		strTip += "------------------------";

		STYLELIST aStyles;
		TPROSTYLE* info = pItem->pStyle;
		char buf[512];

		for( int s=0; s<4; s++ ){
			int rep = s<2 ? 1 : 2;
			for( int r=0; r<rep; r++ ){
				int nSegNum = info->pShare->nSegNum[s];
				int iStart = r * 4,
					iEnd = iStart + ( r==0 ? ( nSegNum & 0x0F ) : ( nSegNum>>4 ));

				for( int n=iStart; n<iEnd; n++ ){
					for( int t=0; t<16 && info->pShare->trkRef[s][n][t].idStyle>0; t++ ){
						TPROSTYLE* pTrkInfo = GetStyleInfo( 0, info->pShare->trkRef[s][n][t].idStyle );
						if( pTrkInfo->pOrigin->cost>0 ){
							bool bMatch = false;
							for( int k=0; k<aStyles.size(); k++ ){
								if( pTrkInfo==aStyles[k] ){
									bMatch = true;
									break;
								}
							}

							if( !bMatch ){
								aStyles.push_back( pTrkInfo );

								sprintf( buf, "\n[%4d]      %d", pTrkInfo->idStyle,
																	pTrkInfo->pOrigin->cost );
								strTip += buf;
							}
						}
					}
				}
			}
		}
	}

	return strTip;
}
//---------------------------------------------------------------------------

TStyleItem* __fastcall TAudStylePanel::AddStyleItem( TPROSTYLE* info, bool bCollected )
{
	TStyleItem* pStyItem = CreateStyleItem( info, bCollected, true );
	InsertStyleItem( pStyItem, m_aItems->Count );

	return pStyItem;
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::ListTypeClick(TObject *Sender)
{
	TPNGButton* pBtn = (TPNGButton*)Sender;

	if( !pBtn->Down ){
		pBtn->Down = true;

		for( int i=1; i<m_nBtnCount; i++ ){
			if( m_lstBtnTools[i]==pBtn ){
				m_iListType = pBtn->Tag;
			}
			else{
				m_lstBtnTools[i]->Down = false;
			}
		}

		if( m_SearchPanel ){
			m_SearchPanel->Reset();
			if( ((TPNGButton*)m_lstBtnTools[0])->Down ){
				CMClick( NULL );
			}
		}

		PostMessage( Handle, UM_SEARCH, 0, 0 );
	}
}
//---------------------------------------------------------------------------

void TAudStylePanel::RefreshList()
{
	bool bAuthority = SOFTWARE_ID==e_Pro_Lite || g_bLogon
								&& (g_infoUser.accountInfo.authority & 0x1000);

	int iStart, iEnd, iStep;
	STYLELIST& lstStyles = m_iListType==LIST_RECOMMAND ? g_aRecomStyles
							: m_iListType==LIST_ORIGIN ? g_aOriginStyles
							: m_iListType==LIST_SHARE ? g_aShareStyles
							: m_iListType==LIST_COLLECTION ? g_aCollectStyles
							: g_aLocalStyles;

	if( !lstStyles.empty() ){
		if( m_SearchPanel->iSortType==0 && m_SearchPanel->iSortMode==1 ){
			iStart = 0;
			iEnd = lstStyles.size();
			iStep = 1;
		}
		else{
			iStart = lstStyles.size()-1;
			iEnd = -1;
			iStep = -1;
		}

		for( int ind=iStart; ind!=iEnd; ind+=iStep ){
			TPROSTYLE* info = lstStyles[ind];

			bool bCollect = false;

			if( m_iListType!=LIST_LOCAL )
				bCollect = IsCollected( info->idLoc, info->idStyle );

			//检查分类
			bool bAdd = false;
			if( m_SearchPanel->DStyle.Length==10 || m_iListType==LIST_LOCAL ){
				bAdd = true;
			}
			else{
				for( int cunt=0; !bAdd && cunt<m_SearchPanel->DStyle.Length; cunt++ ){
					if( info->idLoc==0 ){
						TSTYLEDETAIL& detail = info->pOrigin->detail;
						for( int ity=0;ity<sizeof(detail.type);ity++ ){
								//判断是否添加项
							if( detail.type[ity]>=0 && detail.type[ity]<=23
											&&( detail.type[ity] == m_SearchPanel->DStyle[cunt]
												|| m_SearchPanel->DStyle[cunt] == -2
												&&  detail.type[ity] >8  ) ){ //  “>8" 为 其他
								bAdd = true;
								break;
							}
						}
					}
					else if( info->idLoc==1 ){
						TSTYLESHARE* detail = info->pShare;
						for( int ity=0;ity<sizeof(detail->type);ity++ ){
								//判断是否添加项
							if( detail->type[ity]>=0 && detail->type[ity]<=23
											&&( detail->type[ity] == m_SearchPanel->DStyle[cunt]
												|| m_SearchPanel->DStyle[cunt] == -2
												&&  detail->type[ity] > 8  ) ){ //  “>8" 为 其他
								bAdd = true;
								break;
							}
						}
					}
					else if( m_SearchPanel->DStyle[cunt] == -2 ){
						bAdd = true;
						break;
					}
				}
			}

			if( bAdd ){
				//检查乐器查找
				TStyleItem* pStyItem = NULL;

				bool bInstSearch = m_SearchPanel->DInStr.Length>0;
				if( bInstSearch ){
					pStyItem = CreateInstrumentItem( info, bCollect, bAuthority );
				}
				else if( m_iListType!=LIST_COLLECTION || bCollect ){
					pStyItem = CreateStyleItem( info, bCollect, bAuthority );
				}

				if( pStyItem ){
					if( pStyItem->aItems->Count>0 ){
						int index = m_aItems->Count;
						if( m_SearchPanel->iSortType==3 ){ //速度排序
							int iMode = m_SearchPanel->iSortMode,
								iTempo = info->idLoc==0 ? info->pOrigin->detail.iTempo
												: info->idLoc==1 ? info->pShare->iTempo
																: info->pLocal->iTempo;

							for( int i=0; i<m_aItems->Count; i++ ){
								TStyleItem* pTmpSty = (TStyleItem*)m_aItems->Items[i];
								int tmpTempo = pTmpSty->pStyle->idLoc==0
													? pTmpSty->pStyle->pOrigin->detail.iTempo
													: pTmpSty->pStyle->idLoc==1
														? pTmpSty->pStyle->pShare->iTempo
														: pTmpSty->pStyle->pLocal->iTempo;

								if( iMode==0 && iTempo > tmpTempo
										|| iMode==1 && iTempo < tmpTempo ){
									index = i;
									break;
								}
							}

						}
						else if( ( m_iListType==LIST_ORIGIN || m_iListType==LIST_RECOMMAND )
										&& m_SearchPanel->iSortType!=0 ){ //价格/评分排序
							int iType = m_SearchPanel->iSortType,
								iMode = m_SearchPanel->iSortMode,
								cost = info->pOrigin->cost,
								score = info->pOrigin->score;
							for( int i=0; i<m_aItems->Count; i++ ){
								TStyleItem* pTmpSty = (TStyleItem*)m_aItems->Items[i];
								int tmpCost = pTmpSty->pStyle->pOrigin->cost,
									tmpScore = pTmpSty->pStyle->pOrigin->score;

								if( iMode==0 && ( iType==1 && cost > tmpCost
												|| iType==2	&& score > tmpScore )
										|| iMode==1 && ( iType==1 && cost < tmpCost
												|| iType==2	&& score < tmpScore )){
									index = i;
									break;
								}
							}
						}

						InsertStyleItem( pStyItem, index );
					}
					else{
						delete pStyItem;
					}
				}
			}
		}
	}

	if( m_aItems->Count>0 ){
		m_pTopItem = (TCommonItem*)m_aItems->First();
	}
}
//---------------------------------------------------------------------------

TStyleItem* TAudStylePanel::CreateInstrumentItem( TPROSTYLE* info, bool bCollected, bool bAuthority )
{
	TStyleItem* pStyItem = NULL;

	for( int s=0; s<SEGTYPE_TRACK; s++ ){
		int rep = s<SEGTYPE_INTRO ? 1 : 2;
		for( int r=0; r<rep; r++ ){
			int nSegNum = info->idLoc==0 ? info->pOrigin->detail.nSegNum[s]
								: info->idLoc==1 ? info->pShare->nSegNum[s]
												: info->pLocal->nSegNum[s];
			int num = s<SEGTYPE_INTRO ? nSegNum
								: r==0 ? ( nSegNum & 0x0F )
										: ( nSegNum>>4 );
			if( num>0 ){
				for( int i=0; i<num; i++ ){
					TSegmentItem* pSegItem = NULL;

					int sn = r==0 ? i : i+4;
					for( int j=0; j<16; j++ ){
						if( info->idLoc==0 && info->pOrigin->detail.tracks[s][sn][j].no>=0
											&& info->pOrigin->detail.tracks[s][sn][j].no!=9
									|| info->idLoc==1 && info->pShare->trkRef[s][sn][j].idStyle>=0
											&& info->pShare->trkRef[s][sn][j].chan!=9
									|| info->idLoc>0 && info->pLocal->trkRef[s][sn][j].idStyle>=0
											&& info->pLocal->trkRef[s][sn][j].chan!=9 ){
							char prog = info->idLoc==0 ? info->pOrigin->detail.tracks[s][sn][j].prog
											: info->idLoc==1 ? info->pShare->trkRef[s][sn][j].prog
															: info->pLocal->trkRef[s][sn][j].prog;
							for( int m=0;m<m_SearchPanel->DInStr.Length;m++ ){
								if( m_SearchPanel->DInStr[m]==prog ){
									if( !pStyItem ){   //添加风格
										DWORD dwOpts = GetStyleOptions( info );
										//pStyItem = AddStyle( info, dwOpts );
										pStyItem = new TStyleItem( info, dwOpts );

//										if( bCollected )
//											pStyItem->SetCollect( true );
									}

									if( pStyItem && !pSegItem ){
										int vol = info->idLoc==0 ? 100
												: info->idLoc==1 ? info->pShare->nSegVol[s][sn]
															: info->pLocal->nSegVol[s][sn];
										pSegItem = pStyItem->AddSegment( s, sn, 0, 0, -1, vol );
									}

									if( pSegItem ){      //添加具体项
										pSegItem->AddTrack( info, sn, j, info->idLoc<=1?OPT_COLLECT:0, bAuthority );
									}
								}
							}
						}
					}

					if( pSegItem ){
						if( pSegItem->aItems->Count>0 ){
							if( s==SEGTYPE_INTRO ){
								pSegItem->nBars = info->idLoc==0 ? info->pOrigin->detail.aIntroBars[sn]
													: info->idLoc==1 ? info->pShare->aIEBars[0][sn]
																	: info->pLocal->aIEBars[0][sn];
							}
							else if( s==SEGTYPE_ENDING ){
								pSegItem->nBars = info->idLoc==0 ? info->pOrigin->detail.aEndingBars[sn]
													: info->idLoc==1 ? info->pShare->aIEBars[1][sn]
																	: info->pLocal->aIEBars[1][sn];
							}
						}
						else{
							pStyItem->DeleteSegment( pSegItem );
						}
					}
				}
			}
		}
	}

	return pStyItem;
}
//---------------------------------------------------------------------------

TStyleItem* TAudStylePanel::CreateStyleItem( TPROSTYLE* info, bool bCollected, bool bAuthority )
{
	DWORD dwOpts = GetStyleOptions( info );

	TStyleItem* pStyItem = new TStyleItem( info, dwOpts );

//	if( bCollected ) pStyItem->SetCollect( true );

	for( int s=0; s<SEGTYPE_TRACK; s++ ){
		int rep = s<SEGTYPE_INTRO ? 1 : 2;
		for( int r=0; r<rep; r++ ){
			int nSegNum = info->idLoc==0 ? info->pOrigin->detail.nSegNum[s]
										: info->idLoc==1 ? info->pShare->nSegNum[s]
														: info->pLocal->nSegNum[s];
			int num = s<SEGTYPE_INTRO ? nSegNum
								: r==0 ? ( nSegNum & 0x0F )
										: ( nSegNum>>4 );
			if( num>0 ){
				DWORD opts = s<SEGTYPE_INTRO ? OPT_BRUSH : 0;
				for( int i=0; i<num; i++ ){
					int sn = r==0 ? i : i+4;
					int vol = info->idLoc==0 ? 100
							: info->idLoc==1 ? info->pShare->nSegVol[s][sn]
											: info->pLocal->nSegVol[s][sn];

					TSegmentItem* pSegItem = pStyItem->AddSegment( s, sn, opts, 0, -1, vol );

					for( int j=0; j<16; j++ ){
						pSegItem->AddTrack( info, sn, j, info->idLoc<=1?OPT_COLLECT:0, bAuthority );
					}

					if( pSegItem->aItems->Count>0 ){
						if( s==SEGTYPE_INTRO ){
							pSegItem->nBars = info->idLoc==0 ? info->pOrigin->detail.aIntroBars[sn]
												: info->idLoc==1 ? info->pShare->aIEBars[0][sn]
																: info->pLocal->aIEBars[0][sn];
						}
						else if( s==SEGTYPE_ENDING ){
							pSegItem->nBars = info->idLoc==0 ? info->pOrigin->detail.aEndingBars[sn]
												: info->idLoc==1 ? info->pShare->aIEBars[1][sn]
																: info->pLocal->aIEBars[1][sn];
						}
					}
					else{
						pStyItem->DeleteSegment( pSegItem );
					}
				}
			}
		}
	}

	return pStyItem;
}
//---------------------------------------------------------------------------

void TAudStylePanel::InsertStyleItem( TStyleItem* pStyItem, int index )
{
	if( index<m_aItems->Count ){
		if( index>0 ){
			TCommonItem* pPrev = (TCommonItem*)m_aItems->Items[index-1];
			pPrev->next = pStyItem;
			pStyItem->prev = pPrev;
		}

		TCommonItem* pNext = (TCommonItem*)m_aItems->Items[index];
		pNext->prev = pStyItem;
		pStyItem->next = pNext;
	}
	else if( m_aItems->Count>0 ){
		TCommonItem *pLast = (TCommonItem*)m_aItems->Last();

		pLast->next = pStyItem;
		pStyItem->prev = pLast;
	}

	m_aItems->Insert( index, pStyItem );

	m_nTotalLine++;
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::ReloadLocalStyle( bool bShow )
{
	if( m_iListType==LIST_LOCAL ){
		PostMessage( Handle, UM_SEARCH, 0, 0 );
	}
	else if( bShow ){
		ListTypeClick( m_lstBtnTools[1] );
	}
}
//---------------------------------------------------------------------------

void TAudStylePanel::DeleteItem( TCommonItem *pItem, int iLine )
{
	if( pItem->iType==SEGTYPE_STYLE ){
		TPROSTYLE* pStyle = ((TStyleItem*)pItem)->pStyle;
		//检查是否正在使用
		bool bUsed = false;

		if( g_pUseStyle ){
			TStyleItem* pStyItem = (TStyleItem*)g_pUseStyle;
			if( pStyItem->pStyle==pStyle )
				bUsed = true;

			for( int i=0; !bUsed && i<pStyItem->aItems->Count; i++ ){
				TSegmentItem* pSeg = (TSegmentItem*)pStyItem->aItems->Items[i];
				for( int j=0; !bUsed && j<pSeg->aItems->Count; j++ ){
					TTrackItem* pTrk = (TTrackItem*)pSeg->aItems->Items[j];
					if( pTrk->pStyle==pStyle ){
						bUsed = true;
					}
				}
			}
		}

		if( !bUsed && g_pPreStyle ){
			TStyleItem* pStyItem = (TStyleItem*)g_pPreStyle;
			if( pStyItem->pStyle==pStyle )
				bUsed = true;

			for( int i=0; !bUsed && i<pStyItem->aItems->Count; i++ ){
				TSegmentItem* pSeg = (TSegmentItem*)pStyItem->aItems->Items[i];
				for( int j=0; !bUsed && j<pSeg->aItems->Count; j++ ){
					TTrackItem* pTrk = (TTrackItem*)pSeg->aItems->Items[j];
					if( pTrk->pStyle==pStyle ){
						bUsed = true;
					}
				}
			}
		}

		if( bUsed ){
			MessageForm->ShowMessage( "该风格正在使用或编辑中，无法删除！",
											MB_ICONERROR | MB_OK, "删除风格" );
			return;
		}

		bUsed = false;
		TPROSTYLE* pExampleStyle = NULL;
		for( int i=0; !bUsed && i<m_aItems->Count; i++ ){
			if( pItem==m_aItems->Items[i] )
				continue;

			TStyleItem* pSty = (TStyleItem*)m_aItems->Items[i];
			for( int j=0; !bUsed && j<pSty->aItems->Count; j++ ){
				TSegmentItem* pSeg = (TSegmentItem*)pSty->aItems->Items[j];
				for( int k=0; k<pSeg->aItems->Count; k++ ){
					TTrackItem* pTrk = (TTrackItem*)pSeg->aItems->Items[k];

					if( pTrk->pStyle->idLoc==pStyle->idLoc
							&& pTrk->pStyle->idStyle==pStyle->idStyle ){
						bUsed = true;
						pExampleStyle = pSty->pStyle;
						break;
					}
				}
			}
		}

		String strMsg = "确定删除本地风格【";
		strMsg += UTF8ToMBCS(pStyle->pLocal->strStyleName).c_str();
		strMsg += "】？";

		if( bUsed ){
			char buff[512];
			sprintf( buff, "\n\n该操作将修改 L%d【%s】等风格",
							LOWORD(pExampleStyle->idStyle),
							UTF8ToMBCS(pExampleStyle->pLocal->strStyleName).c_str() );
			strMsg += buff;
		}

		if( mrCancel==MessageForm->ShowMessage(strMsg, MB_ICONQUESTION | MB_OKCANCEL) )
			return;

		f_CM_DeleteLocalStyle( pStyle->idLoc, pStyle->idStyle );
		DeleteStyleInfo( pStyle->idLoc, pStyle->idStyle );

		if( bUsed )
			Perform( UM_SEARCH, 0, 0 );
		else
			TStylePanel::DeleteItem( pItem, iLine );
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::EditChange(TObject *Sender)
{
	TEdit* pEdit = ((TEdit*)Sender);

	AnsiString strName = pEdit->Text.Trim();
	string strTmp = GBToUTF8(strName.c_str());

	if( strTmp.length()>pEdit->MaxLength ){
		pEdit->OnChange = NULL;
		pEdit->Text = pEdit->Text.SubString( 0,	pEdit->Text.Length()-1 );
		pEdit->SelStart = pEdit->Text.Length();
		pEdit->OnChange = EditChange;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::EditMouseMove(TObject *Sender, TShiftState Shift, int X, int Y)
{
	if( X>0 && X<m_editName->Width && Y>0 && Y<m_editName->Height )
		Screen->Cursor = crIBeam;
	else
		Screen->Cursor = crArrow;
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::EditMouseDown(TObject *Sender, TMouseButton Button,
													TShiftState Shift, int X, int Y)
{
	if( X<0 || X>m_editName->Width || Y<0 || Y>m_editName->Height ){
		ReleaseCapture();

		TPoint pt( X, Y );
		pt = m_editName->ClientToScreen( pt );
		pt = ScreenToClient( pt );
		bool bInsideAudPanel = pt.x>0 && pt.x<Width && pt.y>0 && pt.y<Height;

		if( Button==mbLeft && bInsideAudPanel )
			StyleRename();

		m_editName->Hide();
		Screen->Cursor = crDefault;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::EditMouseUp(TObject *Sender, TMouseButton Button,
													TShiftState Shift, int X, int Y)
{
	SetCapture( m_editName->Handle );
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::EditKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
{
	switch( Key ){
	case VK_RETURN:
		StyleRename();
		m_editName->Hide();
		ReleaseCapture();
		Screen->Cursor = crDefault;

		break;

	case VK_ESCAPE:
		m_editName->Hide();
		ReleaseCapture();
		Screen->Cursor = crDefault;

		break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::RenameTiming(int op)
{
	if( m_RenameTimer ){
		delete m_RenameTimer;
		m_RenameTimer = NULL;
	}

	if( m_bDoubleClick ){
		m_bDoubleClick = false;
	}
	else if( op==1 ){
		m_RenameTimer = new TTimer(this);
		m_RenameTimer->Interval = GetDoubleClickTime();
		m_RenameTimer->OnTimer = RenameTimerProc;
		m_RenameTimer->Enabled = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::RenameTimerProc(System::TObject* Sender)
{
	if( m_RenameTimer ){
		DoRename( NULL );

		delete m_RenameTimer;
		m_RenameTimer = NULL;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAudStylePanel::DoRename(TObject* Sender)
{
	if( m_iListType!=LIST_LOCAL )
		return;

	if( Sender ){
		SetSelect( m_pFocItem, m_iFocLine );
	}

	if( m_iFocLine==m_nItemShow-1 ){
		ScrollView( m_iTopLine+1 );
	}

	if( m_editName && m_pSelItem ){
		m_editName->Tag = (int)m_pSelItem;

		String strText;
		m_pSelItem->AddStyleId( strText );
		int left = LEFT_BOUND + OPTION_WIDTH + Canvas->TextWidth( strText );
		int nOpt = m_pSelItem->aOptions->Count;
		int top = ( m_editName->Font->Size==g_szFont9 ? 0 : 2 ) + m_iSelLine*m_nItemHeight+m_nTitleHeight;
		int height = m_editName->Font->Size==g_szFont9 ? 16 : 13;


		m_editName->SetBounds( left + LEFT_BOUND,
							   top,
							   Width - left - nOpt * OPTION_WIDTH - RIGHT_BOUND - 4,
							   height );


		TPROSTYLE* pStyle = ((TStyleItem*)m_pSelItem)->pStyle;
		strText = UTF8ToMBCS(pStyle->pLocal->strStyleName).c_str();

		m_editName->Text = strText;

		m_editName->Show();
		m_editName->SelectAll();

		m_editName->SetFocus();
		SetCapture( m_editName->Handle );
	}
}
//---------------------------------------------------------------------------

void TAudStylePanel::StyleRename()
{
	if( !m_pSelItem )
		return;

	String strOldName, strNewName;

//	TStyleItem* pStyItem = (TStyleItem*)m_editName->Tag;
	TPROSTYLE* pStyle = ((TStyleItem*)m_pSelItem)->pStyle;

/*	if( pStyle->idLoc==1 )
		strOldName = UTF8ToMBCS(pStyle->pShare->strStyleName).c_str();
	else if( pStyle->idLoc!=(UINT)-1 )
*/		strOldName = UTF8ToMBCS(pStyle->pLocal->strStyleName).c_str();

	strNewName = m_editName->Text.Trim();

	if( strNewName.Length()>0 && strNewName.Compare( strOldName ) ){
		string strName = GBToUTF8(AnsiString(strNewName.c_str()).c_str()).c_str();
		strcpy( pStyle->pLocal->strStyleName, strName.c_str() );

		f_CM_ChangeLocalStyle( pStyle );
	}
}
//---------------------------------------------------------------------------

