using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

namespace LF.K3.SCM.BusinessPlugin
{
    [HotUpdate]
    [Description("销售出库单列表插件")]
    public class OutStockListPlugin: AbstractListPlugIn
    {
        public override void AfterDoOperation(AfterDoOperationEventArgs e)
        {
            ShowOutboundParameters(e.Operation.Operation);
            ModifyLastOut(e.Operation.Operation);
            base.AfterDoOperation(e);
        }

        /// <summary>
        /// 显示出库参数设置
        /// </summary>
        /// <param name="key"></param>
        private void ShowOutboundParameters(string key)
        {
            if (key != "OutboundParameters") return;

            DynamicFormShowParameter showParameter = new DynamicFormShowParameter();
            showParameter.FormId = "qaz_outStock";
            this.View.ShowForm(showParameter);
        }

        /// <summary>
        /// 修改末次出库
        /// </summary>
        /// <param name="key"></param>
        private void ModifyLastOut(string key)
        {
            if (key != "ConfirmLastOut") return;

            List<string> outStocks = new List<string>();
            if (this.ListView.SelectedRowsInfo.Count == 0)
            {
                this.View.ShowWarnningMessage("请选择需要修改末次出库的数据。");
                return;
            }
            foreach (ListSelectedRow listSelectedRow in this.ListView.SelectedRowsInfo)
            {
                outStocks.Add(listSelectedRow.PrimaryKeyValue);
            }

            string sql = "select F_QAZ_ASSISTANT1, max(FDATE) FDATE, max(F_QAZ_ISLASTOUT) F_QAZ_ISLASTOUT  from T_SAL_OUTSTOCK where FID in ({0}) and FID in (select FID from T_SAL_OUTSTOCKFIN where FISGENFORIOS = '0') group by F_QAZ_ASSISTANT1 ";
            sql = string.Format("select T2.FBILLNO, T2.FID, T2.F_QAZ_ASSISTANT1, T2.FDATE, T2.F_QAZ_ISLASTOUT from ({0}) T1 inner join T_SAL_OUTSTOCK T2 on T1.F_QAZ_ASSISTANT1 = T2.F_QAZ_ASSISTANT1 and T1.FDATE = T2.FDATE where T2.FID in (select FID from T_SAL_OUTSTOCKFIN where FISGENFORIOS = '0')", sql);
            sql = string.Format(sql, string.Join(",", outStocks));

            bool isMultContract = false;
            bool hasLastOut = false;
            string billNo = string.Empty;
            long id = 0;
            string contractId = string.Empty;
            using (IDataReader reader = DBServiceHelper.ExecuteReader(this.Context, sql))
            {
                while (reader.Read())
                {
                    billNo = reader["FBILLNO"] as string;
                    string curContractId = reader["F_QAZ_ASSISTANT1"] as string;
                    if (string.IsNullOrWhiteSpace(curContractId)) continue;
                    if (contractId == string.Empty)
                    {
                        contractId = curContractId;
                    }
                    else if(curContractId != contractId)
                    {
                        isMultContract = true;
                    }

                    long curId = Convert.ToInt64(reader["FID"]);
                    if (curId > id)
                    {
                        id = curId;

                        string isLastOut = reader["F_QAZ_ISLASTOUT"] as string;
                        if (isLastOut == "1")
                        {
                            hasLastOut = true;
                        }
                        else
                        {
                            hasLastOut = false;
                        }
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(contractId))
            {
                this.View.ShowWarnningMessage("请选择有合同号的出库单。");
                return;
            }

            if (isMultContract)
            {
                this.View.ShowWarnningMessage("请选择同一个合同的出库单。");
                return;
            }

            if (hasLastOut)
            {
                this.View.ShowWarnningMessage("该合同已经存在末次出库的出库单。");
                return;
            }

            this.View.ShowWarnningMessage($"将把出库单\"{billNo}\"作为末次出库单，请确认！", options: MessageBoxOptions.OKCancel, 
                action:(result) => 
                {
                    if (result == MessageBoxResult.OK) 
                    {
                        string updateSQL = $"update T_SAL_OUTSTOCK set F_QAZ_ISLASTOUT = '0' where F_QAZ_ASSISTANT1 = '{contractId}'";
                        DBServiceHelper.Execute(this.Context, updateSQL);

                        updateSQL = $"update T_SAL_OUTSTOCK set F_QAZ_ISLASTOUT = '1' where FBILLNO = '{billNo}'";
                        DBServiceHelper.Execute(this.Context, updateSQL);
                        this.View.ShowMessage($"已将出库单\"{billNo}\"作为末次出库单");

                        LogObject logObject = new LogObject();
                        logObject.pkValue = id.ToString();
                        logObject.OperateName = "确定末次出库";
                        logObject.ObjectTypeId = "SAL_OUTSTOCK";
                        logObject.Environment = OperatingEnvironment.BizOperate;
                        logObject.SubSystemId = "23";
                        logObject.Description = $"\"{this.Context.UserName}\"把销售出库单\"{billNo}\"修改成末次出库。";
                        LogServiceHelper.WriteLog(this.Context, logObject);
                    }
                });
        }
    }
}
