﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LJH.Inventory.BLL;
using LJH.Inventory.BusinessModel;
using LJH.Inventory.BusinessModel.SearchCondition;
using LJH.GeneralLibrary;
using LJH.GeneralLibrary.Core.DAL;
using LJH.GeneralLibrary.Core.UI;

namespace LJH.Inventory.UI.Forms.General
{
    public partial class FrmProductMaster : FrmMasterBase
    {
        public FrmProductMaster()
        {
            InitializeComponent();
        }

        #region 私有变量
        List<Product> _Products = null;
        #endregion

        public ItemClass ProductClass { get; set; }

        public string SupplierID { get; set; }

        #region 私有方法
        private void FreshData()
        {
            List<object> items = FilterData();
            ShowItemsOnGrid(items);
        }

        private List<object> FilterData()
        {
            List<Product> items = _Products.ToList();
            List<ItemCategory> pc = null;
            if (this.categoryTree.SelectedNode != null && this.categoryTree.SelectedNode.Tag != null)
            {
                pc = this.categoryTree.GetCategoryofNode(this.categoryTree.SelectedNode);
            }
            if (pc != null && pc.Count > 0) items = items.Where(it => pc.Exists(p => p.ID == it.CategoryID)).ToList();
            if (!string.IsNullOrEmpty(txtProductName.Text)) items = items.Where(it => it.Name.Contains(txtProductName.Text)).ToList();
            if (!string.IsNullOrEmpty(SupplierID)) items.RemoveAll(it =>
            {
                var temp = it.GetProperty(ItemNote.厂家);
                return string.IsNullOrEmpty(temp) || !temp.Contains(SupplierID);
            });
            return (from p in items
                    orderby p.CategoryID ascending, p.Name ascending, p.Specification ascending
                    select (object)p).ToList();
        }
        #endregion

        #region 重写基类方法
        protected override void Init()
        {
            base.Init();
            if (!string.IsNullOrEmpty(SupplierID))
            {
                var s = new CompanyBLL(AppSettings.Current.ConnStr).GetByID(SupplierID).QueryObject;
                txtSupplier.Text = s != null ? s.Name : null;
            }
            if (ProductClass == ItemClass.商品)
            {
                lnkSupplier.Visible = false;
                txtSupplier.Visible = false;
            }
        }

        public override DataGridView GridView
        {
            get
            {
                return this.dataGridView1;
            }
        }

        public override void ReFreshData()
        {
            this.categoryTree.Init(ProductClass);
            base.ReFreshData();
        }

