using DirectService.Tools;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.LJException;
using JLHHJSvr.Tools;
using LJLib.DAL.SQL;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Linq;

namespace JLHHJSvr.Helper
{
    internal class InterfaceHelper : HelperBase
    {
        /// <summary>
        /// 床垫接口-保存
        /// </summary>
        /// <param name="mattress"></param>
        /// <param name="mxlist"></param>
        /// <param name="qdlist"></param>
        /// <exception cref="LJCommonException"></exception>
        public void SaveMattressInterface(u_mattress mattress, List<u_mattress_interface> mxlist, List<u_mattress_interface_qd> qdlist)
        {
            if (mattress.mattressid <= 0)
            {
                throw new LJCommonException("错误的床垫id");
            }

            //AutoSetMtrlName(mattress, mxlist);

            //if (string.IsNullOrEmpty(mattress.erp_mtrlcode))
            //{
            //    throw new LJCommonException("请输入物料名称!");
            //}

            //if (mattress.erp_mtrltypeid == null || mattress.erp_mtrltypeid <= 0)
            //{
            //    throw new LJCommonException("请选择物料类别!");
            //}

            //if (mattress.erp_configcodetype == null || mattress.erp_configcodetype <= 0)
            //{
            //    throw new LJCommonException("请选择配置类型!");
            //}

            DbSqlHelper.Update(cmd, mattress, "erp_mtrlid,erp_mtrltypeid,erp_mtrlcode,erp_mtrlname,erp_mtrlmode,erp_mtrltype,erp_mtrlunit,erp_mtrlengname,erp_configcodetype,old_mtrlname");

            // 保存接口数据
            var mattressHelper = GetHelper<MattressHelper>(cmd, new HelperBase.Context() { tokendata = context.tokendata });
            mattressHelper.SaveMattressInterface(mattress.mattressid, mxlist, qdlist);
        }

        public void AutoSetMtrlName(u_mattress mattress, List<u_mattress_interface> mxlist)
        {
            string mtrltypename = string.Empty, mtrltypecode = string.Empty;
            string mattresstypename = string.Empty, mattresstypecode = string.Empty;
            string packtypename = string.Empty, packtypecode = string.Empty;
            var materialCodes = new Dictionary<string, string>
            {
                { "两边单层", "21" },
                { "两边直出", "23" },
                { "三边加顶", "32" },
                { "三边直出", "33" },
                { "假三边", "34" },
                { "拉假边", "3C" },
                { "假三边加顶", "42" },
                { "上下假三边", "44" },
                { "四边双顶", "45" },
                { "四边顶上顶", "46" },
                { "四边假分体", "47" }
            };

            var mattressTypeCodes = new Dictionary<string, string>
            {
                { "袋装网", "P" },
                { "拉丝网", "C" },
                { "圆网", "B" }
            };

            var packTypeCodes = new Dictionary<string, string>
            {
                { "平压", "A" },
                { "卷包", "B" }
            };

            foreach (var mx in mxlist)
            {
                if (mx.bj_pzname.IndexOf("床垫类别") > -1)
                {
                    mtrltypename = mx.bj_namemx;
                    break;
                }
            }

            foreach (var mx in mxlist)
            {
                if (mx.bj_pzname.IndexOf("床网") > -1)
                {
                    mattresstypename = mx.bj_namemx;
                    break;
                }
            }

            foreach (var mx in mxlist)
            {
                if (mx.bj_pzname.IndexOf("包装方式") > -1)
                {
                    packtypename = mx.bj_namemx;
                    break;
                }
            }

            mtrltypecode = materialCodes.ContainsKey(mtrltypename) ? materialCodes[mtrltypename] : "99";
            mattresstypecode = mattressTypeCodes.ContainsKey(mtrltypename) ? mattressTypeCodes[mtrltypename] : "Z";
            packtypecode = packTypeCodes.ContainsKey(mtrltypename) ? packTypeCodes[mtrltypename] : "J";

            // 获取mxlist最后一项
            if (mattress.mattressid > 0)
            {
                mattress.erp_mtrlname = new StringBuilder().Append(mtrltypecode).Append(mattresstypecode).Append(packtypecode).ToString();
            }
        }

        public List<u_mattress_interface> GetMattressInterfaceList(int mattressid, int? configuretype)
        {
            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", mattressid } }, "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);

            if(interfaceList.Count <= 0)
            {
                interfaceList = RefreshMattressInterfaceList(mattressid, configuretype);
            } else
            {
                MattressInterfaceFindERPPz(mattressid, interfaceList, configuretype);
            }


            return interfaceList;
        }

        public List<u_mattress_interface_qd> GetMattressInterfaceQdList(int mattressid)
        {
            var qdList = 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.wrkgrpcode1
	                            ,u_mattress_interface_qd.wrkgrpcode2
	                            ,u_mattress_interface_qd.wrkgrpid2
	                            ,u_mattress_interface_qd.ss_rate 
	                            ,u_mattress_interface_qd.ls_rate 
	                            ,u_mattress_interface_qd.sh_rate 
	                            ,u_mattress_interface_qd.formulaid 
                            FROM u_mattress_interface_qd
                            LEFT JOIN u_mtrl_price ON u_mtrl_price.mtrlid = u_mattress_interface_qd.mtrlid";
            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";
            DbSqlHelper.SelectJoin(cmd, selectStr, "mattressid = @mattressid", new Dictionary<string, object>() { { "@mattressid", mattressid } }, "printid", outputFields, 0, 0, qdList);

            if (qdList.Count <= 0)
            {
                qdList = RefreshMattressInterfaceQdList(mattressid);
            }

            return qdList;
        }

