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

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

            if (request.dept == null)
            {
                rslt.ErrMsg = "未提交部门信息";
                return;
            }

            if (string.IsNullOrEmpty(request.dept.deptname))
            {
                rslt.ErrMsg = "请录入部门名称!";
                return;
            }
            if (request.dept.pricelistid == null || request.dept.pricelistid <= 0)
            {
                rslt.ErrMsg = "请选择价格表!";
                return;
            }

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

                // 初始化属性
                AutoInit.AutoInitS(cmd, request.dept);

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

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        var dtNow = DateTime.Now;

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