using DB_Server;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Models;
using Models.Models;
using Models.Models.LOGDB;
using SERVER;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using WebUI.Model;
using System.Security.Cryptography;
using NLog;

namespace WebUI.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class publicApiController : Controller
    {

        private readonly HotelServiceContext _db;

        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="db"></param>
        public publicApiController(HotelServiceContext db)
        {
            _db = db;
        }


        #region  通过mac地址获取房间类型 (暂无用)

        ///// <summary>
        ///// 通过mac地址获取房间类型 (暂无用)
        ///// </summary>
        ///// <param name="mac"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("OTApi/GetRoomType")]
        //public IActionResult GetRoomType(string mac)
        //{
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(mac))
        //        {
        //            var data = (from a in _db.TBL_ROOM_BASIC_INFOS join   b in _db.TBL_ROOM_TYPE_LISTS on a.ROOM_TYPE_OLD_ID equals b.ROOM_TYPE_OLD_ID 
        //                       where a.MAC == mac
        //                       select b).FirstOrDefault();
        //            return Json(new
        //            {
        //                data,
        //                messages = "请求成功",
        //                Status = 200
        //            });
        //        }
        //        else
        //            return Json(new
        //            {
        //                messages = "mac为空值",
        //                Status = 50
        //            });
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return Json(new
        //        {
        //            messages = ex.Message,
        //            Status = 404
        //        });
        //    }
        //}

        #endregion


        #region 同步API

        /// <summary>
        /// 同步API
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("OTApi/SyncData")]
        public IActionResult SyncData(string Pwd, int stepid = 0)
        {
            if (Pwd == "fs%sd")
            {
                var res = SYNC_DATA.SYNC_DATA_ALL(stepid);
                string erMsg = GlobalSyncLockTest.recentErrMsg;
                //return Json(res);
                if (res)
                {
                    return Json(new
                    {
                        messages = "同步成功",
                        Status = true
                    });
                }
                else
                {
                    return Json(new
                    {
                        messages = erMsg,
                        Status = false
                    });
                }

            }
            else
                return Json(new
                {
                    messages = "同步密码错误",
                    Status = false
                });
        }


        #endregion

        #region 通过房间类型id获取文件路径(暂不使用)


        /// <summary>
        /// 通过房间类型id获取文件路径
        /// </summary>
        /// <param name="RoomTypeid"></param>
        /// <returns></returns>

        //public IActionResult GainFile(int RoomTypeid)
        //{
        //    FTPOperation operation = new FTPOperation();
        //    string hexPath2 = "";//App_Cfg_For_L2升级文件tfp路径
        //    string hexPath4 = ""; //App_Cfg_For_L4升级文件tfp路径
        //    string BinPath = ""; //二进制配置文件tfp路径
        //    try
        //    {
        //        if (RoomTypeid != 0)
        //        {
        //            //获取对应的房间类型表的中的字段
        //            var data = (
        //                from a in _db.TBL_ROOM_TYPE_LISTS

        //                join b in _db.TBL_HOTEL_BASIC_INFOS on a.HOTEL_OLD_ID equals b.IDOLD

        //                join c in _db.TBL_HOTEL_GROUP_INFOS on b.HOTEL_OLD_GROUP equals c.HOTEL_GROUP_OLD_ID

        //                where a.ROOM_TYPE_OLD_ID == RoomTypeid
        //                select new
        //                {
        //                    a.CONFIG_BIN,
        //                    a.App_Cfg_For_L2,
        //                    a.App_Cfg_For_L4,
        //                    a.HOTEL_OLD_ID,
        //                    c.HOTEL_GROUP_NAME,
        //                    b.HOTEL_NAME_CN,
        //                    b.PROJECT_NUMBER,
        //                    a.Hex_Code_For_L2,
        //                    a.Hex_Code_For_L4,
        //                    a.APPTYPE,
        //                    a.Hex_Code_For_L2_MD5,
        //                    a.Hex_Code_For_L4_MD5,
        //                    a.App_Cfg_For_L2_MD5,
        //                    a.App_Cfg_For_L4_MD5

        //                }).FirstOrDefault();

        //            //获取对应的酒店编号,酒店名称,酒店分组
        //            //var hotelgroup = (from a in _db.TBL_HOTEL_BASIC_INFOS join b in _db.TBL_HOTEL_GROUP_INFOS on a.HOTEL_OLD_GROUP equals b.HOTEL_GROUP_OLD_ID where a.IDOLD == data.HOTEL_OLD_ID select new { b.HOTEL_GROUP_NAME ,a.PROJECT_NUMBER ,a.HOTEL_NAME_CN }).FirstOrDefault();

        //            if (data == null)
        //            {
        //                return Json(new
        //                {
        //                    messages = "未找到数据",
        //                    Status = 100
        //                });
        //            }

        //            if (data.CONFIG_BIN != null)
        //            {
        //                //BinPath = @"BLV_Studio\Data\Config\" + data.HOTEL_GROUP_NAME + @"\" + data.PROJECT_NUMBER + "-" + data.HOTEL_NAME_CN + @"\" + data.CONFIG_BIN;
        //                BinPath = "ftp://auth.blv-oa.com:50/BLV_Studio/Data/Config/"+ data.HOTEL_GROUP_NAME+ @"/" + data.PROJECT_NUMBER+"-"+data.HOTEL_NAME_CN+ @"/" + data.CONFIG_BIN;
        //            }
        //            if (data.APPTYPE != "")
        //            {
        //                if (data.APPTYPE == "App_Cfg")
        //                {
        //                    if (data.App_Cfg_For_L2 != null)
        //                    {
        //                        //校验MD5是否给修改过
        //                        if (MD5Verify.getMD5Hash(operation.GetFile(data.App_Cfg_For_L2)) == data.App_Cfg_For_L2_MD5)
        //                        {
        //                            hexPath2 = "ftp://auth.blv-oa.com:50/BLV_Studio/Data/Firmware/" + data.App_Cfg_For_L2;
        //                        }
        //                        else
        //                        {
        //                            hexPath2 = "文件修改过对不上MD5";
        //                        }
        //                    }
        //                    if (data.App_Cfg_For_L4 != null)
        //                    {


        //                        if (MD5Verify.getMD5Hash(operation.GetFile(data.App_Cfg_For_L4)) == data.App_Cfg_For_L4_MD5)
        //                        {
        //                            hexPath4 = "ftp://auth.blv-oa.com:50/BLV_Studio/Data/Firmware/" + data.App_Cfg_For_L4;
        //                        }
        //                        else
        //                        {
        //                            hexPath4 = "文件修改过对不上MD5";
        //                        }
        //                    }
        //                }
        //                else if (data.APPTYPE == "Hex_Code")
        //                {
        //                    if (data.Hex_Code_For_L2 != null)
        //                    {

        //                        if (MD5Verify.getMD5Hash(operation.GetFile(data.Hex_Code_For_L2)) == data.Hex_Code_For_L2_MD5)
        //                        {
        //                            hexPath2 = "ftp://auth.blv-oa.com:50/BLV_Studio/Data/Firmware/" + data.Hex_Code_For_L2;
        //                        }
        //                        else
        //                        {
        //                            hexPath2 = "文件修改过对不上MD5";
        //                        }
        //                    }
        //                    if (data.Hex_Code_For_L4 != null)
        //                    {
        //                        if (MD5Verify.getMD5Hash(operation.GetFile(data.Hex_Code_For_L4)) == data.Hex_Code_For_L4_MD5)
        //                        {
        //                            hexPath4 = "ftp://auth.blv-oa.com:50/BLV_Studio/Data/Firmware/" + data.Hex_Code_For_L4;
        //                        }
        //                        else
        //                        {
        //                            hexPath4 = "文件修改过对不上MD5";
        //                        }
        //                    }

        //                }
        //            }
        //            var Filedata = new
        //            {
        //                BinPath = BinPath,
        //                hexPath2 = hexPath2,
        //                hexPath4 = hexPath4,
        //            };

        //            return Json(new
        //            {
        //                Filedata,
        //                messages = "请求成功",
        //                Status = 200
        //            });
        //        }
        //        else
        //            return Json(new
        //            {
        //                messages = "参数为空值",
        //                Status = 50
        //            });
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return Json(new
        //        {
        //            messages = ex.Message,
        //            Status = 404
        //        });
        //    }
        //}
        #endregion


        #region 获取对应的文件下发



        [HttpPost]
        [Route("OTApi/GainFiles")]
        public IActionResult GainFile1s(int RoomTypeid, int DataType)
        {
            FTPOperation operation = new FTPOperation();
            HexFile hexFile = new HexFile();
            // Luncher版本
            string LuncherVer = "";
            //数据主题
            string data = "";
            //状态
            bool Status = false;
            //最后获取的文件
            List<string> FileName = new List<string>();

            //错误信息
            string MrrMsg = null;
            //机型
            string ModelName = "";
            //Hex起初地址
            string HexStart = "";
            //总数据
            List<SendFileLuncher> datalist = new List<SendFileLuncher>();
            //房型名称
            string RoomTypeName = "";
            //项目id
            int hotelId = 0;
            //项目名称
            string hotelName = "";
            //文件数量
            int FileCount = 0;
            int coun = 0;
            //写入日志
            TBL_EQUIPMENTISSUELOG eqlog = new TBL_EQUIPMENTISSUELOG();
            try
            {


                if (RoomTypeid != 0)
                {
                    //获取对应的房间类型表的中的字段
                    var selectdata = (
                        from a in _db.TBL_ROOM_TYPE_LISTS

                        join b in _db.TBL_HOTEL_BASIC_INFOS on a.HOTEL_OLD_ID equals b.IDOLD

                        join c in _db.TBL_HOTEL_GROUP_INFOS on b.HOTEL_OLD_GROUP equals c.HOTEL_GROUP_OLD_ID

                        where a.ROOM_TYPE_OLD_ID == RoomTypeid
                        select new
                        {
                            a.ROOM_TYPE_NAME,
                            a.CONFIG_BIN,
                            a.App_Cfg_For_L2,
                            a.App_Cfg_For_L4,
                            a.HOTEL_OLD_ID,
                            c.HOTEL_GROUP_NAME,
                            b.HOTEL_NAME_CN,
                            b.PROJECT_NUMBER,
                            a.Hex_Code_For_L2,
                            a.Hex_Code_For_L4,
                            a.APPTYPE,
                            a.Hex_Code_For_L2_MD5,
                            a.Hex_Code_For_L4_MD5,
                            a.App_Cfg_For_L2_MD5,
                            a.App_Cfg_For_L4_MD5,
                            a.CONFIG_BIN_MD5
                        }).FirstOrDefault();
                    if (selectdata != null)
                    {
                        //房型名称
                        RoomTypeName = selectdata.ROOM_TYPE_NAME;
                        //项目名称
                        hotelName = selectdata.HOTEL_NAME_CN;
                        //项目id
                        hotelId = selectdata.HOTEL_OLD_ID;
                        //升级文件
                        if (DataType == 2)
                        {
                            //发送类
                            SendFileLuncher send = new SendFileLuncher();
                            if (selectdata.CONFIG_BIN != null)
                            {
                                //校验MD5
                                var NNN = "Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN;
                                logger.Error("开始校验配置文件MD5，文件路径：" + NNN);
                                if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile(NNN))) == selectdata.CONFIG_BIN_MD5)
                                {
                                    var sety = operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN);
                                    var btys = operation.ByteArrayToHexStr(sety);
                                    var ssety = HexFile.Crc16(sety, 4, sety.Length);
                                    byte[] suz = new byte[10000];
                                    var ssety2 = HexFile.NetCRC16_Data(sety, sety.Length, 4);

                                    HexFile.StrToHex(suz, sety, 100);

                                    //找到文件头
                                    if ((sety[0] == 0xCC) && (sety[1] == 0xC0))
                                    {
                                        int data_len = sety[3];
                                        data_len <<= 8;
                                        data_len |= sety[2];

                                        if (data_len <= 1024) //文件长度超出范围,不处理
                                        {
                                            byte[] vaslen = new byte[data_len];
                                            int crc_val = 0;
                                            int temp_crc = 0;

                                            Array.Copy(sety, vaslen, data_len);
                                            crc_val = sety[5];
                                            crc_val <<= 8;
                                            crc_val |= sety[4];

                                            temp_crc = HexFile.NetCRC16_Data(vaslen, data_len, 4);

                                            if (temp_crc == crc_val)
                                            {
                                                /*数据校验成功*/
                                                if (vaslen[10] == 0x01)
                                                {
                                                    var zunsons = vaslen.Skip(157).Take(64).ToArray();
                                                    var seyu = operation.ByteArrayToHexStr(zunsons);
                                                    var setysssy = operation.UnHexs(seyu);
                                                    setysssy = setysssy.Replace("\0", null);
                                                    setysssy = setysssy.Replace("_", "-");
                                                    ModelName = setysssy;
                                                    data = Convert.ToBase64String(sety);
                                                    FileName.Add(selectdata.CONFIG_BIN);
                                                    send.md5 = GetMd5FromString(data);
                                                    send.Filenumber = ++coun;
                                                    send.data = data;
                                                    send.filename = selectdata.CONFIG_BIN;
                                                    datalist.Add(send);
                                                    Status = true;
                                                }
                                            }
                                            else
                                            {
                                                MrrMsg = "文件数据CRC校验失败,请检查文件是否正确";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        MrrMsg = "配置文件头错误,请检查文件是否正确";
                                    }
                                }
                                else
                                {
                                    MrrMsg = "固件（APP）文件校验失败，请检查网络或联系管理员";
                                }
                            }
                            else
                            {
                                MrrMsg = "“获取文件”失败所选房型没上传固件（APP）文件，请检查网络或联系管理员";
                            }
                        }
                        //配置文件
                        else if (DataType == 1)
                        {
                            //判断是代码烧录还是工具烧录
                            if (selectdata.APPTYPE != "")
                            {
                                if (selectdata.APPTYPE == "App_Cfg")
                                {
                                    if (string.IsNullOrEmpty(selectdata.App_Cfg_For_L2) && string.IsNullOrEmpty(selectdata.App_Cfg_For_L4))
                                    {
                                        MrrMsg = "“获取文件”失败所选房型没上传固件（APP）或配置文件，请检查网络或联系管理员";
                                    }
                                    if (!string.IsNullOrEmpty(selectdata.App_Cfg_For_L2))
                                    {
                                        if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L2))) == selectdata.App_Cfg_For_L2_MD5)
                                        {

                                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN))) == selectdata.CONFIG_BIN_MD5)
                                            {
                                                var sety = operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN);
                                                var btys = operation.ByteArrayToHexStr(sety);
                                                var ssety = HexFile.Crc16(sety, 4, sety.Length);
                                                byte[] suz = new byte[10000];
                                                var ssety2 = HexFile.NetCRC16_Data(sety, sety.Length, 4);

                                                HexFile.StrToHex(suz, sety, 100);

                                                //找到文件头
                                                if ((sety[0] == 0xCC) && (sety[1] == 0xC0))
                                                {
                                                    int data_len = sety[3];
                                                    data_len <<= 8;
                                                    data_len |= sety[2];

                                                    if (data_len <= 1024) //文件长度超出范围,不处理
                                                    {
                                                        byte[] vaslen = new byte[data_len];
                                                        int crc_val = 0;
                                                        int temp_crc = 0;

                                                        Array.Copy(sety, vaslen, data_len);
                                                        crc_val = sety[5];
                                                        crc_val <<= 8;
                                                        crc_val |= sety[4];

                                                        temp_crc = HexFile.NetCRC16_Data(vaslen, data_len, 4);

                                                        if (temp_crc == crc_val)
                                                        {
                                                            /*数据校验成功*/
                                                            if (vaslen[10] == 0x01)
                                                            {
                                                                var zunsons = vaslen.Skip(157).Take(64).ToArray();
                                                                var seyu = operation.ByteArrayToHexStr(zunsons);
                                                                var setysssy = operation.UnHexs(seyu);
                                                                setysssy = setysssy.Replace("\0", null);
                                                                setysssy = setysssy.Replace("_", "-");
                                                                ModelName = setysssy;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            MrrMsg = "文件数据CRC校验失败,请检查文件是否正确";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    MrrMsg = "获取机型错误,请检查文件是否正确";
                                                }
                                            }
                                            else
                                            {
                                                MrrMsg = "获取机型失败";
                                            }







                                            FileName.Add(selectdata.App_Cfg_For_L2);
                                            data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L2))));
                                            SendFileLuncher send = new SendFileLuncher();
                                            send.LuncherVer = "Launcher_C1F_V02";
                                            if (selectdata.App_Cfg_For_L2.Substring(selectdata.App_Cfg_For_L2.Length - 4, 4) == ".hex")
                                            {
                                                send.filename = selectdata.App_Cfg_For_L2.Replace(".hex", ".bin");
                                            }
                                            else
                                            {
                                                send.filename = selectdata.App_Cfg_For_L2;
                                            }
                                            send.HexStart = hexFile.Get_HexStart_C1();
                                            send.Filenumber = ++coun;
                                            send.md5 = GetMd5FromString(data);
                                            send.data = data;
                                            datalist.Add(send);
                                            Status = true;
                                        }
                                        else
                                        {
                                            MrrMsg = "配置文件校验失败，请检查网络或联系管理员 ";
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(selectdata.App_Cfg_For_L4))
                                    {


                                        if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L4))) == selectdata.App_Cfg_For_L4_MD5)
                                        {




                                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN))) == selectdata.CONFIG_BIN_MD5)
                                            {
                                                var sety = operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN);
                                                var btys = operation.ByteArrayToHexStr(sety);
                                                var ssety = HexFile.Crc16(sety, 4, sety.Length);
                                                byte[] suz = new byte[10000];
                                                var ssety2 = HexFile.NetCRC16_Data(sety, sety.Length, 4);

                                                HexFile.StrToHex(suz, sety, 100);

                                                //找到文件头
                                                if ((sety[0] == 0xCC) && (sety[1] == 0xC0))
                                                {
                                                    int data_len = sety[3];
                                                    data_len <<= 8;
                                                    data_len |= sety[2];

                                                    if (data_len <= 1024) //文件长度超出范围,不处理
                                                    {
                                                        byte[] vaslen = new byte[data_len];
                                                        int crc_val = 0;
                                                        int temp_crc = 0;

                                                        Array.Copy(sety, vaslen, data_len);
                                                        crc_val = sety[5];
                                                        crc_val <<= 8;
                                                        crc_val |= sety[4];

                                                        temp_crc = HexFile.NetCRC16_Data(vaslen, data_len, 4);

                                                        if (temp_crc == crc_val)
                                                        {
                                                            /*数据校验成功*/
                                                            if (vaslen[10] == 0x01)
                                                            {
                                                                var zunsons = vaslen.Skip(157).Take(64).ToArray();
                                                                var seyu = operation.ByteArrayToHexStr(zunsons);
                                                                var setysssy = operation.UnHexs(seyu);
                                                                setysssy = setysssy.Replace("\0", null);
                                                                setysssy = setysssy.Replace("_", "-");
                                                                ModelName = setysssy;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            MrrMsg = "文件数据CRC校验失败,请检查文件是否正确";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    MrrMsg = "获取机型错误,请检查文件是否正确";
                                                }
                                            }
                                            else
                                            {
                                                MrrMsg = "获取机型失败";
                                            }







                                            FileName.Add(selectdata.App_Cfg_For_L4);
                                            data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L4))));
                                            SendFileLuncher send = new SendFileLuncher();
                                            send.LuncherVer = "Launcher_C1F_V04";
                                            if (selectdata.App_Cfg_For_L4.Substring(selectdata.App_Cfg_For_L4.Length - 4, 4) == ".hex")
                                            {
                                                send.filename = selectdata.App_Cfg_For_L4.Replace(".hex", ".bin");
                                            }
                                            else
                                            {
                                                send.filename = selectdata.App_Cfg_For_L4;
                                            }
                                            send.HexStart = hexFile.Get_HexStart_C1();
                                            send.Filenumber = ++coun;
                                            send.data = data;
                                            send.md5 = GetMd5FromString(data);
                                            datalist.Add(send);
                                            Status = true;
                                        }
                                        else
                                        {
                                            MrrMsg = "配置文件校验失败，请检查网络或联系管理员";
                                        }
                                    }
                                }
                                else if (selectdata.APPTYPE == "Hex_Code")
                                {
                                    if (string.IsNullOrEmpty(selectdata.Hex_Code_For_L2) && string.IsNullOrEmpty(selectdata.Hex_Code_For_L4))
                                    {
                                        MrrMsg = "获取文件”失败所选房型没上传固件（APP）或配置文件，请检查网络或联系管理员";
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(selectdata.Hex_Code_For_L2))
                                        {
                                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L2))) == selectdata.Hex_Code_For_L2_MD5)
                                            {
                                                FileName.Add(selectdata.Hex_Code_For_L2);
                                                data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L2))));
                                                ModelName = hexFile.GetHexInfo();
                                                SendFileLuncher send = new SendFileLuncher();
                                                send.LuncherVer = "Launcher_C1F_V02";
                                                if (selectdata.Hex_Code_For_L2.Substring(selectdata.Hex_Code_For_L2.Length - 4, 4) == ".hex")
                                                {
                                                    send.filename = selectdata.Hex_Code_For_L2.Replace(".hex", ".bin");
                                                }
                                                else
                                                {
                                                    send.filename = selectdata.Hex_Code_For_L2;
                                                }
                                                send.HexStart = hexFile.Get_HexStart_C1();
                                                send.Filenumber = ++coun;
                                                send.data = data;
                                                send.md5 = GetMd5FromString(data);
                                                datalist.Add(send);
                                                Status = true;
                                            }
                                            else
                                            {
                                                MrrMsg = "配置文件校验失败，请检查网络或联系管理员";
                                            }
                                        }

                                        if (!string.IsNullOrEmpty(selectdata.Hex_Code_For_L4))
                                        {
                                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L4))) == selectdata.Hex_Code_For_L4_MD5)
                                            {
                                                FileName.Add(selectdata.Hex_Code_For_L4);
                                                data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L4))));
                                                ModelName = hexFile.GetHexInfo();
                                                SendFileLuncher send = new SendFileLuncher();
                                                send.LuncherVer = "Launcher_C1F_V04";
                                                if (selectdata.Hex_Code_For_L4.Substring(selectdata.Hex_Code_For_L4.Length - 4, 4) == ".hex")
                                                {
                                                    send.filename = selectdata.Hex_Code_For_L4.Replace(".hex", ".bin");
                                                }
                                                else
                                                {
                                                    send.filename = selectdata.Hex_Code_For_L4;
                                                }
                                                send.Filenumber = ++coun;
                                                send.HexStart = hexFile.Get_HexStart_C1();
                                                send.data = data;
                                                send.md5 = GetMd5FromString(data);
                                                datalist.Add(send);
                                                Status = true;
                                            }
                                            else
                                            {
                                                MrrMsg = "配置文件校验失败，请检查网络或联系管理员";
                                            }
                                        }

                                    }
                                }
                            }
                            else
                            {
                                MrrMsg = "无烧录模式,";
                            }
                        }
                        FileCount = datalist.Count;
                        string sum = "";
                        //写入日志
                        eqlog.CreationTime = DateTime.Now;
                        eqlog.Succeed = Status;
                        foreach (var item in FileName)
                        {
                            sum += item + "/";
                        }
                        eqlog.Content = "房间类型id是:" + RoomTypeid + ",升级类型是:" + DataType + ",luncher版本是:" + LuncherVer + ",升级文件名:" + sum + ",机型是:" + ModelName;
                        _db.TBL_EQUIPMENTISSUELOGs.AddRange(eqlog);
                        _db.SaveChanges();
                    }
                    else
                    {
                        return Json(new
                        {
                            RoomTypeid,
                            RoomTypeName,
                            hotelId,
                            hotelName,
                            Status = false,
                            ModelName,
                            //FileName,
                            FileCount,
                            datalist,
                            MrrMsg = "未找到对应的房型，请检查网络或联系管理员"
                        });
                    }
                }


                //if (!string.IsNullOrEmpty(FileName))
                //{
                //    if (FileName.Substring(FileName.Length - 4, 4) == ".hex")
                //    {
                //        FileName = FileName.Replace(".hex", ".bin");
                //    }
                //}

            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
                return Json(new
                {
                    RoomTypeid,
                    RoomTypeName,
                    hotelId,
                    hotelName,
                    Status = false,
                    ModelName,
                    //FileName,
                    FileCount,
                    datalist,
                    MrrMsg = ex.Message
                });
            }
            return Json(new
            {
                RoomTypeid,
                RoomTypeName,
                hotelId,
                hotelName,
                Status,
                ModelName,
                //FileName,
                FileCount,
                datalist,
                MrrMsg

            });
        }

        public static Logger logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <param name="RoomTypeid"></param>
        /// <param name="DataType"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("OTApi/GainFileName")]
        public IActionResult GainFileName(int RoomTypeid, int DataType)
        {
            logger.Error("RoomTypeID:"+RoomTypeid.ToString()+" DataType:"+DataType.ToString());
            FTPOperation operation = new FTPOperation();
            HexFile hexFile = new HexFile();
            // Luncher版本
            string LuncherVer = "";
            //数据主题
            string data = "";
            //状态
            bool Status = false;
            //最后获取的文件
            List<string> FileName = new List<string>();

            //错误信息
            string MrrMsg = null;
            //机型
            string ModelName = "";
            //Hex起初地址
            string HexStart = "";
            //总数据
            List<SendFileLuncher> datalist = new List<SendFileLuncher>();
            //房型名称
            string RoomTypeName = "";
            //项目id
            int hotelId = 0;
            //项目名称
            string hotelName = "";
            //文件数量
            int FileCount = 0;
            int coun = 0;
            //写入日志
            TBL_EQUIPMENTISSUELOG eqlog = new TBL_EQUIPMENTISSUELOG();
            try
            {


                if (RoomTypeid != 0)
                {
                    //获取对应的房间类型表的中的字段
                    var selectdata = (
                        from a in _db.TBL_ROOM_TYPE_LISTS

                        join b in _db.TBL_HOTEL_BASIC_INFOS on a.HOTEL_OLD_ID equals b.IDOLD

                        join c in _db.TBL_HOTEL_GROUP_INFOS on b.HOTEL_OLD_GROUP equals c.HOTEL_GROUP_OLD_ID

                        where a.ROOM_TYPE_OLD_ID == RoomTypeid
                        select new
                        {
                            a.ROOM_TYPE_NAME,
                            a.CONFIG_BIN,
                            a.App_Cfg_For_L2,
                            a.App_Cfg_For_L4,
                            a.HOTEL_OLD_ID,
                            c.HOTEL_GROUP_NAME,
                            b.HOTEL_NAME_CN,
                            b.PROJECT_NUMBER,
                            a.Hex_Code_For_L2,
                            a.Hex_Code_For_L4,
                            a.APPTYPE,
                            a.Hex_Code_For_L2_MD5,
                            a.Hex_Code_For_L4_MD5,
                            a.App_Cfg_For_L2_MD5,
                            a.App_Cfg_For_L4_MD5,
                            a.CONFIG_BIN_MD5
                        }).FirstOrDefault();
                    if (selectdata != null)
                    {
                        //房型名称
                        RoomTypeName = selectdata.ROOM_TYPE_NAME;
                        //项目名称
                        hotelName = selectdata.HOTEL_NAME_CN;
                        //项目id
                        hotelId = selectdata.HOTEL_OLD_ID;
                        //升级文件
                        if (DataType == 2)
                        {
                            //发送类
                            SendFileLuncher send = new SendFileLuncher();
                            if (selectdata.CONFIG_BIN != null)
                            {
                                //校验MD5
                                if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN))) == selectdata.CONFIG_BIN_MD5)
                                {
                                    var sety = operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN);
                                    var btys = operation.ByteArrayToHexStr(sety);
                                    var ssety = HexFile.Crc16(sety, 4, sety.Length);
                                    byte[] suz = new byte[10000];
                                    var ssety2 = HexFile.NetCRC16_Data(sety, sety.Length, 4);

                                    HexFile.StrToHex(suz, sety, 100);

                                    //找到文件头
                                    if ((sety[0] == 0xCC) && (sety[1] == 0xC0))
                                    {
                                        int data_len = sety[3];
                                        data_len <<= 8;
                                        data_len |= sety[2];

                                        if (data_len <= 1024) //文件长度超出范围,不处理
                                        {
                                            byte[] vaslen = new byte[data_len];
                                            int crc_val = 0;
                                            int temp_crc = 0;

                                            Array.Copy(sety, vaslen, data_len);
                                            crc_val = sety[5];
                                            crc_val <<= 8;
                                            crc_val |= sety[4];

                                            temp_crc = HexFile.NetCRC16_Data(vaslen, data_len, 4);

                                            if (temp_crc == crc_val)
                                            {
                                                /*数据校验成功*/
                                                if (vaslen[10] == 0x01)
                                                {
                                                    var zunsons = vaslen.Skip(157).Take(64).ToArray();
                                                    var seyu = operation.ByteArrayToHexStr(zunsons);
                                                    var setysssy = operation.UnHexs(seyu);
                                                    setysssy = setysssy.Replace("\0", null);
                                                    setysssy = setysssy.Replace("_", "-");
                                                    ModelName = setysssy;
                                                    //data = Convert.ToBase64String(sety);
                                                    FileName.Add(selectdata.CONFIG_BIN);
                                                    //send.md5 = GetMd5FromString(data);
                                                    send.Filenumber = ++coun;
                                                    send.filename = selectdata.CONFIG_BIN;
                                                    datalist.Add(send);
                                                    Status = true;
                                                }
                                            }
                                            else
                                            {
                                                MrrMsg = "文件数据CRC校验失败,请检查文件是否正确";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        MrrMsg = "配置文件头错误,请检查文件是否正确";
                                    }
                                }
                                else
                                {
                                    MrrMsg = "固件（APP）文件校验失败，请检查网络或联系管理员";
                                }
                            }
                            else
                            {
                                MrrMsg = "“获取文件”失败所选房型没上传固件（APP）文件，请检查网络或联系管理员";
                            }
                        }
                        //配置文件
                        else if (DataType == 1)
                        {
                            //判断是代码烧录还是工具烧录
                            if (selectdata.APPTYPE != "")
                            {
                                if (selectdata.APPTYPE == "App_Cfg")
                                {
                                    if (string.IsNullOrEmpty(selectdata.App_Cfg_For_L2) && string.IsNullOrEmpty(selectdata.App_Cfg_For_L4))
                                    {
                                        MrrMsg = "“获取文件”失败所选房型没上传固件（APP）或配置文件，请检查网络或联系管理员";
                                    }
                                    if (!string.IsNullOrEmpty(selectdata.App_Cfg_For_L2))
                                    {
                                        if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L2))) == selectdata.App_Cfg_For_L2_MD5)
                                        {

                                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN))) == selectdata.CONFIG_BIN_MD5)
                                            {
                                                var sety = operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN);
                                                var btys = operation.ByteArrayToHexStr(sety);
                                                var ssety = HexFile.Crc16(sety, 4, sety.Length);
                                                byte[] suz = new byte[10000];
                                                var ssety2 = HexFile.NetCRC16_Data(sety, sety.Length, 4);

                                                HexFile.StrToHex(suz, sety, 100);

                                                //找到文件头
                                                if ((sety[0] == 0xCC) && (sety[1] == 0xC0))
                                                {
                                                    int data_len = sety[3];
                                                    data_len <<= 8;
                                                    data_len |= sety[2];

                                                    if (data_len <= 1024) //文件长度超出范围,不处理
                                                    {
                                                        byte[] vaslen = new byte[data_len];
                                                        int crc_val = 0;
                                                        int temp_crc = 0;

                                                        Array.Copy(sety, vaslen, data_len);
                                                        crc_val = sety[5];
                                                        crc_val <<= 8;
                                                        crc_val |= sety[4];

                                                        temp_crc = HexFile.NetCRC16_Data(vaslen, data_len, 4);

                                                        if (temp_crc == crc_val)
                                                        {
                                                            /*数据校验成功*/
                                                            if (vaslen[10] == 0x01)
                                                            {
                                                                var zunsons = vaslen.Skip(157).Take(64).ToArray();
                                                                var seyu = operation.ByteArrayToHexStr(zunsons);
                                                                var setysssy = operation.UnHexs(seyu);
                                                                setysssy = setysssy.Replace("\0", null);
                                                                setysssy = setysssy.Replace("_", "-");
                                                                ModelName = setysssy;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            MrrMsg = "文件数据CRC校验失败,请检查文件是否正确";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    MrrMsg = "获取机型错误,请检查文件是否正确";
                                                }
                                            }
                                            else
                                            {
                                                MrrMsg = "获取机型失败";
                                            }







                                            FileName.Add(selectdata.App_Cfg_For_L2);
                                            //data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L2))));
                                            SendFileLuncher send = new SendFileLuncher();
                                            send.LuncherVer = "Launcher_C1F_V02";
                                            if (selectdata.App_Cfg_For_L2.Substring(selectdata.App_Cfg_For_L2.Length - 4, 4) == ".hex")
                                            {
                                                send.filename = selectdata.App_Cfg_For_L2.Replace(".hex", ".bin");
                                            }
                                            else
                                            {
                                                send.filename = selectdata.App_Cfg_For_L2;
                                            }
                                            send.HexStart = hexFile.Get_HexStart_C1();
                                            send.Filenumber = ++coun;
                                            //send.md5 = GetMd5FromString(data);
                                            datalist.Add(send);
                                            Status = true;
                                        }
                                        else
                                        {
                                            MrrMsg = "配置文件校验失败，请检查网络或联系管理员 ";
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(selectdata.App_Cfg_For_L4))
                                    {


                                        if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L4))) == selectdata.App_Cfg_For_L4_MD5)
                                        {




                                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN))) == selectdata.CONFIG_BIN_MD5)
                                            {
                                                var sety = operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN);
                                                var btys = operation.ByteArrayToHexStr(sety);
                                                var ssety = HexFile.Crc16(sety, 4, sety.Length);
                                                byte[] suz = new byte[10000];
                                                var ssety2 = HexFile.NetCRC16_Data(sety, sety.Length, 4);

                                                HexFile.StrToHex(suz, sety, 100);

                                                //找到文件头
                                                if ((sety[0] == 0xCC) && (sety[1] == 0xC0))
                                                {
                                                    int data_len = sety[3];
                                                    data_len <<= 8;
                                                    data_len |= sety[2];

                                                    if (data_len <= 1024) //文件长度超出范围,不处理
                                                    {
                                                        byte[] vaslen = new byte[data_len];
                                                        int crc_val = 0;
                                                        int temp_crc = 0;

                                                        Array.Copy(sety, vaslen, data_len);
                                                        crc_val = sety[5];
                                                        crc_val <<= 8;
                                                        crc_val |= sety[4];

                                                        temp_crc = HexFile.NetCRC16_Data(vaslen, data_len, 4);

                                                        if (temp_crc == crc_val)
                                                        {
                                                            /*数据校验成功*/
                                                            if (vaslen[10] == 0x01)
                                                            {
                                                                var zunsons = vaslen.Skip(157).Take(64).ToArray();
                                                                var seyu = operation.ByteArrayToHexStr(zunsons);
                                                                var setysssy = operation.UnHexs(seyu);
                                                                setysssy = setysssy.Replace("\0", null);
                                                                setysssy = setysssy.Replace("_", "-");
                                                                ModelName = setysssy;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            MrrMsg = "文件数据CRC校验失败,请检查文件是否正确";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    MrrMsg = "获取机型错误,请检查文件是否正确";
                                                }
                                            }
                                            else
                                            {
                                                MrrMsg = "获取机型失败";
                                            }


                                            FileName.Add(selectdata.App_Cfg_For_L4);
                                            //data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L4))));
                                            SendFileLuncher send = new SendFileLuncher();
                                            send.LuncherVer = "Launcher_C1F_V04";
                                            if (selectdata.App_Cfg_For_L4.Substring(selectdata.App_Cfg_For_L4.Length - 4, 4) == ".hex")
                                            {
                                                send.filename = selectdata.App_Cfg_For_L4.Replace(".hex", ".bin");
                                            }
                                            else
                                            {
                                                send.filename = selectdata.App_Cfg_For_L4;
                                            }
                                            send.HexStart = hexFile.Get_HexStart_C1();
                                            send.Filenumber = ++coun;
                                            //send.md5 = GetMd5FromString(data);
                                            datalist.Add(send);
                                            Status = true;
                                        }
                                        else
                                        {
                                            MrrMsg = "配置文件校验失败，请检查网络或联系管理员";
                                        }
                                    }
                                }
                                else if (selectdata.APPTYPE == "Hex_Code")
                                {
                                    if (string.IsNullOrEmpty(selectdata.Hex_Code_For_L2) && string.IsNullOrEmpty(selectdata.Hex_Code_For_L4))
                                    {
                                        MrrMsg = "获取文件”失败所选房型没上传固件（APP）或配置文件，请检查网络或联系管理员";
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(selectdata.Hex_Code_For_L2))
                                        {
                                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L2))) == selectdata.Hex_Code_For_L2_MD5)
                                            {
                                                FileName.Add(selectdata.Hex_Code_For_L2);
                                                //data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L2))));
                                                ModelName = hexFile.GetHexInfo();
                                                SendFileLuncher send = new SendFileLuncher();
                                                send.LuncherVer = "Launcher_C1F_V02";
                                                if (selectdata.Hex_Code_For_L2.Substring(selectdata.Hex_Code_For_L2.Length - 4, 4) == ".hex")
                                                {
                                                    send.filename = selectdata.Hex_Code_For_L2.Replace(".hex", ".bin");
                                                }
                                                else
                                                {
                                                    send.filename = selectdata.Hex_Code_For_L2;
                                                }
                                                send.HexStart = hexFile.Get_HexStart_C1();
                                                send.Filenumber = ++coun;
                                                //send.md5 = GetMd5FromString(data);
                                                datalist.Add(send);
                                                Status = true;
                                            }
                                            else
                                            {
                                                MrrMsg = "配置文件校验失败，请检查网络或联系管理员";
                                            }
                                        }

                                        if (!string.IsNullOrEmpty(selectdata.Hex_Code_For_L4))
                                        {
                                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L4))) == selectdata.Hex_Code_For_L4_MD5)
                                            {
                                                FileName.Add(selectdata.Hex_Code_For_L4);
                                                //data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L4))));
                                                ModelName = hexFile.GetHexInfo();
                                                SendFileLuncher send = new SendFileLuncher();
                                                send.LuncherVer = "Launcher_C1F_V04";
                                                if (selectdata.Hex_Code_For_L4.Substring(selectdata.Hex_Code_For_L4.Length - 4, 4) == ".hex")
                                                {
                                                    send.filename = selectdata.Hex_Code_For_L4.Replace(".hex", ".bin");
                                                }
                                                else
                                                {
                                                    send.filename = selectdata.Hex_Code_For_L4;
                                                }
                                                send.Filenumber = ++coun;
                                                send.HexStart = hexFile.Get_HexStart_C1();
                                                //send.md5 = GetMd5FromString(data);
                                                datalist.Add(send);
                                                Status = true;
                                            }
                                            else
                                            {
                                                MrrMsg = "配置文件校验失败，请检查网络或联系管理员";
                                            }
                                        }

                                    }
                                }
                            }
                            else
                            {
                                MrrMsg = "无烧录模式,";
                            }
                        }
                        FileCount = datalist.Count;
                        string sum = "";
                        //写入日志
                        eqlog.CreationTime = DateTime.Now;
                        eqlog.Succeed = Status;
                        foreach (var item in FileName)
                        {
                            sum += item + "/";
                        }
                        eqlog.Content = "房间类型id是:" + RoomTypeid + ",升级类型是:" + DataType + ",luncher版本是:" + LuncherVer + ",升级文件名:" + sum + ",机型是:" + ModelName;
                        _db.TBL_EQUIPMENTISSUELOGs.AddRange(eqlog);
                        _db.SaveChanges();
                    }
                    else
                    {
                        return Json(new
                        {
                            RoomTypeid,
                            RoomTypeName,
                            hotelId,
                            hotelName,
                            Status = false,
                            ModelName,
                            FileCount,
                            datalist,
                            MrrMsg = "未找到对应的房型，请检查网络或联系管理员"
                        });
                    }
                }

            }
            catch (Exception ex)
            {

                return Json(new
                {
                    RoomTypeid,
                    RoomTypeName,
                    hotelId,
                    hotelName,
                    Status = false,
                    ModelName,
                    FileCount,
                    datalist,
                    MrrMsg = ex.Message
                });
            }
            return Json(new
            {
                RoomTypeid,
                RoomTypeName,
                hotelId,
                hotelName,
                Status,
                ModelName,
                FileCount,
                datalist,
                MrrMsg

            });
        }



        #endregion
        /// <summary>
        /// 生成字符串的MD5码
        /// </summary>
        /// <param name="sInput"></param>
        /// <returns></returns>
        public static string GetMd5FromString(string sInput)
        {
            var lstData = Encoding.GetEncoding("utf-8").GetBytes(sInput);
            var lstHash = new MD5CryptoServiceProvider().ComputeHash(lstData);
            var result = new StringBuilder(32);
            for (int i = 0; i < lstHash.Length; i++)
            {
                result.Append(lstHash[i].ToString("x2").ToUpper());
            }
            return result.ToString();
        }
        #region 获取对应的文件下发


        [HttpPost]
        [Route("OTApi/GainFile")]
        public IActionResult GainFile1(int RoomTypeid, int DataType, string LuncherVer)
        {
            if (string.IsNullOrEmpty(LuncherVer))
            {
                LuncherVer = "L02";
            }
            FTPOperation operation = new FTPOperation();
            HexFile hexFile = new HexFile();
            //数据主题
            string data = "";
            //状态
            bool Status = false;
            //最后获取的文件
            string FileName = "";
            //错误信息
            string MrrMsg = null;
            //机型
            string ModelName = "";
            //Hex起初地址
            string HexStart = "";
            //
            //写入日志
            TBL_EQUIPMENTISSUELOG eqlog = new TBL_EQUIPMENTISSUELOG();
            try
            {


                if (RoomTypeid != 0)
                {
                    //获取对应的房间类型表的中的字段
                    var selectdata = (
                        from a in _db.TBL_ROOM_TYPE_LISTS

                        join b in _db.TBL_HOTEL_BASIC_INFOS on a.HOTEL_OLD_ID equals b.IDOLD

                        join c in _db.TBL_HOTEL_GROUP_INFOS on b.HOTEL_OLD_GROUP equals c.HOTEL_GROUP_OLD_ID

                        where a.ROOM_TYPE_OLD_ID == RoomTypeid
                        select new
                        {
                            a.CONFIG_BIN,
                            a.App_Cfg_For_L2,
                            a.App_Cfg_For_L4,
                            a.HOTEL_OLD_ID,
                            c.HOTEL_GROUP_NAME,
                            b.HOTEL_NAME_CN,
                            b.PROJECT_NUMBER,
                            a.Hex_Code_For_L2,
                            a.Hex_Code_For_L4,
                            a.APPTYPE,
                            a.Hex_Code_For_L2_MD5,
                            a.Hex_Code_For_L4_MD5,
                            a.App_Cfg_For_L2_MD5,
                            a.App_Cfg_For_L4_MD5,
                            a.CONFIG_BIN_MD5
                        }).FirstOrDefault();
                    //升级文件
                    if (DataType == 2)
                    {

                        if (selectdata.CONFIG_BIN != null)
                        {
                            //校验MD5
                            if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN))) == selectdata.CONFIG_BIN_MD5)
                            {
                                var sety = operation.GetFile("Config/" + selectdata.HOTEL_GROUP_NAME + @"/" + selectdata.PROJECT_NUMBER + "-" + selectdata.HOTEL_NAME_CN + @"/" + selectdata.CONFIG_BIN);
                                data = Convert.ToBase64String(sety);
                                FileName = selectdata.CONFIG_BIN;
                                Status = true;
                            }
                            else
                            {
                                MrrMsg = "配置dat文件校验失败";
                            }
                        }
                        else
                        {
                            MrrMsg = "无配置文件";
                        }
                    }
                    //配置文件
                    else if (DataType == 1)
                    {
                        string lum;
                        if (!string.IsNullOrEmpty(LuncherVer))
                        {
                            lum = LuncherVer.Substring(0, 1) + LuncherVer.Substring(LuncherVer.Length - 2, 2);
                            if (lum == "L02" || lum == "L04")
                            {
                                //判断是代码烧录还是工具烧录
                                if (selectdata.APPTYPE != "")
                                {
                                    if (selectdata.APPTYPE == "App_Cfg")
                                    {
                                        switch (lum)
                                        {
                                            case "L02":
                                                if (!string.IsNullOrEmpty(selectdata.App_Cfg_For_L2))
                                                {
                                                    if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L2))) == selectdata.App_Cfg_For_L2_MD5)
                                                    {
                                                        FileName = selectdata.App_Cfg_For_L2;
                                                        data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L2))));
                                                        ModelName = hexFile.GetHexInfo();
                                                        HexStart = hexFile.Get_HexStart_C1();
                                                        Status = true;
                                                    }
                                                    else
                                                    {
                                                        MrrMsg = "配置App_Cfg_L2文件校验失败";
                                                    }
                                                }
                                                else
                                                {
                                                    MrrMsg = "无App_Cfg_L2文件";
                                                }

                                                break;
                                            case "L04":
                                                if (!string.IsNullOrEmpty(selectdata.App_Cfg_For_L4))
                                                {


                                                    if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L4))) == selectdata.App_Cfg_For_L4_MD5)
                                                    {
                                                        FileName = selectdata.App_Cfg_For_L4;
                                                        data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.App_Cfg_For_L4))));
                                                        ModelName = hexFile.GetHexInfo();
                                                        HexStart = hexFile.Get_HexStart_C1();
                                                        Status = true;
                                                    }
                                                    else
                                                    {
                                                        MrrMsg = "配置App_Cfg_L4文件校验失败";
                                                    }
                                                }
                                                else
                                                {
                                                    MrrMsg = "无App_Cfg_L4文件";
                                                }
                                                break;
                                        }
                                    }
                                    else if (selectdata.APPTYPE == "Hex_Code")
                                    {
                                        switch (lum)
                                        {
                                            case "L02":
                                                if (!string.IsNullOrEmpty(selectdata.Hex_Code_For_L2))
                                                {

                                                    if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L2))) == selectdata.Hex_Code_For_L2_MD5)
                                                    {
                                                        FileName = selectdata.Hex_Code_For_L2;
                                                        data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L2))));
                                                        ModelName = hexFile.GetHexInfo();
                                                        HexStart = hexFile.Get_HexStart_C1();
                                                        Status = true;
                                                    }
                                                    else
                                                    {
                                                        MrrMsg = "配置Hex_Code_For_L2文件校验失败";
                                                    }
                                                }
                                                else
                                                {
                                                    MrrMsg = "无Hex_Code_For_L2文件";
                                                }
                                                break;
                                            case "L04":
                                                if (!string.IsNullOrEmpty(selectdata.Hex_Code_For_L4))
                                                {
                                                    if (MD5Verify.getMD5Hash(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L4))) == selectdata.Hex_Code_For_L4_MD5)
                                                    {
                                                        FileName = selectdata.Hex_Code_For_L4;
                                                        data = Convert.ToBase64String(hexFile.DealHexFile(operation.BytesToStream(operation.GetFile("Firmware/" + selectdata.Hex_Code_For_L4))));
                                                        ModelName = hexFile.GetHexInfo();
                                                        HexStart = hexFile.Get_HexStart_C1();
                                                        Status = true;
                                                    }
                                                    else
                                                    {
                                                        MrrMsg = "配置Hex_Code_For_L4文件校验失败";
                                                    }
                                                }
                                                else
                                                {
                                                    MrrMsg = "无Hex_Code_For_L4文件";
                                                }
                                                break;
                                        }
                                    }
                                }
                                else
                                {
                                    MrrMsg = "无烧录模式";
                                }
                            }
                            else
                            {
                                MrrMsg = "luncher未找到对应的升级文件";
                            }
                        }
                    }
                }
                //写入日志
                eqlog.CreationTime = DateTime.Now;
                eqlog.Succeed = Status;
                eqlog.Content = "房间类型id是:" + RoomTypeid + ",升级类型是:" + DataType + ",luncher版本是:" + LuncherVer + ",升级文件名:" + FileName + ",机型是:" + ModelName;
                _db.TBL_EQUIPMENTISSUELOGs.AddRange(eqlog);
                _db.SaveChanges();

                if (!string.IsNullOrEmpty(FileName))
                {
                    if (FileName.Substring(FileName.Length - 4, 4) == ".hex")
                    {
                        FileName = FileName.Replace(".hex", ".bin");
                    }
                }
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(FileName))
                {
                    if (FileName.Substring(FileName.Length - 4, 4) == ".hex")
                    {
                        FileName = FileName.Replace(".hex", ".bin");
                    }
                }
                return Json(new
                {
                    data,
                    Status = false,
                    ModelName,
                    HexStart,
                    FileName,
                    MrrMsg = ex.Message
                });
            }
            return Json(new
            {
                data,
                Status,
                ModelName,
                HexStart,
                FileName,
                MrrMsg
            });
        }



        #endregion





        #region  同步选住的数据
        /// <summary>
        /// 同步选住的数据
        /// </summary>
        /// <returns></returns>
        /// 

        [HttpPost]
        [Route("OTApi/RoomChange")]
        public IActionResult RoomChange(string projectCode, string roomNumber, string roomLayout, string projectName)
        {
            var db = new DbHelperSQL(DbHelperSQL.DBSel.BLV_RCU_DB);
            if (!string.IsNullOrEmpty(projectCode) && !string.IsNullOrEmpty(roomNumber) && !string.IsNullOrEmpty(roomLayout) && !string.IsNullOrEmpty(projectName))
            {
                var selectdata = (
                          from a in _db.TBL_HOTEL_BASIC_INFOS
                          where a.HOTEL_NAME_CN == projectName
                          select new
                          {
                              a.HOTEL_ID
                          }).FirstOrDefault();
                var roomdata = (
                         from a in _db.TBL_ROOM_TYPE_LISTS
                         where a.ROOM_TYPE_NAME == roomNumber
                         select new
                         {
                             a.ROOM_TYPE_ID
                         }).FirstOrDefault();

                if (selectdata == null)
                {
                    if (db.ExecuteSql($"INSERT INTO tbl_hotel_basic_info(PROJECT_NUMBER, HOTEL_NAME_CN, KEY_ID, IsApprove, HOTEL_GROUP, VALID_STATUS,`STATUS`, SORT, IDOLD, IsDel, HOTEL_OLD_GROUP, BRANDID) VALUES('{projectCode}', '{projectName}', 0, 1, 0, 0, 2, 0, 0, 0, 0, 2); ") != -1)
                    {

                    }
                }

            }
            else
            {
                return Json(new
                {
                    retmsg = "参数不可为空",
                    retcode = "404"
                });
            }
            return Json("");
        }
        #endregion
    }
}
