using JLHHJSvr.Com.Model;
using LJLib.Tools.File;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Windows.Forms;
using JLHHJSvr.Com;
using JLHHJSvr.LJFramework.Tools;
using LJLib.DAL.SQL;
using Newtonsoft.Json.Linq;
using DirectService.Tools;
using LJLib.Tools.DEncrypt;
using JLHHJSvr.BLL;
using JLHHJSvr.Helper;

namespace JLHHJSvr
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("请输入内容");
                return;
            }

            try
            {
                XmlConfig xmlconfig = new XmlConfig();
                string connectionString = xmlconfig.GetXmlFileValue(GlobalVar.XmlFile, string.Empty, "ConnectionString", string.Empty);
                connectionString = DESEncrypt.Decrypt(connectionString, "4A61A8B51C3E42BCAE991F6C913A6A33");

                DbSqlHelper.Add(new SqlServerEngine());
                using (var con = new SqlConnection(connectionString))
                using (var cmd = con.CreateCommand())
                {
                    con.Open();

                    var url = textBox4.Text;

                    var loginReq = new LoginRequest()
                    {
                        usercode = textBox2.Text,
                        psw = textBox3.Text,
                    };
                    var loginRsp = LJHttpUtil.PostRequest(url + loginReq.GetApiName(), JObject.FromObject(loginReq))
                        .ToObject<LoginResponse>();

                    if (!string.IsNullOrEmpty(loginRsp.ErrMsg))
                    {
                        MessageBox.Show("登录失败：" + loginRsp.ErrMsg);
                        return;
                    }

                    var token = loginRsp.token;

                    var list = new List<u_mattress>();
                    var textBox1Str = textBox1.Text;
                    string whereStr;
                    if (textBox1Str.StartsWith("where ", StringComparison.CurrentCultureIgnoreCase))
                    {
                        whereStr = textBox1Str.Substring(6);
                    }
                    else
                    {
                        var textStr = textBox1Str.Replace("，", ",").Split(',');
                        whereStr = $"mattresscode IN {ListEx.getString(textStr)}";
                    }
                    DbSqlHelper.Select(cmd, list, whereStr, "mattressid,deptid,mattresstypeid,mattress_width,mattress_length,mattress_height,packtype,packqty,woodpallettype,total_hr_cost,total_material_cost,fees_dscrp,total_fees_cost,total_cost,taxrate,taxes,commissionrate,commission,fob,profitrate,createtime,createby,extras_cost,dept_profitrate,moneyrate,nottax_factory_cost,nottax_dept_cost,dept_cost,foreign_cost,mattresscode,mattressname,diameter,area,cabinet_type,loading_type,hrcost,biandaicost,fob_replace_formula,hrcost_replace_formula,biandaicost_replace_formula,mattressrelcode,other_rate,gydscrp,flag,dept_profitrate_rangli,auditingrep,auditingdate,profitrate_point,if_moneyrate,discount,if_discount,erp_mtrlid,erp_configcodetype,erp_mtrlcode,erp_mtrlname,erp_mtrlmode,erp_mtrltypeid,erp_mtrltype,erp_mtrlunit,erp_mtrlengname,erp_piccode,yw_flag,yw_auditingrep,yw_auditingdate,js1_flag,js1_auditingrep,js1_auditingdate,js2_flag,js2_auditingrep,js2_auditingdate,creatmtrl_flag,creatmtrl_auditingrep,creatmtrl_auditingdate,creatmtrlqd_flag,creatmtrlqd_auditingrep,creatmtrlqd_auditingdate,if_m_chai,if_z_chai,if_d_chai,if_n_butao,if_w_butao,if_m_wbutao_way,if_db_wbutao_way,s_cover_qty,z_cover_qty,x_cover_qty,biandai_qty,s_m_cover_qty,z_m_cover_qty,x_m_cover_qty,butao_point,chaizhuang_point,if_haimian_type,haimian_point,if_zhedie_type,old_mtrlname,xd_flag,xd_auditingrep,xd_auditingdate,qr_flag,qr_auditingrep,qr_auditingdate,temp_code,erp_cb_updatetime,bcptypeid,if_bcp_type,bcp_m_id,bcp_m_name,bcp_d_id,bcp_d_name,bcp_dc_id,bcp_dc_name,bcp_xc_id,bcp_xc_name,bcp_vc_id,bcp_vc_name,bcp_cw_id,bcp_cw_name,zhizao_amt,guanli_rate,dannum_rate,cubage,foreign_cost_bz,foreign_cost_dd");

                    var idList = list.Select(x => x.mattressid.ToString());
                    var failIDs = new HashSet<string>(idList);
                    var okIDs = new HashSet<string>();

                    var MattressHelper = HelperBase.GetHelper<MattressHelper>(cmd);
                    var BednetHelper = HelperBase.GetHelper<BedNetHelper>(cmd);
                    var InterFaceHelper = HelperBase.GetHelper<InterfaceHelper>(cmd);

                    var errMsg = string.Empty;
                    foreach (var mattress in list)
                    {
                        if (textBox1Str.StartsWith("where ", StringComparison.CurrentCultureIgnoreCase))
                        {
                            errMsg = string.Empty;
                        }
                        var id = mattress.mattressid;
                        var old_mattresscode = mattress.mattresscode;
                        mattress.dannum_type = 0;
                        try
                        {
                            mattress.mattressid = 0;

                            var mxList = MattressHelper.GetMattressMxMtrl(id);

                            if (mxList.Count > 0)
                            {
                                foreach(var mx in mxList)
                                {
                                    mx.mattressid = 0;
                                    mx.mattressmxid = 0;
                                    if (mx.formulatype == 99 && mx.mtrlid > 0)
                                    {
                                        var bednetItm = BednetHelper.GetBedNet(mx.mtrlid.Value);
                                        var bednetMx = BednetHelper.GetBedNetMxList(mx.mtrlid.Value);
                                        var spring = BednetHelper.GetBedNetSpringList(mx.mtrlid.Value);
                                        bednetItm.copy_id = bednetItm.bednetid;

                                        var saveReqBednet = new SaveBedNetRequest()
                                        {
                                            bednet = bednetItm,
                                            bednetMx = bednetMx,
                                            spring = spring,
                                            token = token,
                                        };

                                        var saveRspBednet = LJHttpUtil.PostRequest(url + saveReqBednet.GetApiName(), JObject.FromObject(saveReqBednet))
                                            .ToObject<SaveBedNetResponse>();

                                        if (!string.IsNullOrEmpty(saveRspBednet.ErrMsg))
                                        {
                                            errMsg += $"{old_mattresscode}:ERRMSG Interface==> {saveRspBednet.ErrMsg}\r\n";
                                        }
                                        else
                                        {
                                            mx.mtrlid = saveRspBednet.bednet.bednetid;
                                        }
                                    }
                                }
                            }

                            var saveReq = new SaveMattressRequest()
                            {
                                mattress = mattress,
                                mattressMx = mxList,
                                token = token,
                            };

                            var newid = 0;
                            var saveRsp = LJHttpUtil.PostRequest(url + saveReq.GetApiName(), JObject.FromObject(saveReq))
                                .ToObject<SaveMattressResponse>();
                            if (!string.IsNullOrEmpty(saveRsp.ErrMsg))
                            {
                                errMsg += $"{old_mattresscode}:ERRMSG==> {saveRsp.ErrMsg}\r\n";
                            }
                            else
                            {
                                newid = saveRsp.mattressid;
                                okIDs.Add(old_mattresscode);
                                failIDs.Remove(old_mattresscode);
                            }


                            //var interfaceList = InterFaceHelper.GetMattressInterfaceList(id, mattress.erp_configcodetype);
                            var interfaceList = new List<u_mattress_interface>();
                            var selectStr = @"SELECT mattressid
	                            ,printid
	                            ,itemname
	                            ,bj_pzname
	                            ,bj_namemx
	                            ,actual_size
	                            ,sb_craft
	                            ,actual_size_sb
	                            ,erp_pzid
	                            ,ss_rate
	                            ,ls_rate
	                            ,bj_inputtype
                            FROM u_mattress_interface";
                            DbSqlHelper.SelectJoin(cmd, selectStr, "mattressid = @mattressid", new Dictionary<string, object>() { { "@mattressid", id } }, "printid", "mattressid,printid,itemname,bj_pzname,bj_namemx,actual_size,sb_craft,actual_size_sb,erp_pzid,ss_rate,ls_rate,bj_inputtype", 0, 0, interfaceList);

                            var qdList = InterFaceHelper.GetMattressInterfaceQdList(id);

                            mattress.mattressid = newid;
                            foreach (var mx in interfaceList)
                            {
                                mx.mattressid = newid;
                            }
                            foreach (var mx in qdList)
                            {
                                mx.mattressid = newid;
                            }

                            var saveReqInterface = new SaveMattressInterfaceRequest()
                            {
                                mattress = mattress,
                                interfaceList = interfaceList,
                                qdList = qdList,
                                token = token,
                            };

                            var saveRspInterface = LJHttpUtil.PostRequest(url + saveReqInterface.GetApiName(), JObject.FromObject(saveReqInterface))
                                .ToObject<SaveMattressInterfaceResponse>();
                            if (!string.IsNullOrEmpty(saveRspInterface.ErrMsg))
                            {
                                errMsg += $"{old_mattresscode}:ERRMSG Interface==> {saveRspInterface.ErrMsg}\r\n";
                            }
                        }
                        catch (Exception ex)
                        {
                            errMsg += $"{id}: {ex}\r\n";
                        }

                        if (string.IsNullOrEmpty(errMsg))
                        {
                            cmd.CommandText = "UPDATE u_mattress SET sync_time = GETDATE() WHERE mattressid = @id";
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@id", id);
                            cmd.ExecuteNonQuery();
                        }
                        else
                        {
                            cmd.CommandText = "UPDATE u_mattress SET sync_err = @errmsg WHERE mattressid = @id";
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@id", id);
                            cmd.Parameters.AddWithValue("@errmsg", errMsg);
                            cmd.ExecuteNonQuery();
                        }
                    }

                    if (!textBox1Str.StartsWith("where ", StringComparison.CurrentCultureIgnoreCase))
                    {
                        textBox1.Text = $"{textBox1Str}\r\n同步失败：{string.Join(",", failIDs)}\r\n同步成功：{string.Join(",", okIDs)}\r\n{errMsg}";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
