using System; 
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic; 
using System.Data;
using DSWeb.SoftMng.DBUtility;
using Newtonsoft.Json.Linq;

using DSWeb.Areas.MvcShipping.Comm;
using DSWeb.MvcShipping.DAL.MsSysParamSet;
using DSWeb.SoftMng.Model;
using DSWeb.MvcShipping.DAL.MsOpApplyDAL;
using DSWeb.MvcShipping.Models.MsOpApply;
using HcUtility.Comm;
using DSWeb.MvcShipping.DAL.MsSysBillNoSet;
using HcUtility.Core;
using DSWeb.Areas.MvcShipping.DB;
using DSWeb.SoftMng.BLL;
using System.Linq;
using System.Threading;
using DSWeb.Areas.CommMng.DAL;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DSWeb.MvcShipping.DAL.MsOpReceiptDAL;
using DSWeb.Areas.Import.DAL.ReceiptDoc;
using DSWeb.MvcShipping.DAL.MsCodeOpMustField;
using DSWeb.MvcShipping.DAL.MsCodeOpDef;

// ReSharper disable once CheckNamespace
namespace DSWeb.SoftMng.DAL  
{
    public class SingleCondition
    {
        public string starttime { get; set; }
        public string endtime { get; set; }
        public string CUSTOMNO { get; set; }
        public string MBLNO { get; set; }
        public string ies { get; set; }

        public string cdnType { get; set; }
        public string clearance { get; set; }

        public bool isSecondApply { get; set; }


        public bool withPdf { get; set; }
        public string USERID { get; set; }
        public string SHOWNAME { get; set; }
        public string COMPANYID { get; set; }

        public SingleCondition() { }

        public SingleCondition(string starttime, string endtime, string ies, string cdnType, string clearance, string isSecondApply, string withPdf, string USERID, string SHOWNAME, string COMPANYID) {
            this.starttime = starttime;
            this.endtime = endtime;
            this.ies = ies;
            this.cdnType = cdnType;
            this.clearance = clearance;

            if (isSecondApply == "0") this.isSecondApply = false;
            else this.isSecondApply = true;

            if (withPdf == "0") this.withPdf = false;
            else this.withPdf = true;

            this.USERID = USERID;
            this.SHOWNAME = SHOWNAME;
            this.COMPANYID = COMPANYID;
        }

        public void change(string starttime,string endtime, string ies, string clearance)
        {
            this.starttime = starttime;
            this.endtime = endtime;
            this.ies = ies;
            this.clearance = clearance;
        }

        public SingleCondition copy() {
            return new SingleCondition(starttime, endtime, ies, cdnType, clearance
                , isSecondApply ? "1" : "0"
                , withPdf ? "1" : "0"
                , USERID, SHOWNAME, COMPANYID) ;
        }
    }
    //读取
    public partial class readDAL
	{


        const string _IURL = "http://47.104.90.170:9000/sw/download";

        private static string getPortStr(string starttime = "", string endtime = "", string CUSTOMNO = "", string MBLNO = "", string ies = "", string cdnType = "", string clearance = "0",string startn="1",string endn="10")
        {
            string rtn = "";
            JObject reqObj = new JObject();
            /*网站代号(sw)
卡号
密码(md5加密后)
报关单号
进出口标志(只有两个值) I(大写i): 进口, E: 出口
是否结关(只有两个值) 1:是,0:否
*/

            var swcn = MsSysParamSetDAL.GetSysParamValue("OpApplySingle_User");
            var swpw = MsSysParamSetDAL.GetSysParamValue("OpApplySingle_Pwd"); 
            var yardid = "sw";

            reqObj.Add("yardid", yardid);
            reqObj.Add("swcn", swcn);
            reqObj.Add("swpw", swpw);
            reqObj.Add("cdn", CUSTOMNO);
            reqObj.Add("billno", MBLNO);


            reqObj.Add("ies", ies);


            reqObj.Add("clearance", clearance);//未结关

            reqObj.Add("starttime", starttime);//

            reqObj.Add("endtime", endtime);//

            reqObj.Add("startn", startn);//
            reqObj.Add("endn", endn);//

            //reqObj.Add("billno", "KMTCSIN2287541");
            //reqObj.Add("ies", "I");
            //reqObj.Add("clearance", "0");

            var t_str = reqObj.ToString(Newtonsoft.Json.Formatting.None);
            BasicDataRefDAL.SaveLog(t_str, "", "单一窗口批量读取", "执行读取");
            
            rtn = WebRequestHelper.DoPost(_IURL, t_str, 480000);
            BasicDataRefDAL.SaveLog(rtn, "", "单一窗口批量读取", "读取返回");
            return rtn;
        }


        public static DecHead_WebModel getrtn(SingleCondition sc, string startn = "1", string endn = "10")
        {
            var rtn = getPortStr(sc.starttime, sc.endtime, "", "", sc.ies,sc.cdnType, sc.clearance, startn, endn);
            var _status = Newtonsoft.Json.JsonConvert.DeserializeObject<DecHead_status>(rtn).status;
            var result = new DecHead_WebModel();
            if (_status == "1")
            {
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<DecHead_WebModel>(rtn);  
            }
            return result;
        }

        public static void getPortInfo_thread(SingleCondition SingleCondition)
        {
            Thread_getrtn getrtn = new Thread_getrtn();
            //有参调用实例方法,ParameterizedThreadStart是一个委托,input为object,返回值为void
            Thread thread1 = new Thread(new ParameterizedThreadStart(getrtn.FuncSend));
            
            thread1.Start(SingleCondition);
        }

        class Thread_getrtn
        {

            public void FuncSend(object o)
            {
                SingleCondition condition = o as SingleCondition;
                try
                {
                    BasicDataRefDAL.SaveLog(condition, condition.USERID, "单一窗口批量读取", "开始");

                    doread(condition, 1, 10);

                    //DecHead_WebModel DecHead = getrtn(condition);

                    //if (DecHead.message != null)
                    //{
                    //    Dealrtn(DecHead, condition.USERID, condition.SHOWNAME, condition.COMPANYID);
                    //}
                }
                catch (Exception e) {
                    BasicDataRefDAL.SaveLog(e.Message, condition.USERID, "单一窗口批量读取", "错误");
                }
            }
        }

