using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
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;
using LJLib.SQLEX;
using NPOI.POIFS.Properties;
using NPOI.SS.Formula.Functions;

namespace JLHHJSvr.Excutor
{
    internal sealed class CoverMattressInterfaceExcutor : ExcutorBase<CoverMattressInterfaceRequest, CoverMattressInterfaceResponse>
    {
        protected override void ExcuteInternal(CoverMattressInterfaceRequest request, object state, CoverMattressInterfaceResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (request.list == null)
            {
                rslt.ErrMsg = "提交缺少列表参数,请检查!";
                return;
            }
            if (!request.list.Any())
            {
                rslt.ErrMsg = "至少提交一条需要覆盖的记录";
                return;
            }

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

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

                var mainDict = new Dictionary<int, List<u_mattress_interface>> ();

                bool isUpdateMain = false;
                foreach(var mattress in request.list)
                {
                    DbSqlHelper.SelectOne(cmd, mattress, "mattress_width,mattress_length,mattress_height,mattressname,erp_mtrlmode,erp_mtrlname,erp_mtrltypeid,erp_configcodetype,erp_mtrlunit,parentid");
                    
                    if (!mainDict.ContainsKey(mattress.parentid.Value))
                    {
                        // 获取主规格床垫的配置
                        mainDict.Add(mattress.parentid.Value, interfaceHelper.GetMattressInterfaceList(mattress.parentid.Value, 0));
                    }
                }

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var mattress in request.list)
                        {
                            isUpdateMain = false;

                            if (string.IsNullOrEmpty(mattress.erp_mtrlmode))
                            {
                                mattress.erp_mtrlmode = mattress.mattress_width + "*" + mattress.mattress_length + "*" + mattress.mattress_height;
                                isUpdateMain = true;
                            }

                            if (string.IsNullOrEmpty(mattress.erp_mtrlname))
                            {
                                mattress.erp_mtrlname = mattress.mattressname;
                                isUpdateMain = true;
                            }

                            if (mattress.erp_configcodetype <= 0)
                            {
                                cmd.CommandText = @"SELECT TOP 1 u_configure_type.contfigtypeid
	                                    ,u_configure_type.contfigtypename
	                                    ,u_configure_type.contfigtype
	                                    ,u_configure_type.usechflag
	                                    ,u_configure_type.flag
	                                    ,u_configure_type.auditemp
	                                    ,u_configure_type.auditdate
                                    FROM u_configure_type";
                                cmd.Parameters.Clear();
                                cmd.Parameters.AddWithValue("@empid", tokendata.empid);
                                cmd.Parameters.AddWithValue("@dwname", "dw_mattress_interface_yw_edit");
                                cmd.Parameters.AddWithValue("@itemname", "erp_configcodetype");
                                using (var readerItem = cmd.ExecuteReader())
                                {
                                    if (readerItem.Read())
                                    {
                                        mattress.erp_configcodetype = Convert.ToInt32(readerItem["contfigtypeid"]);
                                    }
                                }
                                isUpdateMain = true;
                            }

                            if (mattress.erp_mtrltypeid <= 0)
                            {
                                cmd.CommandText = @"SELECT itemvalue FROM sys_user_filestring WHERE dwname = @dwname AND itemname = @itemname AND empid = @empid";
                                cmd.Parameters.Clear();
                                cmd.Parameters.AddWithValue("@empid", tokendata.empid);
                                cmd.Parameters.AddWithValue("@dwname", "dw_mattress_interface_yw_edit");
                                cmd.Parameters.AddWithValue("@itemname", "mtrltypeid");
                                using (var readerItem = cmd.ExecuteReader())
                                {
                                    if (readerItem.Read())
                                    {
                                        mattress.erp_mtrltypeid = Convert.ToInt32(readerItem["itemvalue"]);
                                    }
                                }
                                isUpdateMain = true;
                            }

                            if (mattress.erp_mtrlunit == "")
                            {
                                mattress.erp_mtrlunit = "张";
                                isUpdateMain = true;
                            }

                            if(isUpdateMain)
                            {
                                DbSqlHelper.Update(cmd, mattress, "erp_mtrlmode,erp_mtrlname,erp_mtrltypeid,erp_configcodetype,erp_mtrlunit");
                            }

                            var copy_list = new List<u_mattress_interface>();
                            if (mainDict.TryGetValue(mattress.parentid.Value, out var parentlist))
                            {
                                bool isExist = DbSqlHelper.SelectCount(cmd, "u_mattress_interface", "mattressid = @mattressid", new Dictionary<string, object>() { { "@mattressid", mattress.mattressid } }) > 0;
                                
                                // 获取副规格床垫的配置
                                copy_list = interfaceHelper.GetMattressInterfaceList(mattress.mattressid, mattress.erp_configcodetype);

                                var copyDict = parentlist.Where(mx2 => mx2.erp_pzid > 0)
                                        .ToDictionary(mx2 => mx2.erp_pzid, mx2 => mx2);

                                foreach (var mx in copy_list)
                                {
                                    if (mx.bj_inputtype == null) mx.bj_inputtype = 0;

                                    if (mx.erp_pzid > 0 && copyDict.TryGetValue(mx.erp_pzid, out var mx2) && (mx.bj_inputtype == 1 || mx.bj_inputtype == 0))
                                    {
                                        mx.bj_namemx = mx2.bj_namemx;
                                        mx.bj_inputtype = mx2.bj_inputtype;
                                    }

                                    if(isExist)
                                    {
                                        DbSqlHelper.Update(cmd, mx, "bj_inputtype,bj_namemx");
                                    } else
                                    {
                                        mx.mattressid = mattress.mattressid;
                                        DbSqlHelper.Insert(cmd, mx, "mattressid,printid,itemname,bj_pzname,bj_namemx,actual_size,sb_craft,actual_size_sb,erp_pzid,bj_inputtype,ss_rate,ls_rate");
                                    }
                                }
                            }
                        }

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