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

namespace JLHHJSvr.Excutor
{
    internal sealed class CreatMtrldefExcutor : ExcutorBase<CreatMtrldefRequest, CreatMtrldefResponse>
    {
        Dictionary<string, object> replacements = new Dictionary<string, object>();

        protected override void ExcuteInternal(CreatMtrldefRequest request, object state, CreatMtrldefResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (request.list.Count <= 0)
            {
                rslt.ErrMsg = "床垫id参数为空!";
                return;
            }

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

                var toUpdate = new List<u_mattress>();
                foreach(var mattressid in request.list)
                {
                    if (LockHelper.CheckIsLock(cmd, MattressHelper.BillKeyWord, mattressid, tokendata.username, out string arg_msg)) throw new LJCommonException(arg_msg);
                }

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

                    if (mattress.js1_flag == 0)
                    {
                        rslt.ErrMsg = $"床垫报价:{mattress.mattresscode}未产品审核,请检查!";
                        return;
                    }

                    var interfaceList = new List<u_mattress_interface>();
                    var selectStr = @"SELECT u_mattress_interface.mattressid
	                                ,printid
	                                ,itemname
	                                ,bj_pzname
	                                ,bj_namemx
	                                ,actual_size
	                                ,sb_craft
	                                ,actual_size_sb
	                                ,erp_pzid
	                                ,ss_rate
	                                ,ls_rate
	                                ,bj_inputtype
                                    ,u_configure_code.pzcode
                                    ,u_configure_code.name AS pzname
                                FROM u_mattress_interface
                                INNER JOIN u_mattress on u_mattress.mattressid = u_mattress_interface.mattressid
                                INNER JOIN u_configure_code on u_configure_code.typeid = u_mattress.erp_configcodetype 
		                                AND u_mattress_interface.erp_pzid = u_configure_code.pzid";
                    DbSqlHelper.SelectJoin(cmd, selectStr, "u_mattress_interface.mattressid = @mattressid AND u_mattress_interface.erp_pzid > 0 AND u_mattress_interface.bj_pzname <> '' ", 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,pzcode,pzname", 0, 0, interfaceList);

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

                    l1Helper.GetMattressMsg(mattress, interfaceList);

                    var errMsg = l1Helper.SaveMtrldef(mattress, interfaceList);
                    if (!string.IsNullOrEmpty(errMsg))
                    {
                        rslt.ErrMsg = errMsg;
                        return;
                    }

                    toUpdate.Add(mattress);
                }

                using(cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var mattress in toUpdate.Where(m => m.erp_mtrlid > 0))
                        {
                            mattress.creatmtrl_flag = 1;
                            mattress.creatmtrl_auditingrep = tokendata.username;
                            mattress.creatmtrl_auditingdate = DateTime.Now;

                            DbSqlHelper.Update(cmd, mattress, "erp_mtrlid,creatmtrl_flag,erp_mtrlcode,creatmtrl_auditingrep,creatmtrl_auditingdate");
                            rslt.mattress = mattress;
                        }

                        cmd.Transaction.Commit();
                    }
                    catch (Exception ex) 
                    {
                        cmd.Transaction?.Rollback();
                        rslt.ErrMsg = ex.Message;
                        Trace.Write($"Transaction failed: {ex.Message}");
                    }
                }
            }
        }
    }
}
