using Furion.DependencyInjection;
using Nirvana.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Waste.Domain;

namespace Waste.Application
{
    /// <summary>
    /// 苏州设备接入平台管理
    /// </summary>
    public class SZPltService : ISZPltService, ITransient
    {
        private readonly ISqlSugarRepository<W_SZAddress> repository;
        private readonly SqlSugarClient dbClient;
        private readonly ISuZhouService _suZhouService;
        public SZPltService(ISqlSugarRepository<W_SZAddress> sqlSugarRepository, ISuZhouService suZhouService)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            _suZhouService = suZhouService;
        }
        /// <summary>
        /// 删除地产区域
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteAddressAsync(Guid id)
        {
            var data = await dbClient.Queryable<W_SZAddress>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            var result = await _suZhouService.DeleteEstates(data.AdId);
            if (result.code != ResultState.SUCCESS)
            {
                return result;
            }
            //删除数据中的
            await dbClient.Deleteable<W_SZAddress>().Where(x => x.Id == id).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "删除成功");
        }
        /// <summary>
        /// 删除采集点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteCollectAsync(Guid id)
        {
            var tdbClient = repository.Change<W_SZCollect>().Context;
            var data = await tdbClient.Queryable<W_SZCollect>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            var result = await _suZhouService.DeleteCollect(data.CoId);
            if (result.code != ResultState.SUCCESS)
            {
                return result;
            }
            //删除数据中的
            await dbClient.Deleteable<W_SZCollect>().Where(x => x.Id == id).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "删除成功");
        }
        /// <summary>
        /// 地产区域详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<W_SZAddress> DetailAddressAsync(Guid id)
        {
            return await dbClient.Queryable<W_SZAddress>().FirstAsync(x => x.Id == id);
        }
        /// <summary>
        /// 采集点详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<W_SZCollect> DetailCollectAsync(Guid id)
        {
            var tdbClient = repository.Change<W_SZCollect>().Context;
            return await tdbClient.Queryable<W_SZCollect>().FirstAsync(x => x.Id == id);
        }
        /// <summary>
        /// 获取地产区域所有列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<W_SZAddress>> GetAddressAllListAsync()
        {
            return await dbClient.Queryable<W_SZAddress>().ToListAsync();
        }
        /// <summary>
        /// 获取地产区域列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<W_SZAddress>> GetAddressListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            var temquery = dbClient.Queryable<W_SZAddress>();
            if (param.queryParam != null && param.queryParam.Count > 0)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                param.queryParam.ForEach(x =>
                {
                    if (!string.IsNullOrEmpty(x.Value))
                    {
                        conModels.Add(new ConditionalModel()
                        {
                            FieldName = x.Name,
                            ConditionalType = (ConditionalType)x.Type,
                            FieldValue = x.Value.Trim()
                        });
                    }
                });
                if (conModels.Count > 0)
                {
                    temquery = temquery.Where(conModels);
                }
            }
            string sorts = string.Format("{0} {1}", param.sort, param.order);
            var query = await temquery.OrderBy(sorts)
                 .ToPageListAsync(param.offset, param.limit, totalnum);
            return new PageParms<W_SZAddress>
            {
                page = param.offset,
                Items = query,
                totalnum = totalnum,
                limit = param.limit
            };
        }
        /// <summary>
        /// 获取采集点列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<SZCollectList>> GetCollectListAsync(QueryParams param)
        {
            var tdbClient = repository.Change<W_SZCollect>().Context;
            RefAsync<int> totalnum = 0;
            var temquery = tdbClient.Queryable<W_SZCollect>();
            if (param.queryParam != null && param.queryParam.Count > 0)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                param.queryParam.ForEach(x =>
                {
                    if (!string.IsNullOrEmpty(x.Value))
                    {
                        conModels.Add(new ConditionalModel()
                        {
                            FieldName = x.Name,
                            ConditionalType = (ConditionalType)x.Type,
                            FieldValue = x.Value.Trim()
                        });
                    }
                });
                if (conModels.Count > 0)
                {
                    temquery = temquery.Where(conModels);
                }
            }
            string sorts = string.Format("{0} {1}", param.sort, param.order);
            var query = await temquery.OrderBy(sorts)
                .Select(x => new SZCollectList
                {
                    Id = x.Id,
                    Addr = x.Addr,
                    Code = x.Code,
                    CreateTime = x.CreateTime,
                    EstateId = x.EstateId,
                    Name = x.Name
                })
                .Mapper((it, cache) =>
                {
                    var allestate = cache.Get(list =>
                    {
                        var ids = list.Select(x => Guid.Parse(x.EstateId)).ToList();
                        return dbClient.Queryable<W_SZAddress>().Where(e => ids.Contains(e.Id)).ToList();
                    });
                    it.AddressName = allestate.FirstOrDefault(x => x.Id ==Guid.Parse(it.EstateId))?.Name;
                })
                 .ToPageListAsync(param.offset, param.limit, totalnum);
            return new PageParms<SZCollectList>
            {
                page = param.offset,
                Items = query,
                totalnum = totalnum,
                limit = param.limit
            };
        }
        /// <summary>
        /// 地产区域信息提交
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAddressFormAsync(W_SZAddress data)
        {
            data.Code = data.Code.ToStr();
            data.Name = data.Name.ToStr();
            data.Addr = data.Addr.ToStr();
            data.City = data.City.ToStr();
            data.Area = data.Area.ToStr();
            data.Street = data.Street.ToStr();
            if (string.IsNullOrEmpty(data.Code))
            {
                return new ResultInfo(ResultState.FAIL, "编号不可为空");
            }
            if (data.Code.Length < 2 || data.Code.Length > 32)
            {
                return new ResultInfo(ResultState.FAIL, "编号长度范围在2-32位");
            }
            if (string.IsNullOrEmpty(data.Addr))
            {
                return new ResultInfo(ResultState.FAIL, "所在地址不可为空");
            }
            if (data.Addr.Length < 4 || data.Addr.Length > 128)
            {
                return new ResultInfo(ResultState.FAIL, "编号长度范围在4-128位");
            }
            if (string.IsNullOrEmpty(data.City))
            {
                return new ResultInfo(ResultState.FAIL, "城市编码不可为空");
            }
            if (string.IsNullOrEmpty(data.Name))
            {
                return new ResultInfo(ResultState.FAIL, "名称不可为空");
            }
            if (data.Name.Length < 2 || data.Name.Length > 32)
            {
                return new ResultInfo(ResultState.FAIL, "名称长度范围在2-32位");
            }
            if (string.IsNullOrEmpty(data.Area))
            {
                return new ResultInfo(ResultState.FAIL, "区域编码不可为空");
            }
            if (string.IsNullOrEmpty(data.Street))
            {
                return new ResultInfo(ResultState.FAIL, "街道编码不可为空");
            }
            if (data.Id != Guid.Empty)
            {
                if (await dbClient.Queryable<W_SZAddress>().AnyAsync(x => x.Code == data.Code && x.Id != data.Id))
                {
                    return new ResultInfo(ResultState.FAIL, "此编号已存在");
                }
                var addata = await dbClient.Queryable<W_SZAddress>().FirstAsync(x => x.Id == data.Id);
                //先删除,再增加
                var result = await _suZhouService.DeleteEstates(addata.AdId);
                if (result.code != ResultState.SUCCESS)
                {
                    return result;
                }
                result = await _suZhouService.PostEstatesAsync(new EstatesC2SDto
                {
                    Addr = data.Addr,
                    Street = data.Street,
                    Area = data.Area,
                    City = data.City,
                    Code = data.Code,
                    Name = data.Name
                });
                if (result.code != ResultState.SUCCESS)
                {
                    return result;
                }
                string adid = result.data.ToString();
                await dbClient.Updateable<W_SZAddress>().SetColumns(x => new W_SZAddress
                {
                    Addr = data.Addr,
                    Street = data.Street,
                    AdId = adid,
                    Area = data.Area,
                    City = data.City,
                    Code = data.Code,
                    Name = data.Name
                }).Where(x => x.Id == data.Id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "修改成功");
            }
            else
            {
                if (await dbClient.Queryable<W_SZAddress>().AnyAsync(x => x.Code == data.Code))
                {
                    return new ResultInfo(ResultState.FAIL, "此编号已存在");
                }
                var result = await _suZhouService.PostEstatesAsync(new EstatesC2SDto
                {
                    Addr = data.Addr,
                    Street = data.Street,
                    Area = data.Area,
                    City = data.City,
                    Code = data.Code,
                    Name = data.Name
                });
                if (result.code != ResultState.SUCCESS)
                {
                    return result;
                }
                data.AdId = result.data.ToString();
                data.CreateTime = DateTime.Now;
                await dbClient.Insertable<W_SZAddress>(data).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "添加成功");
            }
        }
        /// <summary>
        /// 采集点信息提交
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitCollectFormAsync(W_SZCollect data)
        {
            data.Code = data.Code.ToStr();
            data.Name = data.Name.ToStr();
            data.Addr = data.Addr.ToStr();
            var tdbClient = repository.Change<W_SZCollect>().Context;
            if (string.IsNullOrEmpty(data.Code))
            {
                return new ResultInfo(ResultState.FAIL, "编号不可为空");
            }
            if (data.Code.Length < 2 || data.Code.Length > 32)
            {
                return new ResultInfo(ResultState.FAIL, "编号长度范围在2-32位");
            }
            if (string.IsNullOrEmpty(data.Addr))
            {
                return new ResultInfo(ResultState.FAIL, "所在地址不可为空");
            }
            if (data.Addr.Length < 4 || data.Addr.Length > 128)
            {
                return new ResultInfo(ResultState.FAIL, "地址长度范围在4-128位");
            }
            if (string.IsNullOrEmpty(data.Name))
            {
                return new ResultInfo(ResultState.FAIL, "名称不可为空");
            }
            if (data.Name.Length < 2 || data.Name.Length > 32)
            {
                return new ResultInfo(ResultState.FAIL, "名称长度范围在2-32位");
            }
            Guid eid = Guid.Parse(data.EstateId);
            var address = await dbClient.Queryable<W_SZAddress>().FirstAsync(x => x.Id == eid);
            if (address == null)
            {
                return new ResultInfo(ResultState.FAIL, "地产区域未找到");
            }
            if (data.Id != Guid.Empty)
            {
                if (await tdbClient.Queryable<W_SZCollect>().AnyAsync(x => x.Code == data.Code && x.Id != data.Id))
                {
                    return new ResultInfo(ResultState.FAIL, "此编号已存在");
                }
                var addata = await tdbClient.Queryable<W_SZCollect>().FirstAsync(x => x.Id == data.Id);
                //先删除,再增加
                var result = await _suZhouService.DeleteCollect(addata.CoId);
                if (result.code != ResultState.SUCCESS)
                {
                    return result;
                }
                result = await _suZhouService.PostCollectAsync(new CollectC2SDto
                {
                    Addr = data.Addr,
                    Code = data.Code,
                    Estate = address.AdId,
                    Name = data.Name
                });
                if (result.code != ResultState.SUCCESS)
                {
                    return result;
                }
                string adid = result.data.ToString();
                await tdbClient.Updateable<W_SZCollect>().SetColumns(x => new W_SZCollect
                {
                    Addr = data.Addr,
                    Code = data.Code,
                    Name = data.Name,
                    CoId = adid,
                    EstateId = data.EstateId
                }).Where(x => x.Id == data.Id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "修改成功");
            }
            else
            {
                if (await tdbClient.Queryable<W_SZCollect>().AnyAsync(x => x.Code == data.Code))
                {
                    return new ResultInfo(ResultState.FAIL, "此编号已存在");
                }
                var result = await _suZhouService.PostCollectAsync(new CollectC2SDto
                {
                    Addr = data.Addr,
                    Code = data.Code,
                    Estate = address.AdId,
                    Name = data.Name
                });
                if (result.code != ResultState.SUCCESS)
                {
                    return result;
                }
                data.CoId = result.data.ToString();
                data.CreateTime = DateTime.Now;
                await tdbClient.Insertable<W_SZCollect>(data).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "添加成功");
            }
        }
    }
}