        #region 导入配置方法
        /// <summary>
        /// 刷新带出配置
        /// </summary>
        /// <param name="mattressid"></param>
        /// <returns></returns>
        public List<u_mattress_interface> RefreshMattressInterfaceList(int mattressid, int? configcodetype = 0)
        {
            var interfaceList = new List<u_mattress_interface>();

            // 导入配置
            ImportMattressInterfaceList(mattressid, interfaceList);

            MattressInterfaceFindERPPz(mattressid, interfaceList, configcodetype);

            return interfaceList;
        }
        /// <summary>
        /// 导入产品配置
        /// </summary>
        /// <param name="mattressid"></param>
        /// <exception cref="LJCommonException"></exception>
        public void ImportMattressInterfaceList(int mattressid, List<u_mattress_interface> interfaceList)
        {
            if (mattressid <= 0)
            {
                throw new LJCommonException("床垫id有误");
            }

            var mattressHelper = GetHelper<MattressHelper>(cmd, new HelperBase.Context() { tokendata = context.tokendata });
            var mattress = mattressHelper.GetMattress(mattressid);

            var mattress_type = new u_mattress_type() { mattresstypeid = mattress.mattresstypeid };
            DbSqlHelper.SelectOne(cmd, mattress_type, "typename");

            var mxlist = mattressHelper.GetMattressMxMtrl(mattressid, new List<string>() { "u_mattress_formula.formulatype IN (0,1,2,3,99,104,103)" });

            var mxlist_103 = mattressHelper.GetMattressMxMtrl(mattressid, new List<string>() { "u_mattress_formula.formulatype = 103" });

            var mxlist_101 = mattressHelper.GetMattressMxMtrl(mattressid, new List<string>() { "u_mattress_formula.formulatype = 101" });

            // 高度
            interfaceList.Add(InserMattressInterfacePz("床垫", "高度", 2, new string[] { $"{mattress.mattress_height}" }));

            // 参考外观
            interfaceList.Add(InserMattressInterfacePz("床垫", "参考外观", 1, new string[] { "" }));

            // 尺寸
            mattress.erp_mtrlcode = $"{mattress.mattress_width}*{mattress.mattress_length}*{mattress.mattress_height}";
            interfaceList.Add(InserMattressInterfacePz("床垫", "尺寸", 2, new string[] { mattress.erp_mtrlcode }));

            // 床垫类别
            interfaceList.Add(InserMattressInterfacePz("床垫", "床垫类别", 2, new string[] { mattress_type.typename }));

            // 拆装类型
            var name_arr = new string[1];
            name_arr[0] = string.Empty;
            if (mattress.if_m_chai == 1) name_arr[0] = AppendToString(name_arr[0], "面拆");
            if (mattress.if_z_chai == 1) name_arr[0] = AppendToString(name_arr[0], "中拆");
            if (mattress.if_d_chai == 1) name_arr[0] = AppendToString(name_arr[0], "底拆");
            interfaceList.Add(InserMattressInterfacePz("床垫", "拆装类型", 1, name_arr));

            // 床垫分类
            name_arr[0] = string.Empty;
            if (mattress.if_haimian_type == 1) name_arr[0] = AppendToString(name_arr[0], "海绵床垫");
            else name_arr[0] = AppendToString(name_arr[0], "弹簧床垫");
            if (mattress.if_zhedie_type == 1) name_arr[0] = AppendToString(name_arr[0], "折叠床垫");
            interfaceList.Add(InserMattressInterfacePz("床垫", "床垫分类", 1, name_arr));

            // 外观布套做法
            name_arr[0] = string.Empty;
            if (mattress.if_m_wbutao_way == 1) name_arr[0] = AppendToString(name_arr[0], $"面层向大侧覆盖{mattress.s_m_cover_qty}CM、大侧向底层覆盖{mattress.z_m_cover_qty}CM、底层向大侧覆盖{mattress.x_m_cover_qty}CM");
            interfaceList.Add(InserMattressInterfacePz("床垫", "外观布套做法", 1, name_arr));

            // 边带
            name_arr[0] = string.Empty;
            interfaceList.Add(InserMattressInterfacePz("床垫", "边带", 0, name_arr));

            #region 面料类清单导入 AutoSetFormulaTypeZeroPz()需要优化
            AutoSetFormulaTypeZeroPz(mxlist, interfaceList);
            interfaceList.Add(InserMattressInterfacePz("车位说明", "车位说明", 1, name_arr));
            #endregion

            #region 垫层类清单导入
            AutoSetFormulaTypeOnePz(mxlist, interfaceList);
            #endregion

            #region 辅料类清单导入
            AutoSetFormulaTypeTwoPz(mxlist, interfaceList);
            #endregion

            #region 包装类清单导入
            AutoSetFormulaTypeThreePz(mattress, mxlist, interfaceList);
            #endregion

            #region 内布套类清单导入
            AutoSetFormulaType101Pz(mattress, mxlist_101, interfaceList);
            #endregion

            #region 自定义配置导入
            if(mattress.erp_configcodetype != null && mattress.erp_configcodetype > 0)
            {
                var erpHelper = HelperBase.GetHelper<ERPHelper>(null);

                var parameters = new JObject();
                parameters.Add("dsname", "web_configure_code_list");
                var queryparams = new JObject();
                queryparams.Add("arg_configcodetype", mattress.erp_configcodetype);
                queryparams.Add("arg_ifpack", 1);
                parameters.Add("queryparams", queryparams);

                var resultList = erpHelper.GetERPList<erp_configure_code>("CommonDynamicSelect", parameters);

                foreach(var result in resultList)
                {
                    var pzname = result.name;
                    interfaceList.Add(InserMattressInterfacePz("自定义", pzname, 1, new string[] { "" }));
                }
            }
            #endregion
        }
        public void MattressInterfaceFindERPPz(int mattressid, List<u_mattress_interface> interfaceList, int? configcodetype = 0)
        {
            var mattress = new u_mattress() { mattressid = mattressid };
            DbSqlHelper.SelectOne(cmd, mattress, "erp_configcodetype");

            if (configcodetype != 0)
            {
                mattress.erp_configcodetype = configcodetype;
            }

            MattressInterfaceFindERPPz(mattress, interfaceList);
        }
        public void MattressInterfaceFindERPPz(u_mattress mattress,List<u_mattress_interface> interfaceList)
        {
            var resultList = new List<erp_configure_code>();
            var typeList = new List<erp_configure_code>();
            foreach (var item in interfaceList)
            {
                typeList.Add(new erp_configure_code() { typeid = mattress.erp_configcodetype, name = item.bj_pzname });
            }

            var configure_Type = new u_configure_type() { contfigtypeid = mattress.erp_configcodetype };
            if (DbSqlHelper.SelectOne(cmd, configure_Type, "contfigtypeid") == 1)
            {
                var names = new List<string>();
                foreach (var item in typeList)
                {
                    if (!names.Contains(item.name))
                    {
                        names.Add(item.name);
                    }
                }

                // 查询核价系统的配置资料定义
                cmd.CommandText = @"SELECT u_configure_code.pzid
	                                    ,u_configure_code.pzcode
	                                    ,u_configure_code.name
	                                    ,u_configure_code.inputtype
                                    FROM u_configure_code
                                    WHERE u_configure_code.typeid = @configcodetype
	                                    AND u_configure_code.name IN " + ListEx.getString(names) ;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@configcodetype", mattress.erp_configcodetype);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var item = new erp_configure_code()
                        {
                            pzid = Convert.ToInt32(reader["pzid"]),
                            pzcode = Convert.ToString(reader["pzcode"]),
                            name = Convert.ToString(reader["name"]).Trim(),
                            inputtype = Convert.ToInt32(reader["inputtype"])
                        };
                        resultList.Add(item);
                    }
                }
            }
            else
            {
                // 查询L1部件选配
                var erpHelper = HelperBase.GetHelper<ERPHelper>(null);
                var parameters = new JObject();
                parameters.Add("typeList", JToken.FromObject(typeList));
                resultList = erpHelper.GetERPList<erp_configure_code>("GetL1ConfigureCode", parameters);
            }


            for (var i = 0; i < interfaceList.Count; i++)
            {
                interfaceList[i].printid = i + 1;

                foreach (var result in resultList) 
                {
                    if (interfaceList[i].bj_pzname == result.name)
                    {
                        if (result.pzid > 0)
                        {
                            interfaceList[i].erp_pzid = result.pzid;
                            interfaceList[i].erp_pzcode = result.pzcode;
                            interfaceList[i].erp_pzname = result.name;
                        }

                        if (interfaceList[i].bj_inputtype != 2) interfaceList[i].bj_inputtype = result.inputtype;
                    }
                }
            }
        }
        /// <summary>
        /// 初始化配置信息
        /// </summary>
        /// <param name="itemname"></param>
        /// <param name="bj_pzname"></param>
        /// <param name="inputtype"></param>
        /// <param name="names"></param>
        /// <returns></returns>
        public u_mattress_interface InserMattressInterfacePz(string itemname, string bj_pzname, byte inputtype, string[] names)
        {
            var mattress_interface = new u_mattress_interface()
            {
                itemname = itemname,
                bj_pzname = bj_pzname,
                bj_inputtype = inputtype,
                bj_namemx = names == null ? string.Empty : SetInterfacePzName(names)
            };

            return mattress_interface;
        }
        private string SetInterfacePzName(string[] names)
        {
            var result = string.Empty;

            foreach (var name in names)
            {
                if (string.IsNullOrEmpty(name)) continue;
                result = AppendToString(result, name);
            }

            return result;
        }
        private void AutoSetFormulaTypeZeroPz(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface> interfaceList)
        {
            var powerDict = new Dictionary<string, int[]>()
            {
                {"面裥绵",new int[] { 0, 40, 50, 60, 70, 80 } },
                {"底裥绵",new int[] { 1, 41, 51, 61, 71, 81 } },
                {"顶布裥棉1",new int[] { 0, 40, 50, 60, 70, 80 } },
                {"顶布裥棉2",new int[] { 0, 40, 50, 60, 70, 80 } },
                {"顶布裥棉3",new int[] { 0, 40, 50, 60, 70, 80 } },
                {"顶布裥棉4",new int[] { 0, 40, 50, 60, 70, 80 } },
                {"普通大侧",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"上下拼侧1",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"上下拼侧2",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"上下拼侧3",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"左右拼侧1",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"左右拼侧2",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"左右拼侧3",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"小侧1_EMPTY",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧1",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧1-上下拼侧1",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧1-上下拼侧2",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧1-上下拼侧3",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧2",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧3",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"V侧1_EMPTY",new int[] { 4, 44, 54, 64, 74, 84 } },
                {"V侧1",new int[] { 4, 44, 54, 64, 74, 84 } }
            };
            var chastrArrDict = new Dictionary<string, string[]>()
            {
                {"面裥绵",new string[] { "裥面", "面层裥棉", "面层裥棉图案", "面层裥面说明" } },
                {"底裥绵",new string[] { "裥底", "底层裥棉", "底层裥棉图案", "底层裥棉说明" } },
                {"顶布裥棉1",new string[] { "顶布裥棉", "", "顶布裥棉1图案", "顶布裥棉1说明" } },
                {"顶布裥棉2",new string[] { "顶布裥棉", "", "顶布裥棉2图案", "顶布裥棉2说明" } },
                {"顶布裥棉3",new string[] { "顶布裥棉", "", "顶布裥棉3图案", "顶布裥棉3说明" } },
                {"顶布裥棉4",new string[] { "顶布裥棉","", "顶布裥棉4图案", "顶布裥棉4说明" } },
                {"普通大侧",new string[] { "大侧", "大侧裥棉", "大侧裥棉图案" } },
                {"上下拼侧1",new string[] {"大侧", "大侧-上下拼侧1", "大侧-上下拼侧1", "大侧-上下拼侧1高度"} },
                {"上下拼侧2",new string[] { "大侧", "大侧-上下拼侧2", "大侧-上下拼侧2", "大侧-上下拼侧2高度" } },
                {"上下拼侧3",new string[] { "大侧", "大侧-上下拼侧3", "大侧-上下拼侧3", "大侧-上下拼侧3高度" } },
                {"左右拼侧1",new string[] { "大侧", "大侧-左右拼侧1", "大侧-左右拼侧1裥棉图案", "大侧-左右拼侧1长度" } },
                {"左右拼侧2",new string[] { "大侧", "大侧-左右拼侧2", "大侧-左右拼侧2裥棉图案", "大侧-左右拼侧2长度" } },
                {"左右拼侧3",new string[] { "大侧", "大侧-左右拼侧3", "大侧-左右拼侧3裥棉图案", "大侧-左右拼侧3长度", "大侧说明" } },
                {"小侧1_EMPTY",new string[] { "小侧", "小侧1裥棉", "小侧1裥棉图案" } },
                {"小侧1",new string[] { "小侧", "小侧1裥棉", "小侧1裥棉图案" } },
                {"小侧1-上下拼侧1",new string[] { "小侧", "小侧1-上下拼侧1裥棉", "小侧1-上下拼侧1裥棉图案" } },
                {"小侧1-上下拼侧2",new string[] { "小侧", "小侧1-上下拼侧2裥棉", "小侧1-上下拼侧2裥棉图案" } },
                {"小侧1-上下拼侧3",new string[] { "小侧", "小侧1-上下拼侧3裥棉", "小侧1-上下拼侧3裥棉图案" } },
                {"小侧2",new string[] { "小侧", "小侧2裥棉", "小侧2裥棉图案" } },
                {"小侧3",new string[] { "小侧", "小侧3裥棉", "小侧3裥棉图案", "小侧说明" } },
                {"V侧1_EMPTY",new string[] { "V侧", "V侧1裥棉", "V侧1裥棉图案" } },
                {"V侧1",new string[] { "V侧", "V侧1裥棉", "V侧1裥棉图案" } },
                {"V侧2",new string[] { "V侧", "V侧2裥棉", "V侧2裥棉图案" } },
                {"V侧3",new string[] { "V侧", "V侧3裥棉", "V侧3裥棉图案", "V侧说明" } }
            };
            var jianmianList = mxlist.Where(t => t.formulatype == 0).ToList();
            var dingbuList = mxlist.Where(t => t.formulatype == 103).ToList();

            #region wf_import_qingdan + wf_import_qingdan_1 面料部分
            foreach (var item in powerDict)
            {
                if(item.Key.Contains("顶布裥棉")) SetFormulaTypeZeroPz(dingbuList, interfaceList, item.Value, item.Key, chastrArrDict[item.Key]);
                else SetFormulaTypeZeroPz(jianmianList, interfaceList, item.Value, item.Key, chastrArrDict[item.Key]);
            }
            #endregion

            #region wf_import_qingdan_next 面料部分
            // 拉手
            var lashouList = jianmianList.Where(t => t.formulakind == 5).ToList();
            for (int i = 0; i < lashouList.Count; i++)
            {
                var mx = lashouList[i];
                if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", $"拉手{i + 1}做法", 1, new string[] { $"{mx.qty.Value.ToString("#,##0.0#")}只{mx.mtrlname}" }));
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", $"拉手{i + 1}刺绣", 0, new string[] { "" }));
                }
            }
            // 刺绣
            var cixiuList = jianmianList.Where(t => t.formulakind == 6).ToList();
            var ls_temp_cnt = 0;
            for (int i = 0; i < cixiuList.Count; i++)
            {
                var mx = cixiuList[i];
                if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                {
                    for (int k = 0; k < mx.qty; k++)
                    {
                        ls_temp_cnt++;
                        interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", $"侧刺绣{ls_temp_cnt}做法", 1, new string[] { "" }));
                        interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", $"侧刺绣{ls_temp_cnt}位置", 0, new string[] { "" }));
                    }
                }
            }
            // 大侧压压布
            var dcyybList = jianmianList.Where(t => t.formulakind == 7).ToList();
            for (int i = 0; i < dcyybList.Count; i++)
            {
                var mx = dcyybList[i];
                if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", $"大侧压压布{i + 1}", 1, new string[] { $"{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
            }
            // 大侧压边带
            var dcybdList = jianmianList.Where(t => t.formulakind == 8).ToList();
            for (int i = 0; i < dcybdList.Count; i++)
            {
                var mx = dcybdList[i];
                if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", $"大侧压边带{i + 1}", 1, new string[] { $"{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
            }
            // 大侧压织带
            var dcyzdList = jianmianList.Where(t => t.formulakind == 9).ToList();
            for (int i = 0; i < dcyzdList.Count; i++)
            {
                var mx = dcyzdList[i];
                if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", $"大侧压织带{i + 1}", 1, new string[] { $"{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
            }
            // 大侧压上下压线
            var dcysxyxList = jianmianList.Where(t => t.formulakind == 10).ToList();
            for (int i = 0; i < dcysxyxList.Count; i++)
            {
                var mx = dcysxyxList[i];
                if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", $"大侧压上下压线{i + 1}", 1, new string[] { $"{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
            }
            // 车花边
            var chbList = jianmianList.Where(t => t.formulakind == 205).ToList();
            for (int i = 0; i < chbList.Count; i++)
            {
                var mx = chbList[i];
                if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", "车花边", 1, new string[] { $"{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
            }
            // 防火线
            var fhxList = jianmianList.Where(t => t.formulakind == 30).ToList();
            for (int i = 0; i < fhxList.Count; i++)
            {
                var mx = fhxList[i];
                if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", "防火线", 1, new string[] { mx.mtrlname }));
                }
            }
            // 拉链
            var llList = jianmianList.Where(t => t.formulakind == 202 && string.IsNullOrEmpty(t.chastr) && t.mtrlid > 0).ToList();
            for (int i = 0; i < llList.Count; i++)
            {
                var mx = llList[i];
                if (llList.Count > 1)
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", "拉链" + (i+1), 1, new string[] { $"{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
                else
                {
                    interfaceList.Add(InserMattressInterfacePz("拉手刺绣及其他工艺", "拉链", 1, new string[] { $"{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
            }
            #endregion
        }
        private void SetFormulaTypeZeroPz(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface> interfaceList, int[] powerArr, string key, string[] chastrArr)
        {
            var mianList1 = new HashSet<string> { "面裥绵", "底裥绵" };
            var mianList2 = new string[4] { "顶布裥棉1", "顶布裥棉2", "顶布裥棉3", "顶布裥棉4" };
            var mianList3 = new HashSet<string> { "普通大侧", "上下拼侧1", "上下拼侧2", "上下拼侧3", "左右拼侧1", "左右拼侧2", "左右拼侧3", "小侧1", "小侧2", "小侧3" };
            //var mianList4 = new HashSet<string> { "小侧1", "小侧2", "小侧3" };

            var name_arr = new string[5];
            foreach (var mx in mxlist)
            {
                SetFormulaTypeZeroPzName(mx, key, powerArr, name_arr);
            }

            if (mianList2.Contains(key))
            {
                for (int i = 0; i < mianList2.Length; i++)
                {
                    DingBuLianMian.SetValue(name_arr[i], Array.IndexOf(mianList2, key),i );
                }
            }

            //if (mianList4.Contains(key))
            //{
            //    var _index = 0;
            //    Regex regex = new Regex(@"\d+");
            //    Match match = regex.Match(key);
            //    _index = Convert.ToInt32(match.Value) - 1;
            //    for (int i = 0; i < mianList4.Count; i++)
            //    {
            //        XiaoCePeizhi.SetValue(name_arr[i], i, _index);
            //    }
            //}

            var sb = new StringBuilder();
            foreach (var name2 in name_arr)
            {
                sb.Append(name2);
            }

            bool ifchastr3 = false;
            if (sb.Length > 0)
            {
                if (!string.IsNullOrEmpty(chastrArr[1])) interfaceList.Add(InserMattressInterfacePz(chastrArr[0], chastrArr[1], 2, name_arr));
                interfaceList.Add(InserMattressInterfacePz(chastrArr[0], chastrArr[2], 1, new string[] { "" }));
                if (chastrArr.Length > 3)
                {
                    if (chastrArr[3].Contains("说明")) ifchastr3 = true;
                    interfaceList.Add(InserMattressInterfacePz(chastrArr[0], chastrArr[3], 1, new string[] { "" }));
                }
            }

            foreach (var name in chastrArr)
            {
                if (string.IsNullOrEmpty(name)) continue;
                if (name.Contains("说明") && !ifchastr3)
                {
                    interfaceList.Add(InserMattressInterfacePz(chastrArr[0], name, 1, new string[] { "" }));
                }
            }

        }
        //private bool ifHasXiaoceMtrl()
        //{
        //    bool hasVal = false;
        //    for (int i = 0; i < XiaoCePeizhi.GetLength(0); i++)
        //    {
        //        for (int j = 0; j < XiaoCePeizhi.GetLength(1); j++)
        //        {
        //            if (!string.IsNullOrEmpty(XiaoCePeizhi[i, j]))
        //            {
        //                hasVal = true;
        //                break;
        //            }
        //        }
        //        if (hasVal)
        //        {
        //            break;
        //        }
        //    }
        //    return hasVal;
        //}

        private void SetFormulaTypeZeroPzName(u_mattress_mx_mtrl mx, string key, int[] powerArr, string[] name_arr)
        {
            if (key.Contains("_EMPTY")) key = "";
            if (mx.mtrlid > 0 && key.Equals(mx.chastr) && powerArr.Contains(mx.formulakind.Value))
            {
                if (mx.formulakind == 0 || mx.formulakind == 1 || mx.formulakind == 2 || mx.formulakind == 3 || mx.formulakind == 4)
                {
                    name_arr[0] = AppendToString(name_arr[0], SplitNameCount(mx.mtrlname, Convert.ToInt32(mx.qty.Value)));
                }
                if (mx.formulakind == 40 || mx.formulakind == 41 || mx.formulakind == 42 || mx.formulakind == 43 || mx.formulakind == 44)
                {
                    name_arr[1] = AppendToString(name_arr[1], SplitNameCount(mx.mtrlname, Convert.ToInt32(mx.qty.Value)));
                }
                if (mx.formulakind == 50 || mx.formulakind == 51 || mx.formulakind == 52 || mx.formulakind == 53 || mx.formulakind == 54)
                {
                    var mtrlname_temp = mx.mtrlname;
                    if (!(mx.mtrlname.IndexOf("分") > -1 && mx.thickness == 0 || mx.if_inputqty == 1))
                    {
                        mtrlname_temp = $"{mx.thickness.Value.ToString("#,##0.0#")}分{mx.mtrlname}";
                    }
                    name_arr[2] = AppendToString(name_arr[2], SplitNameCount(mtrlname_temp, Convert.ToInt32(mx.qty.Value)));
                }
                if (mx.formulakind == 60 || mx.formulakind == 61 || mx.formulakind == 62 || mx.formulakind == 63 || mx.formulakind == 64)
                {
                    name_arr[3] = AppendToString(name_arr[3], SplitNameCount(mx.mtrlname, Convert.ToInt32(mx.qty.Value)));
                }

                if (mx.formulakind == 80 || mx.formulakind == 81 || mx.formulakind == 84)
                {
                    name_arr[0] = AppendToString(name_arr[0], mx.mtrlname);
                }
            }
        }
        private void AutoSetFormulaTypeOnePz(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface> interfaceList)
        {
            var diancengList = mxlist.Where(t => t.formulatype == 1).ToList();

            var kindDict = new Dictionary<int, string>()
            {
                { 32,"垫层" },
                { 12,"顶布" },
                { 13,"毡类" },
                { 14,"打底无纺布" },
                { 29,"网面布料" },
                { 999,"床网" },
                { 1201,"顶布裥棉" },
            };
            var chastrSet = new HashSet<string>() { "大侧", "小侧1", "小侧2", "小侧3", "V侧1", "V侧2", "V侧3" };
            var countDict = new Dictionary<string, int>();

            foreach (var cha in chastrSet)
            {
                foreach (var kind in kindDict)
                {
                    countDict.Add($"{cha}-{kind.Value}", 0);
                }
            }

            //var orderedKeys = new List<string>();
            //foreach (var kind in kindDict)
            //{
            //    foreach (var cha in chastrSet)
            //    {
            //        orderedKeys.Add($"{cha}-{kind.Value}");
            //    }
            //}

            //foreach (var key in orderedKeys)
            //{
            //    var parts = key.Split('-');
            //    var cha = parts[0];
            //    var kindName = parts[1];

            //    var kindId = kindDict.FirstOrDefault(x => x.Value == kindName).Key;
            //    var items = diancengList.Where(mx =>
            //        mx.chastr == cha &&
            //        mx.formulakind == kindId);

            //    foreach (var mx in items)
            //    {
            //        if (mx.formulakind == 999)
            //        {
            //            this.ProcessChuangWangPz(mx, interfaceList, mx.chastr, ++countDict[key]);
            //        }
            //        else if (mx.mtrlid > 0 && mx.formulakind == 1201)
            //        {
            //            this.ProcessDingbuLianMianPz(mx, interfaceList, mx.chastr, ++countDict[key]);
            //        }
            //        else if (mx.mtrlid > 0 && new int[] { 32, 12, 13, 14, 29 }.Contains(mx.formulakind.Value))
            //        {
            //            this.ProcessWangMianBLPz(mx, interfaceList, mx.chastr, kindDict[mx.formulakind.Value], ++countDict[key]);
            //        }
            //    }
            //}

            foreach (var mx in diancengList)
            {
                var key = $"{mx.chastr}-{kindDict[mx.formulakind.Value]}";

                if (mx.formulakind == 999)
                {
                    this.ProcessChuangWangPz(mx, interfaceList, mx.chastr, ++countDict[key]);
                }
                else if (mx.mtrlid > 0 && mx.formulakind == 1201)
                {
                    this.ProcessDingbuLianMianPz(mx, interfaceList, mx.chastr, ++countDict[key]);
                }
                else if (mx.mtrlid > 0 && new int[] { 32, 12, 13, 14, 29 }.Contains(mx.formulakind.Value))
                {
                    this.ProcessWangMianBLPz(mx, interfaceList, mx.chastr, kindDict[mx.formulakind.Value], ++countDict[key]);
                }
            }

            if (countDict["大侧-垫层"] > 0)
            {
                interfaceList.Add(InserMattressInterfacePz("垫层", "大侧垫层生产说明", 1, new string[1]));
            }

            if (countDict["小侧1-垫层"] > 0)
            {
                interfaceList.Add(InserMattressInterfacePz("垫层", "小侧垫层生产说明", 1, new string[1]));
            }

            if (countDict["V侧1-垫层"] > 0)
            {
                interfaceList.Add(InserMattressInterfacePz("垫层", "V侧垫层生产说明", 1, new string[1]));
            }
        }
        /// <summary>
        /// 床网
        /// </summary>
        /// <param name="mx"></param>
        /// <param name="interfaceList"></param>
        /// <param name="chastr"></param>
        /// <param name="count"></param>
        private void ProcessChuangWangPz(u_mattress_mx_mtrl mx, List<u_mattress_interface> interfaceList, string chastr, int count)
        {
            var name_arr = new string[5];
            int bednetid = 0;
            int spongeMtrlid = 0; // 是否有海绵包边物料

            cmd.CommandText = @"SELECT u_bednetmx.bednet_height,u_bednetmx.bednetid,u_bednet.sponge_mtrlid
                                FROM u_bednetmx
								LEFT OUTER JOIN u_bednet ON u_bednet.bednetid = u_bednetmx.bednetid
                                INNER JOIN (
	                                SELECT mtrlid
	                                FROM u_mattress_mx_mtrl
	                                INNER JOIN u_mattress_formula ON u_mattress_formula.formulaid = u_mattress_mx_mtrl.formulaid
	                                WHERE u_mattress_formula.formulakind = 99
		                                AND u_mattress_mx_mtrl.mattressid = @mattressid
		                                AND u_mattress_mx_mtrl.mtrlid > 0
	                                ) v_mattress_mx_mtrl ON u_bednetmx.bednetid = v_mattress_mx_mtrl.mtrlid";
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@mattressid", mx.mattressid);
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    decimal height = Convert.ToDecimal(reader["bednet_height"]);
                    if (height == mx.thickness)
                    {
                        bednetid = Convert.ToInt32(reader["bednetid"]);
                        spongeMtrlid = Convert.ToInt32(reader["sponge_mtrlid"]);
                    }
                }
            }

            if (bednetid > 0)
            {
                var bednetHelper = HelperBase.GetHelper<BedNetHelper>(cmd);
                var bednetQdList = bednetHelper.GetBedNetQingDan(bednetid);

                if (bednetQdList.Any())
                {
                    name_arr[0] = bednetQdList[0].pznamemx;
                    name_arr[0] += "丨erp编码:";
                    cmd.CommandText = @"SELECT u_mattress.erp_mtrlcode
                                        FROM u_mattress_mx_mtrl
                                        INNER JOIN u_mattress_formula ON u_mattress_formula.formulaid = u_mattress_mx_mtrl.formulaid
                                        INNER JOIN u_mattress ON u_mattress.mattressid = u_mattress_mx_mtrl.mattressid
                                        WHERE u_mattress_formula.formulakind = 99
	                                        AND u_mattress.bcptypeid <> 0
	                                        AND u_mattress_mx_mtrl.mtrlid = @bednetid";
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@bednetid", bednetid);
                    using(var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            name_arr[0] += Convert.ToString(reader["erp_mtrlcode"]);
                        }
                    }
                }
            }

            if (FuncPowerHelper.CheckFuncPower(cmd, context.tokendata.userid, 98) && "super".Equals(context.tokendata.username.ToLower()))
            {
                interfaceList.Add(InserMattressInterfacePz("垫层", $"{chastr}-床网{count}", 2, name_arr));
            }
            else
            {
                interfaceList.Add(InserMattressInterfacePz("垫层", $"{chastr}-床网{count}", 1, name_arr));
            }

            interfaceList.Add(InserMattressInterfacePz("垫层", $"{chastr}-床网{count}生产说明", 1, new string[] { "" }));

            if (spongeMtrlid > 0) interfaceList.Add(InserMattressInterfacePz("垫层", $"{chastr}-床网{count}包边海绵条", 1, new string[] { "" }));
        }
        /// <summary>
        /// 网面布料 / 打底无纺布 / 毡类 / 顶布 / 垫层
        /// </summary>
        /// <param name="mx"></param>
        /// <param name="interfaceList"></param>
        /// <param name="chastr"></param>
        /// <param name="count"></param>
        private void ProcessWangMianBLPz(u_mattress_mx_mtrl mx, List<u_mattress_interface> interfaceList, string chastr, string typename, int count)
        {
            var name_arr = new string[5];
            var mtrlname_temp = mx.mtrlname;

            var chastr_temp = string.Empty;

            if ("顶布".Equals(typename) && count <= 1)
            {
                chastr_temp = $"{chastr}-{typename}";
            }
            else
            {
                chastr_temp = $"{chastr}-{typename}{count}";
            }

            if ((!mx.mtrlname.Contains("分") && mx.thickness > 0) || ("垫层".Equals(typename)))
            {
                mtrlname_temp = $"{mx.thickness.Value.ToString("#,##0.0#")}分{mx.mtrlname}";
            }

            name_arr[0] = mtrlname_temp;
            interfaceList.Add(InserMattressInterfacePz("垫层", chastr_temp, 2, name_arr));
        }
        /// <summary>
        /// 顶布裥棉
        /// </summary>
        /// <param name="mx"></param>
        /// <param name="interfaceList"></param>
        /// <param name="count"></param>
        private void ProcessDingbuLianMianPz(u_mattress_mx_mtrl mx, List<u_mattress_interface> interfaceList, string chastr, int count)
        {
            string chastr_temp = string.Empty;
            string ls_temp = "";
            string[] name_arr = new string[5];

            if ("顶布裥棉1".Equals(mx.mtrlname))
            {
                chastr_temp = $"{chastr}-顶布裥棉";
                for (int i = 0; i < DingBuLianMian.GetLength(0); i++)
                {
                    name_arr[i] = DingBuLianMian[0, i];
                }
            }
            else if ("顶布裥棉2".Equals(mx.mtrlname))
            {
                chastr_temp = $"{chastr}-顶布裥棉2";
                for (int i = 0; i < DingBuLianMian.GetLength(0); i++)
                {
                    name_arr[i] = DingBuLianMian[1, i];
                }
            }
            else if ("顶布裥棉3".Equals(mx.mtrlname))
            {
                chastr_temp = $"{chastr}-顶布裥棉3";
                for (int i = 0; i < DingBuLianMian.GetLength(0); i++)
                {
                    name_arr[i] = DingBuLianMian[2, i];
                }
            }
            else if ("顶布裥棉4".Equals(mx.mtrlname))
            {
                chastr_temp = $"{chastr}-顶布裥棉4";
                for (int i = 0; i < DingBuLianMian.GetLength(0); i++)
                {
                    name_arr[i] = DingBuLianMian[3, i];
                }
            }

            interfaceList.Add(InserMattressInterfacePz("垫层", chastr_temp, 2, name_arr));
        }
        private void AutoSetFormulaTypeTwoPz(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface> interfaceList)
        {
            var nameSet = new HashSet<string>(new string[] {
                "白色无字包角", "保用卡", "采购小标", "打钮钮扣", "打印小标", "合格证", "画纸", "角网+拉链",
                "开箱刀+开箱说明", "开箱说明+开箱刀", "气钮", "吊标", "说明书", "斜标", "正标", "织唛",
                "织唛斜标", "客供标", "空白牛皮纸包角", "空白珍珠包角"
            });
            // 按照nameSet排序
            Dictionary<string, int> orderDict = nameSet.Select((name, index) => new { Name = name, Index = index }).ToDictionary(x => x.Name, x => x.Index);
            var fuliaoList = mxlist.Where(t => t.formulatype == 2).OrderBy(t => orderDict.ContainsKey(t.mtrlname) ? orderDict[t.mtrlname] : int.MaxValue).ThenBy(t => !orderDict.ContainsKey(t.mtrlname) ? t.mtrlname : null).ToList();

            var extraSet = new HashSet<string>(new string[] { "采购小标", "打印小标", "合格证", "吊标", "斜标", "正标", "织唛", "织唛斜标", "客供标" });
            var specialSet = new HashSet<string>(new string[] { "打钮钮扣", "气钮" });

            foreach (var mx in fuliaoList)
            {
                if (mx.mtrlid > 0)
                {
                    int cnt = Convert.ToInt32(Math.Abs(mx.qty.Value));


                    var mtrldef = new u_mtrl_price() { mtrlid = mx.mtrlid };
                    if (DbSqlHelper.SelectOne(cmd, mtrldef, "erp_mtrlid") == 1)
                    {
                        mx.erp_mtrlid = mtrldef.erp_mtrlid;
                    }
                    // 处理特殊辅料
                    if (specialSet.Contains(mx.mtrlname))
                    {
                        interfaceList.Add(InserMattressInterfacePz("辅料", $"{mx.mtrlname}", 1, new string[] { $"{cnt.ToString("#,##0.0#")}个" }));
                        continue; // 跳过后续的处理
                    }

                    // 处理其他辅料
                    if (nameSet.Contains(mx.mtrlname))
                    {
                        for (int i = 1; i <= cnt; i++)
                        {
                            // 添加辅料接口
                            interfaceList.Add(InserMattressInterfacePz("辅料", $"{mx.mtrlname}{i}", 1, new string[] { "" }));
                            // 如果是额外的辅料，添加位置接口
                            if (extraSet.Contains(mx.mtrlname))
                            {
                                interfaceList.Add(InserMattressInterfacePz("辅料", $"{mx.mtrlname}{i}位置", 0, new string[] { "" }));
                            }
                        }
                    }else if(mx.formulakind == 15 && !nameSet.Contains(mx.mtrlname))
                    {
                        for (int i = 1; i <= cnt; i++)
                        {
                            interfaceList.Add(InserMattressInterfacePz("辅料", $"{mx.mtrlname}{i}", 1, new string[] { "" }));
                            interfaceList.Add(InserMattressInterfacePz("辅料", $"{mx.mtrlname}{i}位置", 0, new string[] { "" }));
                        }
                    }
                }
            }
        }
        private void AutoSetFormulaTypeThreePz(u_mattress mattress, List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface> interfaceList)
        {
            // 筛选 formulatype 为 3 的物料
            var bzList = mxlist.Where(t => t.formulatype == 3).ToList();

            var chastrDict = new Dictionary<int, string>
            {
                {16, "PE袋"},
                {17, "外层PE"},
                {18, "PVC"},
                {19, "卷包包装"},
                {20, "牛皮纸袋"},
                {21, "蓝色PE护角"},
                {22, "无纺布袋"},
                {23, "牛皮袋护角"},
                {24, "编织袋"},
                {27, "拉手脚轮"},
                {201, "无纺布护角"}
            };

            var countDict = new Dictionary<int, int>
            {
                {16, 1}
            };

            // 外观
            interfaceList.Add(InserMattressInterfacePz("床垫", "包装方式", 1, new string[] { Enum.GetName(typeof(PackType), mattress.packtype) }));

            foreach (var mx in bzList)
            {
                if (mx.mtrlid > 0 && chastrDict.TryGetValue(mx.formulakind.GetValueOrDefault(), out var chastr))
                {
                    var name_arr = new string[1];
                    if (mx.qty.HasValue && mx.qty.Value > 1)
                    {
                        name_arr[0] = $"{mx.qty.Value.ToString("#,##0.0#")}个{mx.mtrlname}";
                    }
                    else
                    {
                        name_arr[0] = mx.mtrlname;
                    }

                    if (countDict.ContainsKey(mx.formulakind.Value))
                    {
                        chastr += countDict[mx.formulakind.Value];
                    }

                    // 添加包装信息
                    interfaceList.Add(InserMattressInterfacePz("包装", chastr, 2, name_arr));
                }
            }

            // 压包数量
            interfaceList.Add(InserMattressInterfacePz("包装", "压包数量", 1, new string[] { $"{mattress.packqty.Value.ToString("#,##0.0#")}" }));
            // 包装说明
            interfaceList.Add(InserMattressInterfacePz("包装", "包装说明", 1, new string[] { "" }));
            // 压包说明
            if (mattress.packqty.HasValue && mattress.packqty.Value > 0) interfaceList.Add(InserMattressInterfacePz("包装", "压包说明", 1, new string[] { "" }));
            // 卷包说明
            if (mattress.diameter.HasValue && mattress.diameter.Value > 0) interfaceList.Add(InserMattressInterfacePz("包装", "卷包说明", 1, new string[] { "" }));
        }
        private void AutoSetFormulaType101Pz(u_mattress mattress, List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface> interfaceList)
        {
            var powerDict = new Dictionary<string, int[]>()
            {
                {"面裥绵",new int[] { 0, 40, 50, 60, 70 } },
                {"底裥绵",new int[] { 1, 41, 51, 61, 71 } },
                {"普通大侧",new int[] { 2, 42, 52, 62, 72 } }
            };

            var chastrDict = new Dictionary<string, string[]>()
            {
                {"面裥绵",new string[] { "内布套-面层裥棉", "内布套-面层裥棉裥棉图案" } },
                {"底裥绵",new string[] { "内布套-底层裥棉", "内布套-底层裥棉裥棉图案" } },
                {"普通大侧",new string[] { "内布套-大侧裥棉", "内布套-大侧裥棉裥棉图案" } }
            };

            foreach (var item in powerDict)
            {
                var name_arr = new string[5];
                foreach (var mx in mxlist)
                {
                    SetFormulaTypeZeroPzName(mx, "内布套", item.Value, name_arr);
                }

                var sb = new StringBuilder();
                foreach (var name2 in name_arr)
                {
                    sb.Append(name2);
                }

                if (sb.Length > 0)
                {
                    interfaceList.Add(InserMattressInterfacePz("内布套", chastrDict[item.Key][0], 2, name_arr));
                    interfaceList.Add(InserMattressInterfacePz("内布套", chastrDict[item.Key][1], 1, new string[] { "" }));
                }
            }

            // 内布套-围边边带 / 拉链
            foreach (var mx in mxlist)
            {
                if (mx.mtrlid > 0 && "内布套".Equals(mx.chastr) && mx.formulakind == 203)
                {
                    interfaceList.Add(InserMattressInterfacePz("内布套", "内布套-围边边带", 2, new string[] { $"{mx.thickness.Value.ToString("#,##0.0#")}条共{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
                else if (mx.mtrlid > 0 && "内布套".Equals(mx.chastr) && mx.formulakind == 202)
                {
                    interfaceList.Add(InserMattressInterfacePz("内布套", "内布套-拉链", 2, new string[] { $"{mx.thickness.Value.ToString("#,##0.0#")}条共{mx.qty.Value.ToString("#,##0.0#")}米{mx.mtrlname}" }));
                }
            }

            var butaostring = new string[] { };
            if (mattress.if_n_butao == 1)
            {
                butaostring = new string[] { $"内布套面层向大侧覆盖{mattress.s_cover_qty.Value.ToString("#,##0.0#")}CM、内布套大侧向底层覆盖{mattress.z_cover_qty.Value.ToString("#,##0.0#")}CM、内布套底层向大侧覆盖{mattress.x_cover_qty.Value.ToString("#,##0.0#")}CM" };
                interfaceList.Add(InserMattressInterfacePz("内布套", "内布套做法说明", 1, butaostring));
            }
        }
        #endregion

        #region 导入清单方法 
        public List<u_mattress_interface_qd> RefreshMattressInterfaceQdList(int mattressid)
        {
            var qdList = new List<u_mattress_interface_qd>();
            
            ImportMattressInterfaceQdList(mattressid, qdList);

            MattressInterfaceFindERPPrdPf(qdList,null);

            return qdList;
        }
        /// <summary>
        /// wf_fine_erp_prdpf
        /// </summary>
        /// <param name="qdList"></param>
        /// <param name="interfaceList"></param>
        public void MattressInterfaceFindERPPrdPf(List<u_mattress_interface_qd> qdList,List<u_mattress_interface> interfaceList = null)
        {
            var mtrlidList = new List<int>();
            foreach (var mx in qdList)
            {
                // 带出有设置 的erp_mtrlid
                if ((mx.erp_mtrlid == null || mx.erp_mtrlid == 0) && mx.mtrlid != null && mx.mtrlid > 0)
                {
                    var mtrldef = new u_mtrl_price() { mtrlid = mx.mtrlid };
                    if (DbSqlHelper.SelectOne(cmd, mtrldef, "erp_mtrlid") == 1)
                    {
                        mx.erp_mtrlid = mtrldef.erp_mtrlid;
                    } 
                }

                // 
                if (mx.erp_mtrlid > 0)
                {
                    mtrlidList.Add(mx.erp_mtrlid.Value);
                }
            }

            if (mtrlidList.Count > 0)
            {
                var erpHelper = HelperBase.GetHelper<ERPHelper>(null);
                //var parameters = new JObject();
                //parameters.Add("mtrlids", JToken.FromObject(mtrlidList));
                //var resultList = erpHelper.GetERPList<erp_mtrldef>("GetL1Mtrldef", parameters);
                var total = 0;
                var resultList = erpHelper.GetERPMtrldef(cmd, ref total, "", new L1Mtrldef(), 0, 0, 1, mtrlidList);

                if (resultList != null && resultList.Any())
                {
                    foreach (var mx in qdList)
                    {
                        var result = resultList.FirstOrDefault(o => o.mtrlid == mx.erp_mtrlid);
                        if (result != null)
                        {
                            mx.erp_mtrlcode = result.mtrlcode;
                            mx.erp_mtrlname = result.mtrlname;
                            mx.erp_mtrlmode = result.mtrlmode;
                            mx.erp_unit = result.unit;
                            mx.erp_mtrlengname = result.zxmtrlmode;
                        }
                    }
                }
            }

            //更新 二级明细项目 需要产品配置列表，此部分由前端完成
            if (interfaceList != null && interfaceList.Any())
            {
                // 使用 GroupBy 去重并选择第一个元素
                var distinctList = interfaceList
                    .GroupBy(mb => mb.bj_pzname)
                    .Select(g => g.First())
                    .ToList();
                Dictionary<string, u_mattress_interface> interfaceDict = distinctList.ToDictionary(mb => mb.bj_pzname, mb => mb);
                foreach (var mx in qdList)
                {
                    if (interfaceDict.TryGetValue(mx.bj_pzname, out var mb))
                    {
                        mx.bj_pzname_mx_mx = mb.bj_namemx;

                        if (mx.ss_rate == 0) mx.ss_rate = mb.ss_rate;
                        if (mx.ls_rate == 0) mx.ls_rate = mb.ls_rate;
                    }
                }
            }
        }
        /// <summary>
        /// 导入产品清单
        /// </summary>
        /// <param name="mattressid"></param>
        /// <exception cref="LJCommonException"></exception>
        public void ImportMattressInterfaceQdList(int mattressid, List<u_mattress_interface_qd> qdList)
        {
            if (mattressid <= 0)
            {
                throw new LJCommonException("床垫id有误");
            }

            var mattressHelper = GetHelper<MattressHelper>(cmd, new HelperBase.Context() { tokendata = context.tokendata });
            var mattress = mattressHelper.GetMattress(mattressid);

            var mattress_type = new u_mattress_type() { mattresstypeid = mattress.mattresstypeid };
            DbSqlHelper.SelectOne(cmd, mattress_type, "typename");

            var mxlist = mattressHelper.GetMattressMxMtrl(mattressid, new List<string>() { "u_mattress_formula.formulatype IN (0,1,2,3,99,104)" });

            var mxlist_103 = mattressHelper.GetMattressMxMtrl(mattressid, new List<string>() { "u_mattress_formula.formulatype = 103" });

            var mxlist_101 = mattressHelper.GetMattressMxMtrl(mattressid, new List<string>() { "u_mattress_formula.formulatype = 101" });

            #region 面料类清单导入
            AutoSetFormulaTypeZeroPrdPf(mxlist, qdList);
            #endregion

            #region 垫层类清单导入
            AutoSetFormulaTypeOnePrdPf(mxlist, qdList);
            #endregion

            #region 辅料类清单导入
            AutoSetFormulaTypeTwoPrfPf(mxlist, qdList);
            #endregion

            #region 包装类清单导入
            AutoSetFormulaTypeThreePrdPf(mxlist, qdList);
            #endregion

            #region 内布套类清单导入
            AutoSetFormulaType101PrdPf(mxlist_103, qdList);
            #endregion

            // 最后初始化interfaceList的printid
            for (var i = 0; i < qdList.Count; i++)
            {
                qdList[i].printid = i + 1;
            }
        }
        /// <summary>
        /// 初始化清单信息
        /// </summary>
        /// <param name="itemname"></param>
        /// <param name="bj_pzname"></param>
        /// <param name="inputtype"></param>
        /// <param name="names"></param>
        /// <returns></returns>
        public u_mattress_interface_qd InserMattressInterfacePrdPf(string itemname, string bj_pzname, string namemx, int mtrlid, decimal useqty, int formulaid = 0)
        {
            var _bcpcompare = new u_bcpcompare() { pzname = bj_pzname };
            var _wip_type = "";
            var _wrkgrpcode2 = "";
            if (DbSqlHelper.SelectOne(cmd, _bcpcompare, "wip_type, wrkgrpcode2") == 1)
            {
                _wip_type = _bcpcompare.wip_type;
                _wrkgrpcode2 = _bcpcompare.wrkgrpcode2;
            }

            var mattress_interface_qd = new u_mattress_interface_qd()
            {
                itemname = itemname,
                bj_pzname = bj_pzname,
                bj_pzname_mx = namemx,
                mtrlid = mtrlid,
                useqty = useqty,
                formulaid = formulaid,
                wip_type = _wip_type,
                wrkgrpcode2 = _wrkgrpcode2
            };

            return mattress_interface_qd;
        }

        public u_mattress_interface_qd InserMattressInterfacePrdPf(string itemname, string bj_pzname, string namemx)
        {
            var mattress_interface_qd = new u_mattress_interface_qd()
            {
                itemname = itemname,
                bj_pzname = bj_pzname,
                bj_pzname_mx = namemx
            };

            return mattress_interface_qd;
        }

        private void AutoSetFormulaTypeZeroPrdPf(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface_qd> qdList)
        {
            var powerDict = new Dictionary<string, int[]>()
            {
                {"面裥绵",new int[] { 0, 40, 50, 60, 70, 80 } },
                {"底裥绵",new int[] { 1, 41, 51, 61, 71, 81 } },
                {"顶布裥棉1",new int[] { 0, 40, 50, 60, 70, 80 } },
                {"顶布裥棉2",new int[] { 0, 40, 50, 60, 70, 80 } },
                {"普通大侧",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"上下拼侧1",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"上下拼侧2",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"上下拼侧3",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"左右拼侧1",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"左右拼侧2",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"左右拼侧3",new int[] { 2, 42, 52, 62, 72, 82 } },
                {"小侧1_EMPTY",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧1",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧1-上下拼侧1",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧1-上下拼侧2",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧1-上下拼侧3",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧2",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"小侧3",new int[] { 3, 43, 53, 63, 73, 83 } },
                {"V侧1_EMPTY",new int[] { 4, 44, 54, 64, 74, 84 } },
                {"V侧1",new int[] { 4, 44, 54, 64, 74, 84 } },
                {"V侧2",new int[] { 4, 44, 54, 64, 74, 84 } },
                {"V侧3",new int[] { 4, 44, 54, 64, 74, 84 } }
            };
            var chastrArrDict = new Dictionary<string, string[]>()
            {
                {"面裥绵",new string[] { "裥面", "面层裥棉", "面层裥面说明" } },
                {"底裥绵",new string[] { "裥底", "底层裥棉", "底层裥棉说明" } },
                {"顶布裥棉1",new string[] { "顶布裥棉", "顶布裥棉1" } },
                {"顶布裥棉2",new string[] { "顶布裥棉", "顶布裥棉2" } },
                {"普通大侧",new string[] { "大侧", "大侧裥棉"} },
                {"上下拼侧1",new string[] {"大侧", "大侧-上下拼侧1"} },
                {"上下拼侧2",new string[] { "大侧", "大侧-上下拼侧2" } },
                {"上下拼侧3",new string[] { "大侧", "大侧-上下拼侧3" } },
                {"左右拼侧1",new string[] { "大侧", "大侧-左右拼侧1"} },
                {"左右拼侧2",new string[] { "大侧", "大侧-左右拼侧2"} },
                {"左右拼侧3",new string[] { "大侧", "大侧-左右拼侧3" ,"大侧说明" } },
                {"小侧1_EMPTY",new string[] { "小侧", "小侧1裥棉" } },
                {"小侧1",new string[] { "小侧", "小侧1裥棉"} },
                {"小侧1-上下拼侧1",new string[] { "小侧", "小侧1-上下拼侧1裥棉" } },
                {"小侧1-上下拼侧2",new string[] { "小侧", "小侧1-上下拼侧2裥棉" } },
                {"小侧1-上下拼侧3",new string[] { "小侧", "小侧1-上下拼侧3裥棉" } },
                {"小侧2",new string[] { "小侧", "小侧2裥棉", "小侧2裥棉图案" } },
                {"小侧3",new string[] { "小侧", "小侧3裥棉", "小侧3裥棉图案", "小侧说明" } },
                {"V侧1_EMPTY",new string[] { "V侧", "V侧1裥棉", "V侧1裥棉图案" } },
                {"V侧1",new string[] { "V侧", "V侧1裥棉", "V侧1裥棉图案" } },
                {"V侧2",new string[] { "V侧", "V侧2裥棉", "V侧2裥棉图案" } },
                {"V侧3",new string[] { "V侧", "V侧3裥棉", "V侧3裥棉图案", "V侧说明" } }
            };
            var extreDict = new HashSet<string>() { "小侧", "V侧" };
            var jianmianList = mxlist.Where(t => t.formulatype == 0).ToList();
            var isEnter = false;

            #region wf_import_qingdan_prdpf
            foreach (var item in powerDict)
            {
                // 保证清单列表类别一致，从面裥绵 -> V侧3
                foreach (var mx in jianmianList)
                {
                    if (mx.mtrlid > 0 && (item.Key.Equals(mx.chastr) || (string.IsNullOrEmpty(mx.chastr) && item.Key.Contains("_EMPTY"))) && item.Value.Contains(mx.formulakind.Value))
                    {
                        if (mx.formulakind == 0 || mx.formulakind == 1 || mx.formulakind == 2 || mx.formulakind == 3 || mx.formulakind == 4)
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrArrDict[item.Key][0], chastrArrDict[item.Key][1], "布料", mx.mtrlid.Value, mx.useqty.Value, mx.formulaid.Value));
                        }
                        if (mx.formulakind == 40 || mx.formulakind == 41 || mx.formulakind == 42 || mx.formulakind == 43 || mx.formulakind == 44)
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrArrDict[item.Key][0], chastrArrDict[item.Key][1], "喷胶棉", mx.mtrlid.Value, mx.useqty.Value, mx.formulaid.Value));
                        }
                        if (mx.formulakind == 50 || mx.formulakind == 51 || mx.formulakind == 52 || mx.formulakind == 53 || mx.formulakind == 54)
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrArrDict[item.Key][0], chastrArrDict[item.Key][1], "裥面海绵", mx.mtrlid.Value, mx.useqty.Value, mx.formulaid.Value));
                        }
                        if (mx.formulakind == 60 || mx.formulakind == 61 || mx.formulakind == 62 || mx.formulakind == 63 || mx.formulakind == 64)
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrArrDict[item.Key][0], chastrArrDict[item.Key][1], "无纺布", mx.mtrlid.Value, mx.useqty.Value, mx.formulaid.Value));
                        }
                    }
                }

                if(item.Key.Contains("小侧3") || item.Key.Contains("V侧3"))
                {
                    var list = qdList.FindAll(t => extreDict.Contains(t.itemname)).ToList();
                    if(list.Any())
                    {
                        foreach (var name in chastrArrDict[item.Key])
                        {
                            if (name.Contains("说明"))
                            {
                                qdList.Add(InserMattressInterfacePrdPf(chastrArrDict[item.Key][0], name, ""));
                            }
                        }
                    }
                } else
                {
                    foreach (var name in chastrArrDict[item.Key])
                    {
                        if (name.Contains("说明"))
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrArrDict[item.Key][0], name, ""));
                        }
                    }
                }
            }
            #endregion

            #region wf_import_qingdan_next 面料部分
            // 按照 formulakind 分组
            var grouped = jianmianList
                .Where(t => t.formulakind >= 5 && t.formulakind <= 10)
                .GroupBy(t => t.formulakind);

            // 需要处理的组的名称与编号映射
            var groupNames = new Dictionary<int, string>
            {
                { 5, "拉手" },
                { 6, "刺绣" },
                { 7, "大侧压压布" },
                { 8, "大侧压边带" },
                { 9, "大侧压织带" },
                { 10, "大侧压上下压线" }
            };

            // 处理每一组
            foreach (var group in grouped)
            {
                var formulakind = group.Key.Value;
                var name = groupNames.ContainsKey(formulakind) ? groupNames[formulakind] : "未知组";

                foreach (var mx in group)
                {
                    if (string.IsNullOrEmpty(mx.chastr) && mx.mtrlid > 0)
                    {
                        qdList.Add(InserMattressInterfacePrdPf("拉手刺绣及其他工艺",$"{name}{group.ToList().IndexOf(mx) + 1}","",
                            mx.mtrlid.Value,
                            mx.useqty.Value
                        ));
                    }
                }
            }

            // 统一添加固定项
            qdList.Add(InserMattressInterfacePrdPf("拉手刺绣及其他工艺", "拉手刺绣", ""));
            qdList.Add(InserMattressInterfacePrdPf("拉手刺绣及其他工艺", "拉手无纺布", ""));
            qdList.Add(InserMattressInterfacePrdPf("拉手刺绣及其他工艺", "侧刺绣做法", ""));

            #endregion
        }
        private void AutoSetFormulaTypeOnePrdPf(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface_qd> qdList)
        {
            var diancengList = mxlist.Where(t => t.formulatype == 1).ToList();

            var kindDict = new Dictionary<int, string>()
            {
                { 32,"垫层" },
                { 12,"顶布" },
                { 13,"毡类" },
                { 14,"打底无纺布" },
                { 29,"网面布料" },
                { 999,"床网" },
                {1201,"顶布裥棉" }
            };
            var chastrSet = new HashSet<string>() { "大侧", "小侧1", "小侧2", "小侧3", "V侧1", "V侧2", "V侧3" };
            var countDict = new Dictionary<string, int>();

            foreach (var cha in chastrSet)
            {
                foreach (var kind in kindDict)
                {
                    countDict.Add($"{cha}-{kind.Value}", 0);
                }
            }

            foreach (var mx in diancengList)
            {
                var key = $"{mx.chastr}-{kindDict[mx.formulakind.Value]}";
                if (mx.mtrlid > 0 && new int[] { 32, 12, 13, 14, 29 }.Contains(mx.formulakind.Value))
                {
                    this.ProcessWangMianBLPrdPf(mx, qdList, mx.chastr, kindDict[mx.formulakind.Value], ++countDict[key]);
                } else if (mx.formulakind == 999)
                {
                    this.ProcessChuangWangPrdPf(mx, qdList, mx.chastr, ++countDict[key]);
                } else if(mx.formulakind == 1201)
                {
                    // 不需要操作
                }
            }

            // 顶布裥面说明
            qdList.Add(InserMattressInterfacePrdPf("顶布裥棉", "顶布裥面说明1", ""));
            qdList.Add(InserMattressInterfacePrdPf("顶布裥棉", "顶布裥面说明2", ""));
        }
        /// <summary>
        /// 床网
        /// </summary>
        /// <param name="mx"></param>
        /// <param name="interfaceList"></param>
        /// <param name="chastr"></param>
        /// <param name="count"></param>
        private void ProcessChuangWangPrdPf(u_mattress_mx_mtrl mx, List<u_mattress_interface_qd> qdList, string chastr, int count)
        {
            var namepz = string.Empty;
            int bednetid = 0;
            cmd.CommandText = @"SELECT u_bednetmx.bednet_height,u_bednetmx.bednetid
                                FROM u_bednetmx
                                INNER JOIN (
	                                SELECT mtrlid
	                                FROM u_mattress_mx_mtrl
	                                INNER JOIN u_mattress_formula ON u_mattress_formula.formulaid = u_mattress_mx_mtrl.formulaid
	                                WHERE u_mattress_formula.formulakind = 99
		                                AND u_mattress_mx_mtrl.mattressid = @mattressid
		                                AND u_mattress_mx_mtrl.mtrlid > 0
	                                ) v_mattress_mx_mtrl ON u_bednetmx.bednetid = v_mattress_mx_mtrl.mtrlid";
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@mattressid", mx.mattressid);
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    decimal height = Convert.ToDecimal(reader["bednet_height"]);
                    if (height == mx.thickness) bednetid = Convert.ToInt32(reader["bednetid"]);
                }
            }

            if (bednetid > 0)
            {
                // 获取床网清单
                var bednetList = new List<u_bednetmx>();
                if (bednetList.Any())
                {
                    var bednetHelper = HelperBase.GetHelper<BedNetHelper>(cmd);
                    var bednetQdList = bednetHelper.GetBedNetQingDan(bednetid);

                    if (bednetQdList.Any())
                    {
                        namepz = bednetQdList[0].pznamemx;
                    }
                }
            }

            qdList.Add(InserMattressInterfacePrdPf("垫层", $"{chastr}-床网{count}", namepz, mx.mtrlid.Value, mx.useqty.Value));
            // 海绵条*4    2
            qdList.Add(InserMattressInterfacePrdPf("垫层", "海绵条1", ""));
            qdList.Add(InserMattressInterfacePrdPf("垫层", "海绵条2", ""));
            qdList.Add(InserMattressInterfacePrdPf("垫层", "海绵条3", ""));
            qdList.Add(InserMattressInterfacePrdPf("垫层", "海绵条4", ""));
        }
        /// <summary>
        /// 网面布料 / 打底无纺布 / 毡类 / 顶布 / 垫层
        /// </summary>
        /// <param name="mx"></param>
        /// <param name="interfaceList"></param>
        /// <param name="chastr"></param>
        /// <param name="count"></param>
        private void ProcessWangMianBLPrdPf(u_mattress_mx_mtrl mx, List<u_mattress_interface_qd> qdList, string chastr, string typename, int count)
        {
            var mtrlname_temp = mx.mtrlname;

            if ((!mx.mtrlname.Contains("分") && mx.thickness > 0) || ("垫层".Equals(typename)))
            {
                mtrlname_temp = $"{mx.thickness.Value.ToString("#,##0.0#")}分{mx.mtrlname}";
            }

            qdList.Add(InserMattressInterfacePrdPf("垫层", $"{chastr}-{typename}{count}", "",mx.mtrlid.Value,mx.useqty.Value));
        }
        private void AutoSetFormulaTypeTwoPrfPf(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface_qd> qdList)
        {
            var fuliaoList = mxlist.Where(t => t.formulatype == 2).ToList();

            var nameSet = new HashSet<string>(new string[] {
                "保用卡", "采购小标", "打钮钮扣", "打印小标", "合格证", "画纸", "开箱说明+开箱刀", "吊标", "客供标", 
                "空白牛皮纸包角", "空白珍珠包角", "气钮","说明书","斜标","正标","织唛","织唛斜标"
            });
            var extraSet = new HashSet<string>(new string[] {  "保用卡", "采购小标", "打钮钮扣", "打印小标", "合格证", "画纸", "开箱说明+开箱刀", "吊标", "客供标",
                "空白牛皮纸包角", "空白珍珠包角", "气钮","说明书","斜标","正标","织唛","织唛斜标","角网+拉链","开箱刀+开箱说明" });
            var specialSet = new HashSet<string>(new string[] { "打钮钮扣", "气钮" });

            foreach (var mx in fuliaoList)
            {
                if (mx.mtrlid > 0)
                {
                    int cnt = Convert.ToInt32(Math.Abs(mx.qty.Value));

                    // 处理特殊辅料
                    if (specialSet.Contains(mx.mtrlname))
                    {
                        qdList.Add(InserMattressInterfacePrdPf("辅料", $"{mx.mtrlname}", "", mx.mtrlid.Value, mx.useqty.Value));
                        continue; // 跳过后续的处理
                    }

                    // 处理其他辅料
                    if (nameSet.Contains(mx.mtrlname))
                    {
                        for (int i = 1; i <= cnt; i++)
                        {
                            // 添加辅料接口
                            qdList.Add(InserMattressInterfacePrdPf("辅料", $"{mx.mtrlname}{i}", "",mx.mtrlid.Value,mx.useqty.Value));
                        }
                    } else if(mx.formulakind == 15 && !extraSet.Contains(mx.mtrlname))
                    {
                        for (int i = 1; i <= cnt; i++)
                        {
                            // 添加辅料接口
                            qdList.Add(InserMattressInterfacePrdPf("辅料", $"{mx.mtrlname}{i}", "", mx.mtrlid.Value, mx.useqty.Value));

                            // 如果是额外的辅料，添加位置接口
                            qdList.Add(InserMattressInterfacePrdPf("辅料", $"{mx.mtrlname}{i}位置", "", mx.mtrlid.Value, mx.useqty.Value));
                        }
                    }
                }
            }
        }
        private void AutoSetFormulaTypeThreePrdPf(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface_qd> qdList)
        {
            // 筛选 formulatype 为 3 的物料
            var bzList = mxlist.Where(t => t.formulatype == 3).ToList();

            var chastrDict = new Dictionary<int, string>
            {
                {16, "PE袋"},
                {17, "外层PE"},
                {18, "PVC"},
                {19, "卷包包装"},
                {20, "牛皮纸袋"},
                {21, "蓝色PE护角"},
                {22, "无纺布袋"},
                {23, "牛皮袋护角"},
                {24, "编织袋"},
                {27, "拉手脚轮"},
                {201, "无纺布护角"}
            };

            var countDict = new Dictionary<int, int>
            {
                {16, 0}
            };

            foreach (var mx in bzList)
            {
                if (mx.mtrlid > 0 && chastrDict.TryGetValue(mx.formulakind.GetValueOrDefault(), out var chastr))
                {
                    var name_arr = new string[1];
                    if (mx.qty.HasValue && mx.qty.Value > 1)
                    {
                        name_arr[0] = $"{mx.qty.Value.ToString("#,##0.0#")}个{mx.mtrlname}";
                    }
                    else
                    {
                        name_arr[0] = mx.mtrlname;
                    }

                    if (countDict.ContainsKey(mx.formulakind.Value))
                    {
                        chastr += countDict[mx.formulakind.Value];
                    }

                    // 添加包装信息
                    qdList.Add(InserMattressInterfacePrdPf("包装", chastr,"",mx.mtrlid.Value,mx.useqty.Value));
                }
            }

            // 包装说明
            qdList.Add(InserMattressInterfacePrdPf("包装", "包装说明", ""));
            // 车位说明
            qdList.Add(InserMattressInterfacePrdPf("车位说明", "车位说明", ""));
        }
        private void AutoSetFormulaType101PrdPf(List<u_mattress_mx_mtrl> mxlist, List<u_mattress_interface_qd> qdList)
        {
            var powerDict = new Dictionary<string, int[]>()
            {
                {"面裥绵",new int[] { 0, 40, 50, 60, 70,80 } },
                {"底裥绵",new int[] { 1, 41, 51, 61, 71 } },
                {"普通大侧",new int[] { 2, 42, 52, 62, 72 } }
            };

            var chastrDict = new Dictionary<string, string[]>()
            {
                {"面裥绵",new string[] { "内布套-面层裥棉", "内布套-面层裥棉裥棉图案" } },
                {"底裥绵",new string[] { "内布套-底层裥棉", "内布套-底层裥棉裥棉图案" } },
                {"普通大侧",new string[] { "内布套-大侧裥棉", "内布套-大侧裥棉裥棉图案" } }
            };

            foreach (var item in powerDict)
            {
                var name_arr = new string[5];
                foreach (var mx in mxlist)
                {
                    if (mx.mtrlid > 0 && (item.Key.Equals(mx.chastr) || item.Key.Contains("_EMPTY")) && item.Value.Contains(mx.formulakind.Value))
                    {
                        if (mx.formulakind == 0 || mx.formulakind == 1 || mx.formulakind == 2 || mx.formulakind == 3)
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrDict[item.Key][0], chastrDict[item.Key][1], "布料", mx.mtrlid.Value, mx.useqty.Value));
                        }
                        if (mx.formulakind == 40 || mx.formulakind == 41 || mx.formulakind == 42 || mx.formulakind == 43)
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrDict[item.Key][0], chastrDict[item.Key][1], "喷胶棉", mx.mtrlid.Value, mx.useqty.Value));
                        }
                        if (mx.formulakind == 50 || mx.formulakind == 51 || mx.formulakind == 52 || mx.formulakind == 53)
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrDict[item.Key][0], chastrDict[item.Key][1], "裥面海绵", mx.mtrlid.Value, mx.useqty.Value));
                        }
                        if (mx.formulakind == 60 || mx.formulakind == 61 || mx.formulakind == 62 || mx.formulakind == 63)
                        {
                            qdList.Add(InserMattressInterfacePrdPf(chastrDict[item.Key][0], chastrDict[item.Key][1], "无纺布", mx.mtrlid.Value, mx.useqty.Value));
                        }
                    }
                }
            }

            // 内布套-围边边带 / 拉链
            foreach (var mx in mxlist)
            {
                if (mx.mtrlid > 0 && "内布套".Equals(mx.chastr) && mx.formulakind == 203)
                {
                    qdList.Add(InserMattressInterfacePrdPf("内布套", "内布套-围边边带", "围边",mx.mtrlid.Value,mx.useqty.Value));
                }
                else if (mx.mtrlid > 0 && "内布套".Equals(mx.chastr) && mx.formulakind == 202)
                {
                    qdList.Add(InserMattressInterfacePrdPf("内布套", "内布套-拉链", "拉链", mx.mtrlid.Value, mx.useqty.Value));
                }
            }
        }
        #endregion

        #region 通用方法
        /// <summary>
        /// 用于 字符串 + 字符串格式
        /// </summary>
        /// <param name="currentString"></param>
        /// <param name="newPart"></param>
        /// <returns></returns>
        private string AppendToString(string currentString, string newPart)
        {
            if (string.IsNullOrEmpty(currentString))
            {
                return newPart;
            }
            else
            {
                return currentString + " + " + newPart;
            }
        }
        /// <summary>
        /// 数量分割字符串
        /// </summary>
        /// <param name="name"></param>
        /// <param name="qty"></param>
        /// <returns></returns>
        private string SplitNameCount(string name, int qty)
        {
            if (qty <= 1) return name;
            var result = name;
            result = AppendToString(result, SplitNameCount(name, --qty));
            return result;
        }
        #endregion

        #region 全局变量
        // 储存顶布裥棉数据
        private string[,] DingBuLianMian = new string[4,5];
        private enum PackType
        {
            压包 = 0,
            卷包,
            国内
        }
        #endregion
    }
}
