using System;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using KGIS.Framework.EngineEditor;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
namespace Kingo.Plugin.EngineEditor.Commands.Tools
{
    public class CmdUpdateZZBGJCBHTool : BaseToolCmd
    {
        IFeatureLayer m_Layer;
        public override void OnCreate(object hook)
        {
            base.OnCreate(hook);
        }
        public override bool Deactivate()
        {
            base.Deactivate();
            this.m_deactivate = true;
            return this.m_deactivate;
        }
        public override void OnClick()
        {
            base.OnClick();
            //if (mapService == null)
            //    mapService = MapsManager.Instance.MapService;
            ICursor pCur = null;
            IRow pRow = null;
            IFeatureCursor InsertCursor = null;
            IFeature feature = null;
            try
            {
                m_Layer = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("自主变更图斑");
                Platform.Instance.Progress.ShowProgressBar("正在更新自主变更图斑监测编号……");
                string where = "";
                IQueryDef pQDef = ((m_Layer.FeatureClass as FeatureClass).Workspace as IFeatureWorkspace).CreateQueryDef();
                pQDef.Tables = "BHTB";
                pQDef.WhereClause = "SJLY='2' GROUP BY JCBH having count(*)>1";
                pQDef.SubFields = "JCBH,count(*)";
                pCur = pQDef.Evaluate();
                while ((pRow = pCur.NextRow()) != null)
                {
                    where += "'" + pRow.get_Value(0).ToString() + "',";
                }
                if (!string.IsNullOrEmpty(where))
                {
                    where = where.TrimEnd(',');
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = "JCBH in (" + where + ")";
                    InsertCursor = m_Layer.FeatureClass.Update(queryFilter, true);
                    while ((feature = InsertCursor.NextFeature()) != null)
                    {
                        string jcbh = GetMaxJCBH(m_Layer.FeatureClass, feature.Value[feature.Fields.FindField("XZQDM")].ToString());
                        feature.Value[feature.Fields.FindField("JCBH")] = jcbh;
                        InsertCursor.UpdateFeature(feature);
                    }
                    InsertCursor.Flush();
                }
                Platform.Instance.Progress.CloseProgressBar();
                MessageHelper.Show("更新成功!");
            }
            catch (Exception ex)
            {
                Platform.Instance.Progress.CloseProgressBar();
                LogAPI.Debug(ex);
                MessageHelper.ShowError("更新失败!");
            }
            finally
            {
                if (InsertCursor!=null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(InsertCursor);
                }
            }
        }
        private int maxXH = 0;
        /// 
        /// 生成JCBH
        /// 
        /// 
        /// 
        /// 
        private string GetMaxJCBH(IFeatureClass fc, string xzqdm)
        {
            string JCBH = "";
            string start_jcbh = xzqdm + "DF";
            if (maxXH > 0)
            {
                maxXH++;
            }
            else
            {
                IQueryFilter QueryFilter = new QueryFilterClass();
                QueryFilter.WhereClause = "SJLY='2'";
                if (fc.FeatureCount(QueryFilter) == 0)
                {
                    maxXH = 1;
                }
                else
                {
                    int JCBHIndex = fc.FindField("JCBH");
                    ITable table = (ITable)fc;
                    // 创建一个ITableSort接口对象
                    ITableSort tableSort = new TableSortClass();
                    tableSort.Table = table;
                    tableSort.QueryFilter = QueryFilter;
                    tableSort.Fields = "JCBH";
                    tableSort.set_Ascending("JCBH", false);
                    tableSort.Sort(null);
                    ICursor cursor = tableSort.Rows;
                    IRow row = cursor.NextRow();
                    if (row != null)
                    {
                        int maxBSM = 0;
                        int currBSM = 0;
                        string BSMStr = row.Value[JCBHIndex].ToString();
                        string subBSMStr = BSMStr.Substring(8);
                        try
                        {
                            currBSM = Convert.ToInt32(subBSMStr);
                        }
                        catch (Exception)
                        {
                            return JCBH;
                        }
                        if (currBSM > maxBSM) maxBSM = currBSM;
                        maxBSM++;
                        maxXH = maxBSM;
                    }
                }
            }
            int zeroNum = 5 - maxXH.ToString().Length;
            string maxStr = maxXH.ToString();
            for (int i = 0; i < zeroNum; i++)
            {
                maxStr = 0 + maxStr;
            }
            JCBH = start_jcbh + maxStr;
            return JCBH;
        }
        public override bool Enabled
        {
            get
            {
                //if (m_pEditor == null)
                //{
                //    return false;
                //}
                //if (m_pEditor.EditState != esriEngineEditState.esriEngineStateEditing)
                //{ return false; }
                //if ((m_pEditor as EngineEditorClass).TargetLayer == null)
                //{ return false; }
                return true;
            }
        }
        public override void Refresh(int hDC)
        {
        }
    }
}