using DeviceRepair.Models;
using DeviceRepair.Models.History;
using DeviceRepair.Models.Logs;
using SqlSugar;
using System;
using System.Collections.Generic;

namespace DeviceRepair.DataAccess
{
    public class FieldAccess : DbContext<FieldsInfo>
    {
        private static FieldAccess manager;
        public static FieldAccess Instance
        {
            get
            {
                if (manager == null)
                    manager = new FieldAccess();
                return manager;
            }
        }

        /// <summary>
        /// 根据字段编码获取数据
        /// </summary>
        /// <param name="Codes">字段编码（多字段用逗号分割）</param>
        /// <returns></returns>
        public APIResponseData GetFieldsByCodes(string Codes)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            try
            {
                db.ChangeDatabase("main");

                string[] cds = Codes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                List<FieldsInfo> Datas = CurrentDb.AsQueryable().Where(x => SqlFunc.ContainsArray(cds, x.FieldCode)).ToList();
                apiResponseData.Code = 1;
                apiResponseData.Data = Datas;
                apiResponseData.Message = "";
            }
            catch (SqlSugarException e)
            {
                return new APIResponseData { Code = -1, Message = e.Message };
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return apiResponseData;
        }

        /// <summary>
        /// 检验数据是否存在
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="Text"></param>
        /// <returns></returns>
        public APIResponseData TextIsExists(string Code, string Text)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"检测数据出错！" };
            try
            {
                db.ChangeDatabase("main");
                int Count = CurrentDb.Count(x => x.FieldCode.Equals(Code, StringComparison.CurrentCultureIgnoreCase) && x.FieldText.Equals(Text, StringComparison.CurrentCultureIgnoreCase));

                apiResponseData.Code = 1;
                apiResponseData.Data = Count;
                apiResponseData.Message = "";
            }
            catch (SqlSugarException e)
            {
                return new APIResponseData { Code = -1, Message = e.Message };
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return apiResponseData;
        }

        /// <summary>
        /// 新增或者编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="Operation"></param>
        /// <returns></returns>
        public APIResponseData InsertOrEdit(FieldsInfo entity, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1 };
            try
            {
                if (entity == null || Operation == null)
                    throw new Exception("传入的参数不能为空！");

                DateTime CurrentDate = DateTime.Now;
                bool isSuccess = false;
                EnumOperationType operationType = EnumOperationType.Add;

                db.ChangeDatabase("main");
                db.BeginTran();

                FieldsHistory his = null;
                FieldLog log = null;

                if (entity.AutoID != 0)
                {
                    // 修改
                    operationType = EnumOperationType.Change;

                    var old = db.Queryable<FieldsInfo>().Single(x => x.AutoID == entity.AutoID);
                    if (old == null)
                        throw new Exception($"传入的修改对象出错，主键编号为【{entity.AutoID}】的数据不存在！");

                    //记录历史信息
                    his = new FieldsHistory
                    {
                        FieldID = entity.AutoID,
                        GUID = entity.GUID,
                        FieldCode = entity.FieldCode,
                        FieldText = entity.FieldText,
                        FieldValue = entity.FieldValue,
                        FieldType = entity.FieldType,
                        Status = entity.Status,
                        Description = entity.Description,
                        CreatBy = entity.CreatBy,
                        CreatOn = entity.CreatOn,
                        ModifyBy = entity.ModifyBy,
                        ModifyOn = entity.ModifyOn,
                        Operator = Operation.Operator,
                        OperationDate = CurrentDate
                    };

                    // 修改
                    int Count = db.Updateable<FieldsInfo>().UpdateColumns(x => new { x.FieldText, x.FieldValue, x.FieldType, x.ModifyBy, x.ModifyOn })
                         .SetColumns(x => new FieldsInfo() { FieldText = entity.FieldText, FieldValue = entity.FieldValue, FieldType = entity.FieldType, ModifyBy = Operation.Operator, ModifyOn = CurrentDate })
                         .Where(x => x.AutoID == entity.AutoID)
                         .ExecuteCommand();
                    isSuccess = Count > 0;
                }
                else
                {
                    // 新增
                    entity.GUID = Guid.NewGuid();
                    entity.CreatBy = Operation.Operator;
                    entity.CreatOn = CurrentDate;
                    entity.Status = true;

                    int Count = CurrentDb.Count(x => x.FieldCode.Equals(entity.FieldCode, StringComparison.CurrentCultureIgnoreCase)
                        && x.FieldText.Equals(entity.FieldText, StringComparison.CurrentCultureIgnoreCase));
                    if (Count > 0)
                        throw new Exception($"已存在名称为【{entity.FieldText}】的数据，无法重复添加！");

                    Count = db.Insertable(entity).ExecuteCommand();
                    isSuccess = Count > 0;
                }

                // 记录操作记录
                if (isSuccess)
                {
                    log = new FieldLog
                    {
                        FieldHisGuid = entity.GUID,
                        OperationComputer = Operation.ClientName,
                        OperationDate = CurrentDate,
                        OperationIP = Operation.IPAddress,
                        OperationType = operationType.ToDescription(),
                        Operator = Operation.Operator
                    };
                }

                db.CommitTran();
                apiResponseData.Code = 1;
                apiResponseData.Message = "操作成功！";

                db.ChangeDatabase("log");
                db.Insertable(log).ExecuteCommand();
                db.Insertable(his).ExecuteCommand();
            }
            catch (SqlSugarException ex)
            {
                db.RollbackTran();
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="AutoID"></param>
        /// <param name="Status"></param>
        /// <param name="Operation"></param>
        /// <returns></returns>
        public APIResponseData ChangeStatus(int AutoID, bool Status, string Description, HeaderModel Operation)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1 };

            try
            {
                DateTime CurrentDate = DateTime.Now;
                bool isSuccess = false;
                EnumOperationType operationType = Status ? EnumOperationType.UnLock : EnumOperationType.Lock;

                db.ChangeDatabase("main");
                db.BeginTran();

                FieldLog log = null;

                FieldsInfo data = db.Queryable<FieldsInfo>().Single(x => x.AutoID == AutoID);
                if (data == null)
                    throw new Exception($"{operationType.ToDescription()}出错，主键编号为【{AutoID}】的数据不存在！");

                int Count = db.Updateable<FieldsInfo>().UpdateColumns(x => new { x.Status, x.Description, x.ModifyBy, x.ModifyOn })
                         .SetColumns(x => new FieldsInfo() { Status = Status, Description = Description, ModifyBy = Operation.Operator, ModifyOn = CurrentDate })
                         .Where(x => x.AutoID == AutoID)
                         .ExecuteCommand();
                isSuccess = Count > 0;

                // 记录操作记录
                if (isSuccess)
                {
                    log = new FieldLog
                    {
                        FieldHisGuid = data.GUID,
                        OperationComputer = Operation.ClientName,
                        OperationDate = CurrentDate,
                        OperationIP = Operation.IPAddress,
                        OperationType = operationType.ToDescription(),
                        Operator = Operation.Operator
                    };
                }

                db.CommitTran();
                apiResponseData.Code = 1;
                apiResponseData.Message = "操作成功！";

                db.ChangeDatabase("log");
                db.Insertable(log).ExecuteCommand();
            }
            catch (SqlSugarException ex)
            {
                db.RollbackTran();
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

    }
}