        //20200409 每次读10个 如果读回来的不到10个,就停止 否则再读下面10个。
        private static void doread(SingleCondition condition, int startn, int endn)
        {

            DecHead_WebModel DecHead = getrtn(condition, startn.ToString(), endn.ToString());

            if (DecHead.message != null)
            {
                Dealrtn(DecHead, condition.USERID, condition.SHOWNAME, condition.COMPANYID,condition.clearance);

                if (!(DecHead.message.Count < 10))
                {
                    doread(condition, startn + 10, endn + 10);
                }
            }
            else {
                BasicDataRefDAL.SaveLog("status="+DecHead.status.ToString()+";message="+ DecHead.message.ToString(), condition.USERID, "单一窗口批量读取", "错误");
            }
    
        }


        public static void Dealrtn(DecHead_WebModel PortReturn, string USERID, string SHOWNAME, string COMPANYID,string isclear="0")
        {
            BasicDataRefDAL.SaveLog(PortReturn, USERID, "单一窗口批量读取", "返回值处理");
            try
            {
                if (PortReturn.message == null) return;
                foreach (var head in PortReturn.message)
                {
                    if (head.data == null) continue;
                    var preDecHeadVo = head.data.getdata();

                    if (string.IsNullOrWhiteSpace(preDecHeadVo.entryId))
                    {
                        continue;//没有报关单号的不做处理
                    }

                    var currCUSTOMNO = preDecHeadVo.entryId;
                    //本地是否存在该业务 以报关单号为准

                    //根据报关单号寻找报关业务 看是否存在
                    var OPAPPLY = MsOpApplyDAL.GetData(" CUSTOMNO='" + currCUSTOMNO.Trim() + "'");
                    var needinsert = false;//需要新建 还是更新信息
                    if (string.IsNullOrWhiteSpace(OPAPPLY.CUSTOMNO))
                    {
                        needinsert = true;
                    }
                    //20201021 根据查询条件[已结关]填入[已通关]。
                    OPAPPLY.ISCLEAR = isclear;

                    var bsno = "";

                    var decheadGID = "";

                    if (needinsert)
                    {
                        //新建 op_apply 
                        saveinfo("insert", head, OPAPPLY, USERID, SHOWNAME, COMPANYID, isclear);

                    }
                    else
                    {
                        saveinfo("edit", head, OPAPPLY, USERID, SHOWNAME, COMPANYID, isclear);
                    }

                }
            }
            catch(Exception e)
            {
                BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "返回值处理错误");
            }

        }

        //private static string CUSTNO { get; set; }

        //public static void setCUSTNO(string custno) {
        //    CUSTNO = custno;
        //}

        //private static string getCUSTNO() {
        //    //BasicDataRefDAL.SaveLog(CUSTNO, USERID, "单一窗口批量读取", "新业务编号");
        //    var result = "";
        //    result=CUSTNO.ToString();
        //    var _t_head = CUSTNO.Substring(0, CUSTNO.Length - 4);
        //    var index = Convert.ToInt32(CUSTNO.Substring(CUSTNO.Length - 4, 4));
        //    index++;
        //    var newindex = index.ToString();
        //    while (newindex.Length < 4)
        //    {
        //        newindex = "0" + newindex;
        //    }
        //    CUSTNO = _t_head + newindex;
        //    return result;
        //} 

