using AutoMapper;
using LinqKit;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Ropin.Core.Common;
using Ropin.Inspection.Common;
using Ropin.Inspection.Common.Accessor.Interface;
using Ropin.Inspection.Common.Helper;
using Ropin.Inspection.Model;
using Ropin.Inspection.Model.Entities;
using Ropin.Inspection.Repository;
using Ropin.Inspection.Repository.Interface;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;

namespace Ropin.Inspection.Service
{
    public class TdevBoxService : ITdevBoxService
    {
        private readonly ITdevBoxRepository _repository;
        private readonly IMapper _mapper;
        private readonly IClaimsAccessor _claims;
        private readonly InspectionDbContext _sqlDBContext;
        private readonly ITmtnDevOpsRecordRepository _tmtnDevOpsRecordRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly ITdevBoxDevSpotRepository _devBoxDevSpotRepository;
        public TdevBoxService(ITmtnDevOpsRecordRepository tmtnDevOpsRecordRepository,IClaimsAccessor claims, InspectionDbContext sqlDBContext, ITdevBoxRepository repository, IMapper mapper,IUnitOfWork unitOfWork, ITdevBoxDevSpotRepository devBoxDevSpotRepository)
        {
            _repository = repository;
            _mapper = mapper;
            _claims = claims;
            _sqlDBContext = sqlDBContext;
            _tmtnDevOpsRecordRepository = tmtnDevOpsRecordRepository;
            _unitOfWork = unitOfWork;
            _devBoxDevSpotRepository = devBoxDevSpotRepository;
        }

        public async Task CreateOneAsync(TdevBoxViewModel viewModel)
        {
            var datas = await _repository.GetByConditionAsync(t=>t.C_BoxNo==viewModel.C_BoxNo);
            if (datas.Count()>0&&datas.FirstOrDefault()!=null)
            {
                throw new Exception("网关编号已存在!");
            }
            var id = Guid.NewGuid().ToString();
            var path = QRCoderHelper.RenderQrCode(id, "M", _claims.Linsence);
            var content = _mapper.Map<TDEV_Box>(viewModel);
            content.C_ID = id;
            content.C_CreateBy = _claims.ApiUserId;
            content.D_CreateOn = DateTime.Now;
            content.C_Status = "1";
            content.C_QRCode = path;
            _repository.Create(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("创建失败");
            }
        }
        /// <summary>
        /// 业主盒子-拷贝
        /// </summary>
        /// <param name="oldId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task CopyCreateAsync(string oldId)
        {
            TDEV_Box content = await _repository.GetByIdAsync(oldId);
            if (content == null)
            {
                throw new Exception("没有此数据");
            }
            bool result = false;
            _unitOfWork.BeginTransaction();
            try
            {
                string newId = Guid.NewGuid().ToString();
                var path = QRCoderHelper.RenderQrCode(newId, "M", _claims.Linsence);
                content.C_ID = newId;
                content.C_Name = content.C_Name + "-拷贝";
                content.C_CreateBy = _claims.ApiUserId;
                content.D_CreateOn = DateTime.Now;
                content.C_Status = "1";
                content.C_QRCode = path;
                content.C_LastUpdatedBy = null;
                content.D_LastUpdatedOn = null;
                result = await _unitOfWork.RegisterNew(content);
                if (result)
                {
                    var devBoxDevSpot = await _devBoxDevSpotRepository.GetByConditionAsync(t => t.C_BoxCode == oldId);
                    List<TDEV_BoxDevSpot> boxDevList = new List<TDEV_BoxDevSpot>();
                    foreach (var item in devBoxDevSpot)
                    {
                        if (item != null)
                        {
                            TDEV_BoxDevSpot tDEV_Web = new TDEV_BoxDevSpot();
                            tDEV_Web = item;
                            tDEV_Web.C_ID = Guid.NewGuid().ToString();
                            tDEV_Web.C_BoxCode = content.C_ID;
                            tDEV_Web.C_LastUpdatedBy = null;
                            tDEV_Web.D_LastUpdatedOn = null;
                            tDEV_Web.C_CreateBy = _claims.ApiUserId;
                            tDEV_Web.D_CreateOn = DateTime.Now;
                            boxDevList.Add(tDEV_Web);
                        }
                    }
                    if (boxDevList != null && boxDevList.Count > 0)
                    {
                        result = await _unitOfWork.RegisterRangeNew(boxDevList.ToList());
                    }
                }
            }
            catch
            {
                result = false;
                throw;
            }
            finally
            {
                if (result)
                    await _unitOfWork.CommitAsync();
                else
                    _unitOfWork.Rollback();
            }
        }
        public async Task DeleteAsync(string id)
        {
            var content = await _repository.GetByIdAsync(id);
            if (content == null)
            {
                throw new Exception("数据库中没有此数据");
            }
            content.C_LastUpdatedBy = _claims.ApiUserId;
            content.D_LastUpdatedOn = DateTime.Now;
            content.C_Status = "0";
            _repository.Update(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("删除失败");
            }
        }

