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

namespace JLHHJSvr.Excutor
{
    internal sealed class SaveBedNetAreaExcutor : ExcutorBase<SaveBedNetAreaRequest, SaveBedNetAreaResponse>
    {
        protected override void ExcuteInternal(SaveBedNetAreaRequest request, object state, SaveBedNetAreaResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }

            if (request.area == null)
            {
                rslt.ErrMsg = "未提交床网分区定义";
                return;
            }

            if (string.IsNullOrEmpty(request.area.areaname))
            {
                rslt.ErrMsg = "请填写分区名称";
                return;
            }

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

                var dtNow = DateTime.Now;

                AutoInit.AutoInitS(cmd, request.area);

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        var fields = "areaname,area_1,area_2,area_3,area_4,area_5,area_6,area_7,area_8,area_9,area_10,area_11,area_12,area_13,area_14,area_15,sponge_1,sponge_2,sponge_3,sponge_4,sponge_5,sponge_6,sponge_7,sponge_8,sponge_9,sponge_10,sponge_11,sponge_12,sponge_13,sponge_14,sponge_15";
                        if (request.area.areaid <= 0)
                        {
                            request.area.areaid = BllHelper.GetID(cmd, "u_bednet_area");

                            DbSqlHelper.Insert(cmd, "u_bednet_area", null, request.area, "areaid," + fields);
                        }
                        else
                        {
                            //修改
                            DbSqlHelper.Update(cmd, "u_bednet_area", null, request.area, "areaid", fields);
                        }

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