Imports System.Windows.Forms
Imports System.IO
Imports CommonClassv2
Imports System.Data
Imports System.Threading

Public Class MDiMain

    Public NewList As Boolean = False '//파일을 불러오거나 편집모드를 켯을떄변경

    Dim FB As New FolderBrowserDialog

    Dim strbuff As New System.Text.StringBuilder
    Dim Macro() As Str_Macro

#Region "화면하단에 수량을 표시"
    Delegate Sub showcnt1handler(ByVal cnt1 As Integer, ByVal cnt2 As Integer, ByVal tag As String)
    Sub ShowCnt1(ByVal cnt1 As Integer, ByVal cnt2 As Integer, Optional ByVal tag As String = "")
        If C1StatusBar1.InvokeRequired Then
            C1StatusBar1.Invoke(New showcnt1handler(AddressOf ShowCnt1), New Object() {cnt1, cnt2, tag})
        Else
            Me.lb_cnt1.Text = cnt1 & "/" & cnt2 & Space(1) & tag
            Me.C1StatusBar1.Refresh()
        End If
    End Sub
    Sub ShowCnt2(ByVal cnt1 As Integer, ByVal cnt2 As Integer, Optional ByVal tag As String = "")
        If C1StatusBar1.InvokeRequired Then
            C1StatusBar1.Invoke(New showcnt1handler(AddressOf ShowCnt2), New Object() {cnt1, cnt2, tag})
        Else
            Me.lb_cnt2.Text = cnt1 & "/" & cnt2 & Space(1) & tag
            Me.C1StatusBar1.Refresh()
        End If
    End Sub
#End Region

#Region "운용기록창메세지표시"
    Delegate Sub OLogHandler(m As String)
    Sub OLog(m As String)
        If RichTextBox1.InvokeRequired Then
            RichTextBox1.Invoke(New OLogHandler(AddressOf OLog), New Object() {m})
        Else
            m = String.Format("[{0}] {1}", Now.ToString("HHmmss"), m)
            If RichTextBox1.TextLength > 4000 Then RichTextBox1.Clear() '//일정크기가 되면 데이터를 지운다
            RichTextBox1.AppendText(vbCrLf + m)
            RichTextBox1.ScrollToCaret()
        End If
    End Sub
