using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.ServiceApp.BiddingInfoManager.Request;
using OpenAuth.App.ServiceApp.BidCompanyInfoManager.Request;
using System.ComponentModel;
using Org.BouncyCastle.Ocsp;
using DocumentFormat.OpenXml.Math;
using DocumentFormat.OpenXml.Spreadsheet;

namespace OpenAuth.App.ServiceApp.BidCompanyInfoManager
{
    public class BidCompanyInfoApp : SqlSugarBaseApp<PpCompanyinfo, SugarDbContext>
    {
        private ISqlSugarClient client;

        #region 构造函数
        public BidCompanyInfoApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<PpCompanyinfo> 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<PpCompanyinfo>>>> LoadBidCompanyInfo(BidCompanyInfoReq req)
        {
            var user = _auth.GetCurrentUser();
            RefAsync<int> totalNumber = 0;
            List<PpCompanyinfo> table = new List<PpCompanyinfo>();

            //甲方公司
            if (user != null && user.Roles[0].Name.Contains("甲方公司"))
            {
                //查询当前账号关联的公司
                var companyids = base.Repository.ChangeRepository<SugarRepositiry<PpCompanyaccount>>().AsQueryable().Where(r => r.UserId == user.User.Id.ToString())?.Select(r => r.CompanyId).ToList();

                //查询当前甲方关联的供应商
                var supplier = base.Repository.ChangeRepository<SugarRepositiry<PpBiddingsupplier>>().AsQueryable().Where(r => companyids.Contains(r.BiddingCompanyId))?.Select(r => r.SupplierId).ToList();

                table = await base.Repository.AsQueryable()
                    .Where(r => supplier.Contains(r.Id))
                    .WhereIF(!string.IsNullOrEmpty(req.name), r => r.Name.Contains(req.name))
                    .WhereIF(!string.IsNullOrEmpty(req.code), r => r.Code.Contains(req.code))
                    .WhereIF(!string.IsNullOrEmpty(req.qualification), r => r.Qualification == req.qualification)
                    .OrderByDescending(r => r.CreateTime)
                    .ToPageListAsync(req.page, req.limit, totalNumber);
            }
            //招标代理
            if (user != null && user.Roles[0].Name.Contains("招标代理"))
            {
                //查询当前账号关联的公司
                var agencyids = base.Repository.ChangeRepository<SugarRepositiry<PpAgencyaccount>>().AsQueryable().Where(r => r.UserId == user.User.Id.ToString())?.Select(r => r.AgencyId).ToList();

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

                //查询甲方公司关联的供应商
                var supplier = base.Repository.ChangeRepository<SugarRepositiry<PpBiddingsupplier>>().AsQueryable().Where(r => companyids.Contains(r.BiddingCompanyId))?.Select(r => r.SupplierId).ToList();


                table = await base.Repository.AsQueryable()
                    .Where(r => supplier.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))
                    .WhereIF(!string.IsNullOrEmpty(req.qualification), r => r.Qualification == req.qualification)
                    .OrderByDescending(r => r.CreateTime)
                    .ToPageListAsync(req.page, req.limit, totalNumber);
            }

            //超级管理员
            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))
                .WhereIF(!string.IsNullOrEmpty(req.qualification), r => r.Qualification == req.qualification)
                .OrderByDescending(r => r.CreateTime)
                .ToPageListAsync(req.page, req.limit, totalNumber);
            }

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

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

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

        /// <summary>
        /// 添加企业信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddBidCompanyInfo(PpCompanyinfo info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (db.PpCompanyinfo.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.PpCompanyinfo.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>> EditBidCompanyInfo(PpCompanyinfo info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (db.PpCompanyinfo.GetFirst(r => r.Code == info.Code && r.Id != info.Id) != null)
                {
                    return new Response<bool> { Result = false, Message = "信用代码已存在" };
                }
                else
                {
                    var flag = await db.PpCompanyinfo.UpdateAsync(it => new PpCompanyinfo()
                    {
                        Code = info.Code,
                        Name = info.Name,
                        Qualification = info.Qualification,
                        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>> DeleteBidCompanyInfo(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.PpCompanyinfo.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>> ReviewBidCompanyInfo(string id)
        {
            using (var db = UnitWork.CreateContext())
            {

                var flag = await db.PpCompanyinfo.UpdateAsync(it => new PpCompanyinfo()
                {
                    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<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<PpCompanyinfo>>>> 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<PpCompanyinfo>>>()
                    {
                        Result = new PageInfo<List<PpCompanyinfo>>
                        {
                            Items = data,
                            Total = totalNumber
                        }
                    };
                }
                else
                {

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

    }
}
