using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using DeviceRepair.Models;
using DeviceRepair.Models.Device;
using DeviceRepair.Models.Enum;
using DeviceRepair.Models.Preserve;
using DeviceRepair.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using TsSFCDevice.Client.Biz.Base.Utils;
using TsSFCDevice.Client.Biz.Impl;

namespace TsSFCDevice.Client.Launch.CheckForm
{
    public partial class page_AssignDriveTree : ToolbarForm
    {
        private MaintenanceFormVersionInfo CurrentFormModel = null;
        private List<DeviceInformationInfoTree> RawData;
        private EnumDeviceBelong Belong = EnumDeviceBelong.PM;

        public page_AssignDriveTree() : this(null)
        {

        }

        public page_AssignDriveTree(MaintenanceFormVersionInfo FormModel)
        {
            InitializeComponent();
            CurrentFormModel = FormModel;

            if (CurrentFormModel != null)
            {
                txtFormName.Text = CurrentFormModel.FormName;
                txtRemarks.Text = CurrentFormModel.Remarks;
                txtVersionCode.Text = CurrentFormModel.VersionCode;
                txtVersionRev.Text = CurrentFormModel.VersionRev;
                rdo_FormStatus.EditValue = CurrentFormModel.FormStatus;
                Belong = CurrentFormModel.FormBelong == EnumDeviceBelong.PM.ToString() ? EnumDeviceBelong.PM : EnumDeviceBelong.AM;
            }

            this.Load += Page_AssignDriveTree_Load;
        }

        private void Page_AssignDriveTree_Load(object sender, EventArgs e)
        {
            try
            {
                tvDevices.BeforeCheckNode += tvDevices_BeforeCheckNode;
                tvDevices.AfterCheckNode += tvDevices_AfterCheckNode;

                InitializeGridData();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 勾选已绑定的设备
        /// </summary>
        private void SelectCurrentFormDevices()
        {
            switch (Belong)
            {
                case EnumDeviceBelong.AM:
                    RawData = RawData.Where(x => x.MaintenanceAMFormVersion == CurrentFormModel.AutoID).ToList();
                    break;
                case EnumDeviceBelong.PM:
                    RawData = RawData.Where(x => x.MaintenanceFormVersion == CurrentFormModel.AutoID).ToList();
                    break;
                default:
                    break;
            }

            if (RawData != null && RawData.Count > 0)
            {
                SelectTreeviewItems(tvDevices.Nodes, RawData);
            }
        }

        /// <summary>
        /// 勾选选项
        /// </summary>
        /// <param name="tvds"></param>
        /// <param name="auths"></param>
        private void SelectTreeviewItems(TreeListNodes tvds, List<DeviceInformationInfoTree> auths)
        {
            foreach (TreeListNode item in tvds)
            {
                var drv = tvDevices.GetDataRecordByNode(item) as DeviceInformationInfoTree;
                if (drv != null)
                {
                    int authID = drv.AutoID;
                    if (auths.Exists((A) => { return A.AutoID == authID; }))
                    {
                        item.Checked = true;
                    }
                    else
                    {
                        item.Checked = false;
                    }
                }
                else
                {
                    item.Checked = false;
                }
                if (item.HasChildren)
                {
                    item.CheckState = CheckState.Indeterminate;
                    SelectTreeviewItems(item.Nodes, auths);

                    var vFindUnChecked = item.Nodes.Where(A =>
                    {
                        return A.CheckState == CheckState.Unchecked;
                    });
                    if (vFindUnChecked != null)
                    {
                        if (vFindUnChecked.Count() == 0)
                        {
                            item.CheckState = CheckState.Checked;
                        }
                        else
                        {
                            if (vFindUnChecked.Count() == item.Nodes.Count)
                            {
                                item.CheckState = CheckState.Unchecked;
                            }
                            else
                            {
                                item.CheckState = CheckState.Indeterminate;
                            }
                        }
                    }
                    else
                    {
                        item.CheckState = CheckState.Checked;
                    }
                }
            }
        }

        /// <summary>
        /// 节点更改验证后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvDevices_AfterCheckNode(object sender, NodeEventArgs e)
        {
            SetCheckedChildNodes(e.Node, e.Node.CheckState);
            SetCheckedParentNodes(e.Node, e.Node.CheckState);
        }

        /// <summary>
        /// 节点更改验证前
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvDevices_BeforeCheckNode(object sender, CheckNodeEventArgs e)
        {
            e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
        }


        /// <summary>
        /// 设置子节点的状态
        /// </summary>
        /// <param name="node"></param>
        /// <param name="check"></param>
        private void SetCheckedChildNodes(TreeListNode node, CheckState check)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i].CheckState = check;
                SetCheckedChildNodes(node.Nodes[i], check);
            }
        }

