using System;
using System.Collections.Generic;
using MeterConditionLibrary;
using com.hnshituo.core.webapp.vo;
using Common;

namespace MeterSceneLibrary
{
    /// <summary>
    /// 联达的过磅，只有先毛后皮
    /// 且预报号是扫码的预报号加上“_”
    /// </summary>
    public class LianDaMeter
    {
        private MeterBaseTermTareDataService termTareDate = new MeterBaseTermTareDataService();//期限皮操作

        /// <summary>
        /// 先毛后皮 根据计量流程配置界面中配置的基础数据可知业务是先毛后皮
        /// </summary>
        /// <param name="scale">计量预报</param>
        /// <returns></returns>
        public rtInfo MeterMethod(PreTrackScale scale, CoreAppUser appUser,int lianDaWgt)
        {
            if (appUser == null)
            {
                appUser = new CoreAppUser()
                {
                    userClass = "",
                    userid = "",
                    userGroup = "",
                    username = ""
                };
            }

            rtInfo rt = new rtInfo();
            rt.isError = false;

            //0：批次预报；1：单次预报；2：联运预报；3：分检预报
            if (scale.predictionType == "2")
            {
                rt.result = false;
                rt.isError = false;
                return rt;
            }

            //如果配置了则走下面的流程
            //如果存在一次计量未结净数据，则认为是结净计量，否则认为一次计量
            MeterWorkCarActualFirstService mwcfs = new MeterWorkCarActualFirstService();
            RESTfulResult<List<MeterWorkCarActualFirst>> rmFst = mwcfs.doQueryWf(new MeterWorkCarActualFirst { valueFlag = "1", carNo = scale.carNo });
            RESTfulResult<List<MeterWorkCarActualFirst>> rmX = mwcfs.doQueryWf(new MeterWorkCarActualFirst { valueFlag = "1", predictionNo = scale.predictionNo + "_", carNo = scale.carNo });
            if (!rmX.Succeed || !rmFst.Succeed)
            {
                rt.result = false;
                rt.resultInfo = "没有计量信息点语音求助";
                PbCache.ResultMessage = "获取一次计量数据异常！";
                rt.isError = true;
            }

            //因为是先皮后毛流程，当前为过皮重
            if (rmFst.Data == null || rmFst.Data.Count == 0)
            {
                //验证两次计量时间间隔
                validTimeInterval vti = new validTimeInterval();
                vti.ValidMethod(scale, "2", null);
                if (!PbCache.monitorResult.valid_time_interval)
                {
                    rt.result = false;
                    rt.isError = true;
                    rt.resultInfo = PbCache.ResultMessage;
                    return rt;
                }
                //验证当前皮重是否符合要求；不符合则存毛重
                validWgt vw = new validWgt();
                vw.ValidNotInnerMethod(scale);
                if (PbCache.monitorResult.valid_wgt)
                {
                    //保存皮重信息***********************
                    MeterWorkCarActualFirst mwaf = new MeterWorkCarActualFirst();

                    //相同名称的均赋值一次
                    EntityBase<PreTrackScale> entityBase = new EntityBase<PreTrackScale>();
                    scale.predictionNo = scale.predictionNo + "_";
                    mwaf = entityBase.format<MeterWorkCarActualFirst>(scale, mwaf);
                    mwaf.actualFirstNo = DateTime.Now.ToString("yyyyMMdd");//10
                    mwaf.meterWeight = PbCache.lockWgt;//计量重量
                    //mwaf.addWeight = 0;//附加重量
                    mwaf.weightType = "1"; //0=毛重；1=常规皮重；2=期限皮重；3=历史皮重；4=标识皮重；5=自重皮重
                    mwaf.createManNo = appUser.userid;
                    mwaf.createManName = appUser.username;
                    mwaf.meterGroup = appUser.userGroup;
                    mwaf.meterClass = appUser.userClass;
                    mwaf.createTime = DateTime.Now;
                    mwaf.baseSpotNo = PbCache.sportInfo.baseSpotNo;//计量点编号
                    mwaf.baseSpotName = PbCache.sportInfo.baseSpotName;
                    //mwaf.memo = "";
                    mwaf.valueFlag = "1"; //0有效
                    mwaf.updateManName = "";
                    mwaf.updateManNo = "";
                    mwaf.matterName = mwaf.matterName + "-复磅对比";
                    mwaf.updateTime = null;
                    mwaf.checkFlag = "0"; //0未审核
                    mwaf.meterMode = string.IsNullOrEmpty(appUser.userid) ? "2" : "1"; //1远程计量，2智能计量
                    mwaf.addWeight = PbCache.addWgt;
                    mwaf.meterTypeNo = "001006002"; //联达复磅固定的写法
                    mwaf.meterTypeName = "外销出厂计量";//联达复磅固定的写法

                    //操作日志
                    MeterMonitorNote monitorNote = new MeterMonitorNote();
                    monitorNote.baseSpotNo = mwaf.baseSpotNo;
                    monitorNote.baseSpotName = mwaf.baseSpotName;
                    monitorNote.operationContent = string.Format("联达称重保存");
                    monitorNote.operationTime = mwaf.createTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    monitorNote.carNo = mwaf.carNo;
                    monitorNote.meterNoteSource = string.IsNullOrEmpty(appUser.userid) ? "0" : "4";
                    monitorNote.meterManNo = appUser.userid;
                    monitorNote.meterManName = appUser.username;

                    RESTfulResult<string> rmI = mwcfs.doAddLianDaWf(mwaf, monitorNote);
                    if (rmI.Succeed)
                    {
                        rt.result = true;
                        rt.resultInfo = "称重完成";
                        PbCache.ResultMessage = "称重完成";
                        PbCache.actualFirstNo = rmI.Data;
                        PbCache.strQRCode = rmI.Message;
                        PbCache.isTareWeight = true;//皮重
                        RESTfulResult<string> RESTfulResult = termTareDate.abolishForCSharp(new MeterBaseTermTareData { carNo = mwaf.carNo });
                        if (RESTfulResult.Succeed)
                        {
                            if (!string.IsNullOrEmpty(RESTfulResult.Message))
                            {
                                PbCache.ResultMessage = PbCache.ResultMessage + "；请注意期限皮重已作废";
                            }
                        }
                        else
                        {
                            PbCache.ResultMessage = PbCache.ResultMessage + "；作废期限皮重异常，请点击【语音求助】联系计量员";
                        }
                    }
                    else
                    {
                        rt.result = false;
                        rt.isError = true;
                        rt.resultInfo = "称重数据保存失败";
                        PbCache.ResultMessage = "计量失败：" + rmI.ResultMessage;
                    }
                }
                else
                {
                    rt.result = false;
                    rt.isError = true;
                    rt.resultInfo = PbCache.ResultMessage;
                }
            }
            else if (rmFst.Data.Count == 1)
            {
                //如果只存在一条，则判断这条数据的预报编号是不是联达的预报数据，若是还需要判断当前这个预报是否存在结净的数据，若存在则结净，若不存在则不允许结净并提示需要先去其它磅进行过磅
                if (string.IsNullOrEmpty(scale.forwardingUnitName) || string.IsNullOrEmpty(scale.receivingUintName))
                {
                    PbCache.ResultMessage = "结净时，预报中的发货单位以及收货单位均不允许为空，请点击[语音求助]！";
                    rt.result = false;
                    rt.isError = false;
                    return rt;
                }
                if (rmX.Data == null || rmX.Data.Count == 0)
                {
                    rt.resultInfo = "未找到一次计量数据！";
                    rt.result = false;
                    rt.isError = false;
                    PbCache.ResultMessage = "未找到一次计量数据，请先计量皮重！";
                }
                else if (rmX.Data.Count == 1)
                {
                    //则走其他的验证，比如与历史皮重验证，与其他的信息验证，若验证都通过则保存一次计量信息
                    MeterWorkCarActualFirst first = rmX.Data[0];
                    if (first.weightType == "0") //一次为毛重
                    {
                        rt.result = false;
                        rt.isError = false;
                        PbCache.ResultMessage = "当前为毛重计量环节，已经存在一条重量为[" + first.meterWeight/1000 + " T]的毛重数据，毛重与毛重不能计量！";
                    }
                    else //一次为皮重，那么当前则是走先皮后毛流程
                    {
                        if (!PbCache.isNotValid)
                        {
                            //如果勾选了不验证重量则可以放过 1000kg的判断
                            if (Math.Abs(rmX.Data[0].meterWeight.Value - PbCache.lockWgt) < AppConfigCache.differenceWgt && PbCache.monitor.validWgt != "0")
                            {
                                //重复计量
                                rt.result = false;
                                rt.isError = true;
                                rt.resultInfo = "第一次计量重量和第二次计量重量接近";
                                //PbCache.ResultMessage = "第一次计量重量和第二次计量重量接近";
                                PbCache.ResultMessage = "第一次计量重量【" + rmX.Data[0].meterWeight.Value / 1000 + "T】和第二次计量重量【" + PbCache.lockWgt / 1000 + "T】接近，小于结净最小值【" + AppConfigCache.differenceWgt / 1000 + " T】,请点击[语音求助]，由司秤工过磅！";
                                return rt;
                            }
                        }

                        //验证是否存在历史皮
                        validWgt vw = new validWgt();

                        //一次重量大于当前重量，所以一次的时候应该是毛重
                        if (rmX.Data[0].meterWeight.Value - PbCache.lockWgt > 0)
                        {
                            vw.validHisTare(scale);
                            //没有历史皮的情况下，若配置了先皮后毛与先毛后皮，则会先走先皮流程，然后发现一次大于二次则将一次改为毛，继续走后面的先毛后皮流程
                            if (!PbCache.monitorResult.haveHisTare)
                            {
                                //将一次数据类型修改为皮重
                                mwcfs.doUpdateWf(new MeterWorkCarActualFirst { actualFirstNo = rmX.Data[0].actualFirstNo, weightType = "0" });
                                rt.result = false;
                                rt.isError = false;
                                PbCache.ResultMessage = "请再次点击[保存]按钮";
                                return rt;
                            }
                            else
                            {
                                rt.result = false;
                                rt.isError = true;
                                rt.resultInfo = "存在一次皮重信息，当前重量小于一次皮重皮皮不能结合";
                                PbCache.ResultMessage = "存在一次皮重信息，当前重量小于一次皮重皮皮不能结合";
                                return rt;
                            }
                        }

                        //验证物料时间段
                        validMatTime vmt = new validMatTime();
                        vmt.ValidMethod(scale, "1");
                        if (!PbCache.monitorResult.valid_mat_time)
                        {
                            rt.result = false;
                            rt.isError = true;
                            rt.resultInfo = PbCache.ResultMessage;
                            return rt;
                        }

                        //验证两次计量时间间隔
                        validTimeInterval vti = new validTimeInterval();
                        vti.ValidMethod(scale, "3", first);
                        if (!PbCache.monitorResult.valid_time_interval)
                        {
                            rt.result = false;
                            rt.isError = true;
                            rt.resultInfo = PbCache.ResultMessage;
                            return rt;
                        }

                        //验证危化品验证
                        validExceedWgt vew = new validExceedWgt();
                        vew.validMatMethod(scale, "3", first);
                        if (!PbCache.monitorResult.valid_exceed_wgt)
                        {
                            rt.result = false;
                            rt.isError = true;
                            return rt;
                        }

                        //验证预报超差信息
                        validPredictionDiff vpd = new validPredictionDiff();
                        vpd.ValidMethod(scale, "3", first); //验证净重
                        if (!PbCache.monitorResult.valid_prediction_diff)
                        {
                            rt.result = false;
                            rt.isError = true;
                            rt.resultInfo = PbCache.ResultMessage;
                            return rt;
                        }

                        //验证计量区域：若二次计量数据的计量区域与一次计量的计量区域不一致，则禁止自助计量；
                        validMeterArea vMeterArea = new validMeterArea();
                        vMeterArea.ValidMethod(first.baseSpotNo);
                        if (!PbCache.monitorResult.valid_meter_area)
                        {
                            rt.result = false;
                            rt.isError = true;
                            rt.resultInfo = PbCache.ResultMessage;
                            return rt;
                        }

                        //====所有验证均通过后，此时进行结净=====================
                        //保存毛重信息  即：二次计量信息***********************
                        MeterWorkCarActualFirst secondDb = new MeterWorkCarActualFirst();

                        //相同名称的均赋值一次
                        EntityBase<PreTrackScale> entityBase = new EntityBase<PreTrackScale>();
                        scale.predictionNo = scale.predictionNo + "_";
                        secondDb = entityBase.format<MeterWorkCarActualFirst>(scale, secondDb);

                        secondDb.actualFirstNo = DateTime.Now.ToString("yyyyMMdd");//10
                        secondDb.meterWeight = PbCache.lockWgt;//计量重量
                        secondDb.addWeight = PbCache.addWgt;//附加重量
                        secondDb.weightType = "0"; //0=毛重；1=常规皮重；2=期限皮重；3=历史皮重；4=标识皮重；5=自重皮重
                        secondDb.createManNo = appUser.userid;
                        secondDb.createManName = appUser.username;
                        secondDb.meterGroup = appUser.userGroup;
                        secondDb.meterClass = appUser.userClass;
                        secondDb.createTime = DateTime.Now;
                        secondDb.baseSpotNo = PbCache.sportInfo.baseSpotNo;//计量点编号
                        secondDb.baseSpotName = PbCache.sportInfo.baseSpotName;
                        //secondDb.memo = "";
                        secondDb.valueFlag = "1"; //0有效
                        secondDb.matterName = secondDb.matterName + "-复磅对比";
                        secondDb.updateManName = "";
                        secondDb.updateManNo = "";
                        secondDb.updateTime = null;
                        secondDb.checkFlag = "0"; //0未审核
                        secondDb.meterMode = string.IsNullOrEmpty(appUser.userid) ? "2" : "1"; //1远程计量，2智能计量
                        secondDb.meterTypeNo = "001006002"; //联达复磅固定的写法
                        secondDb.meterTypeName = "外销出厂计量";//联达复磅固定的写法

                        //结净数据
                        MeterWorkCarActual netDb = new MeterWorkCarActual();
                        EntityBase<PreTrackScale> entityActual = new EntityBase<PreTrackScale>();
                        netDb = entityBase.format<MeterWorkCarActual>(scale, netDb);

                        //netDb.actualFirst1No = ""; //毛重计量作业编号
                        netDb.grossTime = DateTime.Now;
                        netDb.grossWeight = PbCache.lockWgt; //毛重
                        netDb.baseSpot1No = PbCache.sportInfo.baseSpotNo; //毛重计量点编号
                        netDb.baseSpot1Name = PbCache.sportInfo.baseSpotName; //毛重计量点
                        netDb.grossMode = string.IsNullOrEmpty(appUser.userid) ? "2" : "1"; //1远程计量，2智能计量
                        netDb.grossGroup = appUser.userGroup;
                        netDb.grossClass = appUser.userClass;
                        netDb.grossManNo = appUser.userid;
                        netDb.grossManName = appUser.username;
                        netDb.matterName = netDb.matterName + "-复磅对比";
                        netDb.actualFirst2No = first.actualFirstNo;
                        netDb.tareWeight = first.meterWeight;
                        netDb.tareTime = first.createTime;
                        netDb.baseSpot2No = first.baseSpotNo;
                        netDb.baseSpot2Name = first.baseSpotName;
                        netDb.tareMode = first.meterMode;
                        netDb.tareClass = first.meterClass;
                        netDb.tareGroup = first.meterGroup;
                        netDb.tareManName = first.createManName;
                        netDb.tareManNo = first.createManNo;

                        netDb.addWeight = PbCache.addWgt;
                        //净重=毛-皮-附加重量
                        netDb.netWeight = netDb.grossWeight - netDb.tareWeight - netDb.addWeight;
                        netDb.netMode = "1"; //1：正常结净；2：匹配结净
                        netDb.valueFlag = "0"; //0=有效，1=作废
                        netDb.uploadFlag = "0"; //0=待审核；1：待上传；2=已上传
                        netDb.netTime = DateTime.Now;

                        netDb.netManNo = appUser.userid; //净重计量员编码 
                        netDb.netManName = appUser.username; //净重计量员名称
                        netDb.netSpot3No = PbCache.sportInfo.baseSpotNo; //净重计量点编号
                        netDb.netSpot3Name = PbCache.sportInfo.baseSpotName; //净重计量点

                        netDb.meterTypeNo = "001006002"; //联达复磅固定的写法
                        netDb.meterTypeName = "外销出厂计量";//联达复磅固定的写法

                        //操作日志
                        MeterMonitorNote monitorNote = new MeterMonitorNote();
                        monitorNote.baseSpotNo = secondDb.baseSpotNo;
                        monitorNote.baseSpotName = secondDb.baseSpotName;
                        monitorNote.operationContent = string.Format("联达结净称重保存");
                        monitorNote.operationTime = secondDb.createTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        monitorNote.carNo = secondDb.carNo;
                        monitorNote.meterNoteSource = string.IsNullOrEmpty(appUser.userid) ? "0" : "4";
                        monitorNote.meterManNo = appUser.userid;
                        monitorNote.meterManName = appUser.username;

                        RESTfulResult<string> rmI = mwcfs.doAddNetLianDaWf(secondDb, netDb, monitorNote);
                        if (rmI.Succeed)
                        {
                            rt.result = true;
                            rt.resultInfo = "称重完成";
                            PbCache.ResultMessage = "称重完成";
                            PbCache.actualFirstNo = rmI.Data;
                            PbCache.strQRCode = rmI.Message;
                            PbCache.isTareWeight = false;//毛重
                            RESTfulResult<string> RESTfulResult = termTareDate.abolishForCSharp(new MeterBaseTermTareData { carNo = netDb.carNo });
                            if (RESTfulResult.Succeed)
                            {
                                if (!string.IsNullOrEmpty(RESTfulResult.Message))
                                {
                                    PbCache.ResultMessage = PbCache.ResultMessage + "；请注意期限皮重已作废";
                                }
                            }
                            else
                            {
                                PbCache.ResultMessage = PbCache.ResultMessage + "；作废期限皮重异常，请点击【语音求助】联系计量员";
                            }
                        }
                        else
                        {
                            rt.result = false;
                            rt.isError = true;
                            rt.resultInfo = "称重数据保存失败";
                            PbCache.ResultMessage = "计量失败：" + rmI.ResultMessage;
                        }
                    }
                }
            }
            else 
            {
                //存在多条未结净的数据，提示存在多条未结净的数据，实际上可能是在其它磅未完成结净就过来过联达结净
                PbCache.ResultMessage = string.Format("当前车辆[{0}]存在多条未结净数据", scale.carNo);
                rt.resultInfo = "找到多条未结净数据";
                rt.result = false;
                rt.isError = true;
            }

            return rt;
        }
    }
}
