using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Utils;

namespace PMS.NetCore.Controllers
{
    /// <summary>
    /// 车牌识别一体机推送车辆信息
    /// </summary>
    [Produces("application/json;charset=UTF-8")]
    [Route("api/AlarmInfoPlate")]
    [ApiController]
    public class AlarmInfoPlateController : BaseController
    {

        /// <summary>
        /// 客户关系
        /// </summary>
        public AlarmInfoPlateController()
        {
            logger = NLog.LogManager.GetCurrentClassLogger();
        }

        /// <summary>
        /// 推送车辆进出信息
        /// </summary>
        /// <param name="carInOrOutInfo">进出车辆信息</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("CarInOrOut")]
        public JsonResult CarInOrOut([FromBody] CarInOrOut carInOrOutInfo)
        {
            var response = new Response_AlarmInfoPlate();
            //logger.Info($"【CarInOrOut】dto:{JsonConvert.SerializeObject(list)}");
            try
            {
                string serialno = string.Empty, vcarcode = string.Empty, msg = "开闸"; int channel = 0;
                if (carInOrOutInfo.AlarmInfoPlate != null && carInOrOutInfo.AlarmInfoPlate.Serialno != null && carInOrOutInfo.AlarmInfoPlate.Result != null && carInOrOutInfo.AlarmInfoPlate.Result.PlateResult != null && carInOrOutInfo.AlarmInfoPlate.Result.PlateResult.License != null)
                {
                    serialno = carInOrOutInfo.AlarmInfoPlate.Serialno;
                    channel = carInOrOutInfo.AlarmInfoPlate.Channel;
                    vcarcode = carInOrOutInfo.AlarmInfoPlate.Result.PlateResult.License;

                    if (!string.IsNullOrEmpty(vcarcode))
                    {
                        //插入推送信息
                        new AlarmInfoPlateLogManager().InsertAlarmInfoPlateLog(carInOrOutInfo.ToString());
                        var carInOrOutManager = new fdc_pm_CarInOrOutManager();
                        var vehicleManager = new fdc_pm_vehicleManager();

                        string status = "0";
                        //判断摄像设备是进入设备
                        var cameradevice = carInOrOutManager.Getfdc_pm_cameradevicestatus(serialno);

                        if (cameradevice == null)
                        {
                            status = "1";
                            vehicleManager.Updatefdc_pm_vehiclecarstatus(vcarcode, 1);
                            response.info = "ok";
                            response.channelNum = channel;
                            response.serialData = new List<SerialData>();
                        }
                        else
                        {
                            // 判断车辆是否属于白名单
                            var whiteList = carInOrOutManager.Getfdc_pm_vehicleWhiteListByvcarcode(vcarcode);
                            if (whiteList != null)
                            {
                                vehicleManager.Updatefdc_pm_vehiclecarstatus(vcarcode, 0);
                                response.info = "ok";
                                response.channelNum = channel;
                                response.serialData = new List<SerialData>();
                            }
                            else
                            {
                                bool isExist = true;
                                var itemdictionaryManager = new itemdictionaryManager();
                                string itemID = "车辆进入时检查业主是否拖欠物业费和停车费";
                                string itemType = "param";
                                var itemdictionaryInfo = itemdictionaryManager.GetItemdictionary(itemID, itemType);

                                string billitemcodeinfo = itemdictionaryInfo.ItemName;
                                string[] sArray = billitemcodeinfo.Split(';');
                                fdc_pm_fare_bManager fare_bManager = new fdc_pm_fare_bManager();

                                for (int i = 0; i < sArray.Length; i++)
                                {
                                    string billitemcode = sArray[i];
                                    if (billitemcode.Contains(","))
                                    {
                                        billitemcode = billitemcode.Replace(",", "','");
                                    }

                                    var fare_b = fare_bManager.Getfdc_pm_fare_bByvcarcodeAndbillitemcode(vcarcode, billitemcode);

                                    if (fare_b.Count == 0)
                                    {
                                        isExist = false;
                                        msg = "费用记录不存在";
                                        break;
                                    }
                                    else
                                    {
                                        decimal nneedpaymny = fare_b[0].nneedpaymny.Value;
                                        decimal nrevmny = fare_b[0].nrevmny.Value;

                                        if (nneedpaymny > nrevmny)
                                        {
                                            isExist = false;
                                            msg = "拖欠费用";
                                            break;
                                        }
                                    }
                                }
                            }


                        }
                    }


                    //var errmsg = "";

                    //var manager = new fdc_pm_ownerManager();
                    //foreach (var dto in list)
                    //{

                    //}
                    //if (errmsg != "")
                    //{
                    //    return Json(errmsg);
                    //}

                    //去除重复的业主主键
                    //var list1 = list.Where((x, i) => list.FindIndex(z => z.ownerid == x.ownerid) == i).ToList();
                    //var list2 = new List<string>();
                    //var owneridMsg = "";
                    //foreach (var dto in list1)
                    //{
                    //    var index = list.IndexOf(dto);
                    //    var entity = manager.GetById(dto.ownerid);
                    //    if (entity != null)
                    //    {
                    //        owneridMsg += $"第{index + 1}条数据{dto.ownerid }业主编码已存在;";
                    //        list2.Add(dto.ownerid);
                    //    }

                    //}
                    //if(owneridMsg.IsNotNullAndEmpty())
                    //{
                    //    return Json(owneridMsg);
                    ////}
                    //for (int i = list1.Count - 1; i >= 0; i--)
                    //{
                    //    var entity = manager.GetById(list1[i].ownerid);
                    //    if (entity != null)
                    //    {
                    //        list1.Remove(list1[i]);
                    //    }
                    //}

                    //int row = 0;
                    //if (list1.Count > 0)
                    //{
                    //    //批量插入
                    //    row = manager.Db.Insertable(list1).ExecuteCommand();
                    //}
                    //else
                    //{
                    //    row = 1;
                    //}



                    //logger.Info($"【Fdc_pm_ownerAdd】row:{row}");


                    response.info = "Ok";
                    response.channelNum = channel;
                    return Json(response);

                }
                response.info = "Ok";
                response.channelNum = channel;
                return Json(response);
            }
            catch (Exception ex)
            {
                logger.Error(ex);

                response.info = "Ok";
                response.channelNum = 0;
                return Json(response);
            }
        }

    }
}