        public override void ShowOperatorRights()
        {
            base.ShowOperatorRights();
            this.cMnu_Add.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Product, PermissionActions.Edit);
            this.cMnu_Edit.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Product, PermissionActions.Edit);
            this.cMnu_Delete.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Product, PermissionActions.Edit);
            this.mnu_合并到.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Product, PermissionActions.Edit);
            this.mnu_合并到.Visible = AppSettings.Current.OperatorPara.IsAdmin;
            this.mnu_AddCategory.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Product, PermissionActions.Edit);
            this.mnu_DeleteCategory.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Product, PermissionActions.Edit);
            this.mnu_CategoryProperty.Enabled = AppSettings.Current.OperatorPara.Permit(Permission.Product, PermissionActions.Edit) || AppSettings.Current.OperatorPara.Permit(Permission.Product, PermissionActions.Read);
        }

        protected override FrmDetailBase GetDetailForm()
        {
            if (ProductClass == ItemClass.其它费用)
            {
                var frm = new Frm其它费用();
                return frm;
            }
            else
            {
                FrmProductDetail frm = new FrmProductDetail();
                if (categoryTree.SelectedNode != null) frm.Category = categoryTree.SelectedNode.Tag as ItemCategory;
                frm.ProductClass = ProductClass;
                return frm;
            }
        }

        protected override List<object> GetDataSource()
        {
            if (SearchCondition == null)
            {
                ProductSearchCondition con = new ProductSearchCondition();
                con.Classes = new List<BusinessModel.ItemClass>() { ProductClass };
                _Products = (new ProductBLL(AppSettings.Current.ConnStr)).GetItems(con).QueryObjects;
            }
            else
            {
                _Products = (new ProductBLL(AppSettings.Current.ConnStr)).GetItems(SearchCondition).QueryObjects;
            }
            if (_Products != null) _Products.RemoveAll(it => it.ClassID != ProductClass);

            List<object> records = FilterData();
            return records;
        }

        protected override void ShowItemInGridViewRow(DataGridViewRow row, object item)
        {
            Product p = item as Product;
            row.Tag = p;
            row.Cells["colImage"].Value = Properties.Resources.product;
            row.Cells["colID"].Value = p.ID;
            row.Cells["colName"].Value = p.Name;
            ItemCategory pc = categoryTree.GetItemCategory(p.CategoryID);
            row.Cells["colCategoryID"].Value = pc != null ? pc.Name : string.Empty;
            row.Cells["colSpecification"].Value = p.Specification;
            row.Cells["colModel"].Value = p.Model;
            row.Cells["colUnit"].Value = p.Unit;
            row.Cells["col库存单位"].Value = p.InventoryUnit;
            //row.Cells["colIsService"].Value = p.IsService;
            row.Cells["colMemo"].Value = p.Memo;
            if (_Products == null || !_Products.Exists(it => it.ID == p.ID))
            {
                if (_Products == null) _Products = new List<Product>();
                _Products.Add(p);
            }
        }

        protected override bool DeletingItem(object item)
        {
            Product p = item as Product;
            CommandResult ret = (new ProductBLL(AppSettings.Current.ConnStr)).Delete(p);
            if (ret.Result != ResultCode.Successful)
            {
                MessageBox.Show(ret.Message);
            }
            else
            {
                _Products.Remove(p);
            }
            return ret.Result == ResultCode.Successful;
        }

        private void mnu_合并到_Click(object sender, EventArgs e)
        {
            if (this.GridView.SelectedRows.Count == 1)
            {
                var c = this.GridView.SelectedRows[0].Tag as Product;
                var frm = new Frm产品合并();
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.Source = c;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    cMnu_Fresh.PerformClick();
                }
            }
        }
        #endregion

        #region 类别树右键菜单
        private void categoryTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            FreshData();
        }

        private void txtProductName_TextChanged(object sender, EventArgs e)
        {
            FreshData();
        }

        private void mnu_AddCategory_Click(object sender, EventArgs e)
        {
            ItemCategory pc = categoryTree.SelectedNode.Tag as ItemCategory;
            var frm = new FrmItemCategoryDetail();
            frm.IsAdding = true;
            frm.ParentCategory = pc;
            frm.ItemClassID= ProductClass;
            frm.ItemAdded += delegate(object obj, ItemAddedEventArgs args)
            {
                ItemCategory item = args.AddedItem as ItemCategory;
                this.categoryTree.AddItemCategoryNode(item, categoryTree.SelectedNode);
                categoryTree.SelectedNode.Expand();
            };
            frm.ShowDialog();
        }

        private void mnu_AddProduct_Click(object sender, EventArgs e)
        {
            PerformAddData();
        }

        private void mnu_DeleteCategory_Click(object sender, EventArgs e)
        {
            ItemCategory pc = categoryTree.SelectedNode.Tag as ItemCategory;
            if (pc != null && MessageBox.Show("是否删除此类别及其子项?", "询问", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
            {
                CommandResult ret = (new ItemCategoryBLL(AppSettings.Current.ConnStr)).Delete(pc);
                if (ret.Result == ResultCode.Successful)
                {
                    categoryTree.SelectedNode.Parent.Nodes.Remove(categoryTree.SelectedNode);
                }
                else
                {
                    MessageBox.Show(ret.Message);
                }
            }
        }

        private void mnu_CategoryProperty_Click(object sender, EventArgs e)
        {
            ItemCategory pc = categoryTree.SelectedNode.Tag as ItemCategory;
            var frm = new FrmItemCategoryDetail();
            frm.IsAdding = false;
            frm.UpdatingItem = pc;
            frm.ItemUpdated += delegate(object obj, ItemUpdatedEventArgs args)
            {
                categoryTree.Init(ItemClass.商品);
                categoryTree.SelectItemCategoryNode(pc.ID);
                FreshData();
            };
            frm.ShowDialog();
        }

        private void lnkSupplier_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var frm = new FrmCompanyMaster();
            frm.CompanyClass = ItemClass.供应商;
            frm.ForSelect = true;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                var s = frm.SelectedItem as Company;
                txtSupplier.Text = s != null ? s.Name : string.Empty;
                SupplierID = s.ID;
                FreshData();
            }
        }

        private void txtSupplier_DoubleClick(object sender, EventArgs e)
        {
            SupplierID = null;
            txtSupplier.Text = string.Empty;
            FreshData();
        }
        #endregion

    }
}
