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 SqlSugar;
using DocumentFormat.OpenXml.EMMA;

namespace OpenAuth.App.ServiceApp.BidAnnouncementManager
{
    public class BidAnnouncementApp : SqlSugarBaseApp<PpAnnouncement, SugarDbContext>
    {
        private ISqlSugarClient client;

        #region 构造函数
        public BidAnnouncementApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<PpAnnouncement> 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<dynamic>>>> LoadBidAnnouncement(string bidtype, short? type, int page = 1, int limit = 10)
        {
            var user = _auth.GetCurrentUser();
            List<dynamic> table = new List<dynamic>();
            RefAsync<int> totalNumber = 0;
            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();

                //根据账号关联的公司，查询招标公司发布的公告
                table = await base.Repository.AsQueryable()
                    .WhereIF(type != null, r => r.Type == type)
                    .LeftJoin<PpBiddinginfo>((r, b) => r.BidingInfoId == b.Id)
                    .WhereIF(!string.IsNullOrEmpty(bidtype), (r, b) => b.BiddingType == bidtype)
                    .Where((r, b) => companyids.Contains(b.BiddingCompanyId))
                    .OrderByDescending((r, b) => r.CreateTime)
                    .Select<dynamic>((r, b) => new
                    {
                        r.Id,
                        r.BidingInfoId,
                        r.Remark,
                        r.CreateTime,
                        r.Title,
                        r.Content,
                        r.Type,
                        b.ProjectName,
                        b.ProjectNum,
                        b.BiddingType,
                        r.Files
                    })
                    .ToPageListAsync(page, limit, totalNumber);
            }
            //招标代理
            if (user != null && user.Roles[0].Name.Contains("招标代理"))
            {
                //查询当前账号关联的公司
                var companyids = base.Repository.ChangeRepository<SugarRepositiry<PpAgencyaccount>>().AsQueryable().Where(r => r.UserId == user.User.Id.ToString())?.Select(r => r.AgencyId).ToList();

                //根据账号关联的公司，查询招标公司发布的公告
                table = await base.Repository.AsQueryable()
                    .WhereIF(type != null, r => r.Type == type)
                    .LeftJoin<PpBiddinginfo>((r, b) => r.BidingInfoId == b.Id)
                    .WhereIF(!string.IsNullOrEmpty(bidtype), (r, b) => b.BiddingType == bidtype)
                    .Where((r, b) => companyids.Contains(b.BidAgent))
                    .OrderByDescending((r, b) => r.CreateTime)
                    .Select<dynamic>((r, b) => new
                    {
                        r.Id,
                        r.BidingInfoId,
                        r.Remark,
                        r.CreateTime,
                        r.Title,
                        r.Content,
                        r.Type,
                        b.ProjectName,
                        b.ProjectNum,
                        b.BiddingType,
                        r.Files
                    })
                    .ToPageListAsync(page, limit, totalNumber);
            }

            //供应商
            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 biddingcomid = base.Repository.ChangeRepository<SugarRepositiry<PpBiddingsupplier>>().AsQueryable().Where(r => companyids.Contains(r.SupplierId))?.Select(r => r.BiddingCompanyId).ToList();

                ////查询供应商的企业资质
                //var zizhi = base.Repository.ChangeRepository<SugarRepositiry<PpCompanyinfo>>().AsQueryable().Where(r => companyids.Contains(r.Id))?.Select(r => r.Qualification).ToList();

                //根据账号关联的公司，查询招标公司发布的公告
                table = await base.Repository.AsQueryable()
                    .WhereIF(type != null, r => r.Type == type && r.IsReview == true)
                    .LeftJoin<PpBiddinginfo>((r, b) => r.BidingInfoId == b.Id)
                    .WhereIF(!string.IsNullOrEmpty(bidtype), (r, b) => b.BiddingType == bidtype)
                    .Where((r, b) => biddingcomid.Contains(b.BiddingCompanyId))
                    .OrderByDescending((r, b) => r.CreateTime)
                    .Select<dynamic>((r, b) => new
                    {
                        r.Id,
                        r.BidingInfoId,
                        r.Remark,
                        r.CreateTime,
                        r.Title,
                        r.Content,
                        r.Type,
                        b.ProjectName,
                        b.ProjectNum,
                        b.BiddingType,
                        r.Files
                    })
                    .ToPageListAsync(page, limit, totalNumber);
            }

