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 SaveWorkmanshipExcutor : ExcutorBase<SaveWorkmanshipRequest, SaveWorkmanshipResponse>
    {
        protected override void ExcuteInternal(SaveWorkmanshipRequest request, object state, SaveWorkmanshipResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }

            if (request.workmanship == null)
            {
                rslt.ErrMsg = "未提交工艺加点设置信息";
                return;
            }

            if (request.workmanship.rate < 0)
            {
                rslt.ErrMsg = "利润率有误,请检查!";
                return;
            }

            if(request.workmanship.deptid <= 0)
            {
                rslt.ErrMsg = "部门选择有误,请检查!";
                return;
            }

            if (request.workmanship.mattresstypeid <= 0)
            {
                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.workmanship);

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        if (request.workmanship.workmanshipid <= 0)
                        {
                            request.workmanship.workmanshipid = BllHelper.GetID(cmd, "u_workmanship_add");

                            var fields = "workmanshipid,deptid,mattresstypeid,workmanshipname,formula,rate";
                            DbSqlHelper.Insert(cmd, "u_workmanship_add", null, request.workmanship, fields);
                        }
                        else
                        {
                            //修改
                            var fields = "deptid,mattresstypeid,formula,rate";
                            DbSqlHelper.Update(cmd, "u_workmanship_add", null, request.workmanship, "workmanshipid", fields);
                        }

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