using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using QMAPP.FJC.Entity.Basic;
using QMAPP.FJC.Entity.Operation;
using QMAPP.ServicesAgent;
using QMAPP.Entity;
using QMAPP.MD.Entity;

namespace QMAPP.WinForm.Forms.Mend
{
    public partial class ReplaceForm : Form
    {
        /// <summary>
        /// 条码格式规则列表
        /// </summary>
        private List<BarcodeRules> _barcodeRules;

        //获取服务代理
        readonly ServiceAgent _agent = ClientContext.GetServiceAgent();
        private Product _product;
        private Product _productReplace;
        private Product _productMaterialCode;
        private List<Product> _productMaterialCodeList;
        public ReplaceForm()
        {
            InitializeComponent(); 
        }

        private void ReplaceForm_Load(object sender, EventArgs e)
        {
            _barcodeRules = _agent.InvokeServiceFunction<List<BarcodeRules>>(B9BasicService.BarcodeRulesBLL_GetAllList.ToString());
            init();
        }

        private void init()
        {
            lblMainMaterialCode.Text = "";
            lblMainMaterialName.Text = "";
            lblPartMaterialCode.Text = "";
            lblPartMaterialName.Text = "";
            txtProcessCode.Focus();
            txtProcessCode.Text = "";
            txtProcessCode.Enabled = true;
            txtReplaceCode.Enabled = false;
            txtReplaceCode.Text = "";
            butReplace.Enabled = false;
            infolabel.Text = "";
            infolabel.ForeColor = Color.Red;
        }
        private void txtProcessCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)//如果输入的是回车键
            {
                return;
            }
            ScanProcessCode();
        }
        //扫描主体条码
        private void ScanProcessCode()
        {
            if (string.IsNullOrWhiteSpace(txtProcessCode.Text.Trim()))
            {
                infolabel.Text = "请扫描条码!";
                txtProcessCode.Focus();
                return;
            }

            _product = _agent.InvokeServiceFunction<Product>("ProductBLL_GetProductByAssembleCode", txtProcessCode.Text.Trim());
            if (_product == null)
            {
                infolabel.Text = "扫描条码不存在!";
                txtProcessCode.SelectAll();
                txtProcessCode.Focus();
                return;
            }
            if (_product.OUTFLAG == "1")
            {
                infolabel.Text = "扫描条码不在库!";
                txtProcessCode.SelectAll();
                txtProcessCode.Focus();
                return;
            }
            if (_product.STATUS == "2")
            {
                infolabel.Text = "扫描条码是报废状态,不允许替换!";
                txtProcessCode.SelectAll();
                txtProcessCode.Focus();
                return;
            }
            var mresult = _agent.InvokeServiceFunction<DataResult<Material>>("MaterialBLL_Get", new Material { MATERIAL_CODE = _product.MATERIAL_CODE });
            var m = mresult.IsSuccess ? mresult.Result : new Material { };
            

            lblMainMaterialCode.Text = _product.MATERIAL_CODE;
            lblMainMaterialName.Text = m.MATERIAL_NAME;

            
            //替换条码获得焦点
            txtProcessCode.Enabled = false;
            txtReplaceCode.Enabled = true;
            txtReplaceCode.Focus();
            txtReplaceCode.Text = "";
            butReplace.Enabled = false;
            //清空提示框
            infolabel.Text = "";
        }

        private void txtReplaceCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)//如果输入的是回车键
            {
                return;
            }
            ScanReplaceCode();
        }

        //扫描替换条码
        private void ScanReplaceCode()
        {
            if (string.IsNullOrWhiteSpace(txtReplaceCode.Text.Trim()))
            {
                infolabel.Text = "请扫描条码!";
                txtReplaceCode.Focus();
                return;
            }
            txtReplaceCode.Text=txtReplaceCode.Text.Trim().ToUpper();

            BarcodeRules matched = null;

            foreach (var rule in _barcodeRules)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(txtReplaceCode.Text, rule.REGEX))
                {
                    matched = rule;
                    break;
                }
            }
            if (matched == null)
            {
                infolabel.Text = "扫描条码格式无法识别!";
                txtReplaceCode.SelectAll();
                txtReplaceCode.Focus();
                return;
            }
            if (matched.DATA_TYPE != "MC")
            {
                _productReplace = _agent.InvokeServiceFunction<Product>("ProductBLL_GetProductByAssembleCode", txtReplaceCode.Text.Trim());
                if (_productReplace == null)
                {
                    if (string.IsNullOrWhiteSpace(matched.MATERIAL_CODE))
                    {
                        infolabel.Text = "扫描条码不存在!";
                        txtReplaceCode.SelectAll();
                        txtReplaceCode.Focus();
                        return;
                    }
                    else
                    {
                        var mresult = _agent.InvokeServiceFunction<DataResult<Material>>("MaterialBLL_Get", new Material { MATERIAL_CODE = matched.MATERIAL_CODE });
                        var m = mresult.IsSuccess ? mresult.Result : new Material { };
                        if (m.OUTSOURCE == "1")
                        {
                            _productReplace = new Product()
                            {
                                PID = "",//Guid.NewGuid().ToString(),
                                CAPACITY = m.STD_QTY,
                                CREATEDATE = DateTime.Now,
                                CREATEUSER = "",
                                MATERIAL_CODE = m.MATERIAL_CODE,
                                MATERIAL_NAME=m.MATERIAL_NAME,
                                OUTFLAG = "0",
                                PRODUCESHIFTTCODE = "",
                                PRODUCTCODE = txtReplaceCode.Text,
                                PRODUCTSOURCE = "1",
                                STATUS = "0",
                                USINGCOUNT = 0,
                                USINGSTATE = "0",
                                WORKCELL_CODE = "",
                                WORKCENTER_CODE = "",
                                WORKLOC_CODE = "",
                                TEAM_CODE = "",
                                MATERIAL_TYPE = m.MATERIAL_TYPE_CODE //data.DAI.MATERIAL_TYPE
                            };
                        }
                        else
                        {
                            infolabel.Text = "扫描条码不存在!";
                            txtReplaceCode.SelectAll();
                            txtReplaceCode.Focus();
                            return;
                        }
                    }
                }
                if (_productReplace.OUTFLAG == "1")
                {
                    infolabel.Text = "扫描条码不在库!";
                    txtReplaceCode.SelectAll();
                    txtReplaceCode.Focus();
                    return;
                }
                if (_productReplace.STATUS == "2")
                {
                    infolabel.Text = "扫描条码是报废状态,不允许替换!";
                    txtReplaceCode.SelectAll();
                    txtReplaceCode.Focus();
                    return;
                }
                if (_productReplace.USINGSTATE != "0")
                {
                    infolabel.Text = "扫描条码不是未使用状态,不允许替换!";
                    txtReplaceCode.SelectAll();
                    txtReplaceCode.Focus();
                    return;
                }
                if (_productReplace.USINGCOUNT >= _productReplace.CAPACITY)
                {
                    infolabel.Text = "扫描条码使用数量不足,不允许替换!";
                    txtReplaceCode.SelectAll();
                    txtReplaceCode.Focus();
                    return;
                }
                var mresult1 = _agent.InvokeServiceFunction<DataResult<Material>>("MaterialBLL_Get", new Material { MATERIAL_CODE = _productReplace.MATERIAL_CODE });
                var m1 = mresult1.IsSuccess ? mresult1.Result : new Material { };
                _productReplace.MATERIAL_NAME = m1.MATERIAL_NAME;
            }
            else
            {
                Material m;
                if (string.IsNullOrWhiteSpace(matched.MATERIAL_CODE))
                {
                    var mresult = _agent.InvokeServiceFunction<DataResult<Material>>("MaterialBLL_GetWithAnyFormate", txtReplaceCode.Text);
                    m = mresult.IsSuccess ? mresult.Result : new Material { };
                }
                else
                {
                    var mresult = _agent.InvokeServiceFunction<DataResult<Material>>("MaterialBLL_Get", new Material { MATERIAL_CODE = matched.MATERIAL_CODE });
                    m = mresult.IsSuccess ? mresult.Result : new Material { };
                }
                if (m == null)
                {
                    infolabel.Text = "扫描条码无法识别!";
                    txtReplaceCode.SelectAll();
                    txtReplaceCode.Focus();
                    return;
                }
                _productReplace = new Product()
                {
                    PID = "",//Guid.NewGuid().ToString(),
                    CAPACITY = m.STD_QTY,
                    CREATEDATE = DateTime.Now,
                    CREATEUSER = "",
                    MATERIAL_CODE = m.MATERIAL_CODE,
                    MATERIAL_NAME = m.MATERIAL_NAME,
                    OUTFLAG = "0",
                    PRODUCESHIFTTCODE = "",
                    PRODUCTCODE = "",//txtReplaceCode.Text,
                    PRODUCTSOURCE = "1",
                    STATUS = "0",
                    USINGCOUNT = 0,
                    USINGSTATE = "0",
                    WORKCELL_CODE = "",
                    WORKCENTER_CODE = "",
                    WORKLOC_CODE = "",
                    TEAM_CODE = "",
                    MATERIAL_TYPE = m.MATERIAL_TYPE_CODE //data.DAI.MATERIAL_TYPE
                };
            }

            lblPartMaterialCode.Text = _productReplace.MATERIAL_CODE;
            lblPartMaterialName.Text = _productReplace.MATERIAL_NAME;

            List<MD.Entity.PbomItem> SubItems = _agent.InvokeServiceFunction<List<MD.Entity.PbomItem>>("PbomBLL_GetSubItem", _product.MATERIAL_CODE);

            if(!SubItems.Exists(p=>p.MATERIAL_CODE==_productReplace.MATERIAL_CODE))
            {
                infolabel.Text = "扫描条码零件号与主体配置不匹配,不允许替换!";
                txtReplaceCode.SelectAll();
                txtReplaceCode.Focus();
                return;
            }
            var bomitem = SubItems.FirstOrDefault(p => p.MATERIAL_CODE == _productReplace.MATERIAL_CODE);
            if (string.IsNullOrWhiteSpace(_productReplace.PID))
            {
                _productReplace.WORKCELL_CODE = bomitem.GMP;
            }

            if (!string.IsNullOrWhiteSpace(_productReplace.PRODUCTCODE))
            {
                _productMaterialCodeList = _agent.InvokeServiceFunction<List<Product>>("ProductBLL_GetMainProductMaterialCodeList", _product.PRODUCTCODE);

                if (_productMaterialCodeList != null && _productMaterialCodeList.Count > 0)
                {
                    _productMaterialCode =
                        _productMaterialCodeList.FirstOrDefault(x => x.MATERIAL_CODE == _productReplace.MATERIAL_CODE);
                    if (_productMaterialCode != null && _productMaterialCode.PRODUCTCODE == _product.PRODUCTCODE)
                    {
                        infolabel.Text = "扫描条码零件号为主体零件,无法替换!";
                        txtReplaceCode.SelectAll();
                        txtReplaceCode.Focus();
                        return;
                    }
                    if (_productMaterialCode == null)
                    {
                        _productMaterialCode = new Product();
                    }
                }
            }
            //替换按钮启用
            butReplace.Enabled = true;
            //清空提示框
            infolabel.Text = "";
        }

        
        private void butReplace_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(_productReplace.PRODUCTCODE))
            {
                var replace = _agent.InvokeServiceFunction<int>("ProductBLL_ReplaceProductMaterialCode", _product, _productMaterialCode, _productReplace);
                if (replace == 0)
                {
                    infolabel.Text = "替换失败!";
                    return;
                }
            }
            init();
            MessageBox.Show("替换成功!");
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            init();
        }

        
    }
}