using FCOMMON;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FPJ0000.JobReport_
{
	public partial class fProjectConnect : fBase
	{
		public fProjectConnect(string sd, string ed)
		{
			InitializeComponent();
			dts.Value = DateTime.Parse(sd);
			dte.Value = DateTime.Parse(ed);
		}

		private void fProjectConnect_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            RefreshList();
		}

		void RefreshList()
		{
			var cn = FCOMMON.DBM.getCn();
			var sd = dts.Value.ToString("yyyy-MM-dd");
			var ed = dte.Value.ToString("yyyy-MM-dd");
			var sql =
					$"select projectName,max(pidx) as pidx " +
					$" from JobReport" +
					$" where gcode = '{FCOMMON.info.Login.gcode}'" +
					$" and uid = '{FCOMMON.info.Login.no}'" +
					$" and pdate between '{sd}'  and '{ed}'" +
					$" and pidx = -1" +
					$" and isnull(projectname,'') <> ''" +
					$" group by projectName" +
					$" order by projectName";

			if (cn.State == ConnectionState.Closed) cn.Open();
			var cmd = new System.Data.SqlClient.SqlCommand(sql, cn);
			var rd = cmd.ExecuteReader();
			listView1.Items.Clear();
			while (rd.Read())
			{
				var title = rd[0].ToString();
				var pidx = int.Parse(rd[1].ToString());

				var lv = this.listView1.Items.Add(pidx.ToString());
				lv.SubItems.Add(title);
			}

			rd.Close();

			//전체프로젝트목록을 가져온다
			sql =
				$" select idx,status,name,pdate,userManager" +
				$" from Projects" +
				$" where gcode = '{FCOMMON.info.Login.gcode}'" +
				$" and isnull(isdel,0) = 0 and isnull(name,'') <> '' and isnull(status,'') <> '취소'" +
				$" order by status ,name,pdate desc";
			cmd.CommandText = sql;
			rd = cmd.ExecuteReader();
			//comboBox1.Items.Clear();
			var dt = new DataTable();
			dt.Columns.Add("idx");
			dt.Columns.Add("title");
			dt.Columns.Add("display");
			dt.Columns.Add("status");
			while (rd.Read())
			{
				var pidx = int.Parse(rd[0].ToString());
				var stats = rd[1].ToString();
				var title = rd[2].ToString();
				var pdate = rd[3].ToString();
				var manager = rd[4].ToString();

				var itemtitle = $"[{pidx:00000}] ({stats}) {title} ##{manager}";
				dt.Rows.Add(new object[] {pidx,title,itemtitle,stats });
				
			}

			comboBox1.DataSource = dt;
			comboBox1.DisplayMember = "display";
			comboBox1.ValueMember = "idx";
			comboBox1.SelectedIndex = -1;

			rd.Close();

			cmd.Dispose();
			cn.Close();
			cn.Dispose();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (comboBox1.SelectedIndex < 0) return;
			var txt = comboBox1.SelectedItem as DataRowView;
			if (txt == null) return;

			List<ListViewItem> lvs = new List<ListViewItem>();
			if(listView1.CheckedItems.Count < 1)
			{
				if (listView1.FocusedItem == null)
				{
					FCOMMON.Util.MsgE("변경할 자료를 선택하세요.");
					return;
				}
				else lvs.Add(listView1.FocusedItem);
			}
			else
			{
				foreach (ListViewItem item in listView1.CheckedItems)
					lvs.Add(item);
			}

			var idx = txt["idx"].ToString();
			var title = txt["title"].ToString();


			var sb = new System.Text.StringBuilder();
			sb.AppendLine("다음 자료의 프로젝트를 연결 할까요?\n");
			foreach (var item in lvs)
				sb.Append($"[ {item.SubItems[1].Text} ]");
			sb.AppendLine();
			sb.AppendLine();
			sb.AppendLine($"연결대상 프로젝트 : [{idx}] {title}");
			if (FCOMMON.Util.MsgQ(sb.ToString()) != DialogResult.Yes) return;



			var cn = FCOMMON.DBM.getCn();
			var sd = dts.Value.ToString("yyyy-MM-dd");
			var ed = dte.Value.ToString("yyyy-MM-dd");
			if (cn.State == ConnectionState.Closed) cn.Open();
			var cmd = new System.Data.SqlClient.SqlCommand("", cn);
		

			foreach (var item in lvs)
			{
				var sql = 
				$" update jobreport set projectName='{title}',pidx={idx}" +
				$" from JobReport" +
				$" where gcode = '{FCOMMON.info.Login.gcode}'" +
				$" and uid = '{FCOMMON.info.Login.no}'" +
				$" and pdate between '{sd}'  and '{ed}'" +
				$" and pidx = -1" +
				$" and isnull(projectname,'') = '{item.SubItems[1].Text}'";
				cmd.CommandText = sql;
				cmd.ExecuteNonQuery();
			}
				
			cmd.Dispose();
			cn.Close();
			cn.Dispose();

		}

		private void btRefresh_Click(object sender, EventArgs e)
		{
			RefreshList();
		}
	}
}
