using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using LQKJ.WebApi.Stub;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

namespace LQKJ.K3.MES.AppServicePlugin
{
    [Description("记录同步数据服务插件")]
    public class SyncdataServerPlugin : AbstractOperationServicePlugIn
    {
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            if (this.BusinessInfo.GetForm().ElementType == 400)
            {
                e.FieldKeys.Add(this.BusinessInfo.GetForm().NumberFieldKey);
                e.FieldKeys.Add(this.BusinessInfo.GetForm().NameFieldKey);
            }
            else if(this.BusinessInfo.GetForm().ElementType == 100)
            {
                if(this.BusinessInfo.GetBillNoField() != null)
                { 
                    e.FieldKeys.Add(this.BusinessInfo.GetBillNoField().Key);
                }
            }
            base.OnPreparePropertys(e);
        }

        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            List<string> list = new List<string>();
            string id = base.BusinessInfo.GetForm().Id;
            string text = base.Context.UserId.ToString();
            string text2 = base.FormOperation.OperationName.ToString();
            string operation = base.FormOperation.Operation;
            var org = base.Context.CurrentOrganizationInfo.ID.ToString();
            string sqlOrg = $@"/*dialect*/select F_LQKJ_CHECKBOX, F_LQKJ_ShowMessage from LQKJ_t_SynchronizationSet where F_LQKJ_ORGID={org}";
            DataTable dtOrg = DBUtils.ExecuteDataSet(this.Context, sqlOrg).Tables[0];
            Logger.Info("SyncList2", "开始");
            if (dtOrg.Rows.Count > 0)
            {
                String showMessage = dtOrg.Rows[0]["F_LQKJ_ShowMessage"].ToString();
                if (dtOrg.Rows[0]["F_LQKJ_CHECKBOX"].ToString() == "1")
                {
                    IEnumerable<ExtendedDataEntity> dataEntitys = e.SelectedRows;
                    string ids = "";
                    HashSet<string> hs = new HashSet<string>();
                    if (id == "ENG_BOM")
                    {
                        foreach (ExtendedDataEntity dynamicObject in dataEntitys)
                        {
                            ids += dynamicObject["Id"].ToString() + ",";
                        }
                        string SQL = $@"/*dialect*/SELECT DISTINCT FID FROM T_ENG_BOMCHILD WHERE FMATERIALID IN(select FMATERIALID from T_ENG_BOM where FID in({ids.Remove(ids.LastIndexOf(','))}))";
                        DataTable dt = DBUtils.ExecuteDataSet(this.Context, SQL).Tables[0];
                        foreach (DataRow row in dt.Rows)
                        {
                            hs.Add(row["FID"].ToString());
                        }
                    }

                    List<string> recordIds = new List<string>();
                    Dictionary<string, DynamicObject> dynamicObjDic = new Dictionary<string, DynamicObject>();

                    foreach (ExtendedDataEntity dynamicObject in dataEntitys)
                    {
                        string text3 = dynamicObject["Id"].ToString();
                        if (hs.Contains(text3)) continue;
                        string recordId = Guid.NewGuid().ToString();
                        recordIds.Add(recordId);
                        dynamicObjDic.Add(recordId, dynamicObject.DataEntity);

                        string item = string.Format("insert into LQKJ_t_IMSSync(FID,F_LQKJ_SYNCDATAID,F_LQKJ_SYNCBILL,F_LQKJ_SYNDDATETIME,FCREATORID,FMODIFIERID,FCREATEDATE,FMODIFYDATE,F_LQKJ_SYNCCHECK,F_LQKJ_Operationname,F_LQKJ_operationinnercode)\r\n              values('{5}','{0}','{1}',null,'{2}','0',GETDATE(),GETDATE(),'0','{3}','{4}')", new object[]
                        {
                    text3,
                    id,
                    text,
                    text2,
                    operation,
                    recordId
                        });
                        list.Add(item);
                    }
                    SyncStaticParam.RecordIds = recordIds;

                    DBUtils.ExecuteBatch(base.Context, list, list.Count);
                    SyncStaticParam.DCSyncInfoDic[this.Context.DBId] = true;

                    if (showMessage != "1") return;
                    
                    while (!hasFinished(recordIds))
                    {
                        System.Threading.Thread.Sleep(1000);
                    }

                    GenMessage(recordIds, dynamicObjDic);


                    SyncStaticParam.RecordIds.Clear();
                    SyncStaticParam.DCSyncResultDic.Clear();
                    SyncStaticParam.DCSyncInfoDic.Clear();
                    SyncStaticParam.DCSyncMessageDic.Clear();

                }
            }
            base.AfterExecuteOperationTransaction(e);
        }

        /***
         * 
         */
        private void GenMessage(List<string> recordIds, Dictionary<string, DynamicObject> dynamicObjDic)
        {
            this.OperationResult.OperateResult.Clear();
            foreach (string recordId in recordIds)
            {
                OperateResult operateResult = new OperateResult();
                bool isSuccess = SyncStaticParam.DCSyncResultDic[recordId];
                operateResult.SuccessStatus = isSuccess;
                if (!isSuccess) operateResult.MessageType = MessageType.FatalError;
                operateResult.PKValue = recordId;
                operateResult.RowIndex = recordIds.IndexOf(recordId);
                DynamicObject dynamicObj = dynamicObjDic[recordId];

                if (dynamicObj != null)
                {
                    if (this.BusinessInfo.GetForm().ElementType == 400)
                    {
                        string numberKey = this.BusinessInfo.GetForm().NumberFieldKey;
                        Field field = this.BusinessInfo.GetField(numberKey);
                        if (field != null)
                        {
                            object numnberObj = field.DynamicProperty.GetValue(dynamicObj);
                            if (numnberObj != null)
                            {
                                operateResult.Number = numnberObj.ToString();
                            }
                        }

                        string nameKey = this.BusinessInfo.GetForm().NameFieldKey;
                        field = this.BusinessInfo.GetField(nameKey);
                        if (field != null)
                        {
                            object nameObj = field.DynamicProperty.GetValue(dynamicObj);
                            if (nameObj != null)
                            {
                                operateResult.Name = nameObj.ToString();
                            }
                        }
                    }
                    else if (this.BusinessInfo.GetForm().ElementType == 100)
                    {
                        Field field = this.BusinessInfo.GetBillNoField();
                        if (field != null)
                        {
                            object numnberObj = field.DynamicProperty.GetValue(dynamicObj);
                            if (numnberObj != null)
                            {
                                operateResult.Number = numnberObj.ToString();
                                operateResult.Name = numnberObj.ToString();
                            }
                        }
                    }
                }
                string message = SyncStaticParam.DCSyncMessageDic[recordId];
                if (message != null)
                {
                    message = message.Replace("保存", "同步");
                    message = message.Replace("提交", "同步");
                    message = message.Replace("审核", "同步");
                }
                operateResult.Message = message;
                if (!isSuccess) this.OperationResult.IsSuccess = false;
                this.OperationResult.OperateResult.Add(operateResult);
                this.OperationResult.FormTitle = message;
            }
        }

        /**
         * 已经同步完成
         */
        private bool hasFinished(List<string> recordIds)
        {
            bool flag = true;
            foreach(string recordId in recordIds)
            {
                if (!SyncStaticParam.DCSyncResultDic.ContainsKey(recordId))
                {
                    flag = false;
                }
            }
            return flag;
        }
    }
}
