using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LQKJ.K3.MFG.PRD.App.ServicePlugIn
{
    [Kingdee.BOS.Util.HotUpdate]
    [Description("审核后校验是否修改物料编码并进行同步【服务插件】")]
    public class AfterReviewAddSynchronizationServerPlugin: AbstractOperationServicePlugIn
    {
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            var data = e.DataEntitys;
            var Number = data[0]["Number"].ToString();
            var masterid = data[0]["msterID"].ToString();
            var selectOldNumber = selectOldumber(masterid);
            DateTime time= DateTime.Now;
            time=time.AddMinutes(1);
            if (string.IsNullOrWhiteSpace(selectOldNumber[0]) && Convert.ToDateTime(selectOldNumber[1])< time)
            {
                integrationMethod(data, Number, masterid, selectOldNumber); //校验完旧物料编码与同步
                return;
            }
            if (string.IsNullOrWhiteSpace(selectOldNumber[0]))
            {
                updateOldNumber(Number, masterid);
                return;
            }
            integrationMethod(data, Number, masterid, selectOldNumber);
            base.EndOperationTransaction(e);

        }

        private void integrationMethod(DynamicObject[] data, string number, string masterid, List<string> selectOldNumber)
        {
            var oldNumber = selectOldNumber[0].ToString();
                if (oldNumber == number)  return;
            List<string> list = new List<string>();
            string id = "ENG_BOM";
            string userId = base.Context.UserId.ToString();
            string operationName = base.FormOperation.OperationName.ToString();
            string operation = base.FormOperation.Operation;
            var FidList = selectEngBomFid(number);
            foreach (var Fid in FidList)
            {

                string item = $@"/*dialect*/
                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)
                values(NEWID(), '{Fid}', '{id}', GETDATE(), '{userId}', '0', GETDATE(), GETDATE(), '0', '{operationName}', '{operation}')";
                list.Add(item);
            }
            DBUtils.ExecuteBatch(base.Context, list, list.Count);
            updateOldNumber(number, masterid);//生成同步记录后同步旧编码
        }

        /// <summary>
        /// 使用修改后的物料编码查询物料清单
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<string> selectEngBomFid(string number)
        {
            var getSql = $@"
            select
            q.FID
            from
            (
            select
                teb.FID
				,max(teb.FFORBIDSTATUS) as FFORBIDSTATUS
            from 
                T_ENG_BOM teb
            left join T_ENG_BOMCHILD tebHild on tebHild.FID=teb.FID
            left join T_BD_MATERIAL tbm on tbm.FMATERIALID=teb.FMATERIALID
            left join T_BD_MATERIAL tbm1 on tbm1.FMATERIALID=tebHild.FMATERIALID
            where 
	            tbm.FNUMBER='{number}' or tbm1.FNUMBER='{number}'
            group by 
	            teb.FID
				)q
				where 
				q.FFORBIDSTATUS<>'B'
";
          var dt=DBServiceHelper.ExecuteDataSet(base.Context, getSql).Tables[0];
              List<string> list = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var item = dt.Rows[i]["FID"].ToString();
                list.Add(item);
            }
            return list;
        }

        /// <summary>
        /// 查询旧编码是否存在
        /// </summary>
        /// <param name="masterid"></param>
        /// <returns></returns>
        private List<string> selectOldumber(string masterid)
        {
            List<string> list=new List<string>();
            string getSql = $@"/*dialect*/
            select
                 F_LQKJ_NumberYC 
                ,FCREATEDATE
            from 
                T_BD_MATERIAL  
            where
                FMASTERID='{masterid}'

";
           var dt= DBServiceHelper.ExecuteDataSet(Context, getSql).Tables[0];
            if (dt.Rows.Count==0)
            {
                list.Add("");

                return list;
            }
            var oldNumber = dt.Rows[0]["F_LQKJ_NumberYC"].ToString();
            var creaTedate = dt.Rows[0]["FCREATEDATE"].ToString();
            list.Add(oldNumber);
            list.Add(creaTedate);
            return list;
        }

        /// <summary>
        /// 更新旧编码字段
        /// </summary>
        /// <param name="number"></param>
        /// <param name="masterid"></param>
        private void updateOldNumber(string number, string masterid)
        {
            string updateSql = $@"/*dialect*/
            update
                T_BD_MATERIAL
            set
                F_LQKJ_NumberYC='{number}'
            where
	            FMASTERID='{masterid}'
";
            DBServiceHelper.Execute(Context, updateSql);
        }
    }
}
