using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.List.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Transactions;

namespace LF.K3.SCM.BusinessPlugin
{
    [Description("打开物料替换弹出框")]   
    [HotUpdate]
    public class GGReplaceModel : AbstractDynamicFormPlugIn
    {
        DataTable dt;
        //弹出窗之前，判断状态
        public override void PreOpenForm(PreOpenFormEventArgs e)
        {
            base.PreOpenForm(e);
            //获取传入的值
            string billno = e.OpenParameter.GetCustomParameter("billno").ToString();
            billno = billno.Remove(billno.LastIndexOf(","));//截断字符
            string sql = $@"/*dialect*/select FNUMBER,case FDOCUMENTSTATUS when 'Z'then '暂存' 
                                        when 'A' THEN '创建'  when 'B' THEN '审核中'
                                        when 'C' THEN '已审核'  when 'D' THEN '重新审核' end FDOCUMENTSTATUS,
                                        case FFORBIDSTATUS when 'A' then '否' when 'B' then '是' end FFORBIDSTATUS 
                                        from T_BD_MATERIAL  WHERE FMATERIALID IN ({billno}) ";
            DataTable dt = DBServiceHelper.ExecuteDataSet(e.Context, sql).Tables[0];
            var state = "";
            var Disable = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var now = dt.Rows[i]["FDOCUMENTSTATUS"].ToString();
                if (dt.Rows[i]["FFORBIDSTATUS"].ToString() == "是")
                {
                    Disable += dt.Rows[i]["FNUMBER"].ToString() + ",";
                }
                else
                {
                    if (now == "审核中" || now == "已审核")
                    {
                        state += dt.Rows[i]["FNUMBER"].ToString() + ",";
                    }
                }
            }
            if (state != "" && Disable == "")
            {
                e.Cancel = true;
                e.CancelMessage = "物料编号：" + state + "的数据状态不允许修改此物料信息";
            }
            else
            if (state == "" && Disable != "")
            {
                e.Cancel = true;
                e.CancelMessage = "物料编号：" + Disable + "已被禁用，不能修改！";
            }
            else if (state != "" && Disable != "")
            {
                e.Cancel = true;
                e.CancelMessage = "物料编号：" + state + "的数据状态不允许修改此物料信息；物料编号：" + Disable + "已被禁用，不能修改！";
            }
            else if (state == "" && Disable == "") { return; }
        }

        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);
            //禁用替换按钮
            this.Enablecontrol("F_qaz_Button1", false);
            this.Enablecontrol("F_qaz_Text1", false);
            //获取传入的值
            string billno = this.View.OpenParameter.GetCustomParameter("billno").ToString();
            billno = billno.Remove(billno.LastIndexOf(","));//截断字符
            //查询数据
            string sql = $@"/*dialect*/select FNUMBER FNUMBER,FNAME FNAME,F_QAZ_REMARK F_FRONT from t_BD_MATERIAL T0  
                left join T_BD_MATERIAL_L T1  on T0.FMATERIALID=T1.FMATERIALID  WHERE T0.FMATERIALID IN ({billno}) ";
            DataSet ds = DBServiceHelper.ExecuteDataSet(this.Context, sql);
            dt = ds.Tables[0];
            //绑定在单据体中
            //var a = dt.Rows.Count-1;
            this.Model.BatchCreateNewEntryRow("F_qaz_Entity", dt.Rows.Count - 1);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                this.View.Model.SetValue("FNUMBER", dt.Rows[i]["FNUMBER"].ToString(), i);
                this.View.Model.SetValue("FNAME", dt.Rows[i]["FNAME"].ToString(), i);
                this.View.Model.SetValue("F_FRONT", dt.Rows[i]["F_FRONT"].ToString(), i);
            }
            this.View.UpdateView("F_qaz_Entity");
        }
        //自定义方法控制页面空页是否禁用
        private void Enablecontrol(string key, bool bEnable)
        {
            this.View.GetControl(key).Enabled = bEnable;
        }
        public override void BeforeDoOperation(BeforeDoOperationEventArgs e)
        {
            //查找规格
            if (e.Operation.FormOperation.Id == "F_qaz_Button")
            {
                if (this.Model.GetValue("F_qaz_Text").ToString() == "")
                {
                    this.View.ShowWarnningMessage("需替换掉的规格，不能为空");
                }
                else
                {
                    //查找数据
                    string msg = this.Model.GetValue("F_qaz_Text").ToString();
                    var entity = this.View.BillBusinessInfo.GetEntity("F_qaz_Entity");
                    var entityObjs = this.View.Model.GetEntityDataObject(entity);
                    string noexistent = "";//不存在数据
                    string repeat = "";//重复数据
                    if (entityObjs != null)
                    {
                        foreach (var entityObj in entityObjs)
                        {
                            if (entityObj["FNUMBER"].IsNullOrEmptyOrWhiteSpace()) break;
                            if (entityObj["F_FRONT"].IsNullOrEmptyOrWhiteSpace()) break;
                            var result = verification(entityObj["F_FRONT"].ToString(), msg);
                            if (result == 0)//如果==0，不存在
                            {
                                noexistent += entityObj["FNUMBER"].ToString() + "，";
                            }
                            else if (result > 1)//如果>1,重复多条
                            {
                                repeat += entityObj["FNUMBER"].ToString() + "，";
                            }
                        }
                    }
                    if (noexistent == "" && repeat == "")
                    {
                        this.View.ShowMessage("需替换规格的所有物料存在此规格，可以开始进行替换");
                        //按钮控制
                        this.Enablecontrol("F_qaz_Button", false);
                        this.Enablecontrol("F_qaz_Button1", true);
                        this.Enablecontrol("F_qaz_Text", false);
                        this.Enablecontrol("F_qaz_Text1", true);
                    }
                    else if (noexistent == "" && repeat != "")
                    {
                        this.View.ShowWarnningMessage("物料编码：" + repeat.Remove(repeat.LastIndexOf("，")) + "重复存在此规格，暂不能进行替换");

                    }
                    else if (noexistent != "" && repeat == "")
                    {
                        this.View.ShowWarnningMessage("物料编码：" + noexistent.Remove(noexistent.LastIndexOf("，")) + "不存在此规格，暂不能进行替换");

                    }
                    else
                    {
                        this.View.ShowWarnningMessage("物料编码：" + noexistent.Remove(noexistent.LastIndexOf("，")) + "不存在此规格，暂不能进行替换；物料编码：" + repeat.Remove(repeat.LastIndexOf("，")) + "重复存在此规格，暂不能进行替换");
                    }
                }

            }
            //开始替换
            if (e.Operation.FormOperation.Id == "F_qaz_Button1")
            {

                if (this.Model.GetValue("F_qaz_Text1").ToString() == "")
                {
                    this.View.ShowWarnningMessage("需替换成的规格不能为空");
                }
                else
                {
                    this.View.ShowMessage("该操作开始后不可逆转，需要确认是否继续？", MessageBoxOptions.OKCancel, new Action<MessageBoxResult>(result =>
                      {
                          if (result == MessageBoxResult.OK)
                          {
                              var rs = replace();
                              if (rs == "1")
                              {
                                  this.View.ShowMessage("替换成功！");
                                  //控件禁用
                                  this.Enablecontrol("F_qaz_Button", false);
                                  this.Enablecontrol("F_qaz_Button1", false);
                                  this.Enablecontrol("F_qaz_Text", false);
                                  this.Enablecontrol("F_qaz_Text1", false);
                                  string sql = @"select FNUMBER,F_QAZ_REMARK F_AFTER from t_BD_MATERIAL where EXISTS (SELECT 1 FROM TABLE(fn_StrSplit(@IDS,',',3)) B WHERE B.FID=t_BD_MATERIAL.FNUMBER)";
                                  DataTable dt = DBUtils.ExecuteDataSet(this.Context, sql, new SqlParam("@IDS", KDDbType.udt_nvarchartable, strl.ToArray())).Tables[0];
                                  for (int i = 0; i < dt.Rows.Count; i++)
                                  {
                                      this.View.Model.SetValue("F_AFTER", dt.Rows[i]["F_AFTER"].ToString(), i);
                                  }
                                  this.View.UpdateView("F_qaz_Entity");
                              }
                              else if (rs == "2")
                              {
                                  this.View.ShowMessage("替换失败！");
                              }
                              else
                              {
                                  this.View.ShowWarnningMessage("物料编码：" + replace() + "已经存着此规格！");
                              }

                          }
                          else if (result == MessageBoxResult.No)
                          {
                              this.View.ShowWarnningMessage("你取消了替换操作");
                          }
                      }));
                }

            }
        }
        //验证字段
        public int verification(string str, string str1)
        {
            //排除空格
            str = str. Replace(" ", "");
            str1 = str1.Replace(" ", "");
            //对特殊字符转义
            var Escape = Regex.Escape(str1);
            //定义规则
            string RegexStr1 = @"^" + Escape + "[,|，|。]";
            string RegexStr2 = @"[,|，|。]" + Escape + "$";
            string RegexStr3 = @"[,|，|。]" + Escape + "[,|，|。]";
            string RegexStr4 = @"^" + Escape + "$";
            //存在的话，累计存在的次数
            var mc = Regex.Matches(str, RegexStr1).Count;
            mc += Regex.Matches(str, RegexStr2).Count;
            mc += Regex.Matches(str, RegexStr3).Count;
            mc += Regex.Matches(str, RegexStr4).Count;
            return mc;
        }
        List<string> strl = new List<string>();//编号
                 
        //替换
        public string replace()
        {
            string front = this.Model.GetValue("F_qaz_Text").ToString();//需替换掉的字段
            string after = this.Model.GetValue("F_qaz_Text1").ToString();//需替换成的字段
                                                                         //获取单据体信息
            var entity = this.View.BillBusinessInfo.GetEntity("F_qaz_Entity");
            var entityObjs = this.View.Model.GetEntityDataObject(entity);
            string fnumber = "";

            List<string> str2 = new List<string>();//替换后
            string Cannotreplace = "";//替换后重复存在
            if (entityObjs != null)
            {
                foreach (var entityObj in entityObjs)
                {
                    // 遍历单据体数据    
                    if (entityObj["FNUMBER"].IsNullOrEmptyOrWhiteSpace()) break;
                    if (entityObj["F_FRONT"].IsNullOrEmptyOrWhiteSpace()) break;
                    strl.Add(entityObj["FNUMBER"].ToString());
                    fnumber += entityObj["FNUMBER"].ToString() + ",";
                    string strth = entityObj["F_FRONT"].ToString();
                    //查看是否重复存在
                    var result = verification(strth, after);
                    if (result == 0) //不存在，则替换
                    {
                        //排除空格
                        front = front.Replace(" ", "");
                        strth = strth.Replace(" ", "");
                        after = after.Replace(" ", "");
                        //对特殊字符转义
                        var Escape = Regex.Escape(front);
                        //定义规则
                        string RegexStr1 = @"^" + Escape + "[,|，|。]";
                        string RegexStr2 = @"[,|，|。]" + Escape + "$";
                        string RegexStr3 = @"[,|，|。]" + Escape + "[,|，|。]";
                        string RegexStr4 = @"^" + Escape + "$";
                        //定义保存需替换的规格
                        var str = "";
                        //根据规则，查找出需替换的规格
                        str += Regex.Match(strth, RegexStr1).ToString();
                        str += Regex.Match(strth, RegexStr2).ToString();
                        str += Regex.Match(strth, RegexStr3).ToString();
                        str += Regex.Match(strth, RegexStr4).ToString();
                        //替换
                        var afterstr = str.Replace(front, after);
                        var afterstrall = strth.Replace(str, afterstr);
                        //带入字段替换
                        str2.Add(afterstrall);
                    }
                    else//存在，则不替换
                    {
                        Cannotreplace += entityObj["FNUMBER"].ToString() + ",";
                    }
                }
                if (Cannotreplace != "")//存在重复规格的物料
                {
                    return Cannotreplace;
                }
                else
                {
                    if (strl.Count == 0 || str2.Count == 0)//编码和替换后字段为空
                    {
                        return "2";
                    }
                    else
                    {
                        List<SqlObject> sqllist = new List<SqlObject>();
                        for (int i = 0; i < strl.Count; i++)
                        {
                            string sql = @"update t_BD_MATERIAL set F_QAZ_REMARK='" + str2[i].ToString() + "' where FNUMBER='" + strl[i] + "'";
                            sqllist.Add(new SqlObject(sql, new List<SqlParam>()));
                        }

                        var a = DBUtils.ExecuteBatch(this.Context, sqllist);
                        if (a > 0)
                        {
                            return "1";//成功返回1
                        }
                    }
                }
            }
            return "2";//失败返回2
        }

    }
}