#End Region

    '''매크로폴더에서 목록을 가져옵니다.
    Private Sub Load_Macro()

        PLog.Add(">> Load_Macro")

        Dim Ini As MyINI
        Dim DI As New DirectoryInfo(PathMacro)
        If Not DI.Exists Then
            PLog.Add("No Macro Dir(" + DI.FullName + ") => Create")
            DI.Create()
        End If

        Dim FI() As FileInfo = DI.GetFiles(MacroPattern & "*.ini")
        ReDim Macro(FI.GetUpperBound(0)) '//매크로 등록한다.
        PLog.Add(Macro.Length.ToString() + "개의 매크로파일을 검색했습니다")

        Dim I As Integer = 0
        Me.cmb_macro.Items.Clear()
        Me.cmb_macro.Items.Add("이전설정")
        For Each F As FileInfo In FI
            Me.Macro(I).FileName = F.FullName
            Ini = New MyINI(F.FullName)
            Me.Macro(I).Desc = Ini.Read("main", "desc", "기본설명")
            Me.cmb_macro.Items.Add(Me.Macro(I).Desc)
            PLog.Add("#Macro File=" + F.Name + ", desc=" + Me.Macro(I).Desc)
            I += 1
        Next
    End Sub

    Public Sub AddScheduleDiv(m As String)
        Dim lv4 As ListViewItem = lvSchedule.Items.Add("※")
        lv4.SubItems.Add("--")
        lv4.SubItems.Add(m)
        lv4.SubItems.Add("완료")
        lv4.SubItems.Add("-")
        lv4.ForeColor = Color.Gray
        lvSchedule.Refresh()
    End Sub


    Public Sub Noti(m As String)
        If NotifyIcon1.Visible = False Then NotifyIcon1.Visible = True
        NotifyIcon1.ShowBalloonTip(1000, "FileManager", m, ToolTipIcon.Info)
    End Sub

    Private Sub MDiMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If MsgBox("프로그램이 종료됩니다", MsgBoxStyle.OkCancel + MsgBoxStyle.Information, "종료확인") <> MsgBoxResult.Ok Then
            e.Cancel = True
            Return
        End If

        '//현재설정을 저장한다
        Setting_Save()

        '//더이상 화면에 로그메세지가 표시되지 않게한다
        RemoveHandler Pub.PLog.RaiseMsg, AddressOf RaiseLogMessage

        NotifyIcon1.Visible = False
        NotifyIcon1.Dispose()

        '//프로그램종료메세지 추가 및 Flush
        Pub.PLog.Add("Program Closing", True)

    End Sub

    Private Sub MDiMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        '제목표시줄에 프로그램명과 버젼을 표시합니다
        Me.Text = My.Application.Info.ProductName & " Ver. {0}.{1:00}.{2}.{3}"
        Me.Text = System.String.Format(Me.Text, My.Application.Info.Version.Major, My.Application.Info.Version.Minor, My.Application.Info.Version.Build, My.Application.Info.Version.Revision)
        Me.Show()
        My.Application.DoEvents()
        RichTextBox1.Clear()

        '//프로그램초기화
        Pub.init()

        '//로그메세지이벤트할당(로그가 들어오면 화면에 뿌릴수있도록 한다)
        AddHandler PLog.RaiseMsg, AddressOf RaiseLogMessage

        PLog.Add("프로그램 실행", True)

        PLog.Add("FTP Class init")
        FTP_0 = New FTPClients.Client_2("127.0.0.1", "Anonymous", "")

        '//매크로기능 초기화
        Load_Macro()
        If Me.cmb_macro.Items.Count > 0 Then Me.cmb_macro.SelectedIndex = 0

        '//툴팁메세지추가
        Dim SB As New System.Text.StringBuilder("[복사]")
        SB.AppendLine()
        SB.AppendLine("복사하려는 파일의 위치")
        SB.AppendLine()
        SB.AppendLine("[삭제]")
        SB.AppendLine("삭제하려는 파일의 위치")
        SB.AppendLine()
        SB.AppendLine("[이동]")
        SB.AppendLine("이동하려는 파일의 위치")
        Me.bt_workdir.ToolTipText = SB.ToString

        PLog.Add("프로그램 초기화 완료", True)
    End Sub

    '//로그클래스로부터의 발생 메세지
    Private Sub RaiseLogMessage(time As String, gubun As String, msg As String)
        OLog(msg)
    End Sub

#Region "설정 불러오기 & 저장하기"

    Private Sub Setting_Load(Optional ByVal Macroindex As Integer = 0)

        Dim ini As MyINI
        If Macroindex = 0 Then
            ini = New MyINI(IniFile)
        Else
            ini = New MyINI(Me.Macro(Macroindex - 1).FileName)
        End If

        '//파일명표시
        PLog.Add(String.Format("Load Setting : {0},{1}", Macroindex, ini.FileName))

        Me.Src_Init()

        '//가져올부분은  작업폴더/백업폴더/백업폴더2/확장자/서브디렉토리참조/백업정책1/백업정책2/중복정책/실행형태/검사형태
        Me.tb_workdir.Text = ini.Read("main", "workdir", "c:\")
        Me.desd_tb_path.Text = ini.Read("main", "desdir", "c:\")

        Me.tb_bakdir1.Text = ini.Read("main", "bakdir1", "c:\")
        Me.tb_ext.Text = ini.Read("main", "ext", "JPG")
        Me.chk_subdir.Checked = ini.Read("main", "subdir", True)

        Dim baktype As String = ini.Read("main", "bak1type", 1)
        If String.IsNullOrEmpty(baktype) Then baktype = "1"
        cbBakType.SelectedIndex = baktype


        If CBool(ini.Read("main", "bak1folder", False)) Then
            cbBakTarget.SelectedIndex = 0
        Else
            cbBakTarget.SelectedIndex = 1
        End If

        Dim runtime As String = ini.Read("main", "runtype", 0)
        btCopy.Pressed = False
        btDel.Pressed = False
        btMove.Pressed = False

        If runtime = "1" Then
            btDel.Pressed = True
        ElseIf runtime = "2" Then
            btMove.Pressed = True
        Else
            btCopy.Pressed = True
        End If
        'Me.cmb_runtype.SelectedIndex = ini.Read("main", "runtype", 0)  //160407

        '//하위폴더목록 불러오기
        Dim SubCnt As Integer = ini.Read("main", "subdirCnt", 0)
        For i As Integer = 1 To SubCnt
            AddSubDirList(ini.Read("subdir", "list" & i, ""))
        Next

        '//srcfile
        '//가져올부분은  작업폴더/백업폴더/백업폴더2/확장자/서브디렉토리참조/백업정책1/백업정책2/중복정책/실행형태/검사형태
        Dim PF As String = ini.Read("srcfile", "prevfile", "")
        If PF = "" Then
            Prev_file = Nothing
        Else
            Prev_file = New System.IO.FileInfo(PF)
        End If

        '//시작,종료영역 복구
        Me.tb_sttrange.Text = ini.Read("srcfile", "sttrange", "1")
        Me.tb_endrange.Text = ini.Read("srcfile", "endrange", "0")
        If Me.tb_sttrange.Text = "0" Then Me.tb_sttrange.Text = "1"

        For Each AA As Control In Me.src_tp.Controls
            If AA.GetType.Name.ToUpper = "IMPCTL" Then
                CType(AA, impctl).열번호 = ini.Read("srcfile", AA.Name & "C", "")
                CType(AA, impctl).문자열자르기 = ini.Read("srcfile", AA.Name & "S", "")
                CType(AA, impctl).포맷마스크 = ini.Read("srcfile", AA.Name & "F", "")
            End If
        Next
        '//DESFile
        For Each AA As Control In Me.desf_pt.Controls
            If AA.GetType.Name.ToUpper = "IMPCTL" Then
                CType(AA, impctl).열번호 = ini.Read("desfile", AA.Name & "C", "")
                CType(AA, impctl).문자열자르기 = ini.Read("desfile", AA.Name & "S", "")
                CType(AA, impctl).포맷마스크 = ini.Read("desfile", AA.Name & "F", "")
            End If
        Next

        '//DESDIR
        For Each AA As Control In Me.desd_pt.Controls
            If AA.GetType.Name.ToUpper = "IMPCTL" Then
                CType(AA, impctl).열번호 = ini.Read("desdir", AA.Name & "C", "")
                CType(AA, impctl).문자열자르기 = ini.Read("desdir", AA.Name & "S", "")
                CType(AA, impctl).포맷마스크 = ini.Read("desdir", AA.Name & "F", "")
            End If
        Next

        Me.des_chk_merge.Checked = ini.Read("desdir", "Chkmerge", False)

        '//srcdir 160408
        For Each AA As Control In Me.srcd_pt.Controls
            If AA.GetType.Name.ToUpper = "IMPCTL" Then
                CType(AA, impctl).열번호 = ini.Read("srcdir", AA.Name & "C", "")
                CType(AA, impctl).문자열자르기 = ini.Read("srcdir", AA.Name & "S", "")
                CType(AA, impctl).포맷마스크 = ini.Read("srcdir", AA.Name & "F", "")
            End If
        Next
        Me.src_chk_merge.Checked = ini.Read("srcdir", "Chkmerge", False)

        '//160716
        Me.chkReplay.Checked = ini.Read("option", "replay", True)
        Me.chkAutoRun.Checked = ini.Read("option", "autorun", False)
        Me.chkHide.Checked = ini.Read("option", "hide", False)

        '//ftp 정보 복구
        FTPServer = ini.Read("ftp", "server", "")
        FTPID = ini.Read("ftp", "id", "Anonymouse")
        FTPPW = ini.Read("ftp", "pass", "")
        FTPPort = ini.Read("ftp", "port", "21")
        FTPPath = ini.Read("ftp", "path", "/")
        FTPPassive = ini.Read("ftp", "passive", False)
        FTPUTF8 = ini.Read("ftp", "utf8", False)

        If String.IsNullOrEmpty(FTPPath) Then FTPPath = "/"
        FTPPath = FTPPath.Replace("//", "/")

        Dim ftpindex As Integer = ini.Read("ftp", "index", "0")

        FTP_0.host = FTPServer + ":" + FTPPort.ToString()
        FTP_0.user = FTPID
        FTP_0.pass = FTPPW
        FTP_0.Passive = FTPPassive
        FTP_0.utf8 = FTPUTF8

        PLog.Add("Load Setting OK", True)
    End Sub
    Private Function Setting_Save(Optional ByVal Macroindex As Integer = 0) As Boolean '//현재 셋팅을 저장합니다.
        '//저장목록은 시작/종료 열번호 아이템의 텍스트이다.

        PLog.Add(">> : Save_Setting")

        Dim Macroname As String
        Dim ini As MyINI
        If Macroindex = 0 Then
            ini = New MyINI(IniFile)
            Macroname = "기본설정"
        ElseIf Macroindex = -999 Then   '//이건 새로운 매크로의 추가다. 매크로 파일명을 새로지어야한다.
            Macroname = InputBox("매크로 설명을 입력하세요", "설명입력", "신규매크로")
            If String.IsNullOrEmpty(Macroname) Then Return False
            Dim i As Integer = 0
            Dim NewName As String = ""
NewName:
            i += 1
            NewName = PathMacro & "\" & MacroPattern & Format(Me.Macro.GetUpperBound(0) + i + 1, "00") & ".ini"
            If New FileInfo(NewName).Exists Then GoTo NewName
            ini = New MyINI(NewName)
        Else
            ini = New MyINI(Me.Macro(Macroindex - 1).FileName)
            Macroname = Me.Macro(Macroindex - 1).Desc
        End If
        ini.Write("main", "desc", Macroname)

        ini.Write("main", "workdir", Me.tb_workdir.Text)
        ini.Write("main", "desdir", Me.desd_tb_path.Text)
        ini.Write("main", "bakdir1", Me.tb_bakdir1.Text)
        ini.Write("main", "ext", Me.tb_ext.Text)
        ini.Write("main", "subdir", Me.chk_subdir.Checked)

        ini.Write("main", "bak1type", cbBakType.SelectedIndex)

        If btDel.Pressed Then
            ini.Write("main", "runtype", "1")
        ElseIf btMove.Pressed Then
            ini.Write("main", "runtype", "2")
        Else
            ini.Write("main", "runtype", "0")
        End If

        If cbBakTarget.SelectedIndex = 0 Then
            ini.Write("main", "bak1folder", Boolean.TrueString)
        Else
            ini.Write("main", "bak1folder", Boolean.FalseString)
        End If

        '//하위폴더목록을 저장한다.
        ini.Write("main", "subdirCnt", Me.list_subdir.Items.Count)
        For i As Integer = 1 To Me.list_subdir.Items.Count
            ini.Write("subdir", "list" & i, Me.list_subdir.Items(i - 1).Text)
        Next

        '//srcfile
        If Not Prev_file Is Nothing Then ini.Write("srcfile", "prevfile", Prev_file.FullName)
        ini.Write("srcfile", "sttrange", Me.tb_sttrange.Text)
        ini.Write("srcfile", "endrange", Me.tb_endrange.Text)

        For Each AA As Control In Me.src_tp.Controls
            If AA.GetType.Name.ToUpper = "IMPCTL" Then
                ini.Write("srcfile", AA.Name & "C", CType(AA, impctl).열번호)
                ini.Write("srcfile", AA.Name & "S", CType(AA, impctl).문자열자르기)
                ini.Write("srcfile", AA.Name & "F", CType(AA, impctl).포맷마스크)
            End If
        Next

        '//desfile
        For Each AA As Control In Me.desf_pt.Controls
            If AA.GetType.Name.ToUpper = "IMPCTL" Then
                ini.Write("desfile", AA.Name & "C", CType(AA, impctl).열번호)
                ini.Write("desfile", AA.Name & "S", CType(AA, impctl).문자열자르기)
                ini.Write("desfile", AA.Name & "F", CType(AA, impctl).포맷마스크)
            End If
        Next


        '//desdir
        For Each AA As Control In Me.desd_pt.Controls
            If AA.GetType.Name.ToUpper = "IMPCTL" Then
                ini.Write("desdir", AA.Name & "C", CType(AA, impctl).열번호)
                ini.Write("desdir", AA.Name & "S", CType(AA, impctl).문자열자르기)
                ini.Write("desdir", AA.Name & "F", CType(AA, impctl).포맷마스크)
            End If
        Next
        ini.Write("desdir", "Chkmerge", Me.des_chk_merge.Checked)

        '//srcdir 160408
        For Each AA As Control In Me.srcd_pt.Controls
            If AA.GetType.Name.ToUpper = "IMPCTL" Then
                ini.Write("srcdir", AA.Name & "C", CType(AA, impctl).열번호)
                ini.Write("srcdir", AA.Name & "S", CType(AA, impctl).문자열자르기)
                ini.Write("srcdir", AA.Name & "F", CType(AA, impctl).포맷마스크)
            End If
        Next
        ini.Write("srcdir", "Chkmerge", Me.src_chk_merge.Checked)

        '//160716
        ini.Write("option", "replay", Me.chkReplay.Checked)
        ini.Write("option", "autorun", Me.chkAutoRun.Checked)
        ini.Write("option", "hide", Me.chkHide.Checked)

        ini.Write("ftp", "server", FTPServer)
        ini.Write("ftp", "id", FTPID)
        ini.Write("ftp", "pass", FTPPW)
        ini.Write("ftp", "port", FTPPort)
        ini.Write("ftp", "passive", FTPPassive.ToString())
        ini.Write("ftp", "utf8", FTPUTF8.ToString())
        ini.Write("ftp", "path", FTPPath)

        PLog.Add("<< : Save Setting(" + Macroindex.ToString() + ")")
        Return True
    End Function

#End Region

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        '//타이머가 작동중임을 표시한다.
        If RibbonLabel2.Text = "●" Then
            RibbonLabel2.Text = "○"
        Else
            RibbonLabel2.Text = "●"
        End If

        If Not RibbonGroup1.Enabled Then
            RibbonGroup1.Enabled = True
            RibbonGroup2.Enabled = True
            RibbonGroup3.Enabled = True
            RibbonGroup4.Enabled = True
            RibbonGroup6.Enabled = True
            RibbonGroup7.Enabled = True
        End If

        '//현재 상태값을 화면에 보여준다.
        strbuff = New System.Text.StringBuilder
        Select Case cbBakTarget.SelectedIndex
            Case 0
                strbuff.Append("[폴더]")
            Case 1
                strbuff.Append("[파일]")
        End Select

        strbuff = New System.Text.StringBuilder
        '//---원본목록부분
        If IsNumeric(Me.tb_sttrange.Text) = False OrElse Me.tb_sttrange.Text <= 0 Then
            Me.preview1.Text = "시작범위값이 숫자가 아니거나 0보다 작습니다"
            Me.preview1.ForeColor = Color.Red
        ElseIf Me.NewList = False Then
            Me.preview1.Text = "원본목록이 정의되지 않았습니다."
            Me.preview1.ForeColor = Color.Red
        Else
            strbuff.Append(Me.src_Impctl1.getValue(Me.src_view1, Me.tb_sttrange.Text)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl2.getValue(Me.src_view1, Me.tb_sttrange.Text)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl3.getValue(Me.src_view1, Me.tb_sttrange.Text)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl4.getValue(Me.src_view1, Me.tb_sttrange.Text)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl5.getValue(Me.src_view1, Me.tb_sttrange.Text)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl6.getValue(Me.src_view1, Me.tb_sttrange.Text)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl7.getValue(Me.src_view1, Me.tb_sttrange.Text)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            Me.preview1.Text = "미리보기 : " & strbuff.ToString & Pub.GetExtendFromMdi.Trim("*")
            Me.preview1.ForeColor = Color.Black
        End If

        '//원보폴더 160408
        If src_chk_merge.Checked Then
            pviewSrcDir.Text = ""

            Me.pviewSrcDir.ForeColor = Color.Black
            Me.pviewSrcDir.Text = "[대기]"

            If IsNumeric(getSP) = False OrElse getSP() <= 0 Then
                Me.pviewSrcDir.Text = "[원본파일] 시작범위값이 숫자가 아니거나 0보다 작습니다"
                Me.pviewSrcDir.ForeColor = Color.Red
            Else
                Me.pviewSrcDir.Text = "미리보기 : " & Me.DESD_GetSrcDir(getSP, "파일명", "확장자", "") ' Me.tb_path.Text & "\" & Get_FileList(Frm_srcfile.tb_sttrange.Text + 1, "파일명", "확장자").ToString
                If Me.pviewSrcDir.Text.IndexOf("*") >= 0 OrElse Me.pviewDesDir.Text.IndexOf("?") >= 0 Then
                    Me.pviewSrcDir.Text = "원본폴더조합시에는 * 또는 ? 를 사용할 수 없습니다"
                    Me.pviewSrcDir.ForeColor = Color.Red
                End If
            End If
        Else
            pviewSrcDir.Text = tb_workdir.Text
            Me.pviewSrcDir.ForeColor = Color.Gray
        End If

        '//대상폴더
        If Me.desd_Impctl1.enabled = False Then Me.desd_Impctl1.enabled = True
        If Me.desd_Impctl2.enabled = False Then Me.desd_Impctl2.enabled = True
        If Me.desd_Impctl3.enabled = False Then Me.desd_Impctl3.enabled = True
        If Me.desd_Impctl4.enabled = False Then Me.desd_Impctl4.enabled = True
        If Me.desd_Impctl5.enabled = False Then Me.desd_Impctl5.enabled = True
        If Me.desd_Impctl6.enabled = False Then Me.desd_Impctl6.enabled = True
        If Me.desd_Impctl7.enabled = False Then Me.desd_Impctl7.enabled = True
        Me.pviewDesDir.ForeColor = Color.Black
        Me.pviewDesDir.Text = "[대기]"

        If IsNumeric(getSP) = False OrElse getSP() <= 0 Then
            Me.pviewDesDir.Text = "[원본파일] 시작범위값이 숫자가 아니거나 0보다 작습니다"
            Me.pviewDesDir.ForeColor = Color.Red
        Else
            Me.pviewDesDir.Text = "미리보기 : " & Me.DESD_GetDesDir(getSP, "파일명", "확장자", "") ' Me.tb_path.Text & "\" & Get_FileList(Frm_srcfile.tb_sttrange.Text + 1, "파일명", "확장자").ToString
            If Me.pviewDesDir.Text.IndexOf("*") >= 0 OrElse Me.pviewDesDir.Text.IndexOf("?") >= 0 Then
                Me.pviewDesDir.Text = "대상폴더조합시에는 * 또는 ? 를 사용할 수 없습니다"
                Me.pviewDesDir.ForeColor = Color.Red
            End If
        End If

        '//대상파일부분
        If Me.desf_Impctl1.enabled = False Then Me.desf_Impctl1.enabled = True
        If Me.desf_Impctl2.enabled = False Then Me.desf_Impctl2.enabled = True
        If Me.desf_Impctl3.enabled = False Then Me.desf_Impctl3.enabled = True
        If Me.desf_Impctl4.enabled = False Then Me.desf_Impctl4.enabled = True
        If Me.desf_Impctl5.enabled = False Then Me.desf_Impctl5.enabled = True
        If Me.desf_Impctl6.enabled = False Then Me.desf_Impctl6.enabled = True
        If Me.desf_Impctl7.enabled = False Then Me.desf_Impctl7.enabled = True
        Me.pviewDesFile.ForeColor = Color.Black
        Me.pviewDesFile.Text = "[대기]"

        If IsNumeric(getSP) = False OrElse getSP() < 1 Then
            Me.pviewDesFile.Text = "[원본파일] 시작범위값이 숫자가 아니거나 1보다 작습니다"
            Me.pviewDesFile.ForeColor = Color.Red
            Return
        End If

        Me.pviewDesFile.Text = "미리보기 : " & Me.Desf_Get_FileList(getSP, "파일명", "확장자") & Pub.GetExtendFromMdi.Trim("*")
        If Me.pviewDesFile.Text.IndexOf("*") >= 0 OrElse Me.pviewDesFile.Text.IndexOf("?") >= 0 Then
            Me.pviewDesFile.Text = "대상파일조합시에는 * 또는 ? 를 사용할 수 없습니다"
            Me.pviewDesFile.ForeColor = Color.Red
        End If

    End Sub

    '''입력값에 오류를 체크한다.
    Private Function Check_InputError() As Boolean

        If Me.NewList = False Then
            MsgBox("원본 목록이 정의되지않았습니다", MsgBoxStyle.Critical, "확인")
            Return True
        End If

        Ep = Me.GetLastRowCount    '//목록에서 종료줄번호
        Addlog2("원본목록 줄번호 범위 " & getSP() & " ~ " & Ep, True)

        If Val(getSP) < 1 OrElse Val(Ep) < Val(getSP) Then
            MsgBox("목록의 시작줄번호가 1보다 작거나 종료번호가 시작번호보다 작습니다.", MsgBoxStyle.Critical, Ep & " 학인")
            Return True
        End If

        If tb_workdir.Text.StartsWith("ftp:/") Then
            If btCopy.Pressed = False Then
                MsgBox("FTP를 원본으로 사용할 때에는 '이동/삭제' 작업을 할 수 없습니다", MsgBoxStyle.Critical, "확인")
                Return True
            End If
        Else
            If Directory.Exists(Me.tb_workdir.Text) = False Then
                MsgBox("지정된 작업폴더가 존재하지 않거나" & vbCrLf & "경로에 문제가있습니다", MsgBoxStyle.Critical, "확인")
                Return True
            End If
        End If

        '//백업폳러확인
        If Directory.Exists(GetBakDir1) = False AndAlso (GetBackType1() = E_baktype.Folder1) Then
            MsgBox("사용자지정폴더1이 존재하지않지않습니다" & vbCrLf & "백업정책을 해제하거나 경로를 다시 설정하세요", MsgBoxStyle.Critical, "확인")
            Return True
        End If

        '//여기까지 왔다면 오류 없음
        Return False
    End Function

    Public Delegate Sub Msghandler(s As String)
    Public Sub MSG(ByVal s As String)
        If C1StatusBar1.InvokeRequired Then
            C1StatusBar1.Invoke(New Msghandler(AddressOf MSG), New Object() {s})
        Else
            lb_msg.Text = s
            C1StatusBar1.Refresh()
        End If
    End Sub