        public static void saveinfo(string dealtype, MessageModel head, MsOpApply OPAPPLY,string USERID,string SHOWNAME,string COMPANYID,string ISCLEAR)
        {
            var mark = 0;
            try
            {
                
                DecHeadBLL bll = new DecHeadBLL();
                ContainerBLL cbll = new ContainerBLL();
                DecListBLL lbll = new DecListBLL();

                if (dealtype == "insert")
                {
                    OPAPPLY.DbOperationType = DbOperationType.DbotIns;
                    OPAPPLY.ModelUIStatus = "I";

                    OPAPPLY.BSNO = Guid.NewGuid().ToString();
                    OPAPPLY.MASTERNO = OPAPPLY.BSNO;
                    mark = 11;
                    var _r = MsOpApplyDAL.getCUSTNO(OPAPPLY, USERID,SHOWNAME,COMPANYID);
                    if (_r.Success)
                        OPAPPLY.CUSTNO = _r.Data.ToString();
                    else {
                        BasicDataRefDAL.SaveLog(_r.Message, USERID, "单一窗口批量读取", "获取单号出错");
                        return;
                    }

                    //OPAPPLY.CUSTNO = MsSysBillNoSetDAL.GetNewNo("报关业务", "委托编号", "0602", COMPANYID, System.DateTime.Now.ToString("yyyy-MM-dd"));
                    mark = 12;
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存1.1");

                }
                else
                {
                    OPAPPLY.DbOperationType = DbOperationType.DbotUpd;
                    OPAPPLY.ModelUIStatus = "E";
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存1.2");
                    mark = 1;
                }

                var bsno = OPAPPLY.BSNO;
                var preDecHeadVo = head.data.getdata();
                mark = 2;
                OPAPPLY.CUSTOMNO = preDecHeadVo.entryId;

                //根据报关单号 结尾0出口  结尾1进口
                OPAPPLY.setbstype();
                OPAPPLY.BSSTATUS = false;
                OPAPPLY.FEESTATUS = false;
                OPAPPLY.BSDATE = Convert.ToDateTime(preDecHeadVo.dDate);
                OPAPPLY.CUSTOMDATE = preDecHeadVo.dDate;//报关日期=申报日期
                OPAPPLY.OPDATE = preDecHeadVo.dDate;//业务日期=申报日期

                OPAPPLY.MBLNO = preDecHeadVo.billNo;
                //OPAPPLY.PORTLOAD = preDecHeadVo.despPortCode
                mark = 3;
                OPAPPLY.INPUTBY = SHOWNAME;
                OPAPPLY.CORPID = COMPANYID;
                OPAPPLY.TRADETYPE = preDecHeadVo.supvModeCddeName;
                OPAPPLY.ISDY = "1";
                OPAPPLY.CUSCIQNO = preDecHeadVo.cusCiqNo;
                OPAPPLY.GOODSOURCE = preDecHeadVo.ciqDespCtryCodeName;
                OPAPPLY.EXPCUSTOMTYPE = preDecHeadVo.iEPortName;
                OPAPPLY.DESPPORT = preDecHeadVo.despPortCodeName;
                OPAPPLY.CONSIGNEE = preDecHeadVo.consigneeCname;
                OPAPPLY.ENTERP = preDecHeadVo.consignorCname;
                if (preDecHeadVo.ciqTrafMode == "3")
                    OPAPPLY.BSTYPE = "5";

                OPAPPLY.ISCLEAR = ISCLEAR;
                if (OPAPPLY.CUSTOMERNAME == "") OPAPPLY.CUSTOMERNAME = MsCodeOpDefDAL.GetData("BSTYPE='OP_APPLY' AND FIELDNAME='CUSTOMERNAME'", COMPANYID).DEFVALUE;

                var modb = new ModelObjectDB();
                var tempresult = modb.Save(OPAPPLY);
                OPAPPLY.DbOperationType = DbOperationType.DbotUpd;
                OPAPPLY.ModelUIStatus = "E";

                //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存2");
                #region 单一窗口信息
                var dealtype_detail = "edit";
                var DecHead_Local = bll.GetModelList("BSNO='" + OPAPPLY.BSNO + "'").FirstOrDefault();
                if (DecHead_Local == null)
                {
                    DecHead_Local = new DecHead();
                    dealtype_detail = "insert";
                }
                //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存3");
                
                if (dealtype_detail == "insert")
                {

                    DecHead_Local.GID = Guid.NewGuid().ToString();
                    DecHead_Local.BSNO = OPAPPLY.BSNO;
                    
                    preDecHeadVo.setvalue(DecHead_Local);
                    bll.Add(DecHead_Local);
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存4.1");
                    
                }
                else
                {
                    preDecHeadVo.setvalue(DecHead_Local);
                    mark++;
                    bll.Update(DecHead_Local);
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存4.2");
                    
                }
                #endregion

                #region 电子文档信息


                var docdataList = ReceiptDocDAL.GetDocList("BSNO='" + bsno + "'");

                //ReceiptContext receiptContext = new ReceiptContext();

                foreach (var pdf in head.pdfFile)
                {

                    //Receipt_Doc receipt = receiptContext.ReceiptDocs.FirstOrDefault(o => o.BSNO == bsno && o.URL == pdf.filename);
                    var doc = docdataList.Find(x=>x.URL==pdf.filename);
                    if (doc == null||doc.BSNO == "")
                    {
                        Database db = DatabaseFactory.CreateDatabase();
                        using (var conn = db.CreateConnection())
                        {
                            conn.Open();
                            var tran = conn.BeginTransaction();

                            try
                            {

                                var cmdInsert =
                                    db.GetSqlStringCommand(
                                           @"insert into Receipt_Doc (GID,BSNO,URL,Driect_URL,MODIFIEDUSER,MODIFIEDTIME,RECEIPTTYPE,DOCUMENTATTACHEDCODE,DOCUMENTATTACHEDNO) 
                                   values (@GID,@BSNO,@URL,@Driect_URL,@MODIFIEDUSER,@MODIFIEDTIME,@RECEIPTTYPE,@DOCUMENTATTACHEDCODE,@DOCUMENTATTACHEDNO) ");


                                cmdInsert.Parameters.Clear();
                                db.AddInParameter(cmdInsert, "@GID", DbType.String, Guid.NewGuid().ToString());
                                db.AddInParameter(cmdInsert, "@BSNO", DbType.String, bsno);
                                db.AddInParameter(cmdInsert, "@URL", DbType.String, pdf.filename);
                                db.AddInParameter(cmdInsert, "@Driect_URL", DbType.String,pdf.path);
                                db.AddInParameter(cmdInsert, "@MODIFIEDUSER", DbType.String, USERID);
                                db.AddInParameter(cmdInsert, "@MODIFIEDTIME", DbType.String, DateTime.Now.ToString());
                                db.AddInParameter(cmdInsert, "@RECEIPTTYPE", DbType.String,"");
                                db.AddInParameter(cmdInsert, "@DOCUMENTATTACHEDCODE", DbType.String, "");
                                db.AddInParameter(cmdInsert, "@DOCUMENTATTACHEDNO", DbType.String, "");
                                db.ExecuteNonQuery(cmdInsert, tran);

                                tran.Commit();
                            }
                            catch (Exception e)
                            {
                                BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + e.Message);
                                tran.Rollback();
                            }
                        }
                    }
                    else {
                        Database db = DatabaseFactory.CreateDatabase();
                        using (var conn = db.CreateConnection())
                        {
                            conn.Open();
                            var tran = conn.BeginTransaction();

                            try
                            {

                                var cmdInsert =
                                    db.GetSqlStringCommand(
                                           @"update Receipt_Doc set URL=@URL,Driect_URL=@Driect_URL,MODIFIEDUSER=@MODIFIEDUSER,MODIFIEDTIME=@MODIFIEDTIME 
                                   WHERE GID=@GID ");


                                        cmdInsert.Parameters.Clear();
                                        db.AddInParameter(cmdInsert, "@GID", DbType.String, doc.GID);
                                        db.AddInParameter(cmdInsert, "@URL", DbType.String, pdf.filename);
                                        db.AddInParameter(cmdInsert, "@Driect_URL", DbType.String, pdf.path);
                                        db.AddInParameter(cmdInsert, "@MODIFIEDUSER", DbType.String, USERID);
                                        db.AddInParameter(cmdInsert, "@MODIFIEDTIME", DbType.String, DateTime.Now.ToString());
                                        db.ExecuteNonQuery(cmdInsert, tran);
                                tran.Commit();
                            }
                            catch (Exception e)
                            {
                                BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + e.Message);
                                tran.Rollback();
                            }
                        }


                    }

                    //if (receipt == null)
                    //{
                    //    receipt = new Receipt_Doc();
                    //    receipt.GID = Guid.NewGuid().ToString();
                    //    receipt.BSNO = bsno;
                    //    receipt.URL = pdf.filename;
                    //    receipt.Driect_URL = pdf.path;
                    //    receipt.MODIFIEDUSER = USERID;
                    //    receipt.MODIFIEDTIME = System.DateTime.Now;
                    //    receiptContext.ReceiptDocs.Add(receipt);
                    //}
                    //else
                    //{
                    //    receipt.URL = pdf.filename;
                    //    receipt.Driect_URL = pdf.path;
                    //    receipt.MODIFIEDUSER = USERID;
                    //    receipt.MODIFIEDTIME = System.DateTime.Now;
                    //}
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存5");
                    //var _r = receiptContext.SaveChanges();
                }
                mark = 7;
                #endregion

                #region 集装箱信息

                var opapplyctnlist= MsOpApplyDAL.GetCtnBodyList("BSNO='" + OPAPPLY.BSNO + "'", "");
                var containerlist = cbll.GetModelList("PID='" + DecHead_Local.GID + "'");
                var portContainerlist = preDecHeadVo.getpreDecContainerVo();
                mark = 71;
                if (portContainerlist.Count > 0)
                {
                    Database db = DatabaseFactory.CreateDatabase();
                    using (var conn = db.CreateConnection())
                    {
                        conn.Open();
                        mark = 72;
                        foreach (var portContainer in portContainerlist)
                      {
                        var upd = false;
                        foreach (var container in containerlist)
                        {
                            if (container.ContainerId.Trim() == portContainer.containerNo.Trim())
                            {
                                upd = true;
                                var updcontainer = portContainer.getContainerValue(container);
                                cbll.Update(updcontainer);
                            }
                        }
                        if (!upd)
                        {
                            var updcontainer = new Container();
                            updcontainer = portContainer.getContainerValue(updcontainer);
                            updcontainer.GID = Guid.NewGuid().ToString();
                            updcontainer.PID = DecHead_Local.GID;
                            cbll.Add(updcontainer);
                        }
                        var updapply = false;
                        foreach (var container in opapplyctnlist)
                        {
                            if (container.CNTRNO.Trim() == portContainer.containerNo.Trim())
                            {
                                    updapply = true;
                            }
                        }
                        if (!updapply)
                        {

  
                                var tran = conn.BeginTransaction();
                                try
                                {
                                    var cmdInsert = db.GetSqlStringCommand(@"insert into op_ctn (CTN_ID,BSNO,CTNNUM,CNTRNO,CTNALL) values (NEWID()"
                                        + ",'" + OPAPPLY.BSNO + "',1,'" + portContainer.containerNo.Trim() + "','40GP')");
                                    db.ExecuteNonQuery(cmdInsert, tran);

                                    tran.Commit();
                                }
                                catch (Exception e)
                                {
                                    BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + e.Message);
                                    tran.Rollback();
                                }
                   

                        }

                      }
                    }
                }
                mark = 8;
                //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存6");
                containerlist = cbll.GetModelList("PID='" + DecHead_Local.GID + "'");
                mark = 9;
                #endregion

                #region 项信息
                var declist_List = lbll.GetModelList(0, 99, "PID='" + DecHead_Local.GID + "'", String.Format("{0}", "gNo", ""));

                var port_decMergeListVoList = preDecHeadVo.getdecMergeListVo();
                var curr = "USD";
                decimal cargovalue = 0;
                if (port_decMergeListVoList.Count > 0)
                    foreach (var port_decMergeListVo in port_decMergeListVoList)
                    {
                        var upd = false;
                        foreach (var declist in declist_List)
                        {
                            if (declist.GNo.Trim() == port_decMergeListVo.gNo.Trim())
                            {
                                upd = true;
                                var upddeclist = port_decMergeListVo.getDecListValue(declist);
                                lbll.Update(upddeclist);
                            }
                        }
                        if (!upd)
                        {
                            var upddeclist = new DecList();
                            upddeclist = port_decMergeListVo.getDecListValue(upddeclist);
                            upddeclist.GID = Guid.NewGuid().ToString();
                            upddeclist.PID = DecHead_Local.GID;
                            lbll.Add(upddeclist);
                        }
                        try
                        {
                            cargovalue = cargovalue + Convert.ToDecimal(port_decMergeListVo.declTotal);
                            curr = port_decMergeListVo.tradeCurr;
                        }
                        catch (Exception e)
                        {
                            BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + e.Message);
                        }
                   }
                OPAPPLY.CARGOVALUE = cargovalue.ToString();
                OPAPPLY.CURRENCY = curr;

