using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.Helper;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;
using Newtonsoft.Json.Linq;

namespace JLHHJSvr.Excutor
{
    internal sealed class CreatPrdPfExcutor : ExcutorBase<CreatPrdPfRequest, CreatPrdPfResponse>
    {
        Dictionary<string, object> replacements = new Dictionary<string, object>();

        protected override void ExcuteInternal(CreatPrdPfRequest request, object state, CreatPrdPfResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (request.list.Count <= 0)
            {
                rslt.ErrMsg = "床垫id参数为空!";
                return;
            }

            using (var con = new SqlConnection(GlobalVar.ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                con.Open();

                foreach (var mattressid in request.list)
                {
                    var mattress = new u_mattress();
                    if (DbSqlHelper.SelectOne(cmd, "u_mattress", "mattressid = @mattressid", new Dictionary<string, object>() { { "mattressid", mattressid } }, mattress, "erp_mtrlid,erp_mtrlcode, erp_mtrlname, erp_mtrlmode, erp_mtrltypeid, erp_mtrltype, erp_mtrlunit, erp_mtrlengname,nottax_factory_cost,dept_profitrate,dept_profitrate_rangli,commission,taxes,fob,extras_cost,mattresstypeid,erp_configcodetype") != 1)
                    {
                        rslt.ErrMsg = "床垫报价单匹配失败";
                        return;
                    }

                    var mattress_interface_qd_list = new List<u_mattress_interface_qd>();

                    var selectStr = @"SELECT u_mattress_interface_qd.mattressid 
	                                ,u_mattress_interface_qd.printid 
	                                ,u_mattress_interface_qd.itemname 
	                                ,u_mattress_interface_qd.bj_pzname 
	                                ,u_mattress_interface_qd.bj_pzname_mx 
	                                ,u_mattress_interface_qd.bj_pzname_mx_mx 
	                                ,u_mattress_interface_qd.wip_type 
	                                ,u_mattress_interface_qd.mtrlid 
	                                ,u_mattress_interface_qd.erp_mtrlid 
	                                ,u_mattress_interface_qd.useqty 
	                                ,u_mattress_interface_qd.dscrp 
	                                ,u_mtrl_price.name AS mtrlname
	                                ,u_mattress_interface_qd.actual_useqty 
	                                ,u_mattress_interface_qd.qd_actual_size 
	                                ,u_mattress_interface_qd.qd_pfgroupqty 
	                                ,u_mattress_interface_qd.wrkgrpid 
	                                ,u_mattress_interface_qd.wrkgrpid2 
	                                ,u_mattress_interface_qd.wrkgrpcode1
	                                ,u_mattress_interface_qd.wrkgrpcode2
	                                ,u_mattress_interface_qd.ss_rate 
	                                ,u_mattress_interface_qd.ls_rate 
	                                ,u_mattress_interface_qd.sh_rate
                                    ,ISNULL('[>0,<=5]={' + left(cast(u_mtrltype.dannum1_rate as char(10)),4) + '};[>5,<=10]={'+ + '[>0,<=100]={' + left(cast(u_mtrltype.dannum4_rate as char(10)),4) + '};[>10,<=200]={' + left(cast(u_mtrltype.dannum2_rate as char(10)),4) + '};[>200]={' + left(cast(u_mtrltype.dannum3_rate as char(10)),4) + '};', '') AS sonLossstr
                                FROM u_mattress_interface_qd
                                LEFT JOIN u_mtrl_price ON u_mtrl_price.mtrlid = u_mattress_interface_qd.mtrlid
                                LEFT JOIN u_mtrltype ON u_mtrltype.mtrltypeid = u_mtrl_price.mtrltype";
                    var outputFields = "mattressid,printid,itemname,bj_pzname,bj_pzname_mx,bj_pzname_mx_mx,wip_type,mtrlid,erp_mtrlid,useqty,dscrp,mtrlname,actual_useqty,qd_actual_size,qd_pfgroupqty,wrkgrpid,wrkgrpid2,ss_rate,ls_rate,sh_rate,wrkgrpcode1,wrkgrpcode2,sonLossstr";
                    DbSqlHelper.SelectJoin(cmd, selectStr, "mattressid = @mattressid", new Dictionary<string, object>() { { "@mattressid", mattressid } }, "printid", outputFields, 0, 0, mattress_interface_qd_list);

                    var interfaceHelper = HelperBase.GetHelper<InterfaceHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });
                    var interfaceList = interfaceHelper.GetMattressInterfaceList(mattressid, 0);

                    var ll_temp_dftwrkgrpid = 0;

                    // var ErpMtrl = new erp_mtrldef() { mtrlid = mattress.erp_mtrlid };
                    // if (DbSqlHelper.SelectOne(erp_cmd, ErpMtrl, "dftwrkgrpid") == 1)
                    // {
                    //     ll_temp_dftwrkgrpid = ErpMtrl.dftwrkgrpid.Value;
                    // }

                    var pfcode = $"{mattress.erp_mtrlcode}_V2.0";
                    var l1Req = new SavePrdPfRequest()
                    {
                        mtrl_pf = new u_mtrl_pf()
                        {
                            mtrlid = mattress.erp_mtrlid.Value,
                            pfcode = pfcode,
                            ifdft = 1,
                            inuse = 1,
                            opemp = tokendata.usercode,
                            opdate = DateTime.Now,
                            flag = 1,
                            auditdate = DateTime.Now,
                            auditemp = tokendata.usercode,
                            wrkid = ll_temp_dftwrkgrpid
                        },
                        prdPfs = new List<u_PrdPF>()
                    };

                    var bcpNames = new Dictionary<string, string> { };
                    var bcpDscrp = new Dictionary<string, string> { };
                    foreach (var mx in mattress_interface_qd_list)
                    {
                        if (!string.IsNullOrEmpty(mx.wip_type) && !string.IsNullOrEmpty(mx.bj_pzname_mx_mx) && !bcpNames.ContainsKey(mx.wip_type))
                        {
                            var _name = mx.bj_pzname_mx_mx;
                            var interfaceL = interfaceList.Where(o => _name == o.bj_namemx && mx.bj_pzname == o.bj_pzname).ToList();
                            if (interfaceL.Count > 0)
                            {
                                _name = interfaceL[0].bj_namemx;
                                if (!string.IsNullOrEmpty(interfaceL[0].actual_size)) _name += " + " + interfaceL[0].actual_size;
                                if (!string.IsNullOrEmpty(interfaceL[0].sb_craft)) _name += " + " + interfaceL[0].sb_craft;
                                if (!string.IsNullOrEmpty(interfaceL[0].actual_size_sb)) _name += " + " + interfaceL[0].actual_size_sb;
                                if (interfaceL[0].ss_rate != null && interfaceL[0].ss_rate > 0) _name += " + " + interfaceL[0].ss_rate;
                                if (interfaceL[0].ls_rate != null && interfaceL[0].ls_rate > 0) _name += " + " + interfaceL[0].ls_rate;
                            }

                            bcpNames.Add(mx.wip_type, _name);
                            bcpDscrp.Add(mx.wip_type, mx.bj_pzname_mx_mx);
                        }
                    }

                    var i = 0;
                    foreach (var mx in mattress_interface_qd_list)
                    {

                        var ls_temp_pfgroup = mx.itemname + '-' + mx.bj_pzname;
                        var ll_cnt_temp = 0;
                        for (var j = 0; j < i - 1; j++)
                        {
                            if (ls_temp_pfgroup == mattress_interface_qd_list[j].itemname + '-' + mattress_interface_qd_list[j].bj_pzname)
                            {
                                ll_cnt_temp++;
                            }
                        }
                        if (ll_cnt_temp > 0)
                        {
                            ls_temp_pfgroup = ls_temp_pfgroup + (ll_cnt_temp).ToString();
                        }

                        var _name = mx.bj_pzname_mx_mx;
                        if (!string.IsNullOrEmpty(mx.wip_type) && bcpNames.ContainsKey(mx.wip_type) && !string.IsNullOrEmpty(bcpNames[mx.wip_type]))
                        {
                            _name = bcpNames[mx.wip_type];
                        }
                        var _dscrp = mx.bj_pzname_mx_mx;
                        if (!string.IsNullOrEmpty(mx.wip_type) && bcpDscrp.ContainsKey(mx.wip_type) && !string.IsNullOrEmpty(bcpDscrp[mx.wip_type]))
                        {
                            _dscrp = bcpDscrp[mx.wip_type];
                        }

                        string ls_azcode = i.ToString("D3");

                        var prdpf = new u_PrdPF()
                        {
                            mtrlid = mattress.erp_mtrlid.Value,
                            pfcode = pfcode,
                            pfgroup = ls_temp_pfgroup,
                            SonMtrlid = mx.erp_mtrlid,
                            wrkgrpid = mx.wrkgrpid,
                            wrkgrpcode1 = mx.wrkgrpcode1,
                            wrkgrpcode2 = mx.wrkgrpcode2,
                            sonpfcode = "[常规]",
                            dscrp = _dscrp,
                            pfgroupqty = mx.qd_pfgroupqty,
                            Sonscale = mx.actual_useqty,
                            pfklmode = mx.qd_actual_size,
                            printid = mx.printid,
                            azcode = ls_azcode,
                            promode = mx.ss_rate.ToString(),
                            SonLossstr = mx.sonLossstr,
                            SonLoss = mx.sh_rate,
                            SonDECLosS = 0,
                            wip_name = _name,
                            wip_type = mx.wip_type
                        };
                        l1Req.prdPfs.Add(prdpf);
                        i++;
                    }

                    l1Req.token = GlobalVar.ERP_TOKEN;

                    var l1Helper = HelperBase.GetHelper<ERPHelper>(cmd);
                    l1Helper.context = new HelperBase.Context() { tokendata = tokendata };

                    l1Helper.CheckLogin();

                    var l1Rslt = l1Helper.DoExecute("SavePrdPf", JObject.FromObject(l1Req));
                    rslt.ErrMsg = $"{l1Rslt.GetValue("ErrMsg")}";

                    if (string.IsNullOrEmpty(rslt.ErrMsg))
                    {
                        mattress.creatmtrlqd_flag = 1;
                        mattress.mattressid = mattressid;
                        DbSqlHelper.Update(cmd, mattress, "creatmtrlqd_flag");
                    }
                }
            }
        }

        /// <summary>
        /// 保存物料清单请求参数,没有传入的参数按默认值
        /// </summary>
        private class SavePrdPfRequest
        {
            public string token { get; set; }
            /// <summary>
            /// 物料清单主表 mtrlid,pfcode,flag,affirmflag,Ifdft,inuse,wrkid
            /// </summary>
            public u_mtrl_pf mtrl_pf { get; set; }
            /// <summary>
            /// 物料清单明细表 mtrlid,pfcode,sonmtrlid,printid,wrkgrpid,sonpfcode,Sonscale,sonloss,sondecloss
            /// pfgroup,dscrp,pfgroupqty,pfklmode,azcode,promode
            /// </summary>
            public List<u_PrdPF> prdPfs { get; set; }
        }
    }
}