#Region "SubDir"

    Public ReadOnly Property HasSubDir As Boolean
        Get
            If Me.list_subdir.Items.Count > 0 Then
                Return True
            Else
                Return False
            End If
        End Get
    End Property

    Public ReadOnly Property SubDirCount As Integer
        Get
            Return Me.list_subdir.Items.Count
        End Get
    End Property

    Private Sub list_subdir_KeyDown(sender As Object, e As KeyEventArgs) Handles list_subdir.KeyDown
        If e.KeyCode = Keys.Delete Then
            If Me.list_subdir.Items.Count < 1 OrElse Me.list_subdir.FocusedItem Is Nothing Then Return
            Dim 현재위치 As Integer = Me.list_subdir.FocusedItem.Index

            PLog.Add("Remove SubDir Item : " + Me.list_subdir.Items(현재위치).Text)

            Me.list_subdir.Items.Remove(Me.list_subdir.Items(현재위치))
            If Me.list_subdir.Items.Count >= 현재위치 + 1 Then
                Me.list_subdir.FocusedItem = Me.list_subdir.Items(현재위치)
            ElseIf Me.list_subdir.Items.Count > 0 Then
                Me.list_subdir.FocusedItem = Me.list_subdir.Items(0)
            End If
        End If
    End Sub

    '''하위폴더목록을 추가한다.
    Public Sub AddSubDirList(ByVal s As String)
        If s <> "" Then
            If list_subdir.InvokeRequired Then
                list_subdir.Invoke(New addsubDirlistHandler(AddressOf AddSubDirList), New Object() {s})
            Else
                If Me.list_subdir.Items.IndexOfKey(s.ToUpper) = -1 Then
                    Dim lv As ListViewItem = Me.list_subdir.Items.Add(s.ToUpper, s.ToString, 0)
                    lv.ForeColor = Color.Black
                    lv.SubItems.Add("")
                End If
            End If
        End If
    End Sub
    Private Delegate Sub addsubDirlistHandler(s As String)

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btAddSubDir.Click
        Dim A As String
input:
        A = InputBox("\,/는 제외하고 입력하세요", "서브폴더명입력")
        If A = "" Then Return
        AddSubDirList(A)
        GoTo input
    End Sub

    Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btDeleteSubDir.Click
        If Me.list_subdir.Items.Count = 0 OrElse Me.list_subdir.SelectedItems.Count < 1 Then Return
        Me.list_subdir.Items.Remove(Me.list_subdir.SelectedItems(0))
    End Sub

#End Region

#Region "SRCFILE"
    Private Sub src_bt_read_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub
    Private Sub Src_RenameColumnname()
        PLog.Add("Rename : Column Title")
        For i As Integer = 0 To Me.src_view1.Sheets.Count - 1
            For Each CL As FarPoint.Win.Spread.Column In Me.src_view1.Sheets(i).Columns
                Me.src_view1.Sheets(i).Columns(CL.Index).Label = CL.Index + 1
            Next
        Next
        Me.NewList = True
    End Sub
    Private Sub Src_Init()
        PLog.Add("Farpoint Init")
        Dim im As New FarPoint.Win.Spread.InputMap
        im = src_view1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenAncestorOfFocused)
        im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextColumnWrap)
        im = src_view1.GetInputMap(FarPoint.Win.Spread.InputMapMode.WhenFocused)
        im.Put(New FarPoint.Win.Spread.Keystroke(Keys.Enter, Keys.None), FarPoint.Win.Spread.SpreadActions.MoveToNextColumnWrap)
    End Sub

    Public Function Get_SrcFileList(ByVal sp As Integer) As String
        If sp = 0 Then Return ""
        Dim strbuff As New System.Text.StringBuilder
        strbuff.Append(Me.src_Impctl1.getValue(Me.src_view1, sp - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.src_Impctl2.getValue(Me.src_view1, sp - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.src_Impctl3.getValue(Me.src_view1, sp - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.src_Impctl4.getValue(Me.src_view1, sp - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.src_Impctl5.getValue(Me.src_view1, sp - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.src_Impctl6.getValue(Me.src_view1, sp - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.src_Impctl7.getValue(Me.src_view1, sp - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        Return strbuff.ToString
    End Function

    Public Function GetLastRowCount() As Integer '//마지막 줄번호를 리턴
        If Me.tb_endrange.Text = "" Then Me.tb_endrange.Text = "0"

        Dim Ep As String = Me.tb_endrange.Text   '//종료줄번호
        Dim Sp As String = Me.tb_sttrange.Text     '//시작줄번호

        Dim nullcnt As Integer = 0
        Dim Offset As Integer = 10
        If Ep = "" OrElse Ep = "0" Then  '//끝까지이므로 여기서 계산을 해준다. 1,2,3번열이 연속 5번 비어있으면  멈춘다.
            For i As Integer = Val(Sp) To Me.src_view1.ActiveSheet.RowCount
                If Me.src_view1.ActiveSheet.Cells(i, 0).Text = "" AndAlso Me.src_view1.ActiveSheet.Cells(i, 1).Text = "" AndAlso Me.src_view1.ActiveSheet.Cells(i, 2).Text = "" Then
                    nullcnt += 1
                    If nullcnt = 5 Then
                        Ep = i - 4  '//160407 4 to 3
                        Exit For
                    End If
                Else
                    nullcnt = 0
                End If
            Next
            Return Val(Ep)
        End If
        Return Ep
    End Function

    Public Function Get_FileListArray() As ArrayList
        Dim FileList As New ArrayList
        If NewList = False Then Return Nothing '//목록자체가 결정되지않았다.
        Dim strbuff As System.Text.StringBuilder

        Dim SP, Ep As String
        SP = Me.tb_sttrange.Text
        Ep = Me.tb_endrange.Text
        If Ep = "" OrElse Ep = "0" Then Ep = Me.src_view1.ActiveSheet.RowCount
        If SP < 1 OrElse Ep < SP Then Return Nothing '//1이상으로시작하고 종료숫자는 시작보다 커야한다.

        '//파일목록을 작성합니다.
        MSG("파일목록을 작성합니다")

        Dim NullCnt As Short = 0
        For i As Integer = SP To Ep
            MSG(i & "번줄을 작성하는중...")
            strbuff = New System.Text.StringBuilder
            strbuff.Append(Me.src_Impctl1.getValue(Me.src_view1, SP - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl2.getValue(Me.src_view1, SP - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl3.getValue(Me.src_view1, SP - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl4.getValue(Me.src_view1, SP - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl5.getValue(Me.src_view1, SP - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl6.getValue(Me.src_view1, SP - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.src_Impctl7.getValue(Me.src_view1, SP - 1)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            If strbuff.ToString.Trim <> "" Then
                FileList.Add(strbuff.ToString) '//내용이있으면 배열에저장한다.
                NullCnt = 0
            Else
                NullCnt += 1
                If NullCnt = 5 Then '//빈줄이나올때 널카운트를 증가시키고 빈줄이 5번연속나올때는 빠져나온다.
                    Exit For
                End If
            End If
        Next
        MSG("파일목록을 작성완료")
        If FileList.Count = 0 Then Return Nothing
        Return FileList
    End Function

    Private Sub SRC_Imp_Enable(ByVal value As Boolean)
        PLog.Add("Import Control Enable Set = " + value.ToString())
        If Me.src_Impctl1.enabled <> value Then Me.src_Impctl1.enabled = value
        If Me.src_Impctl2.enabled <> value Then Me.src_Impctl2.enabled = value
        If Me.src_Impctl3.enabled <> value Then Me.src_Impctl3.enabled = value
        If Me.src_Impctl4.enabled <> value Then Me.src_Impctl4.enabled = value
        If Me.src_Impctl5.enabled <> value Then Me.src_Impctl5.enabled = value
        If Me.src_Impctl6.enabled <> value Then Me.src_Impctl6.enabled = value
        If Me.src_Impctl7.enabled <> value Then Me.src_Impctl7.enabled = value
    End Sub

#End Region

#Region "DESDIR"
    Private Sub ToolStripButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles desd_find_folder.Click
        Dim FB As New FolderBrowserDialog
        FB.SelectedPath = Me.desd_tb_path.Text
        If FB.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.desd_tb_path.Text = FB.SelectedPath
        End If
    End Sub
    Public Function DESD_GetSrcDir(ByVal Rownum As Integer, ByVal orgfn As String, ByVal orgext As String, ByVal subfolder As String) As String
        '//sp는 목록을 사용햇을때 몇번째 row인지의 오프셋이다.
        If Rownum = 0 Then Return "#Err"
        Dim pathdiv As Char = "\"c
        If tb_workdir.Text.StartsWith("ftp:") Then pathdiv = "/"c

        Dim NewDir As String
        If Me.src_chk_merge.Checked Then  '//폴더만사용
            ' Addlog2(Get_FileList(Rownum, orgfn, orgext).ToString)
            NewDir = Me.tb_workdir.Text.Trim(pathdiv) & pathdiv & srcd_Get_FileList(Rownum, orgfn, orgext).ToString
        Else
            NewDir = Me.tb_workdir.Text.Trim(pathdiv) & pathdiv & subfolder
        End If
        ' MsgBox(NewDir.Replace("\\", "\"), MsgBoxStyle.Information, subfolder)
        Return (NewDir.Replace(pathdiv + pathdiv, pathdiv))
    End Function
    Public Function DESD_GetDesDir(ByVal Rownum As Integer, ByVal orgfn As String, ByVal orgext As String, ByVal subfolder As String) As String
        '//sp는 목록을 사용햇을때 몇번째 row인지의 오프셋이다.
        If Rownum = 0 Then Return "#Err"

        Dim NewDir As String
        If Me.des_chk_merge.Checked Then  '//폴더만사용
            ' Addlog2(Get_FileList(Rownum, orgfn, orgext).ToString)
            NewDir = Me.desd_tb_path.Text.Trim("\") & "\" & desd_Get_FileList(Rownum, orgfn, orgext).ToString
        Else
            NewDir = Me.desd_tb_path.Text.Trim("\") & "\" & subfolder
        End If
        ' MsgBox(NewDir.Replace("\\", "\"), MsgBoxStyle.Information, subfolder)
        Return (NewDir.Replace("\\", "\"))
    End Function

    Delegate Function desd_Get_FileListHandler(ByVal sp As Integer, ByVal orgfn As String, ByVal orgext As String) As String
    Private Function desd_Get_FileList(ByVal sp As Integer, ByVal orgfn As String, ByVal orgext As String) As String
        If im1.InvokeRequired Then
            Return im1.Invoke(New desd_Get_FileListHandler(AddressOf desd_Get_FileList), New Object() {sp, orgfn, orgext})
        Else
            Dim strbuff As New System.Text.StringBuilder
            strbuff.Append(Me.desd_Impctl1.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.desd_Impctl2.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.desd_Impctl3.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.desd_Impctl4.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.desd_Impctl5.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.desd_Impctl6.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.desd_Impctl7.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            Return strbuff.ToString
        End If
    End Function

    Delegate Function srcd_Get_FileListHandler(ByVal sp As Integer, ByVal orgfn As String, ByVal orgext As String) As String
    Public Function srcd_Get_FileList(ByVal sp As Integer, ByVal orgfn As String, ByVal orgext As String) As String
        If im1.InvokeRequired Then
            Return im1.Invoke(New srcd_Get_FileListHandler(AddressOf srcd_Get_FileList), New Object() {sp, orgfn, orgext})
        Else
            Dim strbuff As New System.Text.StringBuilder
            strbuff.Append(Me.im1.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.im2.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.im3.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.im4.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.im5.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.im6.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            strbuff.Append(Me.im7.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
            Return strbuff.ToString
        End If
    End Function
#End Region

#Region "DESFILE"
    Public Function Desf_Get_FileList(ByVal sp As Integer, ByVal orgfn As String, ByVal orgext As String) As String
        Dim strbuff As New System.Text.StringBuilder
        strbuff.Append(Me.desf_Impctl1.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.desf_Impctl2.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.desf_Impctl3.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.desf_Impctl4.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.desf_Impctl5.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.desf_Impctl6.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        strbuff.Append(Me.desf_Impctl7.getValue(Me.src_view1, sp, orgfn, orgext)) '  Me.view1.ActiveSheet.Cells(Me.tb_sttrange.Text, CT.열번호.Substring(1)).Text)
        Return strbuff.ToString
    End Function
#End Region

    'Private Sub StatusStrip1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
    '    '//사용자가 파일목록을 직접 구성하려고할때를 가정한다.
    '    '//기존파일뒤에 추가할것인지 초기화하고 추가할것인지 묻는다
    '    If MsgBox("기존파일의 목록을 유지하고 추가하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "원본목록 사용자생성") <> MsgBoxResult.Ok Then
    '        Me.DataSet1.FileList.Rows.Clear()
    '        Me.DataSet1.FileList.AcceptChanges()
    '    End If

    '    '//이렇게되면 이제 추가를 한다.
    '    If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
    '        Dim STR() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
    '        For Each fn As String In STR
    '            My.Application.DoEvents()
    '            Dim Fi As New System.IO.FileInfo(fn)
    '            Dim Dir As System.IO.DirectoryInfo
    '            If Fi.Exists = False Then    '//디렉토리다.
    '                Dir = New System.IO.DirectoryInfo(fn)
    '                For Each Ff As System.IO.FileInfo In Dir.GetFiles("*.jpg", 1)
    '                    Me.DataSet1.FileList.Rows.Add(New String() {Ff.DirectoryName, Ff.Name})
    '                    Me.lb_cnt1.Text = "파일검색중(" & Me.DataSet1.FileList.Rows.Count & ")"
    '                    My.Application.DoEvents()
    '                Next
    '            Else   '//파일일경우에
    '                If Fi.Extension.ToUpper = ".JPG" Then Me.DataSet1.FileList.Rows.Add(New String() {Fi.DirectoryName, Fi.Name})
    '                Me.lb_cnt1.Text = "파일검색중(" & Me.DataSet1.FileList.Rows.Count & ")"
    '                My.Application.DoEvents()
    '            End If
    '        Next
    '    End If
    '    MsgBox(Me.DataSet1.FileList.Rows.Count, MsgBoxStyle.Information, "수집")
    '    'Me.dv_filelist.DataSource = Me.DataSet1.FileList
    'End Sub

    'Private Sub StatusStrip1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
    '    '//대상목록파일을 직접 지정할려고할때 쓴다.
    '    If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
    '        e.Effect = DragDropEffects.Copy
    '    ElseIf (e.Data.GetDataPresent(DataFormats.StringFormat)) Then
    '        ' MsgBox("string")
    '        e.Effect = DragDropEffects.Copy
    '    ElseIf (e.Data.GetDataPresent(DataFormats.Text)) Then
    '        ' MsgBox("text")
    '        e.Effect = DragDropEffects.Copy
    '    Else
    '        e.Effect = DragDropEffects.None
    '    End If
    'End Sub

    Private Sub des_chk_merge_CheckedChanged(sender As Object, e As EventArgs) Handles des_chk_merge.CheckedChanged
        desd_pt.Enabled = des_chk_merge.Checked
        PLog.Add("대상폴더조합기능 변경 : " + des_chk_merge.Checked.ToString(), True)
    End Sub

    Private Sub src_chk_merge_CheckedChanged(sender As Object, e As EventArgs) Handles src_chk_merge.CheckedChanged
        srcd_pt.Enabled = src_chk_merge.Checked
        ToolStrip1.Enabled = Not src_chk_merge.Checked
        'list_subdir.Enabled = Not src_chk_merge.Checked
        PLog.Add("원본폴더조합기능 변경 : " + src_chk_merge.Checked.ToString(), True)
    End Sub

    Private Sub srcd_find_ftp_Click(sender As Object, e As EventArgs) Handles srcd_find_ftp.Click
        Dim f As New fFtpPath(FTPServer, FTPID, FTPPW, FTPPort, FTPPassive, FTPUTF8, FTPPath)
        If f.ShowDialog() = Windows.Forms.DialogResult.OK Then
            tb_workdir.Text = "ftp:/" + f.Selpath
            PLog.Add("FTP 원본경로 변경 : " + f.Selpath)

            FTPServer = f.tb_ftpserver.Text
            FTPID = f.tb_ftpid.Text
            FTPPW = f.tb_ftppass.Text
            FTPPort = f.tb_ftpport.Text
            FTPPassive = f.chk_ftpPassive.Checked
            FTPUTF8 = f.chk_ftputf8.Checked
            FTPPath = f.tb_ftppath.Text
        Else
            MsgBox("선택이 취소되었습니다", MsgBoxStyle.Information, "확인")
        End If

        FTP_0.Close()
    End Sub

    Private Sub srcd_find_folder_Click(sender As Object, e As EventArgs) Handles bt_workdir.Click
        Me.FB.SelectedPath = Me.tb_workdir.Text
        If Me.FB.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.tb_workdir.Text = FB.SelectedPath
            PLog.Add("원본경로 변경 : " + FB.SelectedPath)
        End If
    End Sub

    Private Sub ToolStripButton4_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton4.Click
        Dim SB As New System.Text.StringBuilder("[복사]")
        SB.AppendLine()
        SB.AppendLine("복사가될 위치 : 원본폴더로부터 이곳에 복사됩니다")
        SB.AppendLine()
        SB.AppendLine("[삭제]")
        SB.AppendLine("사용되지않음")
        SB.AppendLine()
        SB.AppendLine("[이동]")
        SB.AppendLine("원본폴더로부터 이동되는 위치")
        MsgBox(SB.ToString, MsgBoxStyle.Information, "확인")
    End Sub

    Private Sub RibbonButton10_Click(sender As Object, e As EventArgs) Handles RibbonButton10.Click
        PLog.Add("닫기버튼클릭")
        Me.Close()
    End Sub

    Private Sub btCopy_Click(sender As Object, e As EventArgs) Handles btCopy.Click, btDel.Click, btMove.Click

        Dim bt As C1.Win.C1Ribbon.RibbonToggleButton = sender
        If bt.Name.ToLower = "btdel" Then
            btCopy.Pressed = False
            btDel.Pressed = True
            btMove.Pressed = False
            PLog.Add("작업형태 [delete] 클릭")
        ElseIf bt.Name.ToLower = "btmove" Then
            btCopy.Pressed = False
            btDel.Pressed = False
            btMove.Pressed = True
            PLog.Add("작업형태 [move] 클릭")
        Else
            btCopy.Pressed = True
            btDel.Pressed = False
            btMove.Pressed = False
            PLog.Add("작업형태 [copy] 클릭")
        End If

    End Sub

    Private Sub RibbonButton11_Click_1(sender As Object, e As EventArgs) Handles RibbonButton11.Click
        Form_Status.Winhide = False
        Form_Status.AutoRun = False
        Form_Status.Show()
    End Sub

    Private Sub RibbonTextBox2_TextChanged(sender As Object, e As EventArgs) Handles tb_sttrange.TextChanged
        If Me.tb_sttrange.Text = "0" Then
            MsgBox("목록의 시작값은 반드시 1보다 커야합니다", MsgBoxStyle.Critical, "확인")
            Me.tb_sttrange.Text = "1"
        End If
    End Sub

    '''파일(엑셀)열기
    Private Sub RibbonButton8_Click(sender As Object, e As EventArgs) Handles btOpenFile.Click
        Dim fn As String
        If Prev_file Is Nothing Then
            fn = ARINCLASS.OpenFile("", "엑셀파일|*.xls")
        Else
            fn = ARINCLASS.OpenFile(Prev_file.FullName, "엑셀파일|*.xls")
        End If

        If fn <> "" Then

            '//설정창으로 표시를 해준다.
            TabControl1.SelectedIndex = 0

            Prev_file = New System.IO.FileInfo(fn)

            Noti("File Open" + vbCrLf + fn)
            PLog.Add("File Open : " + fn)
            Me.src_view1.OpenExcel(fn)
            Src_RenameColumnname()

            '//줄너비값을 이용하여 처리해준다
            If chk_autorow.Checked Then
                tb_endrange.Text = "0"
                Dim 마지막줄번호 As Integer = GetLastRowCount()
                tb_endrange.Text = 마지막줄번호.ToString()
                src_view1_Sheet1.RowCount = CInt(tb_endrange.Text) + 5
                PLog.Add("Auto RowCount = " + tb_endrange.Text, True)
            End If
        End If
    End Sub

    '''목록직접작성하기
    Private Sub RibbonButton9_Click(sender As Object, e As EventArgs) Handles btMakeNewList.Click

        '//설정창으로 표시를 해준다.
        TabControl1.SelectedIndex = 0

        Prev_file = Nothing
        Me.src_view1.ActiveSheet.RowCount = 0
        Me.src_view1.ActiveSheet.RowCount = 100
        Me.src_view1.ActiveSheet.ColumnCount = 0
        Me.src_view1.ActiveSheet.ColumnCount = 100
        Dim CT As New FarPoint.Win.Spread.CellType.TextCellType

        For i As Integer = 0 To Me.src_view1.Sheets.Count - 1
            For Each CL As FarPoint.Win.Spread.Column In Me.src_view1.Sheets(i).Columns
                CL.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center
                CL.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center
                Me.src_view1.Sheets(i).Columns(CL.Index).CellType = CT
            Next
        Next
        Src_RenameColumnname()
    End Sub

    Private Sub RibbonButton8_Click_1(sender As Object, e As EventArgs) Handles bT_netdrvconn.Click
        Dim DirName As Char = "X"
        Dim Path As String = "\\Kepgis_4822\ndis\photo"
dname:
        If Directory.Exists(DirName & ":\") Then
            MsgBox("지정된 드라이브가 존재합니다 다른드라이브명을 사용하세요", MsgBoxStyle.Critical, "확인")
            DirName = Chr(Asc(DirName) + 1)
            GoTo dname
        End If

        Dim A As New System.Text.StringBuilder("사용할 네트워크 드라이브/네트워크경로를 입력하세요")
        A.AppendLine()
        A.AppendLine("예) X/\\Kepgis_<지점코드>\ndis\photo")
        Dim n As String = InputBox(A.ToString, "드라이브연결", DirName & "/" & Path)
        If n = "" Then Return
        Dim S() As String = n.Split("/")

        If Directory.Exists(S(0) & ":\") Then
            MsgBox("지정된 드라이브가 존재합니다 다른드라이브명을 사용하세요", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Dim P As New Process
        P.StartInfo.FileName = "net"
        P.StartInfo.Arguments = " use " & S(0) & ": " & S(1)

        PLog.Add("Net Drive Connect : " + P.StartInfo.Arguments)
        P.Start()

    End Sub

    Private Sub RibbonButton12_Click(sender As Object, e As EventArgs) Handles bt_netdrvdel.Click
        Dim A As String = InputBox("드라이브명을 입력하세요" & vbCrLf & "X", "네트워크드라이브 삭제", "X")
        If A = "" Then Return
        Dim P As New Process
        P.StartInfo.FileName = "net"
        P.StartInfo.Arguments = " use " & A & ": /d"

        PLog.Add("Net Drive Delete : " + P.StartInfo.Arguments)
        P.Start()
    End Sub

    Private Sub RibbonButton8_Click_2(sender As Object, e As EventArgs) Handles RibbonButton8.Click
        If Me.Setting_Save(-999) Then
            MsgBox("매크로가 저장되었습니다", MsgBoxStyle.Information, "확인")
            Me.Load_Macro()
        End If
    End Sub

    Private Sub RibbonButton12_Click_1(sender As Object, e As EventArgs) Handles RibbonButton12.Click
        If Me.cmb_macro.SelectedIndex <= 0 Then
            MsgBox("저장될 매크로가 선택되지않았습니다", MsgBoxStyle.Information, "확인")
            Return
        End If
        If Me.Setting_Save(Me.cmb_macro.SelectedIndex) Then
            MsgBox("매크로가 저장되었습니다", MsgBoxStyle.Information, "확인")
            Me.Load_Macro()
        End If
    End Sub

    Private Sub RibbonButton13_Click(sender As Object, e As EventArgs) Handles RibbonButton13.Click
        If Me.cmb_macro.SelectedIndex <= 0 Then
            MsgBox("삭제될 매크로가 선택되지않았습니다", MsgBoxStyle.Information, "확인")
            Return
        End If
        File.Delete(Me.Macro(Me.cmb_macro.SelectedIndex - 1).FileName)
        MsgBox("매크로가 삭제되었습니다", MsgBoxStyle.Information, "확인")
        Me.Load_Macro()
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmb_macro.SelectedIndexChanged
        Setting_Load(Me.cmb_macro.SelectedIndex)
    End Sub

#Region "실행버튼"

    Private Sub RibbonButton1_Click(sender As Object, e As EventArgs) Handles bt_run.Click
        Job_Start(chkReplay.Checked)
    End Sub

    Sub Job_Start(replay As Boolean)
        If Check_InputError() Then Return
        Me.Timer1.Enabled = False

        Dim startP As Integer = Integer.Parse(tb_sttrange.Text) '//시작줄
        Dim endP As Integer = GetLastRowCount() '//종료줄
        Dim WorkDir As String = GetWorkDIr()

        If MsgBox("시스템 데이터를 수집합니다" & vbCrLf & "이후 실행 메세지가 출력됩니다" & vbCrLf & "계속하시겠습니까?", MsgBoxStyle.Information + MsgBoxStyle.OkCancel, "실행확인") <> MsgBoxResult.Ok Then Return

        '//작업창으로 화면을 돌려준다.
        Me.TabControl1.SelectedIndex = 1
        Me.TabControl1.Refresh()

        '//데이터테이블초기화(대상목록이저장된다)
        PLog.Add("데이터테이블초기화")
        DataSet1.SrcList.Rows.Clear()
        DataSet1.FileList.Rows.Clear()
        DataSet1.WorkList.Rows.Clear()
        DataSet1.SrcList.AcceptChanges() '//삭제승인
        DataSet1.FileList.AcceptChanges()
        DataSet1.WorkList.AcceptChanges()

        '//스케쥴창표시
        lvSchedule.Items.Clear()
        lvSchedule.Refresh()

        '//작업파라미터를 생성
        Dim param As New RunParam
        param.StartP = startP
        param.Replay = replay
        param.EndP = endP
        param.WorkDir = WorkDir
        param.isCopy = btCopy.Pressed
        param.원본폴더조합 = src_chk_merge.Checked
        param.확장자 = Me.GetExt()

        If chkHide.Checked Then
            Me.WindowState = FormWindowState.Minimized
            Noti("작업실행")
        End If

        '//작업시작
        If Job.Run(param) Then

            '//스케쥴데이터도 기록을 해준다. 160717
            Dim fn As String = PathList + "\스케쥴" + Format(Now, "yyMMddHHmm") + ".txt"
            Dim buf As New System.Text.StringBuilder
            For i As Integer = 1 To lvSchedule.Columns.Count
                buf.Append(vbTab + lvSchedule.Columns(i - 1).Text)
            Next
            buf.AppendLine()
            For Each lv As ListViewItem In lvSchedule.Items
                For i As Integer = 1 To lvSchedule.Columns.Count
                    buf.Append(vbTab + lv.SubItems(i - 1).Text)
                Next
                buf.AppendLine()
            Next
            System.IO.File.WriteAllText(fn, buf.ToString())

            '//목록을 미리 저장해준다.
            'Dim 파일_전체 As String = PathList + "\" + Format(Now, "yyMMddHHmm") + "전체파일목록.xls"
            'Dim 파일_작업 As String = PathList + "\" + Format(Now, "yyMMddHHmm") + "작업파일목록.xls"
            'Dim 파일_원본 As String = PathList + "\" + Format(Now, "yyMMddHHmm") + "원본파일목록.xls"

            'SaveExcelFile(파일_전체, DataSet1.FileList)
            'SaveExcelFile(파일_작업, DataSet1.WorkList)
            'SaveExcelFile(파일_원본, DataSet1.SrcList)

            If chkHide.Checked Then
                Form_Status.WindowState = FormWindowState.Minimized
            Else
                Form_Status.WindowState = FormWindowState.Normal
            End If
            Form_Status.Show()
            Application.DoEvents()

            '//svae List
            Form_Status.AutoRun = chkAutoRun.Checked
            Form_Status.Winhide = chkHide.Checked
            Form_Status.SaveList(Form_Status.E_SaveType.FileList, False)
            Form_Status.SaveList(Form_Status.E_SaveType.SrcList, False)
            Form_Status.SaveList(Form_Status.E_SaveType.WorkList, False)

            '//작업내용표시
            If chkAutoRun.Checked Then
                Form_Status.btRun.PerformClick()
            End If
        End If

        '//임시로 뷰에 보여준다.
        Me.Timer1.Enabled = True
    End Sub

#End Region

   

#Region "Progress Bar"

    Private Delegate Sub PorgressSetHandler(Max As Integer, Min As Integer, value As Integer)
    Public Sub ProgressSet(Max As Integer, Min As Integer, value As Integer)
        If C1StatusBar1.InvokeRequired Then
            C1StatusBar1.Invoke(New PorgressSetHandler(AddressOf ProgressSet), New Object() {Max, Min})
        Else
            prb1.Maximum = Max
            prb1.Minimum = Min
            prb1.Value = value
            C1StatusBar1.Refresh()
        End If
    End Sub

    Private Delegate Sub ProgressvalHandler(value As Integer)
    Public Sub ProgressVal(value As Integer)
        If C1StatusBar1.InvokeRequired Then
            C1StatusBar1.Invoke(New ProgressvalHandler(AddressOf ProgressVal), New Object() {value})
        Else
            prb1.Value = value
            C1StatusBar1.Refresh()
        End If
    End Sub

#End Region

    '''확장자명을 가져옵니다.
    Function GetExt() As String
        If C1Ribbon1.InvokeRequired Then
            Return C1Ribbon1.Invoke(New GetExtHandler(AddressOf GetExt), New Object() {})
        Else
            Dim ext As String = tb_ext.Text.Trim()
            If String.IsNullOrEmpty(ext) Then ext = "JPG"
            Return ext
        End If
    End Function
    Delegate Sub GetExtHandler()

    '''입력된 하위폴더목록이 현재 존재하는가 확인합니다.
    Function CheckExistSubDir(subdir As String) As Boolean
        If list_subdir.InvokeRequired Then
            Return list_subdir.Invoke(New CheckExistSubDirHandler(AddressOf CheckExistSubDir), New Object() {subdir})
        Else
            If list_subdir.Items.IndexOfKey(subdir) = -1 Then
                Return False
            Else
                Return True
            End If
        End If
    End Function
    Delegate Sub CheckExistSubDirHandler(subdir As String)

    Sub SubDirListCler()
        If list_subdir.InvokeRequired Then
            list_subdir.Invoke(New MethodInvoker(AddressOf SubDirListCler), New Object() {})
        Else
            list_subdir.Items.Clear()
            list_subdir.Refresh()
        End If
    End Sub

    Sub ScheduleListCler()
        If lvSchedule.InvokeRequired Then
            lvSchedule.Invoke(New MethodInvoker(AddressOf ScheduleListCler), New Object() {})
        Else
            lvSchedule.Items.Clear()
            lvSchedule.Refresh()
        End If
    End Sub

    Function GetSrcMerge() As Boolean
        If ToolStrip5.InvokeRequired Then
            ToolStrip5.Invoke(New MethodInvoker(AddressOf GetSrcMerge), New Object() {})
        Else
            Return src_chk_merge.Checked
        End If
    End Function

    Function GetStartPosition() As Integer
        If C1Ribbon1.InvokeRequired Then
            C1Ribbon1.Invoke(New MethodInvoker(AddressOf GetStartPosition), New Object() {})
        Else
            Return tb_sttrange.Text
        End If
    End Function

    Function GetSubDirCount() As Integer
        If list_subdir.InvokeRequired Then
            list_subdir.Invoke(New MethodInvoker(AddressOf GetSubDirCount), New Object() {})
        Else
            Return list_subdir.Items.Count
        End If
    End Function

    Delegate Sub GetSubDirItemStringHandler(rowindex As Integer, colindex As Integer)
    Function GetSubDirItemString(rowindex As Integer, colindex As Integer) As String
        If list_subdir.InvokeRequired Then
            Return list_subdir.Invoke(New GetSubDirItemStringHandler(AddressOf GetSubDirItemString), New Object() {rowindex, colindex})
        Else
            Return list_subdir.Items(rowindex).SubItems(colindex).Text
        End If
    End Function

    Delegate Sub AddScheduleItemHanlder(A As String, B As String, C As String, D As String)
    Sub AddScheduleItem(A As String, B As String, C As String, D As String)
        If lvSchedule.InvokeRequired Then
            lvSchedule.Invoke(New AddScheduleItemHanlder(AddressOf AddScheduleItem), New Object() {A, B, C, D})
        Else
            Dim lv As ListViewItem = lvSchedule.Items.Add(A)
            lv.SubItems.Add(B)
            lv.SubItems.Add(C)
            lv.SubItems.Add(D)
            lvSchedule.Refresh()
        End If
    End Sub

    Private Sub RibbonButton1_Click_1(sender As Object, e As EventArgs) Handles RibbonButton1.Click
        If cbBakType.SelectedIndex <> 1 Then
            MsgBox("백업방법이 사용자지정폴더일때에 사용됩니다.", MsgBoxStyle.Information, "확인")
        End If
        Me.FB.SelectedPath = Me.tb_bakdir1.Text
        Me.FB.ShowDialog()
        Me.tb_bakdir1.Text = FB.SelectedPath
    End Sub

    Private Sub src_chk_merge_Click(sender As Object, e As EventArgs) Handles src_chk_merge.Click
        If src_chk_merge.Checked Then
            MsgBox("원본폴더를 조합할 경우 '하위폴더목록'을 수동으로 입력할 수 없습니다" + vbCrLf + "하위폴더는 원본조합에서 자동으로 설정됩니다")
        End If
    End Sub

    Private Sub chkReplay_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkReplay.CheckedChanged
        PLog.Add("작업이어하기 클릭 변경값=" + chkReplay.Checked.ToString())
    End Sub

    Private Sub chkAutoRun_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkAutoRun.CheckedChanged
        PLog.Add("작업자동실행 클릭 변경값=" + chkAutoRun.Checked.ToString())
    End Sub

    Private Sub btMakeCache_Click(sender As System.Object, e As System.EventArgs) Handles btMakeCache.Click
        '//Summary 파일을 재 생성한다.
        If Not GetWorkDIr().ToLower.StartsWith("ftp:") Then
            MsgBox("캐쉬파일(Summary.txt)는 FTP대상일때만 사용할 수 있습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Dim CacheDirName As String = PathJob + "\" + FTPServer
        CacheDirName = CacheDirName.Replace("\\", "\")

        MsgBox("캐쉬파일(Summary.txt)을 생성할 폴더를 선택하세요", MsgBoxStyle.Information, "확인")
        Dim fd As New FolderBrowserDialog
        fd.SelectedPath = CacheDirName
        If (fd.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            Dim di As New System.IO.DirectoryInfo(fd.SelectedPath)
            If Not di.Exists Then
                MsgBox("대상폴더" + vbCrLf + di.FullName + "가 존재하지 않습니다", MsgBoxStyle.Critical, "확인")
                Return
            End If

            '//summary 파일이 존재하는가?
            Dim Summary As New System.IO.FileInfo(di.FullName + "\Summary.txt")
            If Summary.Exists Then
                If MsgBox("캐쉬파일(Summary.txt)가 현재 존재합니다. 새로 생성하시겠습니까?", MsgBoxStyle.YesNo + MsgBoxStyle.Information, "확인") <> MsgBoxResult.Yes Then
                    Return
                End If
            End If

            Dim files() As System.IO.FileInfo = di.GetFiles("*." + GetExt())
            If files.Length < 1 Then
                If MsgBox("대상폴더에 파일이 존재하지 않습니다." + vbCrLf + "진행하시겠습니까?", _
                             MsgBoxStyle.YesNo Or MsgBoxStyle.Question, "확인") <> MsgBoxResult.Yes Then
                    Return
                End If
            End If


            '//이대상파일의 summay를 먼저 생성하고 하위폴더를 추가로 생성한다.
            Dim summaryCur As New ArinSetting.ArinSetting(Summary.FullName)
            summaryCur.CreateFile()
            summaryCur.Data("file", "count") = files.Length.ToString()

            Dim filelist As String = ""
            For Each fi As System.IO.FileInfo In files
                filelist += "," + fi.Name
            Next
            summaryCur.Data("file", "list") = filelist

            Dim 하위폴더() As System.IO.DirectoryInfo = di.GetDirectories()
            summaryCur.Data("subdir", "count") = 하위폴더.Length.ToString()

            Dim 하위폴더목록 As String = ""
            For Each subdr As System.IO.DirectoryInfo In 하위폴더
                하위폴더목록 += "," + subdr.Name
            Next
            summaryCur.Data("subdir", "list") = 하위폴더목록
            summaryCur.Save()

            MsgBox("캐쉬파일(Summary.txt)이 생성되었습니다" + vbCrLf + _
                "폴더내에 하위폴더가 있다면 해당 폴더도 개별 생성해야합니다", MsgBoxStyle.Information, "확인")
        End If

    End Sub
End Class

