using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using DirectService.Tools;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.Helper;
using JLHHJSvr.LJException;
using JLHHJSvr.Tools;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;

namespace JLHHJSvr.Excutor
{
    internal sealed class SaveMattressExcutor : ExcutorBase<SaveMattressRequest, SaveMattressResponse>
    {
        protected override void ExcuteInternal(SaveMattressRequest request, object state, SaveMattressResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (request.mattress == null)
            {
                rslt.ErrMsg = "缺少主表信息";
                return;
            }

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

                // 初始化属性
                AutoInit.AutoInitS(cmd, request.mattress);

                if(request.mattress.copy_id != null && request.mattress.copy_id > 0)
                {
                    request.mattress.mattressid = 0;
                    request.mattress.mattresscode = string.Empty;
                    request.mattress.js1_flag = 0;
                    request.mattress.xd_flag = 0;
                    request.mattress.xd_auditingrep = "";
                    request.mattress.xd_auditingdate = null;
                    request.mattress.flag = 0;
                    request.mattress.auditingrep = "";
                    request.mattress.auditingdate = null;
                    request.mattress.qr_auditingrep = "";
                    request.mattress.qr_auditingdate = null;

                    foreach (var mx in request.mattressMx)
                    {
                        mx.mattressid = 0;
                        mx.mattressmxid = 0;
                    }
                }

                foreach(var mx in request.mattressMx)
                {
                    AutoInit.AutoInitS(cmd, mx);
                }

                using (cmd.Transaction = con.BeginTransaction())
                {

                    var helper = HelperBase.GetHelper<MattressHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });

                    var helperBednet = HelperBase.GetHelper<BedNetHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });

                    try
                    {
                        rslt.mxmessage = new List<string>();

                        rslt.mxmessage = toSaveMattress(cmd, request.mattress, request.mattressMx, request.extraProcesses, request.extraCosts, tokendata);

                        rslt.mattressid = request.mattress.mattressid;
                        rslt.mattresscode = request.mattress.mattresscode;

                        var subspecsList = helper.GetMattressSubspecs(request.mattress.mattressid);

                        if (subspecsList.Count > 0)
                        {

                            foreach (var submx in subspecsList)
                            {
                                // 删除副规格特殊工艺表
                                cmd.CommandText = @"DELETE u_mattress_mx_extra WHERE mattressid = @mattressid";
                                cmd.Parameters.Clear();
                                cmd.Parameters.AddWithValue("@mattressid", submx.mattressid);
                                cmd.ExecuteNonQuery();

                                // 删除副规格明细
                                cmd.CommandText = @"DELETE u_mattress_mx_mtrl WHERE mattressid = @mattressid";
                                cmd.Parameters.Clear();
                                cmd.Parameters.AddWithValue("@mattressid", submx.mattressid);
                                cmd.ExecuteNonQuery();

                                // 删除副规格
                                cmd.CommandText = @"DELETE u_mattress WHERE mattressid = @mattressid";
                                cmd.Parameters.Clear();
                                cmd.Parameters.AddWithValue("@mattressid", submx.mattressid);
                                cmd.ExecuteNonQuery();
                            }
                        }

                        if (request.subspecs != null && request.subspecs.Count > 0)
                        {
                            // 排序：宽、长，从小到大
                            var _subspecs = request.subspecs.OrderBy(o => o["mattress_width"]).ThenBy(o => o["mattress_length"]).ToList();
                            // 副规格
                            foreach (var submx in _subspecs)
                            {
                                var _mattress = ObjectHelper.DeepCopy(request.mattress);
                                _mattress.parentid = request.mattress.mattressid;
                                _mattress.mattressid = 0;
                                _mattress.mattresscode = "";
                                _mattress.mattress_width = Convert.ToInt32(submx["mattress_width"]);
                                _mattress.mattress_length = Convert.ToInt32(submx["mattress_length"]);
                                _mattress.mattress_height = Convert.ToInt32(submx["mattress_height"]);
                                _mattress.mattressrelcode = Convert.ToString(submx["mattressrelcode"]);
                                _mattress.mattressname = Convert.ToString(submx["mattressname"]);

                                var _mattressMx = new List<u_mattress_mx_mtrl>();
                                if (request.mattressMx != null && request.mattressMx.Any())
                                {
                                    var bednetIndex = 0; // 床网索引
                                    var ifSubspecsIndex = 0; // 垫层主副规格物料索引
                                    foreach (var itemMx in request.mattressMx)
                                    {
                                        var item = ObjectHelper.DeepCopy(itemMx);
                                        item.mattressid = _mattress.mattressid;
                                        item.mattressmxid = 0;
                                        item.message = "";

                                        #region 副规格床网自动匹配/新增逻辑
                                        if (item.formulatype == 99 && item.mtrlid > 0)
                                        {
                                            bednetIndex++;
                                            var oBednet = new u_bednet();
                                            var _bednet = helperBednet.GetBedNet(item.mtrlid.Value);
                                            var _bednetMx = helperBednet.GetBedNetMxList(item.mtrlid.Value);
                                            var _bednetSpring = helperBednet.GetBedNetSpringList(item.mtrlid.Value);

                                            _bednet.mattress_width = Convert.ToInt32(submx["mattress_width"]) - (request.mattress.mattress_width - _bednet.mattress_width);
                                            _bednet.mattress_length = Convert.ToInt32(submx["mattress_length"]) - (request.mattress.mattress_length - _bednet.mattress_length);

                                            var _spring_qty_width = Convert.ToInt32(submx["spring_qty_width_" + bednetIndex]);
                                            var _spring_qty_length = Convert.ToInt32(submx["spring_qty_length_" + bednetIndex]);
                                            var _bednet_fork_qty = _bednet.fork_qty;
                                            if (submx.Value<string>("bednet_fork_qty_" + bednetIndex) != null)
                                            {
                                                _bednet_fork_qty = Convert.ToInt32(submx["bednet_fork_qty_" + bednetIndex]);
                                            }

                                            if (_bednetMx.Count > 0)
                                            {

                                                cmd.CommandText = @"SELECT TOP 1 u_bednet.bednetid
                                                                            ,u_bednet_type.typename
                                                                            ,bednetcode
                                                                            ,mattress_width
                                                                            ,mattress_length
                                                                            ,mattress_height
                                                                            ,nottax_factory_cost
                                                                    FROM u_bednetmx
                                                                    INNER JOIN u_bednet on u_bednet.bednetid = u_bednetmx.bednetid
                                                                    INNER JOIN u_bednet_type on u_bednet_type.bednettypeid = u_bednet.bednettypeid
                                                                    WHERE u_bednet.bednettypeid = @bednettypeid
                                                                        AND u_bednet.mattress_width = @mattress_width
                                                                        AND u_bednet.mattress_length = @mattress_length
                                                                        AND u_bednet.if_doublenet = @if_doublenet
                                                                        AND u_bednet.if_doublespring = @if_doublespring
                                                                        AND u_bednet.snake_wire_diameter = @snake_wire_diameter
                                                                        AND u_bednet.if_rsorwa = @if_rsorwa
                                                                        AND u_bednet.if_sponge_drilling = @if_sponge_drilling
                                                                        AND u_bednet.ifsaleout = 0
                                                                        AND u_bednet.sponge_mtrlid = @sponge_mtrlid
                                                                        AND u_bednet.sponge_thickness = @sponge_thickness
                                                                        AND u_bednet.sponge_height = @sponge_height
                                                                        AND u_bednet.sponge_tc_mtrlid = @sponge_tc_mtrlid
                                                                        AND u_bednet.sponge_tc_thickness = @sponge_tc_thickness
                                                                        AND u_bednet.sponge_tc_height = @sponge_tc_height
                                                                        AND u_bednet.edge_mtrlid = @edge_mtrlid
                                                                        AND u_bednet.edge_height = @edge_height
                                                                        AND u_bednet.felt_mtrlid = @felt_mtrlid
                                                                        AND u_bednet.felt_qty = @felt_qty
                                                                        AND u_bednet.felt_x_mtrlid = @felt_x_mtrlid
                                                                        AND u_bednet.felt_x_qty = @felt_x_qty
                                                                        AND u_bednet.fork_qty = @fork_qty
                                                                        AND u_bednet.felt_dscrp = @felt_dscrp
                                                                        AND u_bednet.duo_qv_str = @duo_qv_str
                                                                        AND u_bednetmx.bednet_height = @bednet_height
                                                                        AND u_bednetmx.springid = @springid
                                                                        AND u_bednetmx.spring_qty_width = @spring_qty_width
                                                                        AND u_bednetmx.spring_qty_length = @spring_qty_length
                                                                        AND u_bednetmx.if_side_iron = @if_side_iron
                                                                        AND u_bednetmx.side_iron_qty = @side_iron_qty
                                                                        AND u_bednetmx.fabrics2_mtrlid = @fabrics2_mtrlid
                                                                        AND u_bednetmx.fabrics1_mtrlid = @fabrics1_mtrlid
                                                                        AND u_bednetmx.if_hard_around = @if_hard_around
                                                                        AND u_bednetmx.hard_around_springid = @hard_around_springid
                                                                        AND u_bednetmx.hard_around_row = @hard_around_row
                                                                        AND u_bednetmx.if_15strip = @if_15strip
                                                                    ";
                                                cmd.Parameters.Clear();
                                                cmd.Parameters.AddWithValue("@bednettypeid", _bednet.bednettypeid);
                                                cmd.Parameters.AddWithValue("@mattress_width", _bednet.mattress_width);
                                                cmd.Parameters.AddWithValue("@mattress_length", _bednet.mattress_length);
                                                cmd.Parameters.AddWithValue("@if_doublenet", _bednet.if_doublenet);
                                                cmd.Parameters.AddWithValue("@if_doublespring", _bednet.if_doublespring);
                                                cmd.Parameters.AddWithValue("@snake_wire_diameter", _bednet.snake_wire_diameter);
                                                cmd.Parameters.AddWithValue("@if_rsorwa", _bednet.if_rsorwa);
                                                cmd.Parameters.AddWithValue("@if_sponge_drilling", _bednet.if_sponge_drilling);
                                                cmd.Parameters.AddWithValue("@sponge_mtrlid", _bednet.sponge_mtrlid);
                                                cmd.Parameters.AddWithValue("@sponge_thickness", _bednet.sponge_thickness);
                                                cmd.Parameters.AddWithValue("@sponge_height", _bednet.sponge_height);
                                                cmd.Parameters.AddWithValue("@sponge_tc_mtrlid", _bednet.sponge_tc_mtrlid);
                                                cmd.Parameters.AddWithValue("@sponge_tc_thickness", _bednet.sponge_tc_thickness);
                                                cmd.Parameters.AddWithValue("@sponge_tc_height", _bednet.sponge_tc_height);
                                                cmd.Parameters.AddWithValue("@edge_mtrlid", _bednet.edge_mtrlid);
                                                cmd.Parameters.AddWithValue("@edge_height", _bednet.edge_height);
                                                cmd.Parameters.AddWithValue("@felt_mtrlid", _bednet.felt_mtrlid);
                                                cmd.Parameters.AddWithValue("@felt_qty", _bednet.felt_qty);
                                                cmd.Parameters.AddWithValue("@felt_x_mtrlid", _bednet.felt_x_mtrlid);
                                                cmd.Parameters.AddWithValue("@felt_x_qty", _bednet.felt_x_qty);
                                                cmd.Parameters.AddWithValue("@felt_dscrp", _bednet.felt_dscrp);
                                                cmd.Parameters.AddWithValue("@duo_qv_str", _bednet.duo_qv_str);
                                                cmd.Parameters.AddWithValue("@fork_qty", _bednet.iffork == 1 ? _bednet_fork_qty : 0);
                                                cmd.Parameters.AddWithValue("@bednet_height", _bednetMx[0].bednet_height);
                                                cmd.Parameters.AddWithValue("@springid", _bednetMx[0].springid);
                                                cmd.Parameters.AddWithValue("@spring_qty_width", _spring_qty_width);
                                                cmd.Parameters.AddWithValue("@spring_qty_length", _spring_qty_length);
                                                cmd.Parameters.AddWithValue("@if_side_iron", _bednetMx[0].if_side_iron);
                                                cmd.Parameters.AddWithValue("@side_iron_qty", _bednetMx[0].side_iron_qty);
                                                cmd.Parameters.AddWithValue("@fabrics2_mtrlid", _bednetMx[0].fabrics2_mtrlid);
                                                cmd.Parameters.AddWithValue("@fabrics1_mtrlid", _bednetMx[0].fabrics1_mtrlid);
                                                cmd.Parameters.AddWithValue("@if_hard_around", _bednetMx[0].if_hard_around);
                                                cmd.Parameters.AddWithValue("@hard_around_springid", _bednetMx[0].hard_around_springid);
                                                cmd.Parameters.AddWithValue("@hard_around_row", _bednetMx[0].hard_around_row);
                                                cmd.Parameters.AddWithValue("@if_15strip", _bednetMx[0].if_15strip);
                                                using (var reader = cmd.ExecuteReader())
                                                {
                                                    if (reader.Read())
                                                    {
                                                        oBednet = new u_bednet() {
                                                            bednetid = Convert.ToInt32(reader["bednetid"]),
                                                            typename = Convert.ToString(reader["typename"]),
                                                            bednetcode = Convert.ToString(reader["bednetcode"]),
                                                            mattress_width = Convert.ToInt32(reader["mattress_width"]),
                                                            mattress_length = Convert.ToInt32(reader["mattress_length"]),
                                                            mattress_height = Convert.ToInt32(reader["mattress_height"]),
                                                            nottax_factory_cost = Convert.ToDecimal(reader["nottax_factory_cost"])
                                                        };
                                                    }
                                                }
                                            }

                                            // 匹配失败，自动新建
                                            if (oBednet.bednetid == null)
                                            {
                                                oBednet = _bednet;
                                                _bednetMx[0].spring_qty_width = _spring_qty_width;
                                                _bednetMx[0].spring_qty_length = _spring_qty_length;
                                                oBednet.fork_qty = _bednet_fork_qty;
                                                oBednet.bednetid = 0;

                                                // 袋装网，多个分区时，重新分配弹簧
                                                helperBednet.GetSpringListQty(oBednet, _bednetMx[0], ref _bednetSpring);

                                                helperBednet.SaveBedNet(oBednet, _bednetMx, _bednetSpring);
                                            }

                                            var _mtrlname = oBednet.typename +
                                                            " " +
                                                            oBednet.bednetcode +
                                                            " " +
                                                            oBednet.mattress_width +
                                                            "*" +
                                                            oBednet.mattress_length +
                                                            "*" +
                                                            oBednet.mattress_height;

                                            item.mtrlid = oBednet.bednetid;
                                            item.mtrlname = _mtrlname;
                                            item.price = oBednet.nottax_factory_cost;
                                            item.qty = 1;

                                        }
                                        #endregion

                                        #region 垫层改动逻辑
                                        if (item.formulatype == 1 && item.mtrlid > 0 )
                                        {
                                            // 规格长/宽，按比例缩放
                                            if (item.mattress_width > 0)
                                            {
                                                item.mattress_width = (int)Math.Floor((decimal)item.mattress_width * (Convert.ToDecimal(submx["mattress_width"]) / (decimal)request.mattress.mattress_width));
                                            }
                                            if (item.mattress_length > 0)
                                            {
                                                item.mattress_length = (int)Math.Floor((decimal)item.mattress_length * (Convert.ToDecimal(submx["mattress_length"]) / (decimal)request.mattress.mattress_length));
                                            }

                                            // 副规格-垫层物料替换
                                            if (item.if_subspecs == 1)
                                            {
                                                ifSubspecsIndex++;
                                                item.mtrlid = Convert.ToInt32(submx["cushions_subspecs_" + ifSubspecsIndex]);
                                            }
                                        }
                                        #endregion

                                        _mattressMx.Add(item);
                                    }
                                }

                                toSaveMattress(cmd, _mattress, _mattressMx, request.extraProcesses, request.extraCosts, tokendata);
                            }
                        }

                        cmd.Transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        cmd.Transaction.Rollback();
                        rslt.ErrMsg = e.ToString();
                        Trace.Write(e);
                    }



                }
            }
        }

        public List<string> toSaveMattress(SqlCommand cmd, u_mattress mattress, List<u_mattress_mx_mtrl> mattressMx, List<u_mattress_mx_extra> extraProcesses, List<u_mattress_mx_extra> extraCosts, TokenData tokendata)
        {
            var helper = HelperBase.GetHelper<MattressHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });

            List<string> message = new List<string>();

            helper.MattressCalculateCost(mattress, mattressMx, extraProcesses, extraCosts);

            var mxmessageList = mattressMx.Where(item => !string.IsNullOrEmpty(item.message)).ToList();
            if (mxmessageList.Any())
            {
                foreach (var mx in mxmessageList)
                {
                    message.Add(mx.message);
                }
            }

            try
            {
                helper.SaveMattress(mattress, mattressMx, extraProcesses, extraCosts);

                if (mattress.copy_id != null && mattress.copy_id > 0)
                {
                    helper.CopyMattressInterface(mattress.copy_id.Value, mattress.mattressid);
                }

            }
            catch (Exception e)
            {
                throw new LJCommonException(e.Message);
            }

            return message;
        }
    }
}
