using DeviceRepair.Models;
using DeviceRepair.Models.Tag;
using NLog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DeviceRepair.DataAccess
{
    public class TagAccess : DbContext<TagRecordInfo>
    {
        private static readonly Logger log = LogManager.GetCurrentClassLogger();

        private static TagAccess manager;
        public static TagAccess Instance
        {
            get
            {
                if (manager == null)
                    manager = new TagAccess();
                return manager;
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public APIResponseData GetDatas(TagRecordFilter filter, string LoginCode)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            try
            {
                if (filter == null)
                    filter = new TagRecordFilter();

                if (filter.sDate.Year < 2000)
                {
                    filter.sDate = filter.sDate.AddYears((2000 - filter.sDate.Year));
                }

                if (filter.eDate.Year < 2000)
                {
                    filter.eDate = filter.eDate.AddYears((2000 - filter.eDate.Year));
                }

                List<DeviceInformationInfo> Devs = DeviceAccess.Instance.GetDevsByLoginAuths(LoginCode);
                if (Devs.Count == 0)
                    return new APIResponseData { Code = -1, Message = $"没有查询到数据！" };
                int[] ids = Devs.Select(x => x.AutoID).ToArray();

                db.ChangeDatabase("main");
                var exp = Expressionable.Create<TagRecordInfo>()
                       .And(t1 => t1.CreatOn >= filter.sDate)
                       .And(t1 => t1.CreatOn <= filter.eDate)
                       .AndIF(!string.IsNullOrWhiteSpace(filter.EquipmentDisPlayID), t1 => t1.EquipmentDisPlayID == filter.EquipmentDisPlayID)
                       .AndIF(!string.IsNullOrWhiteSpace(filter.TagFormStatus), t1 => t1.TagFormStatus == filter.TagFormStatus).ToExpression();//拼接表达式

                var Datas = db.Queryable<TagRecordInfo>().Where(x => SqlFunc.ContainsArray(ids, x.EquipmentID)).Where(exp).ToList();

                apiResponseData.Code = 1;
                apiResponseData.Data = Datas;
                apiResponseData.Message = "";
            }
            catch (SqlSugarException e)
            {
                log.Error(e);
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 数据新增
        /// </summary>
        /// <param name="Model"></param>
        /// <param name="Operation"></param>
        /// <returns></returns>
        public APIResponseData Creat(TagRecordInfo Model, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"创建数据失败！" };
            try
            {
                if (Model == null)
                    throw new Exception("新增的数据不能为空!");

                if (string.IsNullOrWhiteSpace(Model.EquipmentDisPlayID) || Model.EquipmentID == 0)
                    throw new Exception("传入的设备信息不能为空!");

                db.ChangeDatabase("main");
                if (Model.AutoID != 0)
                {
                    // tag 表单修改
                    TagRecordInfo tag = db.Queryable<TagRecordInfo>().First(x => x.AutoID == Model.AutoID);
                    if (tag == null)
                        throw new Exception($"TagNo.{Model.AutoID}的数据不存在,修改失败!");

                    if (tag.TagFormStatus == "C")
                        throw new Exception($"TagNo.{Model.AutoID}的数据已被修改!");

                    tag.BrokenDamaged = Model.BrokenDamaged;
                    tag.Access = Model.Access;
                    tag.Clean = Model.Clean;
                    tag.Inspect = Model.Inspect;
                    tag.SourceOfContamination = Model.SourceOfContamination;
                    tag.NotInUse = Model.NotInUse;
                    tag.NotNeeded = Model.NotNeeded;
                    tag.UnsafeConditions = Model.UnsafeConditions;
                    tag.MissingComponents = Model.MissingComponents;
                    tag.DetailsOfIssue = Model.DetailsOfIssue;
                    tag.ModifyBy = Operation.Operator;
                    tag.ModifyName = Operation.OperatorName;
                    tag.ModifyOn = DateTime.Now;
                    if (db.Updateable(tag).ExecuteCommand() > 0)
                    {
                        apiResponseData.Code = 1;
                        apiResponseData.Data = tag;
                        apiResponseData.Message = "操作成功!";
                        return apiResponseData;
                    }
                }


                DeviceInformationInfo dev = db.Queryable<DeviceInformationInfo>().First(x => x.EquipmentID == Model.EquipmentDisPlayID && x.EquipmentStatus == 1);
                if (dev == null)
                    throw new Exception("传入的设备信息出错或设备未启用!");

                Model.EquipmentDisPlayID = dev.EquipmentID;
                Model.EquipmentName = dev.EquipmentName;
                Model.EquipmentID = dev.AutoID;
                Model.CreateBy = Operation.Operator;
                Model.CreatOn = DateTime.Now;
                Model.CreatorName = Operation.OperatorName;
                Model.TagFormStatus = "N";

                db.BeginTran();
                TagRecordInfo Rtn = db.Insertable(Model).ExecuteReturnEntity();
                if (Rtn == null)
                {
                    db.RollbackTran();
                    throw new Exception("数据库写入出错!");
                }
                db.CommitTran();
                apiResponseData.Code = 1;
                apiResponseData.Data = Rtn;
                apiResponseData.Message = "操作成功!";
            }
            catch (SqlSugarException e)
            {
                log.Error(e);
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 接受/维修
        /// </summary>
        /// <param name="Model"></param>
        /// <param name="Operation"></param>
        /// <returns></returns>
        public APIResponseData Receipt(TagRecordInfo Model, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"维修数据失败！" };
            try
            {
                if (Model == null)
                    throw new Exception("维修的数据不能为空!");

                db.ChangeDatabase("main");

                TagRecordInfo tagRecordInfo = db.Queryable<TagRecordInfo>().First(x => x.AutoID == Model.AutoID);
                if (tagRecordInfo == null)
                    throw new Exception($"找不到Tag编号为【{Model.AutoID}】的Tag表单!");

                tagRecordInfo.ReceiptBy = Operation.Operator;
                tagRecordInfo.ReceiptName = Operation.OperatorName;
                tagRecordInfo.ReceiptOn = DateTime.Now;
                tagRecordInfo.ReceiptDetailsOfIssue = Model.ReceiptDetailsOfIssue;
                tagRecordInfo.TagFormStatus = "C";

                db.BeginTran();
                int Rtn = db.Updateable(tagRecordInfo).ExecuteCommand();
                if (Rtn > 0)
                {
                    db.CommitTran();
                    apiResponseData.Code = 1;
                    apiResponseData.Message = "操作成功";
                    apiResponseData.Data = tagRecordInfo;
                }
                else
                {
                    db.RollbackTran();
                }
            }
            catch (SqlSugarException e)
            {
                log.Error(e);
                apiResponseData.Code = -1;
                apiResponseData.Message = e.Message;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

    }
}
