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;

namespace JLHHJSvr.Excutor
{
    internal sealed class CopyMattressAuditedExcutor : ExcutorBase<CopyMattressAuditedRequest, CopyMattressAuditedResponse>
    {
        protected override void ExcuteInternal(CopyMattressAuditedRequest request, object state, CopyMattressAuditedResponse 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 = new SqlConnection(GlobalVar.ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                con.Open();

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

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

                    if (mattress.flag == 0) throw new LJCommonException("存在报价单未财务审核,不能复制");

                    if(mattress.deptid <= 0) throw new LJCommonException("存在报价单没有选择部门,不能复制");

                    if (string.IsNullOrEmpty(mattress.area)) mattress.area = "维持原状";
                    if (string.IsNullOrEmpty(mattress.cabinet_type)) mattress.cabinet_type = "维持原状";

                    mattress.mattress_width = 0;
                    mattress.mattress_length = 0;
                }

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        helper.CopyMattress(request.list, 0, 0);

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