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;

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 = new SqlConnection(GlobalVar.ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                con.Open();

                var dtNow = DateTime.Now;

                AutoInit.AutoInitS(cmd, request.area);

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        if (request.area.areaid <= 0)
                        {
                            request.area.areaid = BllHelper.GetID(cmd, "u_bednet_area");

                            var fields = @"areaid,areaname,area_1,area_2,area_3,area_4,area_5,area_6,area_7";
                            DbSqlHelper.Insert(cmd, "u_bednet_area", null, request.area, fields);
                        }
                        else
                        {
                            //修改
                            var fields = @"areaname,area_1,area_2,area_3,area_4,area_5,area_6,area_7";
                            DbSqlHelper.Update(cmd, "u_bednet_area", null, request.area, "areaid", fields);
                        }

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