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

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

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

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

                foreach (var bednet in request.list)
                {
                    DbSqlHelper.SelectOne(cmd, bednet, "flag,deptid");

                    if (bednet.flag == 1) throw new LJCommonException("存在报价单已审核,不能重算!");

                    if (bednet.deptid <= 0) throw new LJCommonException("存在报价单部门id错误,不能重算!");

                    var dept = helper.Cache.GetData<u_dept, DeptMapping>(bednet.deptid.Value);

                    if (dept.pricelistid <= 0) throw new LJCommonException("存在报价单部门pricelistid错误,不能重算!");

                }

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var bednet in request.list)
                        {
                            var mxList = helper.GetBedNetMxList(bednet.bednetid.Value);
                            var springList = helper.GetBedNetSpringList(bednet.bednetid.Value);
                            var bednet_temp = helper.GetBedNet(bednet.bednetid.Value);

                            helper.SaveBedNet(bednet_temp, mxList,springList);
                        }
                        cmd.Transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        cmd.Transaction.Rollback();
                        rslt.ErrMsg = e.Message;
                    }
                }
            }
        }
    }
}
