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.BiddingAgencyManager.Request;
using SqlSugar;
using DocumentFormat.OpenXml.Office2010.Excel;
using Org.BouncyCastle.Ocsp;
using DocumentFormat.OpenXml.Spreadsheet;

namespace OpenAuth.App.ServiceApp.BiddingAgencyManager
{
    public class BiddingAgencyApp : SqlSugarBaseApp<PpBiddingagency, SugarDbContext>
    {
        private ISqlSugarClient client;

        #region 构造函数
        public BiddingAgencyApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<PpBiddingagency> 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<PpBiddingagency>>>> LoadBiddingAgency(BiddingAgencyReq req)
        {
            RefAsync<int> totalNumber = 0;
            var user=_auth.GetCurrentUser();
            List<PpBiddingagency> table=new List<PpBiddingagency>();
            //超级管理员
            if (user != null && user.User.Id == -1)
            {
                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);
            }
            else
            {
                //查询当前账号关联的公司
                var companyids = base.Repository.ChangeRepository<SugarRepositiry<PpCompanyaccount>>().AsQueryable().Where(r => r.UserId == user.User.Id.ToString())?.Select(r => r.CompanyId).ToList();

                //查询当前甲方关联的招标代理
                var agencyids = base.Repository.ChangeRepository<SugarRepositiry<PpBidagencycompany>>().AsQueryable().Where(r => companyids.Contains(r.BiddingCompanyId))?.Select(r => r.AgencyId).ToList();

                table = await base.Repository.AsQueryable()
                    .Where(r=> agencyids.Contains(r.Id)||r.CreateUser==user.User.Id.ToString())
                    .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<PpBiddingagency>>>()
            {
                Result = new PageInfo<List<PpBiddingagency>>
                {
                    Items = table,
                    Total = totalNumber
                }
            };
        }

        /// <summary>
        /// 根据id查询单个代理商信息--编辑代理商加载使用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<PpBiddingagency>> LoadBiddingAgencyById(string id)
        {
            var data = await base.Repository.AsQueryable().Where(r => r.Id == id).FirstAsync();

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

        /// <summary>
        /// 添加代理商信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddBiddingAgency(PpBiddingagency info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (db.PpBiddingagency.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();
                    info.IsReview = false;
                    var flag = await db.PpBiddingagency.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>> EditBiddingAgency(PpBiddingagency info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (db.PpBiddingagency.GetFirst(r => r.Code == info.Code && r.Id != info.Id) != null)
                {
                    return new Response<bool> { Result = false, Message = "代理商标题已存在" };
                }
                else
                {
                    var flag = await db.PpBiddingagency.UpdateAsync(it => new PpBiddingagency()
                    {
                        Code = info.Code,
                        Name = info.Name,
                        License = info.License,
                        LegalPerson = info.LegalPerson,
                        AccountState = info.AccountState,
                        ContactPerson = info.ContactPerson,
                        Phone = info.Phone,
                        Remark = info.Remark,
                        IsReview = info.IsReview
                    }, 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>> DeleteBiddingAgency(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                var info = db.PpAgencyaccount.AsQueryable().Where(r => r.AgencyId == id).ToList();
                if (info.Any())
                {
                    var flag1 = await db.PpAgencyaccount.DeleteAsync(info);
                }

                var flag = await db.PpBiddingagency.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=""></param>
        /// <returns></returns>
        public async Task<Response<bool>> ReviewBiddingAgency(string id)
        {
            using (var db = UnitWork.CreateContext())
            {

                var flag = await db.PpBiddingagency.UpdateAsync(it => new PpBiddingagency()
                {
                    IsReview = true,
                }, it => it.Id == 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="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddCompanyAccount(List<PpAgencyaccount> info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (info != null && info.Count() > 0)
                {
                    var pac = db.PpAgencyaccount.AsQueryable().Where(r => r.AgencyId == info[0].AgencyId).ToList();
                    if (pac.Any())
                    {
                        await db.PpAgencyaccount.DeleteAsync(pac);
                    }
                    var flag = await db.PpAgencyaccount.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>> LoadBidAgencyUserInfoById(string id)
        {
            var data = await base.Repository.ChangeRepository<SugarRepositiry<PpAgencyaccount>>().AsQueryable()
                .Where(r => r.AgencyId == 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<PpBiddingagency>>>> LoadBiddingAgencyByUser()
        {
            var user=_auth.GetCurrentUser();
            RefAsync<int> totalNumber = 0;
            if (user != null)
            {
                var acc = await base.Repository.ChangeRepository<SugarRepositiry<PpAgencyaccount>>().AsQueryable()
                    .Where(r => r.UserId == user.User.Id.ToString()).FirstAsync();
                if (acc != null)
                {
                    var data = await base.Repository.AsQueryable().Where(r => r.Id == acc.AgencyId).ToPageListAsync(1, 10, totalNumber); 
                    return new Response<PageInfo<List<PpBiddingagency>>>()
                    {
                        Result = new PageInfo<List<PpBiddingagency>>
                        {
                            Items = data,
                            Total = totalNumber
                        }
                    };
                }
                else
                {
                    return new Response<PageInfo<List<PpBiddingagency>>>()
                    {
                        Result = new PageInfo<List<PpBiddingagency>>
                        {
                            Items = null,
                            Total = totalNumber
                        }
                    };
                }
            }
            else
            {
                throw new Exception("请登录");
            }
        }
        #endregion
    }
}
