using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using System.Data;
using Kingdee.BOS.Orm.DataEntity;

namespace LF.K3.SCM.BusinessPlugin
{
    [HotUpdate]
    [Description("销售出库单表单插件")]
    public class OutStockEditPlugin: AbstractBillPlugIn
    {
        public override void AfterBindData(EventArgs e)
        {
            SetArrivalTime();
            base.AfterBindData(e);
        }

        /// <summary>
        /// 设置预计到货时间
        /// </summary>
        private void SetArrivalTime()
        {
            int shipingDays = GetShippingDays();
            if (this.View.Model.GetValue("FDate") == null) return;
            var date = Convert.ToDateTime(this.View.Model.GetValue("FDate"));
            date = date.AddDays(shipingDays);
            this.View.Model.SetValue("F_qaz_arrivalTime", date);
        }

        /// <summary>
        /// 获取运输天数
        /// </summary>
        /// <returns></returns>
        private int GetShippingDays()
        {
            return Convert.ToInt32(SystemParameterServiceHelper.GetParamter(this.Context, 0, 0, "qaz_outStock", "F_qaz_ShippingDays"));
        }

        public override void DataChanged(DataChangedEventArgs e)
        {
            if (e.Field.Key == "FDate")
            {
                SetArrivalTime();
            }
            base.DataChanged(e);
        }

        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            string contractId = this.Model.DataObject["F_qaz_Assistant1_Id"] as string;
            if (string.IsNullOrEmpty(contractId)) return;
            

            string sql = $"select 1 from T_SAL_OUTSTOCK where F_qaz_isLastOut = '1' and F_QAZ_ASSISTANT1 = '{contractId}'";

            using (IDataReader reader = DBServiceHelper.ExecuteReader(this.Context, sql))
            {
                if (reader.Read())
                {
                    return;
                }
            }


            sql = $"select F_QAZ_AMOUNT from T_BAS_ASSISTANTDATAENTRY where FEntryID = '{contractId}' ";

            decimal contractAmount = 0;

            using (IDataReader reader = DBServiceHelper.ExecuteReader(this.Context, sql))
            {
                if (reader.Read())
                {
                    contractAmount = Convert.ToDecimal(reader["F_QAZ_AMOUNT"]);
                }
                else
                {
                    return;
                }
            }

            sql = $"select isnull(sum(FALLAMOUNT), 0) FALLAMOUNT from T_SAL_OUTSTOCKENTRY_F where FID in (select FID from T_SAL_OUTSTOCK where F_qaz_isLastOut = '0' and F_QAZ_ASSISTANT1 = '{contractId}') and FID <> {this.Model.DataObject["Id"]}";

            decimal outStockSumAmount = 0;
            using (IDataReader reader = DBServiceHelper.ExecuteReader(this.Context, sql))
            {
                if (reader.Read())
                {
                    outStockSumAmount = Convert.ToDecimal(reader["FALLAMOUNT"]);
                }
            }

            var entity = this.Model.GetEntityDataObject(this.Model.BillBusinessInfo.GetEntity("FEntity"));
            decimal curOutAmount = 0;
            foreach (DynamicObject entityObj in entity)
            {
                curOutAmount += Convert.ToDecimal(entityObj["AllAmount"]);
            }

            if (outStockSumAmount + curOutAmount - contractAmount < 0.1m && outStockSumAmount + curOutAmount - contractAmount > -0.1m)
            {
                this.Model.SetValue("F_qaz_isLastOut", true);
            }

            base.BeforeSave(e);
        }
    }
}
