using System;
using System.Collections.Generic;
using System.Data.SqlClient;
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 GetMattressImportDW2Excutor : ExcutorBase<GetMattressImportDW2Request, GetMattressImportDW2Response>
    {
        protected override void ExcuteInternal(GetMattressImportDW2Request request, object state, GetMattressImportDW2Response rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }

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

                // 初始化属性
                //foreach (var mx in request.mattressMx)
                //{
                //    AutoInit.AutoInitS(cmd, mx);
                //}

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

                    if (request.mattresstypeid == 0)
                    {
                        if (request.mattressid == 0)
                        {
                            rslt.ErrMsg = "床垫类别不能为0";
                            return;
                        }
                        else
                        {
                            // 床垫报价修改时，获取相关数据

                            var matterss = new u_mattress() { mattressid = request.mattressid };
                            DbSqlHelper.SelectOne(cmd, matterss, "mattresstypeid");

                            var mattersstype = new u_mattress_type() { mattresstypeid = matterss.mattresstypeid };
                            DbSqlHelper.SelectOne(cmd, mattersstype, "biandaiqty, if_top_side, if_button_sdie, if_big_side, if_small_side, if_v_side, if_in_cloth_cover, if_out_cloth_cover, if_small_side2, if_small_side3, if_v_side2, if_v_side3, dianceng_sort, dianceng_area");
                           
                            rslt.diancengarea = new List<replacement>();
                            if (!string.IsNullOrEmpty(mattersstype.dianceng_area))
                            {
                                rslt.diancengarea = wf_add_dianceng_area_bytype(cmd, mattersstype.dianceng_area);
                            }

                            var extraEnum = new List<u_mattress_extra>();
                            var extraTypeEnum = new List<u_mattress_extra_type>();
                            getExtraType(cmd, ref extraTypeEnum, ref extraEnum);
                            rslt.extraEnum = extraEnum;
                            rslt.extraTypeEnum = extraTypeEnum;
                        }
                    }
                    else
                    {
                        var mattersstype = new u_mattress_type() { mattresstypeid = request.mattresstypeid };
                        DbSqlHelper.SelectOne(cmd, mattersstype, "biandaiqty, if_top_side, if_button_sdie, if_big_side, if_small_side, if_v_side, if_in_cloth_cover, if_out_cloth_cover, if_small_side2, if_small_side3, if_v_side2, if_v_side3, dianceng_sort, dianceng_area");
                        rslt.biandai_qty = mattersstype.biandaiqty;

                        AutoInit.AutoInitS(cmd, mattersstype);

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

                        var selectStr = @"
                                SELECT formulaid
	                                ,formulakind
	                                ,formulatype
	                                ,sortcode
	                                ,if_mtrl
	                                ,formula
	                                ,usetype
	                                ,if_packtype0
	                                ,if_packtype1
	                                ,if_packtype2
	                                ,default_mtrlid
	                                ,createtime
	                                ,createby
	                                ,useformula
	                                ,gydscrp
	                                ,mtrltype
                                FROM u_mattress_formula";
                        var outFields = "formulaid, formulakind, formulatype, sortcode, if_mtrl, formula, usetype, if_packtype0, if_packtype1, if_packtype2, default_mtrlid, createtime, createby, useformula, gydscrp, mtrltype";
                        var whereList = new List<string>();
                        whereList.Add("u_mattress_formula.formulatype IN (0, 1, 2, 3, 99, 104)");
                        whereList.Add("u_mattress_formula.usetype = @usetype");
                        var param = new Dictionary<string, object>();


                        //   导入 0-通用类型  的公式
                        param.Add("@usetype", 0);
                        var mattressFormulaList0 = new List<u_mattress_formula>();
                        DbSqlHelper.SelectJoin(cmd, selectStr, ListEx.GetWhereStr(whereList), param, "formulatype, sortcode", outFields, 0, 0, mattressFormulaList0);

                        var dw_2 = new List<u_mattress_mx_mtrl>();

                        foreach (var mx in mattressFormulaList0)
                        {
                            if (new[] { 11, 12, 32, 33, 13, 14, 29, 999, 1201 }.Contains(mx.formulakind.Value)) continue;

                            var newDw2 = new u_mattress_mx_mtrl();
                            AutoInit.AutoInitS(newDw2);
                            if (mx.if_mtrl > 1)
                            {
                                newDw2.addmx = "+";
                                newDw2.delmx = "-";
                            }
                            newDw2.formulatype = mx.formulatype;
                            newDw2.if_mtrl = mx.if_mtrl;
                            newDw2.formulaid = mx.formulaid;
                            newDw2.sortcode = mx.sortcode;
                            newDw2.formulakind = mx.formulakind;
                            newDw2.formula = mx.formula;
                            newDw2.useformula = mx.useformula;
                            newDw2.gydscrp = mx.gydscrp;

                            dw_2.Add(newDw2);
                        }

                        //   导入 1-按床垫类别  的公式
                        var mattressFormulaList1 = new List<u_mattress_formula>();
                        param.Clear();
                        param.Add("@usetype", 1);
                        DbSqlHelper.SelectJoin(cmd, selectStr, ListEx.GetWhereStr(whereList), param, "formulatype, sortcode", outFields, 0, 0, mattressFormulaList1);

                        foreach (var mx in mattressFormulaList1)
                        {
                            var ls_chastr = "";

                            if (request.ifbcptype == 1)
                            {
                                if (new[] { 0, 40, 50, 60, 70, 80, 1, 41, 51, 61, 71, 81, 2, 42, 52, 62, 72, 82, 3, 43, 53, 63, 73, 83, 4, 44, 54, 64, 74, 84 }.Contains(mx.formulakind.Value))
                                {
                                    continue;
                                }
                            }

                            if (new[] { 0, 40, 50, 60, 70, 80 }.Contains(mx.formulakind.Value))
                            {
                                ls_chastr = "面裥绵";
                                if (mattersstype.if_top_side == 0) continue;
                            }

                            if (new[] { 1, 41, 51, 61, 71, 81 }.Contains(mx.formulakind.Value))
                            {
                                ls_chastr = "底裥绵";
                                if (mattersstype.if_button_sdie == 0) continue;
                            }

                            if (new[] { 2, 42, 52, 62, 72, 82 }.Contains(mx.formulakind.Value))
                            {
                                ls_chastr = "普通大侧";
                                if (mattersstype.if_big_side == 0) continue;
                            }

                            if (new[] { 3, 43, 53, 63, 73, 83 }.Contains(mx.formulakind.Value))
                            {
                                ls_chastr = "小侧1";
                                if (mattersstype.if_small_side == 0) continue;
                            }

                            if (new[] { 4, 44, 54, 64, 74, 84 }.Contains(mx.formulakind.Value))
                            {
                                ls_chastr = "V侧1";
                                if (mattersstype.if_v_side == 0) continue;
                            }

                            if (new[] { 101, 102, 103, 104, 105, 106 }.Contains(mx.formulakind.Value))
                            {
                                if (mattersstype.if_in_cloth_cover == 0) continue;
                            }

                            if (new[] { 111, 112, 113, 114, 115, 116 }.Contains(mx.formulakind.Value))
                            {
                                if (mattersstype.if_out_cloth_cover == 0) continue;
                            }

                            var newDw2 = new u_mattress_mx_mtrl();
                            AutoInit.AutoInitS(newDw2);
                            if (mx.if_mtrl > 1)
                            {
                                newDw2.addmx = "+";
                                newDw2.delmx = "-";
                            }
                            newDw2.formulatype = mx.formulatype;
                            newDw2.if_mtrl = mx.if_mtrl;
                            newDw2.formulaid = mx.formulaid;
                            newDw2.sortcode = mx.sortcode;
                            newDw2.formulakind = mx.formulakind;
                            newDw2.formula = mx.formula;
                            newDw2.chastr = ls_chastr;
                            newDw2.useformula = mx.useformula;
                            newDw2.gydscrp = mx.gydscrp;

                            dw_2.Add(newDw2);
                        }

                        //   导入 2-按包装方式  的公式
                        helper.wf_import_bz(request.packtype, ref dw_2);


                        //加多一个 小侧2
                        if (mattersstype.if_small_side2 == 1 && request.ifbcptype == 0)
                        {
                            wf_add_side(cmd, new[] { 3, 83, 43, 53, 63, 73 }, "小侧2", ref dw_2);
                        }
                        //加多一个 小侧3
                        if (mattersstype.if_small_side3 == 1 && request.ifbcptype == 0)
                        {
                            wf_add_side(cmd, new[] { 3, 83, 43, 53, 63, 73 }, "小侧3", ref dw_2);
                        }
                        //加多一个 V侧2
                        if (mattersstype.if_v_side2 == 1 && request.ifbcptype == 0)
                        {
                            wf_add_side(cmd, new[] { 4, 84, 44, 54, 64, 74 }, "V侧2", ref dw_2);
                        }
                        //加多一个 V侧3
                        if (mattersstype.if_v_side3 == 1 && request.ifbcptype == 0)
                        {
                            wf_add_side(cmd, new[] { 4, 84, 44, 54, 64, 74 }, "V侧3", ref dw_2);
                        }

                        // 在 床垫类型 定义里面   按垫层默认配置  自动带出 垫层配置  和  垫层可选项
                        if (!string.IsNullOrEmpty(mattersstype.dianceng_sort))
                        {
                            wf_add_dianceng_bytype(cmd, mattersstype.dianceng_sort, ref dw_2);
                        }

                        rslt.diancengarea = new List<replacement>();
                        if (!string.IsNullOrEmpty(mattersstype.dianceng_area))
                        {
                            rslt.diancengarea = wf_add_dianceng_area_bytype(cmd, mattersstype.dianceng_area);
                        }

                        // 明细排序
                        helper.wf_sort_mx(ref dw_2);

                        if (request.mattressid == 0)
                        {
                            helper.wf_default_mtrlid(request.pricelistid, ref dw_2);
                            helper.wf_default_mtrlid_notbz(request.pricelistid, ref dw_2);
                        }

                        rslt.mattressMx = dw_2;

                        #region 导入其他额外费用和特殊工艺
                        var extraEnum = new List<u_mattress_extra>();
                        var extraTypeEnum = new List<u_mattress_extra_type>();
                        getExtraType(cmd, ref extraTypeEnum, ref extraEnum);
                        rslt.extraEnum = extraEnum.Where(item => item.ifinit.Value == 0).ToList();
                        rslt.extraTypeEnum = extraTypeEnum;

                        rslt.extraProcessesMx = new List<u_mattress_mx_extra>();
                        rslt.extraCostsMx = new List<u_mattress_mx_extra>();
                        var processesMx = extraEnum.Where(item => item.ifinit == 1 && item.typeid == 1).ToArray();
                        var costsMx = extraEnum.Where(item => item.ifinit == 1 && item.typeid == 2).ToArray();
                        foreach (var mx in processesMx)
                        {
                            u_mattress_mx_extra mxItem = new u_mattress_mx_extra
                            {
                                mattressid = 0,
                                mattressmxid = 0,
                                extraid = mx.extraid,
                                extraname = mx.extramxname,
                                dscrp = mx.dscrp,
                                price = mx.price,
                                qty = mx.qty,
                                typeid = mx.typeid,
                                inputtype = mx.inputtype
                            };
                            rslt.extraProcessesMx.Add(mxItem);
                        }
                        foreach (var mx in costsMx)
                        {
                            u_mattress_mx_extra mxItem = new u_mattress_mx_extra
                            {
                                mattressid = 0,
                                mattressmxid = 0,
                                extraid = mx.extraid,
                                extraname = mx.extramxname,
                                dscrp = mx.dscrp,
                                price = mx.price,
                                qty = mx.qty,
                                typeid = mx.typeid,
                                inputtype = mx.inputtype
                            };
                            rslt.extraCostsMx.Add(mxItem);
                        }
                        #endregion
                    }

                }
            }
        }
        private void getExtraType(SqlCommand cmd, ref List<u_mattress_extra_type> extraTypeEnum, ref List<u_mattress_extra> extraEnum)
        {
            #region 查询额外费用定义项目
            var selectStr = @"
                                SELECT
			                        u_mattress_extra.extraid
			                        ,extramxid
			                        ,extramxname
			                        ,u_mattress_extra_type.typeid
			                        ,price
			                        ,dscrp
                                    ,qty
			                        ,u_mattress_extra.inuse
			                        ,u_mattress_extra.inputtype
			                        ,ifinit
		                        From u_mattress_extra
		                        inner join u_mattress_extra_type on u_mattress_extra_type.extraid = u_mattress_extra.extraid 
                                    AND u_mattress_extra_type.inuse = 0
		                        ";
            var outFields = "extraid,extramxid,extramxname,typeid,price,dscrp,qty,inuse,inputtype,ifinit";
            var whereList = new List<string>();
            whereList.Add("u_mattress_extra.inuse = 0");
            var param = new Dictionary<string, object>();

            var mattressExtra = new List<u_mattress_extra>();
            DbSqlHelper.SelectJoin(cmd, selectStr, ListEx.GetWhereStr(whereList), param, "typeid, extraid", outFields, 0, 0, mattressExtra);
            extraEnum = mattressExtra;
            #endregion

            #region 查询额外费用定义类型
            selectStr = @"
                                SELECT
			                        extraid
                                    ,typename
                                    ,typeid
                                    ,inuse
                                    ,inputtype
                                    ,createby
                                    ,createtime
		                        From u_mattress_extra_type
		                        ";
            outFields = "extraid, typename, typeid, inuse, createby, createtime, inputtype";
            whereList = new List<string>();
            whereList.Add("u_mattress_extra_type.inuse = 0");
            param = new Dictionary<string, object>();

            var mattressExtraType = new List<u_mattress_extra_type>();
            DbSqlHelper.SelectJoin(cmd, selectStr, ListEx.GetWhereStr(whereList), param, "typeid, extraid", outFields, 0, 0, mattressExtraType);
            extraTypeEnum = mattressExtraType;
            #endregion

        }
        private void wf_add_side(SqlCommand cmd, int[] formulakindList, string arg_name, ref List<u_mattress_mx_mtrl> dw_2)
        {
            foreach(int ll_formulakind in formulakindList)
            {
                cmd.CommandText = @"SELECT TOP 1
	                                    formulatype,
	                                    formulaid,
	                                    sortcode,
	                                    formula,
	                                    if_mtrl,
	                                    useformula,
	                                    gydscrp
                                    FROM u_mattress_formula
                                    WHERE formulakind = @formulakind
	                                    AND u_mattress_formula.formulatype in (0,1,2,3)";
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@formulakind", ll_formulakind);
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        var newDw2 = new u_mattress_mx_mtrl();
                        AutoInit.AutoInitS(newDw2);
                        if (Convert.ToInt32(reader["if_mtrl"]) > 1)
                        {
                            newDw2.addmx = "+";
                            newDw2.delmx = "-";
                        }
                        newDw2.formulatype = Convert.ToInt32(reader["formulatype"]);
                        newDw2.if_mtrl = Convert.ToInt32(reader["if_mtrl"]);
                        newDw2.formulaid = Convert.ToInt32(reader["formulaid"]);
                        newDw2.sortcode = arg_name;
                        newDw2.formulakind = ll_formulakind;
                        newDw2.formula = Convert.ToString(reader["formula"]);
                        newDw2.chastr = arg_name;
                        newDw2.useformula = Convert.ToString(reader["useformula"]);
                        newDw2.gydscrp = Convert.ToString(reader["gydscrp"]);

                        dw_2.Add(newDw2);
                    }
                }
            }

        }
        private void wf_add_dianceng_bytype(SqlCommand cmd, string dianceng_sort, ref List<u_mattress_mx_mtrl> dw_2)
        {
            var arg_dianceng_sort = dianceng_sort.Replace("，", " , ");
            arg_dianceng_sort = arg_dianceng_sort.Replace("~r~n", "");
            arg_dianceng_sort = arg_dianceng_sort.Replace("~r", "");
            arg_dianceng_sort = arg_dianceng_sort.Replace("~n", "");

            //var ls_pzsplitstr_arr = f_pb_split(arg_dianceng_sort, "/");
            var ls_pzsplitstr_arr = arg_dianceng_sort.Split('/');
            string arg_left_str, arg_right_str;
            int ll_formulakind;
            int index = 0;

            foreach (var ls_pzsplitstr in ls_pzsplitstr_arr)
            {
                index++;
                arg_left_str = "";
                arg_right_str = "";

                wf_get_str(ls_pzsplitstr, ref arg_left_str, ref arg_right_str);

                switch(arg_left_str)
                {
                    case "垫层":
                        ll_formulakind = 32;
                        break;
                    case "床网":
                        ll_formulakind = 999;
                        break;
                    case "顶布":
                        ll_formulakind = 12;
                        break;
                    case "毡类":
                        ll_formulakind = 13;
                        break;
                    case "打底无纺布":
                        ll_formulakind = 14;
                        break;
                    case "网面布料":
                        ll_formulakind = 29;
                        break;
                    default:
                        ll_formulakind = -1;
                        break;
                }

                if (ll_formulakind == -1) continue;

                cmd.CommandText = @"SELECT TOP 1
	                                    formulatype,
	                                    formulaid,
	                                    sortcode,
	                                    formula,
	                                    if_mtrl,
	                                    useformula,
	                                    gydscrp
                                    FROM u_mattress_formula
                                    WHERE formulakind = @formulakind
	                                    AND u_mattress_formula.formulatype in (0,1,2,3)";
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@formulakind", ll_formulakind);
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        var newDw2 = new u_mattress_mx_mtrl();
                        AutoInit.AutoInitS(newDw2);
                        if (Convert.ToInt32(reader["if_mtrl"]) > 1)
                        {
                            newDw2.addmx = "+";
                            newDw2.delmx = "-";
                        }
                        newDw2.formulatype = Convert.ToInt32(reader["formulatype"]);
                        newDw2.if_mtrl = 2;
                        newDw2.formulaid = Convert.ToInt32(reader["formulaid"]);
                        newDw2.sortcode = Convert.ToString(reader["sortcode"]);
                        newDw2.formulakind = ll_formulakind;
                        newDw2.formula = Convert.ToString(reader["formula"]);
                        newDw2.chastr = wf_set_area_text(arg_right_str);
                        newDw2.qty = 1;
                        newDw2.xu = index;
                        newDw2.useformula = Convert.ToString(reader["useformula"]);
                        newDw2.gydscrp = Convert.ToString(reader["gydscrp"]);

                        dw_2.Add(newDw2);
                    }
                }

            }
        }
        private void wf_get_str(string arg_source, ref string arg_left_str, ref string arg_right_str)
        {
            if (string.IsNullOrEmpty(arg_source)) return;

            int commaPosition = arg_source.IndexOf(',');

            if (commaPosition > 0)
            {
                arg_left_str = arg_source.Substring(0, commaPosition).Trim();
                arg_right_str = arg_source.Substring(commaPosition + 1).Trim();
            }
            else
            {
                arg_left_str = arg_source.Trim();
                arg_right_str = "";
            }
        }

        private string wf_set_area_text(string arg_str)
        {
            string ls_rtn = "";

            // V侧1
            // V侧2
            // V侧3
            // 小侧1
            // 小侧2
            // 小侧3
            // 大侧

            if (arg_str.IndexOf("大侧") >= 0)
            {
                ls_rtn = "大侧";
            }
            else if (arg_str.IndexOf("小侧1") >= 0)
            {
                ls_rtn = "小侧1";
            }
            else if (arg_str.IndexOf("小侧2") >= 0)
            {
                ls_rtn = "小侧2";
            }
            else if (arg_str.IndexOf("小侧3") >= 0)
            {
                ls_rtn = "小侧3";
            }
            else if (arg_str.IndexOf("V侧1") >= 0)
            {
                ls_rtn = "V侧1";
            }
            else if (arg_str.IndexOf("V侧2") >= 0)
            {
                ls_rtn = "V侧2";
            }
            else if (arg_str.IndexOf("V侧3") >= 0)
            {
                ls_rtn = "V侧3";
            }
            else
            {
                ls_rtn = "";
            }

            return ls_rtn;
        }
        private List<replacement> wf_add_dianceng_area_bytype(SqlCommand cmd, string dianceng_area)
        {
            string ls_dianceng_area = dianceng_area;
            var diancengarea = new List<replacement>();

            // 替换中文逗号和其他特殊字符
            ls_dianceng_area = ls_dianceng_area.Replace('，', ',');
            ls_dianceng_area = ls_dianceng_area.Replace("\r\n", "");
            ls_dianceng_area = ls_dianceng_area.Replace("\r", "");
            ls_dianceng_area = ls_dianceng_area.Replace("\n", "");

            // 分割字符串
            string[] ls_pzsplitstr_arr = ls_dianceng_area.Split(',');

            for (int ll_i = 0; ll_i < ls_pzsplitstr_arr.Length; ll_i++)
            {
                string trimmedStr = ls_pzsplitstr_arr[ll_i].Trim();
                if (string.IsNullOrEmpty(trimmedStr)) continue;

                var child = new replacement()
                {
                    label = wf_set_area_text(trimmedStr.Trim()),
                    value = wf_set_area_text(trimmedStr.Trim())
                };
                diancengarea.Add(child);
            }
            return diancengarea;
        }
    }
}
