using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Common;
using DeviceRepair.Models.View;
using DeviceRepair.Models.Preserve;
using DeviceRepairAndOptimization.Biz;

namespace DeviceRepairAndOptimization.Pages.DriveMaintenance
{
    /// <summary>
    /// 点检表分配到设备
    /// </summary>
    public partial class Page_AssignDrives : ToolbarForm
    {
        private MaintenanceFormVersionInfo CurrentFormModel = null;
        private List<View_AssignMaintenanceFormTree> RawData;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="FormModel"></param>
        public Page_AssignDrives(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;
            }

            this.Load += Page_AssignDrives_Load;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Page_AssignDrives_Load(object sender, EventArgs e)
        {
            try
            {
                tvDevices.BeforeCheckNode += tvDevices_BeforeCheckNode;
                tvDevices.AfterCheckNode += tvDevices_AfterCheckNode;

                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = FormManager.Instance.GetDeviceInformationTreeView();
                if (apiResponseData.Code != 1)
                    throw new Exception(apiResponseData.Message);

                RawData = apiResponseData.ToDeserializeObject<List<View_AssignMaintenanceFormTree>>();
                tvDevices.DataSource = RawData.ToList();
                tvDevices.KeyFieldName = "TreeId";
                tvDevices.ParentFieldName = "ParentId";
                tvDevices.ExpandAll();

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

        /// <summary>
        /// 勾选已绑定的设备
        /// </summary>
        private void SelectCurrentFormDevices()
        {
            RawData = RawData.Where(x => x.MaintenanceFormVersion == CurrentFormModel.AutoID).ToList();
            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<View_AssignMaintenanceFormTree> auths)
        {
            foreach (TreeListNode item in tvds)
            {
                var drv = tvDevices.GetDataRecordByNode(item) as View_AssignMaintenanceFormTree;
                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);
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            try
            {
                if (tvDevices.Nodes.Count > 0)
                {
                    foreach (TreeListNode root in tvDevices.Nodes)
                    {
                        GetCheckedAuthorizatioId(root);
                    }
                }

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

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

                List<SubmitAssignFormsToDevices> subDatas = new List<SubmitAssignFormsToDevices>();
                foreach (View_AssignMaintenanceFormTree 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
                    });
                }

                foreach (View_AssignMaintenanceFormTree 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,
                        VersionCode = CurrentFormModel.VersionCode,
                        VersionRev = CurrentFormModel.VersionRev
                    });
                }

                APIResponseData apiResponseData = FormManager.Instance.AssigningFormToDevices(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);
            }
        }

        /// <summary>
        /// 获取选中的节点对象
        /// </summary>
        private List<View_AssignMaintenanceFormTree> deviceLst = new List<View_AssignMaintenanceFormTree>();//所选择的权限的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 View_AssignMaintenanceFormTree;
                    if (drv != null)
                        deviceLst.Add(drv);
                }
                GetCheckedAuthorizatioId(node);
            }
        }
    }
}