using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.BiddingCompanyManager.Request;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.BiddingCompanyManager
{
    public class PpBiddingcompanyApp : SqlSugarBaseApp<PpBiddingcompany, SugarDbContext>
    {
        private ISqlSugarClient client;

        #region 构造函数
        public PpBiddingcompanyApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<PpBiddingcompany> repository,
            IAuth auth,
            ISqlSugarClient sqlSugarClient
            ) : base(unitWork, repository, auth)
        {
            this.client = sqlSugarClient;
        }
        #endregion

        #region 数据查询
        /// <summary>
        /// 查询招标企业
        /// </summary>
        /// <param name="type"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<PpBiddingcompany>>>> LoadBiddingCompanyInfo(BiddingCompanyInfoReq req)
        {
            RefAsync<int> totalNumber = 0;
            var table = await base.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(req.name), r => r.Name.Contains(req.name))
                .WhereIF(!string.IsNullOrEmpty(req.code), r => r.Code.Contains(req.code))
                .OrderByDescending(r => r.CreateTime)
                .ToPageListAsync(req.page, req.limit, totalNumber);

            return new Response<PageInfo<List<PpBiddingcompany>>>()
            {
                Result = new PageInfo<List<PpBiddingcompany>>
                {
                    Items = table,
                    Total = totalNumber
                }
            };
        }

        /// <summary>
        /// 根据id查询单个招标企业--编辑企业加载使用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<PpBiddingcompany>> LoadBiddingCompanyInfoById(string id)
        {
            var data = await base.Repository.AsQueryable().Where(r => r.Id == id).FirstAsync();

            return new Response<PpBiddingcompany>()
            {
                Result = data
            };
        }

        /// <summary>
        /// 添加招标企业
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddBiddingCompanyInfo(PpBiddingcompany info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (db.PpBiddingcompany.GetFirst(r => r.Code == info.Code) != null)
                {
                    return new Response<bool> { Result = false, Message = "信用代码已存在" };
                }
                else
                {
                    var user = _auth.GetCurrentUser().User;
                    info.Id = Guid.NewGuid().ToString();
                    info.CreateTime = DateTime.Now;
                    info.CreateUser = user.Id.ToString();
                    var flag = await db.PpBiddingcompany.InsertAsync(info);
                    var flags = db.Commit();
                    if (flag && flags)
                    {
                        return new Response<bool> { Result = true, Message = "添加成功," + info.Id };
                    }
                    else
                    {
                        return new Response<bool> { Result = false, Message = "添加失败" };
                    }
                }
            }
        }

        /// <summary>
        /// 编辑招标企业
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public async Task<Response<bool>> EditBiddingCompanyInfo(PpBiddingcompany info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (db.PpBiddingcompany.GetFirst(r => r.Code == info.Code && r.Id != info.Id) != null)
                {
                    return new Response<bool> { Result = false, Message = "企业信用代码已存在" };
                }
                else
                {
                    var flag = await db.PpBiddingcompany.UpdateAsync(it => new PpBiddingcompany()
                    {
                        Code = info.Code,
                        Name = info.Name,
                        License = info.License,
                        LegalPerson = info.LegalPerson,
                        AccountState = info.AccountState,
                        ContactPerson = info.ContactPerson,
                        Phone = info.Phone,
                        Remark = info.Remark
                    }, it => it.Id == info.Id);

                    var flags = db.Commit();
                    if (flag && flags)
                    {
                        return new Response<bool> { Result = true, Message = "编辑成功" };
                    }
                    else
                    {
                        return new Response<bool> { Result = false, Message = "编辑失败" };
                    }
                }
            }
        }

        /// <summary>
        /// 删除招标企业
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteBiddingCompanyInfo(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                var info = db.PpCompanyaccount.AsQueryable().Where(r => r.CompanyId == id).ToList();
                if (info.Any())
                {
                    var flag1 = await db.PpCompanyaccount.DeleteAsync(info);
                }

                var flag = await db.PpBiddingcompany.DeleteAsync(r => r.Id == id);
                if (db.Commit() && flag)
                {
                    return new Response<bool> { Result = true, Message = "删除成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "删除失败" };
                }
            }
        }


        /// <summary>
        /// 为企业分配账号
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddCompanyAccount(List<PpCompanyaccount> info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (info != null && info.Count() > 0)
                {
                    var pac = db.PpCompanyaccount.AsQueryable().Where(r => r.CompanyId == info[0].CompanyId).ToList();
                    if (pac.Any())
                    {
                        await db.PpCompanyaccount.DeleteAsync(pac);
                    }
                    var flag = await db.PpCompanyaccount.InsertRangeAsync(info);
                    var flags = db.Commit();
                    if (flag && flags)
                    {
                        return new Response<bool> { Result = true, Message = "分配账号成功" };
                    }
                    else
                    {
                        return new Response<bool> { Result = false, Message = "分配账号失败" };
                    }
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "分配账号失败" };
                }
            }
        }

        /// <summary>
        /// 根据企业id查询分配的账号信息--编辑企业账号分配时使用
        /// </summary>
        /// <param name="id">招标企业id</param>
        /// <returns></returns>
        public async Task<Response<string>> LoadBidUserInfoById(string id)
        {
            var data = await base.Repository.ChangeRepository<SugarRepositiry<PpCompanyaccount>>().AsQueryable()
                .Where(r => r.CompanyId == id).FirstAsync();
            if (data != null)
            {
                return new Response<string>()
                {
                    Result = data.UserId
                };
            }
            else
            {
                return new Response<string>()
                {
                    Result = null
                };
            }
        }
        #endregion
        #region  查询企业
        /// <summary>
        /// 根据id查询当前登录招标企业
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<PpBiddingcompany>>>> LoadCompanyInfoByUser()
        {
            var user = _auth.GetCurrentUser();
            RefAsync<int> totalNumber = 0;
            if (user != null)
            {
                var acc = await base.Repository.ChangeRepository<SugarRepositiry<PpCompanyaccount>>().AsQueryable()
                    .Where(r => r.UserId == user.User.Id.ToString()).FirstAsync();
                if (acc != null)
                {
                    var data = await base.Repository.AsQueryable().Where(r => r.Id == acc.CompanyId).ToPageListAsync(1, 10, totalNumber);
                    return new Response<PageInfo<List<PpBiddingcompany>>>()
                    {
                        Result = new PageInfo<List<PpBiddingcompany>>
                        {
                            Items = data,
                            Total = totalNumber
                        }
                    };
                }
                else
                {

                    return new Response<PageInfo<List<PpBiddingcompany>>>()
                    {
                        Result = new PageInfo<List<PpBiddingcompany>>
                        {
                            Items = null,
                            Total = totalNumber
                        }
                    };
                }
            }
            else
            {
                throw new Exception("请登录");
            }
        }
        #endregion

        #region 

        /// <summary>
        /// 为招标企业分配供应商
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AllocateSupplier(List<PpBiddingsupplier> info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (info != null && info.Count() > 0)
                {
                    var pac = db.PpBiddingsupplier.AsQueryable().Where(r => r.BiddingCompanyId == info[0].BiddingCompanyId).ToList();
                    if (pac.Any())
                    {
                        await db.PpBiddingsupplier.DeleteAsync(pac);
                    }
                    var flag = await db.PpBiddingsupplier.InsertRangeAsync(info);
                    var flags = db.Commit();
                    if (flag && flags)
                    {
                        return new Response<bool> { Result = true, Message = "分配供应商成功" };
                    }
                    else
                    {
                        return new Response<bool> { Result = false, Message = "分配供应商失败" };
                    }
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "分配供应商失败" };
                }
            }
        }


        /// <summary>
        /// 根据招标企业id查询分配的供应商
        /// </summary>
        /// <param name="id">招标企业id</param>
        /// <returns></returns>
        public async Task<Response<List<string>>> LoadBidcompanyById(string id)
        {
            var data = await base.Repository.ChangeRepository<SugarRepositiry<PpBiddingsupplier>>()
                .AsQueryable()
                .Where(r => r.BiddingCompanyId == id)
                .Select(r => r.SupplierId)
                .ToListAsync();
            if (data.Count > 0)
            {
                return new Response<List<string>>()
                {
                    Result = data
                };
            }
            else
            {
                return new Response<List<string>>()
                {
                    Result = null
                };
            }
        }
        #endregion

        #region 

        /// <summary>
        /// 为招标企业分配招标代理
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AllocateAgency(List<PpBidagencycompany> info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (info != null && info.Count() > 0)
                {
                    var pac = db.PpBidagencycompany.AsQueryable().Where(r => r.BiddingCompanyId == info[0].BiddingCompanyId).ToList();
                    if (pac.Any())
                    {
                        await db.PpBidagencycompany.DeleteAsync(pac);
                    }
                    var flag = await db.PpBidagencycompany.InsertRangeAsync(info);
                    var flags = db.Commit();
                    if (flag && flags)
                    {
                        return new Response<bool> { Result = true, Message = "分配招标代理成功" };
                    }
                    else
                    {
                        return new Response<bool> { Result = false, Message = "分配招标代理失败" };
                    }
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "分配招标代理失败" };
                }
            }
        }

        /// <summary>
        /// 根据招标企业id查询分配的招标代理
        /// </summary>
        /// <param name="id">招标企业id</param>
        /// <returns></returns>
        public async Task<Response<List<string>>> LoadBidAgencyById(string id)
        {
            var data = await base.Repository.ChangeRepository<SugarRepositiry<PpBidagencycompany>>()
                .AsQueryable()
                .Where(r => r.BiddingCompanyId == id)
                .Select(r => r.AgencyId)
                .ToListAsync();
            if (data.Count>0)
            {
                return new Response<List<string>>()
                {
                    Result = data
                };
            }
            else
            {
                return new Response<List<string>>()
                {
                    Result = null
                };
            }
        }
        #endregion
    }
}
