using log4net;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using JobAutoCreateFee.Model;
using System.IO;

namespace JobCreateFee
{
    public class JobBcEdiReplyContrast : IJob
    {
        private ILog log = LogManager.GetLogger(typeof(JobBcEdiReplyContrast));

        public void Execute(IJobExecutionContext context)
        {
            log.Debug($"Execute开始");
            try
            {
                string connStr = context.JobDetail.JobDataMap.GetString("ConnectString");
                string BcPath = context.JobDetail.JobDataMap.GetString("BcPath");



                string tempPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BcTmp");
                //string BcPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BcPath");

                if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }



             string[] files = Directory.GetFiles(BcPath);
            if (files.Length > 0)
            {
                foreach (string file in files)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    string pathtxt = File.ReadAllText(file);
                    var opList = pathtxt.Split('\'');
                    var MBLNO = "";
                    var BSNO = "";
                    var PORTDISCHARGID = "";
                    var PORTDISCHARG = "";
                        var DESTINATIONID = "";
                        var DESTINATION = "";
                        var TMPSTR = "";
                    var CTNTYPE = "";
                    var CTNNUM = "";
                        int LOCCOUNT =0;
                        var FILETYPE = "";
                        log.Debug($"文件名"+ fileInfo.Name);
                        var ctnlist = new List<JsonCtn>();
                        foreach (var opstr in opList)
                        {
                            var line = opstr;
                            if (string.IsNullOrEmpty(line))
                                continue;
                            var head = "";
                            if (line.Length>=3)
                                head = line.Substring(0, 3);
                            if (head == "RFF")
                            {
                                var strtmp = GetPosStringplus(line, 2);
                                var strtmp2 = GetPosString(strtmp, 1);
                                  string strRFF_Value = GetPosString(strtmp, 2);
                                if (strtmp2 == "BN") {
                                    BSNO = strRFF_Value;
                                }
                            }
                            if (head == "LOC")
                            {
                                var strtmp = GetPosStringplus(line, 2);
                                var strtmp2 = GetPosStringplus(line, 3);
                                if (strtmp == "11")
                                {
                                    var locValue1 = GetPosString(strtmp2, 1);
                                    var locValue2 = GetPosString(strtmp2, 4);
                                    if (LOCCOUNT==0)
                                    {
                                        PORTDISCHARGID = locValue1;
                                        PORTDISCHARG = locValue2;
                                        DESTINATIONID = locValue1;
                                        DESTINATION = locValue2;
                                    }
                                    else {
                                        DESTINATIONID = locValue1;
                                        DESTINATION = locValue2;
                                    }
                                    LOCCOUNT = LOCCOUNT + 1;
                                }
                            }
                            if (head == "TMP")
                            {
                                TMPSTR=GetPosString(GetPosStringplus(line, 3), 1);
                            }
                            if (head == "EQD")
                            {
                                CTNTYPE = GetPosStringplus(line, 4);
                            }
                            if (head == "EQN")
                            {
                                CTNNUM = GetPosStringplus(line, 2);
                                var ctn = new JsonCtn();
                                ctn.CTNTYPE = CTNTYPE;
                                ctn.CTNNUM=CTNNUM;
                                ctnlist.Add(ctn);
                            }
                            if (head == "BGM")
                            {
                                FILETYPE = GetPosStringplus(line, 5);
                            }
                        }
                        if (!string.IsNullOrEmpty(BSNO)&& FILETYPE=="AP")
                        {
                            log.Debug($"提单号:" + BSNO);
                            var OPSEAE = GetOPSEAE(connStr, BSNO);
                            if (OPSEAE != null && !string.IsNullOrEmpty(OPSEAE.BSNO))
                            {
                                var ISBEUPDATE = false;
                                var bodystr = "";
                                if (OPSEAE.CTNLIST != null && OPSEAE.CTNLIST.Count != 0 && ctnlist != null && ctnlist.Count != 0)
                                {
                                    foreach (var ctn in OPSEAE.CTNLIST)
                                    {
                                        var isfind = false;
                                        ctnlist.ForEach(i =>
                                        {
                                            if (i.CTNTYPE == ctn.CTNTYPE)
                                            {
                                                if (i.CTNNUM != ctn.CTNNUM)
                                                {
                                                    ISBEUPDATE = true;
                                                    bodystr = bodystr + Environment.NewLine + "集装箱不一致:" + ctn.CTNTYPE + "*" + ctn.CTNNUM + "----" + i.CTNTYPE + "*" + i.CTNNUM;
                                                }
                                                isfind = true;
                                            }
                                        });
                                        if (!isfind)
                                        {
                                            bodystr = bodystr + Environment.NewLine + "集装箱不一致:" + ctn.CTNTYPE + "*" + ctn.CTNNUM + "----";
                                            ISBEUPDATE = true;
                                        }

                                    }
                                }
                                else
                                {
                                    bodystr = bodystr + Environment.NewLine + "集装箱不一致";
                                    ISBEUPDATE = true;

                                }



                                //if ((OPSEAE.PORTDISCHARG != PORTDISCHARG))
                                //{

                                //    bodystr = bodystr + Environment.NewLine + "卸货港不一致:" + OPSEAE.PORTDISCHARG + "----" + PORTDISCHARG;
                                //    ISBEUPDATE = true;
                                //}
                                if ((OPSEAE.PORTDISCHARGID != PORTDISCHARGID))
                                {

                                    bodystr = bodystr + Environment.NewLine + "卸货港代码不一致:" + OPSEAE.PORTDISCHARGID + "----" + PORTDISCHARGID;
                                    ISBEUPDATE = true;
                                }
                                if ((OPSEAE.DESTINATIONID != DESTINATIONID))
                                {

                                    bodystr = bodystr + Environment.NewLine + "目的地代码不一致:" + OPSEAE.DESTINATIONID + "----" + DESTINATIONID;
                                    ISBEUPDATE = true;
                                }
                                if ((OPSEAE.TMPSTR != TMPSTR))
                                {

                                    bodystr = bodystr + Environment.NewLine + "温度不一致:" + OPSEAE.TMPSTR + "----" + TMPSTR;
                                    ISBEUPDATE = true;
                                }



                                if (ISBEUPDATE)
                                {
                                    var stmpid = GetMailStmp(connStr);
                                    SaveMail(connStr, OPSEAE.EMAIL, "CMA订舱信息不一致:" + BSNO, bodystr, stmpid);
                                }
                            }
                            if (File.Exists(Path.Combine(tempPath, fileInfo.Name))){
                                File.Delete(Path.Combine(tempPath, fileInfo.Name));
                            }
                            File.Copy(file, Path.Combine(tempPath, fileInfo.Name));
                            File.Delete(file);
                        }
                        else {
                            if (File.Exists(Path.Combine(tempPath, fileInfo.Name)))
                            {
                                File.Delete(Path.Combine(tempPath, fileInfo.Name));
                            }
                            File.Copy(file, Path.Combine(tempPath, fileInfo.Name));
                            File.Delete(file);

                        }



                    }

              }


            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                log.Error(ex.StackTrace);
            }


        }


        public static JsonOpSeae GetOPSEAE(string connStr,string BSNO)
        {

            
            var result =new JsonOpSeae();

            var sqlQuery = $" select top 1 主提单号,编号,卸货港,卸货代码,目的地,目的地代码,isnull(设置温度,'') 设置温度,isnull((select top 1 邮箱 from t_sys_employee where 姓名=t_op_seae.操作员),'') 邮箱 from t_op_seae where 主提单号='{BSNO}' ";

            DataTable tQuery = QuerySql(connStr, sqlQuery);

            if (tQuery.Rows.Count >= 0)
            {
                foreach (DataRow row in tQuery.Rows)
                {
                    result.PORTDISCHARG= row["卸货港"].ToString();
                    result.PORTDISCHARGID = row["卸货代码"].ToString();
                    result.TMPSTR = row["设置温度"].ToString();
                    result.BSNO = row["编号"].ToString();
                    result.EMAIL= row["邮箱"].ToString();
                    result.DESTINATION = row["目的地"].ToString();
                    result.DESTINATIONID = row["目的地代码"].ToString();

                    sqlQuery = $" select t_code_ctn.EDI代码,sum(t_op_ctn.数量) 数量 from t_op_ctn INNER JOIN t_code_ctn ON t_op_ctn.代码 = t_code_ctn.代码 where t_op_ctn.编号='{result.BSNO}' GROUP BY t_code_ctn.EDI代码 ";

                    var ctnlist = new List<JsonCtn>();

                    DataTable ctnQuery = QuerySql(connStr, sqlQuery);
                    if (ctnQuery.Rows.Count >= 0)
                    {
                        foreach (DataRow row2 in ctnQuery.Rows)
                        {
                            var ctn = new JsonCtn();
                            ctn.CTNTYPE = row2["EDI代码"].ToString();
                            ctn.CTNNUM = row2["数量"].ToString();
                            ctnlist.Add(ctn);
                        }
                    }
                    result.CTNLIST = ctnlist;

                }


            }

            return result;
        }

        public static DataTable QuerySql(string connStr, string condition)
        {
            SqlConnection conn = new SqlConnection(connStr);
            SqlDataAdapter dataAdapter = new SqlDataAdapter(condition, conn);
            DataTable tQuery = new DataTable();
            dataAdapter.Fill(tQuery);
            return tQuery;
        }
        public static string GetMailStmp(string connStr, string StmpID = "")
        {


            var result = "";

            var sqlQuery = " select * from Mail_Send_Smtp ";
            if (StmpID != "") sqlQuery = sqlQuery + " WHERE GID='" + StmpID + "'";

            DataTable tQuery = QuerySql(connStr, sqlQuery);

            if (tQuery.Rows.Count >= 0)
            {
                result = tQuery.Rows[0]["GID"].ToString();
            }

            return result;
        }
        public static int ExecSql(string connStr, string SqlStr)
        {
            SqlConnection SCON = null;//连接对象

            SqlCommand SCom = new SqlCommand();//命令对象

            SCON = new SqlConnection(connStr);

            SCON.Open();

            SCom.CommandText = SqlStr;

            SCom.Connection = SCON;

            SCom.CommandType = CommandType.Text;

            int num = SCom.ExecuteNonQuery();

            SCON.Close();

            return num;
        }

        public static int SaveMail(string connStr, string sendto, string title, string body, string smtpid)
        {

            var sqlstr = $" INSERT INTO  [Mail_Send] ([GID],[SendTo],[Title],[Body],[SendStatus],[TryCount],[CreateTime],[SmtpConfig],[Sender],[ShowName]) select newid(),'{sendto}','{title}','{body.Replace("'", "''")}','Create',0,GETDATE(),'{smtpid}','','' ";
            return ExecSql(connStr, sqlstr);

        }
        public static string GetPosStringplus(string str, int pos, bool isnum = false)
        {
            var result = "";
            if (isnum) result = "0";
            var j = 0;
            if (str.IndexOf("+") == -1) return result;
            str = str.Replace("??", "?").Replace("?'", "'").Replace("?+", "し");
            for (int i = 1; i < pos; i++)
            {
                if (str.IndexOf("+") == -1) return result;
                if (str.IndexOf("+") != -1)
                {
                    j = str.IndexOf("+");
                    str = str.Substring(j + 1, str.Length - j - 1);
                }
            }
            j = str.IndexOf("+");

            if (j != -1)
            {
                str = str.Substring(0, j);
            }
            else
            {
                if (str.Length != 0)
                    str = str.Substring(0, str.Length);
            }

            result = str.Replace("し", "+");
            if (isnum)
            {
                if (result == "")
                    result = "0";
            }

            return result;

        }
        public static string GetPosString(string str, int pos, bool isnum = false)
        {
            var result = "";
            if (isnum) result = "0";
            var j = 0;
            if (str.IndexOf(":") == -1) return result;
            str = str.Replace("??", "?").Replace("?:", "^").Replace("?'", "'");
            for (int i = 1; i < pos; i++)
            {
                if (str.IndexOf(":") == -1) return result;
                if (str.IndexOf(":") != -1)
                {
                    j = str.IndexOf(":");
                    str = str.Substring(j + 1, str.Length - j - 1);
                }
            }
            j = str.IndexOf(":");

            if (j != -1)
            {
                str = str.Substring(0, j);
            }
            else
            {
                if (str.Length != 0)
                    str = str.Substring(0, str.Length);
            }

            result = str.Replace("^", ":");
            if (isnum)
            {
                if (result == "")
                    result = "0";
            }

            return result;

        }
        public class JsonCtn
        {

            public string CTNTYPE { get; set; }
            public string CTNNUM { get; set; }
        }

        public class JsonOpSeae
        {

            public string BSNO { get; set; }
            public string MBLNO { get; set; }
            public string EMAIL { get; set; }
            public string PORTDISCHARGID { get; set; }
            public string PORTDISCHARG { get; set; }
            public string TMPSTR { get; set; }
            public string DESTINATIONID { get; set; }
            public string DESTINATION { get; set; }
            public List<JsonCtn> CTNLIST { get; set; }
        }
    }
}