        /// <summary>
        /// 设置父节点的状态
        /// </summary>
        /// <param name="node"></param>
        /// <param name="check"></param>
        private void SetCheckedParentNodes(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                bool bCheck = false;
                CheckState state;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    state = node.ParentNode.Nodes[i].CheckState;
                    if (!check.Equals(state))
                    {
                        bCheck = !bCheck;
                        break;
                    }
                }
                node.ParentNode.CheckState = bCheck ? CheckState.Indeterminate : check;
                SetCheckedParentNodes(node.ParentNode, check);
            }
        }

        void InitializeGridData()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();

                List<string> auths = new List<string>();
                if (Utility.SystemRuntimeInfo.AuthValidate(Utility.SystemRuntimeInfo.DEVICE_OEM))
                    auths.Add("OEM");
                if (Utility.SystemRuntimeInfo.AuthValidate(Utility.SystemRuntimeInfo.DEVICE_KH))
                    auths.Add("KH");

                DevRepository devDa = new DevRepository();
                IList<DeviceInformationInfoTree> Datas = devDa.GetTreeDatas(auths);
                RawData = Datas.ToList();

                tvDevices.DataSource = RawData;
                tvDevices.KeyFieldName = "RouteAutoId";
                tvDevices.ParentFieldName = "ParentRouteId";
                tvDevices.ExpandAll();
                tvDevices.BestFitColumns();

                SelectCurrentFormDevices();
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 获取选中的节点对象
        /// </summary>
        private List<DeviceInformationInfoTree> deviceLst = new List<DeviceInformationInfoTree>();//所选择的权限的ID集合
        private void GetCheckedAuthorizatioId(TreeListNode parentNode)
        {
            if (parentNode.Nodes.Count == 0)
            {
                return;//递归终止
            }
            foreach (TreeListNode node in parentNode.Nodes)
            {
                if (node.CheckState == CheckState.Checked || node.CheckState == CheckState.Indeterminate)
                {
                    var drv = tvDevices.GetDataRecordByNode(node) as DeviceInformationInfoTree;
                    if (drv != null && drv.AutoID != 0)
                        deviceLst.Add(drv);
                }
                GetCheckedAuthorizatioId(node);
            }
        }

        private void bBtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            try
            {
                deviceLst.Clear();
                if (tvDevices.Nodes.Count > 0)
                {
                    foreach (TreeListNode root in tvDevices.Nodes)
                    {
                        if (root.Nodes.Count == 0 && root.CheckState == CheckState.Checked)
                        {
                            var drv = tvDevices.GetDataRecordByNode(root) as DeviceInformationInfoTree;
                            if (drv != null && drv.AutoID != 0)
                                deviceLst.Add(drv);
                        }
                        else
                        {
                            GetCheckedAuthorizatioId(root);
                        }
                    }
                }

                // 当前数据库已经设定的数据
                List<DeviceInformationInfoTree> OldFormDatas = new List<DeviceInformationInfoTree>();
                switch (Belong)
                {
                    case EnumDeviceBelong.AM:
                        OldFormDatas = RawData.Where(x => x.MaintenanceAMFormVersion == CurrentFormModel.AutoID && x.EquipmentStatus == 1).ToList();
                        break;
                    case EnumDeviceBelong.PM:
                        OldFormDatas = RawData.Where(x => x.MaintenanceFormVersion == CurrentFormModel.AutoID && x.EquipmentStatus == 1).ToList();
                        break;
                    default:
                        break;
                }

                // 待删除的对象
                List<DeviceInformationInfoTree> RemoveData = OldFormDatas.Except(deviceLst).ToList();

                // 待新增的对象
                List<DeviceInformationInfoTree> InsertData = deviceLst.Except(OldFormDatas).ToList();

                List<SubmitAssignFormsToDevices> subDatas = new List<SubmitAssignFormsToDevices>();
                foreach (DeviceInformationInfoTree item in InsertData)
                {
                    subDatas.Add(new SubmitAssignFormsToDevices
                    {
                        EquipmentAutoID = item.AutoID,
                        EquipmentID = item.EquipmentID,
                        EquipmentName = item.EquipmentName,
                        FormAutoID = CurrentFormModel.AutoID,
                        FormName = CurrentFormModel.FormName,
                        OperationType = EnumOperationType.Bind,
                        Specification = item.Specification,
                        VersionCode = CurrentFormModel.VersionCode,
                        VersionRev = CurrentFormModel.VersionRev,
                        Belong = Belong
                    });
                }

                foreach (DeviceInformationInfoTree item in RemoveData)
                {
                    subDatas.Add(new SubmitAssignFormsToDevices
                    {
                        EquipmentAutoID = item.AutoID,
                        EquipmentID = item.EquipmentID,
                        EquipmentName = item.EquipmentName,
                        FormAutoID = CurrentFormModel.AutoID,
                        FormName = CurrentFormModel.FormName,
                        OperationType = EnumOperationType.UnBind,
                        Specification = item.Specification.IsNull() ? "" : item.Specification,
                        VersionCode = CurrentFormModel.VersionCode,
                        VersionRev = CurrentFormModel.VersionRev
                    });
                }

                if (subDatas.Count == 0)
                {
                    this.DialogResult = DialogResult.OK;
                    splashScreenManager1.TryCloseWait();
                    return;
                }

                APIResponseData apiResponseData = CheckFormRepository.Instance.AssigFormToDevice(subDatas);
                if (apiResponseData.Code != 1)
                    throw new Exception(apiResponseData.Message);

                this.DialogResult = DialogResult.OK;
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}