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

namespace JLHHJSvr.Excutor
{
    internal sealed class UpdateMtrldefPriceExcutor : ExcutorBase<UpdateMtrldefPriceRequest, UpdateMtrldefPriceResponse>
    {
        protected override void ExcuteInternal(UpdateMtrldefPriceRequest request, object state, UpdateMtrldefPriceResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (!request.list.Any())
            {
                rslt.ErrMsg = "至少提交一条需要更新价格的记录";
                return;
            }

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

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var mtrl in request.list)
                        {
                            if (mtrl.mtrlid > 0)
                            {
                                var fields = @"price";

                                if (mtrl.pricelistid > 0)
                                {
                                    var mxlist = new List<u_mtrl_price_pricelist>();
                                    DbSqlHelper.SelectJoin(cmd, "SELECT pricelistid,mtrlid,price,pricetype,price_formula,qty_formula FROM u_mtrl_price_pricelist", "mtrlid = @mtrlid AND pricelistid = @pricelistid", new Dictionary<string, object>() { { "@mtrlid", mtrl.mtrlid }, { "@pricelistid", mtrl.pricelistid } }, "mtrlid", "pricelistid,mtrlid,price,pricetype,price_formula,qty_formula", 0, 0, mxlist);

                                    foreach (var mx in mxlist)
                                    {
                                        // 通过kingdee获取单价
                                    }

                                    mtrl.mxlist = mxlist;
                                }

                                foreach (var mx in mtrl.mxlist)
                                {
                                    DbSqlHelper.Update(cmd, "u_mtrl_price_pricelist", null, mx, "mtrlid,pricelistid", fields);
                                }
                            }
                        }

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