using com.hnshituo.core.webapp.vo;
using Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace CarMeterSystem
{
    public class JGLimsInterface
    {
        int iCarOrder = 0; //检化验第几车
        private Log lg = Log.GetInstance(); //写日志
        private MeterWorkCarActualFirstService actualFirstService = new MeterWorkCarActualFirstService(); //一次计量服务
        private PreTrackScaleService scaleService = new PreTrackScaleService(); //预报接口服务
        /// <summary>
        /// 计量车辆采样及提醒
        /// </summary>
        /// <param name="trackScale"></param>
        public void imsCarLims(PreTrackScale trackScale) {
            string limsResult = "";
            try
            {
                //2021年12月25日 只有船转汽才掉检化验接口：即压港序号不为空！！！
                if (trackScale == null || string.IsNullOrEmpty(trackScale.holddockSeq))
                {
                    return;
                }
                limsResult = SendPostToLims(trackScale).Replace("msg", "data");

                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                if (limsResult.Contains("-1,"))
                {
                    RESTfulResult<string> list = js.Deserialize<RESTfulResult<string>>(limsResult);    //将json数据转化为对象类型并赋值给list
                    if (list != null)
                    {
                        PbCache.ResultMessage += "；检化验接口异常，请点【语音求助】联系司秤工处理！" + list.Data;
                        lg.WriteLog(24, "检化验接口异常：" + limsResult);
                    }
                }
                else
                {
                    RESTfulResult<JGLimsMsg> list = js.Deserialize<RESTfulResult<JGLimsMsg>>(limsResult);    //将json数据转化为对象类型并赋值给list
                    if (list != null)
                    {
                        if (list.Status.ToString().Equals("1"))
                        {
                            RESTfulResult<JGLimsMsg> listMsg = js.Deserialize<RESTfulResult<JGLimsMsg>>(limsResult);
                            if (listMsg.Data.place!=null && listMsg.Data.place!=null)
                            {
                                PbCache.ResultMessage += "；车辆需要采样，卸货点为：" + listMsg.Data.place;

                                trackScale.loadPointNo = listMsg.Data.placecode;
                                trackScale.loadPointName = listMsg.Data.place;
                                if (trackScale.loadPointName!=null && trackScale.loadPointName.Contains("西区"))
                                {
                                    trackScale.receivingUintNo = "505307";
                                    trackScale.receivingUintName = "西区物流运输部废钢管理站";
                                }
                                else
                                {
                                    trackScale.receivingUintNo = "505306";
                                    trackScale.receivingUintName = "东区物流运输部废钢管理站";
                                }
                              
                                trackScale.updateManNo = "检化验抽检";
                                trackScale.updateManName = "检化验抽检（第 "+ iCarOrder + " 车次）";
                                trackScale.limsSamplingFlag = "1"; //检化验取样状态（0=不需要取样；1=待取样(已中签)；2=已取样；3=待确认（默认值））
                                RESTfulResult<string> rESTful = scaleService.updateLoadInfoFroInterface(trackScale);

                                lg.WriteLog(24, "车辆需要采样，卸货点为：" + listMsg.Data.place + limsResult);
                            }
                            else
                            {
                                trackScale.updateManNo = "检化验不抽检";
                                trackScale.updateManName = "检化验不抽检（第 " + iCarOrder + " 车次）";
                                trackScale.limsSamplingFlag = "0"; //检化验取样状态（0=不需要取样；1=待取样(已中签)；2=已取样；3=待确认（默认值））
                                RESTfulResult<string> rESTful = scaleService.updateLoadInfoFroInterface(trackScale);

                                PbCache.ResultMessage += "；车辆不需要采样";
                                lg.WriteLog(24, "车辆不需要采样");
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                PbCache.ResultMessage += "检化验接口异常，请点【语音求助】联系司秤工处理！";
            }

        }

        /// <summary>
        /// 向检化验接口传参
        /// </summary>
        /// <param name="trackScale"></param>
        /// <returns></returns>
        public string SendPostToLims(PreTrackScale trackScale)
        {
            iCarOrder = carOrder(trackScale);
            HttpHelper http = new HttpHelper();
            var item = new HttpItem()
            {
                URL = "http://192.168.127.1/external/login",
                Method = "POST",
                ContentType = "application/json",
                PostEncoding = Encoding.UTF8,
            };
            item.Header.Add("Accept-Encoding", "gzip, deflate");
            item.Header.Add("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");

            dynamic backObj = new
            {
                user = "admin",
                password = "xxzxjg009118"
            };
            var pr = JsonConvert.SerializeObject(backObj);
            item.Postdata = pr;
            var result = http.GetHtml(item);
            string html = result.Html;
            item = new HttpItem()
            {
                URL = "http://192.168.127.1/external/mes/getisspot",
                Method = "POST",
                ContentType = "application/json",
                PostEncoding = Encoding.UTF8,
            };
            item.Header.Add("Authorization", $"Bearer {html}");
            item.Header.Add("Accept-Encoding", "gzip, deflate");
            item.Header.Add("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
            dynamic Obj = new
            {
                HODEDOCKSEQ = trackScale.holddockSeq,//"h201908230003",  //压港序号=卸货计划号(MES)
                ORDER = iCarOrder + "", //同一压港序号下的第几车
                CONTRACTNO =trackScale.contractNo , //合同号
                CAR_NO = trackScale.carNo , //车号
                SHIP_NO = trackScale.shipNo , //船号
                MAT_NAME = trackScale.matterName ,//物料名
                MAT_CODE = trackScale.matterNo ,//物料编号
                SDR_NAME = trackScale.forwardingUnitName ,//发货单位名称
                SDR_CODE = trackScale.forwardingUnitNo ,//发货单位编号
                REC_NAME = trackScale.receivingUintName ,//收货单位名称
                REC_CODE = trackScale.receivingUintNo ,//收货单位编码
                SCALE_NAME = PbCache.sportInfo.baseSpotName,//汽车衡名称
                SCALE_CODE = PbCache.sportInfo.baseSpotNo,//汽车衡编码
            };
            var cc = JsonConvert.SerializeObject(Obj);
            item.Postdata = cc;
            result = http.GetHtml(item);
            html = result.Html; //
            return html;
        }

        /// <summary>
        /// 查询当前是第几车;计量完成后才调用的，所以直接count就可以了 
        /// </summary>
        /// <returns></returns>
        public int carOrder(PreTrackScale trackScale)
        {
            int i = 1;
            string strMat = "0";
            PbModelDbService<List<PbModelDb>> pbRelation = new PbModelDbService<List<PbModelDb>>();
            string sql = $"select count(1)  text from (select t.prediction_no  from meter_work_car_actual_first t where " +
                $"t.holddock_seq = '"+ trackScale .holddockSeq+ "' " +
                $"and t.value_flag in ('1', '2') group by t.prediction_no)";
            RESTfulResult<List<PbModelDb>> rmRelation = pbRelation.executeSqlDataWf(sql);
            if (rmRelation.Succeed && rmRelation.Data != null && rmRelation.Data.Count > 0)
            {
                strMat = rmRelation.Data[0].text;
                i = int.Parse(strMat);
            }
            return i;
        }
    }
}