            //超级管理员
            if (user != null && user.User.Id == -1)
            {
                //根据账号关联的公司，查询招标公司发布的公告
                table = await base.Repository.AsQueryable()
                    .WhereIF(type != null, r => r.Type == type)
                    .LeftJoin<PpBiddinginfo>((r, b) => r.BidingInfoId == b.Id)
                    .WhereIF(!string.IsNullOrEmpty(bidtype), (r, b) => b.BiddingType == bidtype)
                    .OrderByDescending((r, b) => r.CreateTime)
                    .Select<dynamic>((r, b) => new
                    {
                        r.Id,
                        r.BidingInfoId,
                        r.Remark,
                        r.CreateTime,
                        r.Title,
                        r.Content,
                        r.Type,
                        b.ProjectName,
                        b.ProjectNum,
                        b.BiddingType,
                        r.Files
                    })
                    .ToPageListAsync(page, limit, totalNumber);
            }

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

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

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

        /// <summary>
        /// 添加招标公告
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<string>> AddBidAnnouncement(PpAnnouncement info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (db.PpAnnouncement.GetFirst(r => r.Title == info.Title) != null)
                {
                    return new Response<string> { Result = "", 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.PpAnnouncement.InsertAsync(info);
                    var flags = db.Commit();
                    if (flag && flags)
                    {
                        return new Response<string> { Result = info.Id, Message = "添加成功" };
                    }
                    else
                    {
                        return new Response<string> { Result = "", Message = "添加失败" };
                    }
                }
            }
        }

        /// <summary>
        /// 编辑招标公告
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public async Task<Response<bool>> EditBidAnnouncement(PpAnnouncement info)
        {
            using (var db = UnitWork.CreateContext())
            {
                if (db.PpAnnouncement.GetFirst(r => r.Title == info.Title && r.Id != info.Id) != null)
                {
                    return new Response<bool> { Result = false, Message = "公告标题已存在" };
                }
                else
                {
                    var flag = await db.PpAnnouncement.UpdateAsync(it => new PpAnnouncement()
                    {
                        Title = info.Title,
                        Content = info.Content,
                        Type = info.Type,
                        BidingInfoId = info.BidingInfoId,
                        Remark = info.Remark,
                        Files = info.Files
                    }, 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>> DeleteBidAnnouncement(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.PpAnnouncement.DeleteAsync(r => r.Id == id);
                if (db.Commit() && flag)
                {
                    return new Response<bool> { Result = true, Message = "删除成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "删除失败" };
                }
            }
        }
        #endregion

        #region 添加报名信息
        public async Task<Response<bool>> AddPpRegistration(string biddingInfoId)
        {
            var user = _auth.GetCurrentUser();
            using (var db = UnitWork.CreateContext())
            {
                if (user != null)
                {
                    var acc = await base.Repository.ChangeRepository<SugarRepositiry<PpCompanyaccount>>().AsQueryable()
                        .Where(r => r.UserId == user.User.Id.ToString()).FirstAsync();
                    if (acc != null)
                    {
                        if (db.PpRegistration.GetFirst(r => r.BiddingInfoId == biddingInfoId && r.CompanyId == acc.CompanyId) != null)
                        {
                            return new Response<bool> { Result = false, Message = "不能重复报名" };
                        }
                        else
                        {
                            PpRegistration pp = new PpRegistration();
                            pp.CompanyId = acc.CompanyId;
                            pp.BiddingInfoId = biddingInfoId;
                            var flag = await db.PpRegistration.InsertAsync(pp);
                            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 = "请绑定企业信息" };
                    }
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "请登录" };
                }

            }
        }
        #endregion


        #region  审核招标公告
        /// <summary>
        /// 审核招标公告
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public async Task<Response<bool>> ReviewAnnouncement(string announcementid, bool isagree)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.PpAnnouncement.UpdateAsync(it => new PpAnnouncement()
                {
                    IsReview = isagree
                }, it => it.Id == announcementid);

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