                modb = new ModelObjectDB();
                tempresult = modb.Save(OPAPPLY);

                mark = 10;
                var Declist = lbll.GetModelList(0, 99, "PID='" + DecHead_Local.GID + "'", String.Format("{0}", "gNo", ""));
                var count = lbll.GetRecordCount("PID='" + DecHead_Local.GID + "'");
                //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存7");
                mark = 11;
                #endregion

            }
            catch (Exception e)
            {
                BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误"+ mark.ToString());
            }

        }

    }


    public partial class readDAL_2
    {
        const string _IURL_noPdf = "http://47.104.90.170:9000/sw/merge/detail";
        /*
         * ### 单一窗口数据详情查询 API

        #### 请求的数据:

        请求方式:POST

        url定义:http://47.104.90.170:9000/sw/merge/detail
                 请求参数:formdata

        |    参数     |  类型  | 是否必须传 |                             描述                             |
        | :---------: | :----: | :--------: | :----------------------------------------------------------: |
        |    card     | 字符串 |     是     |                             卡号                             |
        |     pwd     | 字符串 |     是     |                             密码                             |
        |     ies     | 字符串 |     是     |      进出口标志 (只有两个值) I (大写i) : 进口, E: 出口       |
        |    clear    | 布尔型 |     是     |               是否结关 (只有两个值) 1:是,0:否               |
        |   cdnType   | 字符串 |     是     | 报关单类型 (0: 一般报关单, 1: 转关提前报关单, <br />2: 备案清单, 3: 转关提前备案清单, 4: 出口二次转关) |
        |     cdn     | 字符串 |     否     |                           报关单号                           |
        |    bill     | 字符串 |     否     |                            提单号                            |
        |   unicode   | 字符串 |     否     |                           统一编号                           |
        |    start    | 字符串 |     否     |                  查询开始日期 (2020-06-09)                   |
        |     end     | 字符串 |     否     |                  查询结束日期 (2020-06-09)                   |
        | startNumber |  数值  |     否     |                 查询数据开始数,如:1,11,21                  |
        |  endNumber  |  数值  |     否     |                 查询数据结束数,如:10,20,30                 |
         */

        const string _IURL_withPdf = "http://47.104.90.170:9000/sw/merge/downloads";

        /*
         ### 单一窗口总数据详情和pdf查询 API

        #### 请求的数据:

        请求方式:POST

        url定义:http://47.104.90.170:9000/sw/merge/downloads

        请求参数:formdata

        |    参数     |  类型  | 是否必须传 |                       描述                        |
        | :---------: | :----: | :--------: | :-----------------------------------------------: |
        |    card     | 字符串 |     是     |                       卡号                        |
        |     pwd     | 字符串 |     是     |                       密码                        |
        |     ies     | 字符串 |     是     | 进出口标志 (只有两个值) I (大写i) : 进口, E: 出口 |
        |    clear    | 布尔型 |     是     |         是否结关 (只有两个值) 1:是,0:否          |
        |     cdn     | 字符串 |     否     |                     报关单号                      |
        |    bill     | 字符串 |     否     |                      提单号                       |
        |   unicode   | 字符串 |     否     |                     统一编号                      |
        |    start    | 字符串 |     否     |             查询开始日期 (2020-06-09)             |
        |     end     | 字符串 |     否     |             查询结束日期 (2020-06-09)             |
        | startNumber |  数值  |     否     |            查询数据开始数,如:1,11,21            |
        |  endNumber  |  数值  |     否     |           查询数据结束数,如:10,20,30            |

        > 注:startNumber和endNumber输入其他的数不一定是想要的结果

         */

        const string _IURL_secondapply_noPdf = "http://47.104.90.170:9000/sw/ts/detail";
        /*
        ### 单一窗口两步申报数据详情查询 API

        #### 请求的数据:

        请求方式:POST

        url定义:http://47.104.90.170:9000/sw/ts/detail

        请求参数:formdata

        |    参数     |  类型  | 是否必须传 |                  描述                   |
        | :---------: | :----: | :--------: | :-------------------------------------: |
        |    card     | 字符串 |     是     |                  卡号                   |
        |     pwd     | 字符串 |     是     |                  密码                   |
        |   cdnType   | 字符串 |     是     | 报关单类型 (0: 一般报关单, 2: 备案清单) |
        |     cdn     | 字符串 |     否     |                报关单号                 |
        |    bill     | 字符串 |     否     |                 提单号                  |
        |   unicode   | 字符串 |     否     |                统一编号                 |
        |    start    | 字符串 |     否     |        查询开始日期 (2020-06-09)        |
        |     end     | 字符串 |     否     |        查询结束日期 (2020-06-09)        |
        | startNumber |  数值  |     否     |       查询数据开始数,如:1,11,21       |
        |  endNumber  |  数值  |     否     |      查询数据结束数,如:10,20,30       |
         */

        const string _IURL_secondapply_withPdf = "http://47.104.90.170:9000/sw/ts/downloads";
        /*
        ### 单一窗口两步申报数据详情和pdf查询 API

        #### 请求的数据:

        请求方式:POST

        url定义:http://47.104.90.170:9000/sw/ts/download

        请求参数:formdata

        |    参数     |  类型  | 是否必须传 |                  描述                   |
        | :---------: | :----: | :--------: | :-------------------------------------: |
        |    card     | 字符串 |     是     |                  卡号                   |
        |     pwd     | 字符串 |     是     |                  密码                   |
        |   cdnType   | 字符串 |     是     | 报关单类型 (0: 一般报关单, 2: 备案清单) |
        |     cdn     | 字符串 |     否     |                报关单号                 |
        |    bill     | 字符串 |     否     |                 提单号                  |
        |   unicode   | 字符串 |     否     |                统一编号                 |
        |    start    | 字符串 |     否     |        查询开始日期 (2020-06-09)        |
        |     end     | 字符串 |     否     |        查询结束日期 (2020-06-09)        |
        | startNumber |  数值  |     否     |       查询数据开始数,如:1,11,21       |
        |  endNumber  |  数值  |     否     |      查询数据结束数,如:10,20,30       |
 
         */

        private static string getPortStr(SingleCondition sc,string startn = "1", string endn = "10")
        {
            string rtn = "";
            JObject reqObj = new JObject();
            /*网站代号(sw)
卡号
密码(md5加密后)
报关单号
进出口标志(只有两个值) I(大写i): 进口, E: 出口
是否结关(只有两个值) 1:是,0:否
*/

            var swcn = MsSysParamSetDAL.GetSysParamValue("OpApplySingle_User");
            var swpw = MsSysParamSetDAL.GetSysParamValue("OpApplySingle_Pwd");
            //var yardid = "sw";

            //reqObj.Add("yardid", yardid);
            reqObj.Add("card", swcn);
            reqObj.Add("pwd", swpw);

            reqObj.Add("ies", sc.ies);


            reqObj.Add("clear", sc.clearance);//未结关

            reqObj.Add("cdnType", sc.cdnType);

            //reqObj.Add("bill", sc.MBLNO);

            reqObj.Add("cdn", "");//
            reqObj.Add("bill", "");//
            reqObj.Add("unicode", "");//

            reqObj.Add("start", sc.starttime);//

            reqObj.Add("end", sc.endtime);//

            reqObj.Add("startNumber", startn);//
            reqObj.Add("endNumber", endn);//



            //reqObj.Add("billno", "KMTCSIN2287541");
            //reqObj.Add("ies", "I");
            //reqObj.Add("clearance", "0");

            var t_str = reqObj.ToString(Newtonsoft.Json.Formatting.None);
            BasicDataRefDAL.SaveLog(t_str, "", "单一窗口批量读取_新", "执行读取");


            if (!sc.isSecondApply)
            {
                if (sc.withPdf)
                    rtn = WebRequestHelper.DoPost(_IURL_withPdf, t_str, 480000);
                else
                    rtn = WebRequestHelper.DoPost(_IURL_noPdf, t_str, 480000);
            }
            else {
                if (sc.withPdf)
                    rtn = WebRequestHelper.DoPost(_IURL_secondapply_withPdf, t_str, 480000);
                else
                    rtn = WebRequestHelper.DoPost(_IURL_secondapply_noPdf, t_str, 480000);
            }

            BasicDataRefDAL.SaveLog(rtn, "", "单一窗口批量读取_新", "读取返回");
            return rtn;
        }


        public static DecHead_WebModel getrtn(SingleCondition sc, string startn = "1", string endn = "10")
        {
            var rtn = getPortStr(sc, startn, endn);
            var _status = Newtonsoft.Json.JsonConvert.DeserializeObject<DecHead_status>(rtn).status;
            var result = new DecHead_WebModel();
            if (_status == "1")
            {
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<DecHead_WebModel>(rtn);
            }
            return result;
        }

        public static void getPortInfo_thread(SingleCondition SingleCondition)
        {
            Thread_getrtn getrtn = new Thread_getrtn();
            //有参调用实例方法,ParameterizedThreadStart是一个委托,input为object,返回值为void
            Thread thread1 = new Thread(new ParameterizedThreadStart(getrtn.FuncSend));

            thread1.Start(SingleCondition);
        }

        class Thread_getrtn
        {

            public void FuncSend(object o)
            {
                SingleCondition condition = o as SingleCondition;
                try
                {
                    BasicDataRefDAL.SaveLog(condition, condition.USERID, "单一窗口批量读取", "开始");

                    doread(condition, 1, 10);

                    //DecHead_WebModel DecHead = getrtn(condition);

                    //if (DecHead.message != null)
                    //{
                    //    Dealrtn(DecHead, condition.USERID, condition.SHOWNAME, condition.COMPANYID);
                    //}
                }
                catch (Exception e)
                {
                    BasicDataRefDAL.SaveLog(e.Message, condition.USERID, "单一窗口批量读取", "错误");
                }
            }
        }

        //20200409 每次读10个 如果读回来的不到10个,就停止 否则再读下面10个。
        private static void doread(SingleCondition condition, int startn, int endn)
        {

            DecHead_WebModel DecHead = getrtn(condition, startn.ToString(), endn.ToString());

            if (DecHead.message != null)
            {
                Dealrtn(DecHead, condition.USERID, condition.SHOWNAME, condition.COMPANYID, condition.clearance);

                if (!(DecHead.message.Count < 10))
                {
                    doread(condition, startn + 10, endn + 10);
                }
            }
            else
            {
                BasicDataRefDAL.SaveLog("status=" + DecHead.status.ToString() + ";message=" + DecHead.message.ToString(), condition.USERID, "单一窗口批量读取", "错误");
            }

        }


        public static void Dealrtn(DecHead_WebModel PortReturn, string USERID, string SHOWNAME, string COMPANYID, string isclear = "0")
        {
            BasicDataRefDAL.SaveLog(PortReturn, USERID, "单一窗口批量读取", "返回值处理");
            try
            {
                if (PortReturn.message == null) return;
                foreach (var head in PortReturn.message)
                {
                    if (head.data == null) continue;
                    var preDecHeadVo = head.data.getdata();

                    if (string.IsNullOrWhiteSpace(preDecHeadVo.entryId))
                    {
                        continue;//没有报关单号的不做处理
                    }

                    var currCUSTOMNO = preDecHeadVo.entryId;
                    //本地是否存在该业务 以报关单号为准

                    //根据报关单号寻找报关业务 看是否存在
                    var OPAPPLY = MsOpApplyDAL.GetData(" CUSTOMNO='" + currCUSTOMNO.Trim() + "'");
                    var needinsert = false;//需要新建 还是更新信息
                    if (string.IsNullOrWhiteSpace(OPAPPLY.CUSTOMNO))
                    {
                        needinsert = true;
                    }
                    //20201021 根据查询条件[已结关]填入[已通关]。
                    OPAPPLY.ISCLEAR = isclear;

                    var bsno = "";

                    var decheadGID = "";

                    if (needinsert)
                    {
                        //新建 op_apply 
                        saveinfo("insert", head, OPAPPLY, USERID, SHOWNAME, COMPANYID, isclear);

                    }
                    else
                    {
                        saveinfo("edit", head, OPAPPLY, USERID, SHOWNAME, COMPANYID, isclear);
                    }

                }
            }
            catch (Exception e)
            {
                BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "返回值处理错误");
            }

        }

        //private static string CUSTNO { get; set; }

        //public static void setCUSTNO(string custno) {
        //    CUSTNO = custno;
        //}

        //private static string getCUSTNO() {
        //    //BasicDataRefDAL.SaveLog(CUSTNO, USERID, "单一窗口批量读取", "新业务编号");
        //    var result = "";
        //    result=CUSTNO.ToString();
        //    var _t_head = CUSTNO.Substring(0, CUSTNO.Length - 4);
        //    var index = Convert.ToInt32(CUSTNO.Substring(CUSTNO.Length - 4, 4));
        //    index++;
        //    var newindex = index.ToString();
        //    while (newindex.Length < 4)
        //    {
        //        newindex = "0" + newindex;
        //    }
        //    CUSTNO = _t_head + newindex;
        //    return result;
        //} 

        public static void saveinfo(string dealtype, MessageModel head, MsOpApply OPAPPLY, string USERID, string SHOWNAME, string COMPANYID, string ISCLEAR)
        {
            var mark = 0;
            try
            {

                DecHeadBLL bll = new DecHeadBLL();
                ContainerBLL cbll = new ContainerBLL();
                DecListBLL lbll = new DecListBLL();

                if (dealtype == "insert")
                {
                    OPAPPLY.DbOperationType = DbOperationType.DbotIns;
                    OPAPPLY.ModelUIStatus = "I";

                    OPAPPLY.BSNO = Guid.NewGuid().ToString();
                    OPAPPLY.MASTERNO = OPAPPLY.BSNO;
                    mark = 11;
                    var _r = MsOpApplyDAL.getCUSTNO(OPAPPLY, USERID, SHOWNAME, COMPANYID);
                    if (_r.Success)
                        OPAPPLY.CUSTNO = _r.Data.ToString();
                    else
                    {
                        BasicDataRefDAL.SaveLog(_r.Message, USERID, "单一窗口批量读取", "获取单号出错");
                        return;
                    }

                    //OPAPPLY.CUSTNO = MsSysBillNoSetDAL.GetNewNo("报关业务", "委托编号", "0602", COMPANYID, System.DateTime.Now.ToString("yyyy-MM-dd"));
                    mark = 12;
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存1.1");

                }
                else
                {
                    OPAPPLY.DbOperationType = DbOperationType.DbotUpd;
                    OPAPPLY.ModelUIStatus = "E";
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存1.2");
                    mark = 1;
                }

                var bsno = OPAPPLY.BSNO;
                var preDecHeadVo = head.data.getdata();
                mark = 2;
                OPAPPLY.CUSTOMNO = preDecHeadVo.entryId;

                //根据报关单号 结尾0出口  结尾1进口
                OPAPPLY.setbstype();
                OPAPPLY.BSSTATUS = false;
                OPAPPLY.FEESTATUS = false;
                OPAPPLY.BSDATE = Convert.ToDateTime(preDecHeadVo.dDate);
                OPAPPLY.CUSTOMDATE = preDecHeadVo.dDate;//报关日期=申报日期
                OPAPPLY.OPDATE = preDecHeadVo.dDate;//业务日期=申报日期

                OPAPPLY.MBLNO = preDecHeadVo.billNo;
                //OPAPPLY.PORTLOAD = preDecHeadVo.despPortCode
                mark = 3;
                OPAPPLY.INPUTBY = SHOWNAME;
                OPAPPLY.CORPID = COMPANYID;
                OPAPPLY.TRADETYPE = preDecHeadVo.supvModeCddeName;
                OPAPPLY.ISDY = "1";
                OPAPPLY.CUSCIQNO = preDecHeadVo.cusCiqNo;
                OPAPPLY.GOODSOURCE = preDecHeadVo.ciqDespCtryCodeName;
                OPAPPLY.EXPCUSTOMTYPE = preDecHeadVo.iEPortName;
                OPAPPLY.DESPPORT = preDecHeadVo.despPortCodeName;
                OPAPPLY.CONSIGNEE = preDecHeadVo.consigneeCname;
                OPAPPLY.ENTERP = preDecHeadVo.consignorCname;
                if (preDecHeadVo.ciqTrafMode == "3")
                    OPAPPLY.BSTYPE = "5";

                OPAPPLY.ISCLEAR = ISCLEAR;
                if (OPAPPLY.CUSTOMERNAME == "") OPAPPLY.CUSTOMERNAME = MsCodeOpDefDAL.GetData("BSTYPE='OP_APPLY' AND FIELDNAME='CUSTOMERNAME'", COMPANYID).DEFVALUE;

                var modb = new ModelObjectDB();
                var tempresult = modb.Save(OPAPPLY);
                OPAPPLY.DbOperationType = DbOperationType.DbotUpd;
                OPAPPLY.ModelUIStatus = "E";

                

                //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存2");
                #region 单一窗口信息
                var dealtype_detail = "edit";
                var DecHead_Local = bll.GetModelList("BSNO='" + OPAPPLY.BSNO + "'").FirstOrDefault();
                if (DecHead_Local == null)
                {
                    DecHead_Local = new DecHead();
                    dealtype_detail = "insert";
                }
                //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存3");

                if (dealtype_detail == "insert")
                {

                    DecHead_Local.GID = Guid.NewGuid().ToString();
                    DecHead_Local.BSNO = OPAPPLY.BSNO;

                    preDecHeadVo.setvalue(DecHead_Local);
                    bll.Add(DecHead_Local);
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存4.1");

                }
                else
                {
                    preDecHeadVo.setvalue(DecHead_Local);
                    mark++;
                    bll.Update(DecHead_Local);
                    //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存4.2");

                }

                //20210707 境内收发货人 填入 op_apply.CUSTOMER(ENTERP)

                //!string.IsNullOrWhiteSpace(cnsnTradeScc) ? cnsnTradeScc : rcvgdTradeScc;

                OPAPPLY.ENTERP = DecHead_Local.TradeCoScc;

                //20210708 合同协议号 DecHead.ContrNo 填入  OPAPPLY.CONTRACTNO
                OPAPPLY.CONTRACTNO = DecHead_Local.ContrNo;
                
                #endregion

                #region 电子文档信息

                var docdataList = ReceiptDocDAL.GetDocList("BSNO='" + bsno + "'");

                    //ReceiptContext receiptContext = new ReceiptContext();

                    foreach (var pdf in head.pdfFile)
                    {

                        //Receipt_Doc receipt = receiptContext.ReceiptDocs.FirstOrDefault(o => o.BSNO == bsno && o.URL == pdf.filename);
                        var doc = docdataList.Find(x => x.URL == pdf.filename);
                        if (doc == null || doc.BSNO == "")
                        {
                            Database db = DatabaseFactory.CreateDatabase();
                            using (var conn = db.CreateConnection())
                            {
                                conn.Open();
                                var tran = conn.BeginTransaction();

                                try
                                {

                                    var cmdInsert =
                                        db.GetSqlStringCommand(
                                            @"insert into Receipt_Doc (GID,BSNO,URL,Driect_URL,MODIFIEDUSER,MODIFIEDTIME,RECEIPTTYPE,DOCUMENTATTACHEDCODE,DOCUMENTATTACHEDNO) 
                                    values (@GID,@BSNO,@URL,@Driect_URL,@MODIFIEDUSER,@MODIFIEDTIME,@RECEIPTTYPE,@DOCUMENTATTACHEDCODE,@DOCUMENTATTACHEDNO) ");


                                    cmdInsert.Parameters.Clear();
                                    db.AddInParameter(cmdInsert, "@GID", DbType.String, Guid.NewGuid().ToString());
                                    db.AddInParameter(cmdInsert, "@BSNO", DbType.String, bsno);
                                    db.AddInParameter(cmdInsert, "@URL", DbType.String, pdf.filename);
                                    db.AddInParameter(cmdInsert, "@Driect_URL", DbType.String, pdf.path);
                                    db.AddInParameter(cmdInsert, "@MODIFIEDUSER", DbType.String, USERID);
                                    db.AddInParameter(cmdInsert, "@MODIFIEDTIME", DbType.String, DateTime.Now.ToString());
                                    db.AddInParameter(cmdInsert, "@RECEIPTTYPE", DbType.String, "");
                                    db.AddInParameter(cmdInsert, "@DOCUMENTATTACHEDCODE", DbType.String, "");
                                    db.AddInParameter(cmdInsert, "@DOCUMENTATTACHEDNO", DbType.String, "");
                                    db.ExecuteNonQuery(cmdInsert, tran);

                                    tran.Commit();
                                }
                                catch (Exception e)
                                {
                                    BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + e.Message);
                                    tran.Rollback();
                                }
                            }
                        }
                        else
                        {
                            Database db = DatabaseFactory.CreateDatabase();
                            using (var conn = db.CreateConnection())
                            {
                                conn.Open();
                                var tran = conn.BeginTransaction();

                                try
                                {

                                    var cmdInsert =
                                        db.GetSqlStringCommand(
                                            @"update Receipt_Doc set URL=@URL,Driect_URL=@Driect_URL,MODIFIEDUSER=@MODIFIEDUSER,MODIFIEDTIME=@MODIFIEDTIME 
                                    WHERE GID=@GID ");


                                    cmdInsert.Parameters.Clear();
                                    db.AddInParameter(cmdInsert, "@GID", DbType.String, doc.GID);
                                    db.AddInParameter(cmdInsert, "@URL", DbType.String, pdf.filename);
                                    db.AddInParameter(cmdInsert, "@Driect_URL", DbType.String, pdf.path);
                                    db.AddInParameter(cmdInsert, "@MODIFIEDUSER", DbType.String, USERID);
                                    db.AddInParameter(cmdInsert, "@MODIFIEDTIME", DbType.String, DateTime.Now.ToString());
                                    db.ExecuteNonQuery(cmdInsert, tran);
                                    tran.Commit();
                                }
                                catch (Exception e)
                                {
                                    BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + e.Message);
                                    tran.Rollback();
                                }
                            }


                        }

                        //if (receipt == null)
                        //{
                        //    receipt = new Receipt_Doc();
                        //    receipt.GID = Guid.NewGuid().ToString();
                        //    receipt.BSNO = bsno;
                        //    receipt.URL = pdf.filename;
                        //    receipt.Driect_URL = pdf.path;
                        //    receipt.MODIFIEDUSER = USERID;
                        //    receipt.MODIFIEDTIME = System.DateTime.Now;
                        //    receiptContext.ReceiptDocs.Add(receipt);
                        //}
                        //else
                        //{
                        //    receipt.URL = pdf.filename;
                        //    receipt.Driect_URL = pdf.path;
                        //    receipt.MODIFIEDUSER = USERID;
                        //    receipt.MODIFIEDTIME = System.DateTime.Now;
                        //}
                        //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存5");
                        //var _r = receiptContext.SaveChanges();
                    }
                    mark = 7;
                    #endregion

                #region 集装箱信息

                var opapplyctnlist = MsOpApplyDAL.GetCtnBodyList("BSNO='" + OPAPPLY.BSNO + "'", "");
                var containerlist = cbll.GetModelList("PID='" + DecHead_Local.GID + "'");
                var portContainerlist = preDecHeadVo.getpreDecContainerVo();
                mark = 71;
                if (portContainerlist.Count > 0)
                {
                    Database db = DatabaseFactory.CreateDatabase();
                    using (var conn = db.CreateConnection())
                    {
                        conn.Open();
                        mark = 72;
                        foreach (var portContainer in portContainerlist)
                        {
                            var upd = false;
                            foreach (var container in containerlist)
                            {
                                if (container.ContainerId.Trim() == portContainer.containerNo.Trim())
                                {
                                    upd = true;
                                    var updcontainer = portContainer.getContainerValue(container);
                                    cbll.Update(updcontainer);
                                }
                            }
                            if (!upd)
                            {
                                var updcontainer = new Container();
                                updcontainer = portContainer.getContainerValue(updcontainer);
                                updcontainer.GID = Guid.NewGuid().ToString();
                                updcontainer.PID = DecHead_Local.GID;
                                cbll.Add(updcontainer);
                            }
                            var updapply = false;
                            foreach (var container in opapplyctnlist)
                            {
                                if (container.CNTRNO.Trim() == portContainer.containerNo.Trim())
                                {
                                    updapply = true;
                                }
                            }
                            if (!updapply)
                            {


                                var tran = conn.BeginTransaction();
                                try
                                {
                                    var cmdInsert = db.GetSqlStringCommand(@"insert into op_ctn (CTN_ID,BSNO,CTNNUM,CNTRNO,CTNALL) values (NEWID()"
                                        + ",'" + OPAPPLY.BSNO + "',1,'" + portContainer.containerNo.Trim() + "','40GP')");
                                    db.ExecuteNonQuery(cmdInsert, tran);

                                    tran.Commit();
                                }
                                catch (Exception e)
                                {
                                    BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + e.Message);
                                    tran.Rollback();
                                }


                            }

                        }
                    }
                }
                mark = 8;
                //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存6");
                containerlist = cbll.GetModelList("PID='" + DecHead_Local.GID + "'");
                mark = 9;
                #endregion

                #region 项信息
                var declist_List = lbll.GetModelList(0, 99, "PID='" + DecHead_Local.GID + "'", String.Format("{0}", "gNo", ""));

                var port_decMergeListVoList = preDecHeadVo.getdecMergeListVo();
                var curr = "USD";
                decimal cargovalue = 0;
                if (port_decMergeListVoList.Count > 0)
                    foreach (var port_decMergeListVo in port_decMergeListVoList)
                    {
                        var upd = false;
                        foreach (var declist in declist_List)
                        {
                            if (declist.GNo.Trim() == port_decMergeListVo.gNo.Trim())
                            {
                                upd = true;
                                var upddeclist = port_decMergeListVo.getDecListValue(declist);
                                lbll.Update(upddeclist);
                            }
                        }
                        if (!upd)
                        {
                            var upddeclist = new DecList();
                            upddeclist = port_decMergeListVo.getDecListValue(upddeclist);
                            upddeclist.GID = Guid.NewGuid().ToString();
                            upddeclist.PID = DecHead_Local.GID;
                            lbll.Add(upddeclist);
                        }
                        try
                        {
                            cargovalue = cargovalue + Convert.ToDecimal(port_decMergeListVo.declTotal);
                            curr = port_decMergeListVo.tradeCurr;
                        }
                        catch (Exception e)
                        {
                            BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + e.Message);
                        }
                    }
                OPAPPLY.CARGOVALUE = cargovalue.ToString();
                OPAPPLY.CURRENCY = curr;

                modb = new ModelObjectDB();
                tempresult = modb.Save(OPAPPLY);

                mark = 10;
                var Declist = lbll.GetModelList(0, 99, "PID='" + DecHead_Local.GID + "'", String.Format("{0}", "gNo", ""));
                var count = lbll.GetRecordCount("PID='" + DecHead_Local.GID + "'");
                //BasicDataRefDAL.SaveLog(OPAPPLY, USERID, "单一窗口批量读取", "保存7");
                mark = 11;
                #endregion

            }
            catch (Exception e)
            {
                BasicDataRefDAL.SaveLog(e.Message, USERID, "单一窗口批量读取", "保存错误" + mark.ToString());
            }

        }

    }
}