using AutoMapper;
using LinqKit;
using Ropin.Core.Common;
using Ropin.Inspection.Common.Accessor.Interface;
using Ropin.Inspection.Model;
using Ropin.Inspection.Model.Entities;
using Ropin.Inspection.Model.ViewModel.DEV;
using Ropin.Inspection.Repository;
using Ropin.Inspection.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Ropin.Inspection.Service
{
    public class TbdmCodeService : ITbdmCodeService
    {
        private readonly ITbdmCodeRepository _repository;
        private readonly ITbdmCodeDetailRepository _codeDetailrepository;
        private readonly IMapper _mapper;
        private readonly IClaimsAccessor _claims;
        private readonly IUnitOfWork _unitOfWork;
        public TbdmCodeService(IClaimsAccessor claims, 
            ITbdmCodeRepository repository, 
            ITbdmCodeDetailRepository codeDetailrepository, 
            IMapper mapper, IUnitOfWork unitOfWork)
        {
            _repository = repository;
            _codeDetailrepository = codeDetailrepository;
            _mapper = mapper;
            _claims = claims;
            _unitOfWork = unitOfWork;
        }
        public async Task<List<TbdmCodeViewModel>> GetCodeListTreeAsync()
        {
            return await _repository.GetProvListTreeAsync();
        }
        /// <summary>
        /// 子表
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        public async Task<IEnumerable<TbdmDetailCode>> GetConditionDetailAsync(TbdmCodeSearchModel searchModel) 
        {
            var predicate = PredicateBuilder.New<TBDM_CodeDetail>(true);//查询条件,推荐后台使用这种方式灵活筛选
            #region 添加条件查询
            if (!string.IsNullOrEmpty(searchModel.C_Status))
            {
                if (searchModel.C_Status == "all") { }
                else
                {
                    predicate = predicate.And(i => i.C_Status.Equals(searchModel.C_Status));
                }
            }
            else
            {
                predicate = predicate.And(i => i.C_Status.Equals("1"));
            }
            if (!string.IsNullOrEmpty(searchModel.C_MainCode))
            {
                predicate = predicate.And(i => i.C_MainCode.Equals(searchModel.C_MainCode));
            }
            if (!string.IsNullOrEmpty(searchModel.C_Code))
            {
                predicate = predicate.And(i => i.C_Code.Equals(searchModel.C_Code));
            }
            if (!string.IsNullOrEmpty(searchModel.C_Name))
            {
                predicate = predicate.And(i => i.C_Name.Contains(searchModel.C_Name));
            }
            #endregion
            var list = await _codeDetailrepository.GetPageAsync(predicate, "I_Sort,-D_CreateOn", searchModel.IsPagination, searchModel.PageIndex, searchModel.PageSize);
            searchModel.TotalCount = list.Totals;
            var dtoList = _mapper.Map<List<TBDM_CodeDetail>, List<TbdmDetailCode>>(list.Rows);
            return dtoList;
        }
        /// <summary>
        /// 主表
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        public async Task<IEnumerable<TbdmCodeViewModel>> GetConditionAsync(TbdmCodeSearchModel searchModel)
        {
            var predicate = PredicateBuilder.New<TBDM_CodeMain>(true);//查询条件,推荐后台使用这种方式灵活筛选
            #region 添加条件查询
            if (!string.IsNullOrEmpty(searchModel.C_Status))
            {
                if (searchModel.C_Status=="all") { }
                else
                {
                    predicate = predicate.And(i => i.C_Status.Equals(searchModel.C_Status));
                }
            }
            else
            {
                predicate = predicate.And(i => i.C_Status.Equals("1"));
            }
            if (!string.IsNullOrEmpty(searchModel.C_Code))
            {
                predicate = predicate.And(i => i.C_Code.Equals(searchModel.C_Code));
            }
            if (!string.IsNullOrEmpty(searchModel.C_Name))
            {
                predicate = predicate.And(i => i.C_Name.Contains(searchModel.C_Name));
            }
            #endregion
            var list = await _repository.GetPageAsync(predicate, "I_Sort,-D_CreateOn", searchModel.IsPagination, searchModel.PageIndex, searchModel.PageSize);
            searchModel.TotalCount = list.Totals;
            var dtoList = _mapper.Map<List<TBDM_CodeMain>, List<TbdmCodeViewModel>>(list.Rows);
            return dtoList;
        }
        public Task<int> UpdateOneAsync(TbdmCodeViewModel viewModel, params string[] fields)
        {
            throw new NotImplementedException();
        }

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

        public Task<IEnumerable<TbdmCodeViewModel>> GetByConditionAsync(Expression<Func<TbdmCodeViewModel, bool>> expression)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 主表添加
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task CreateOneAsync(TbdmCodeViewModel viewModel)
        {
            var info = await _repository.GetByConditionAsync(t => t.C_Code == viewModel.C_Code);
            if (info != null && info.Count() > 0)
            {
                throw new Exception($"“{viewModel.C_Code}”编号已经存在");
            }
            var content = _mapper.Map<TBDM_CodeMain>(viewModel);
            content.C_CreateBy = _claims.ApiUserId;
            content.D_CreateOn = DateTime.Now;
            content.C_Status = "1";
            _repository.Create(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("创建失败");
            }
        }

        /// <summary>
        /// 子表添加
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task CreateDetailAsync(TbdmCodeDetailCreateModel viewModel)
        {
            var detail = await _codeDetailrepository.GetByConditionAsync(t => t.C_Code == viewModel.C_Code);
            if (detail!=null&&detail.Count()>0)
            {
                throw new Exception($"“{viewModel.C_Code}”编号已经存在");
            }
            var content = _mapper.Map<TBDM_CodeDetail>(viewModel);
            content.C_CreateBy = _claims.ApiUserId;
            content.D_CreateOn = DateTime.Now;
            content.C_Status = "1";
            _codeDetailrepository.Create(content);
            var result = await _codeDetailrepository.SaveAsync();
            if (!result)
            {
                throw new Exception("创建失败");
            }
        }
        public Task<TbdmCodeViewModel> GetByIdAsync(string id)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 主表和子表真删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task DeleteAsync(string id)
        {
            bool result = false;
            var content = await _repository.GetByIdAsync(id);
            if (content == null)
            {
                throw new Exception("数据库中没有此数据");
            }
            var detail = await _codeDetailrepository.GetByConditionAsync(t => t.C_MainCode == content.C_Code);
            if (detail!=null&& detail.Count()>0)
            {
                result = await _codeDetailrepository.RemoveRangeAsync(detail) > 0;
            }
            else
            {
                result = true;
            }
            if (result)
            {
                result = await _repository.RemoveAsync(content) > 0;
                if (!result)
                {
                    throw new Exception("删除失败");
                }
            }
            else
            {
                throw new Exception("删除失败");
            }
        }
        /// <summary>
        /// 子表真删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task DeleteDetailAsync(string id)
        {
            var content = await _codeDetailrepository.GetByIdAsync(id);
            if (content == null)
            {
                throw new Exception("数据库中没有此数据");
            }
            var result= await _codeDetailrepository.RemoveAsync(content)>0;
            if (!result)
            {
                throw new Exception("删除失败");
            }
        }
        /// <summary>
        /// 禁用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task DisabledStatusAsync(string id)
        {
            var content = await _repository.GetByIdAsync(id);
            if (content == null)
            {
                throw new Exception("数据库中没有此数据");
            }
            bool result = await _repository.DeleteByCodeAsync(id);
            if (!result)
            {
                throw new Exception("禁用失败");
            }
        }
        /// <summary>
        /// 禁用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task DisabledDetailStatusAsync(string id)
        {
            var content = await _codeDetailrepository.GetByIdAsync(id);
            if (content == null)
            {
                throw new Exception("数据库中没有此数据");
            }
            content.C_Status = "0";
            _codeDetailrepository.Update(content);
            var result = await _codeDetailrepository.SaveAsync();
            if (!result)
            {
                throw new Exception("禁用失败");
            }
        }
        /// <summary>
        /// 主表修改
        /// </summary>
        /// <param name="code"></param>
        /// <param name="updateModel"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task UpdateAsync(string code, TbdmCodeViewModel updateModel)
        {
            var content = await _repository.GetByIdAsync(code);
            if (content == 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(TbdmCodeViewModel), typeof(TBDM_CodeMain));
            _repository.Update(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("更新失败");
            }
        }

        /// <summary>
        /// 子表修改
        /// </summary>
        /// <param name="code"></param>
        /// <param name="updateModel"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task UpdateDetailAsync(string code, TbdmCodeDetailUpdateModel updateModel)
        {
            var content = await _codeDetailrepository.GetByIdAsync(code);
            if (content == 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(TbdmCodeDetailUpdateModel), typeof(TBDM_CodeDetail));
            _codeDetailrepository.Update(content);
            var result = await _codeDetailrepository.SaveAsync();
            if (!result)
            {
                throw new Exception("更新失败");
            }
        }
    }
}