        public async Task UpdateAsync(string code, TdevBoxUpdateModel updateModel)
        {
            var items = await _repository.GetByConditionAsync(C => C.C_ID == code);
            var content = items.FirstOrDefault();
            if (content == null)
            {
                throw new Exception("没有此数据");
            }
            var datas = await _repository.GetByConditionAsync(t => t.C_BoxNo == updateModel.C_BoxNo&&t.C_ID!= code);
            if (datas.Count() > 0 && datas.FirstOrDefault() != null)
            {
                throw new Exception("网关编号已存在!");
            }
            content.C_LastUpdatedBy = _claims.Linsence == null ? _claims.ApiUserId : Guid.Parse("6e864cbc-5252-11ec-8681-fa163e02b3e4");
            content.D_LastUpdatedOn = DateTime.Now;
            _mapper.Map(updateModel, content, typeof(TdevBoxUpdateModel), typeof(TDEV_Box));
            _repository.Update(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("更新失败");
            }
        }

        public async Task<IEnumerable<TdevBoxViewModel>> GetConditionAsync(TdevBoxSearchModel searchModel)
        {
            return await _repository.GetConditionAsync(searchModel);
            //var predicate = PredicateBuilder.New<TDEV_Box>(true);//查询条件,推荐后台使用这种方式灵活筛选
            //#region 添加条件查询
            //if (!string.IsNullOrEmpty(searchModel.C_Status))
            //{
            //    predicate = predicate.And(i => i.C_Status.Equals(searchModel.C_Status));
            //}
            //else
            //{
            //    predicate = predicate.And(i => !i.C_Status.Equals("0"));
            //}
            //if (!string.IsNullOrEmpty(searchModel.C_ID))
            //{
            //    predicate = predicate.And(i => i.C_ID.Equals(searchModel.C_ID));
            //}
            //if (!string.IsNullOrEmpty(searchModel.C_Name))
            //{
            //    predicate = predicate.And(i => i.C_Name.Contains(searchModel.C_Name));
            //}
            //if (!string.IsNullOrEmpty(searchModel.C_StoreCode))
            //{
            //    predicate = predicate.And(i => i.C_StoreCode == searchModel.C_StoreCode);
            //}
            //#endregion
            //var list = await _repository.GetPageAsync(predicate, "I_Sort", searchModel.IsPagination, searchModel.PageIndex, searchModel.PageSize);//C_Name,-D_CreateOn
            //searchModel.TotalCount = list.Totals;
            //var dtoList = _mapper.Map<List<TDEV_Box>, List<TdevBoxViewModel>>(list.Rows);
            //return dtoList;
        }
        
        public async Task<TdevBoxViewModel> GetConditionByIdAsync(string code)
        {
            var items = await _repository.GetByConditionAsync(C => C.C_ID == code);
            var content = items.FirstOrDefault();
            if (content != null)
            {
                var entity = _mapper.Map<TDEV_Box, TdevBoxViewModel>(content);
                return entity;
            }
            else
            {
                return null;
            }
        }
        public Task<int> UpdateOneAsync(TdevBoxViewModel viewModel, params string[] fields)
        {
            throw new NotImplementedException();
        }

        public Task<TdevBoxViewModel> GetByIdAsync(string id)
        {
            throw new NotImplementedException();
        }

        public Task<bool> IsExistAsync(string id)
        {
            throw new NotImplementedException();
        }
    }
}