using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.CacheManager.User;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Enum.Goods;
using Mall.Common.Enum.User;
using Mall.Common.Plugin;
using Mall.Model.Extend.TradePavilion;
using Mall.Module.TradePavilion;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.TradePavilion
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletTradeController : BaseController
    {
        /// <summary>
        /// 联系人处理类对象
        /// </summary>
        private readonly ContractModule module = new ContractModule();

        /// <summary>
        /// 投资采购处理类对象
        /// </summary>
        private readonly InvestmentProcurementModule procurementModule = new InvestmentProcurementModule();

        /// <summary>
        /// 公司信息处理类对象
        /// </summary>
        private readonly CompanyModule companyModule = new CompanyModule();


        /// <summary>
        /// 商会活动处理类对象
        /// </summary>
        private readonly CommerceActivityModule activityModule = new CommerceActivityModule();

        /// <summary>
        /// 商会活动报名处理类对象
        /// </summary>
        private readonly CommerceConsultModule consultModule = new CommerceConsultModule();

        /// <summary>
        /// 新闻处理类对象
        /// </summary>
        private readonly CommerceNewsModule commerceNewsModule = new CommerceNewsModule();

        /// <summary>
        /// Fat资料处理类对象
        /// </summary>
        private readonly CommerceAskModule askModule = new CommerceAskModule();

        /// <summary>
        /// 载体处理类对象
        /// </summary>
        private readonly CarrierModule carrierModule = new CarrierModule();

        /// <summary>
        /// 活动评论处理类对象
        /// </summary>
        private readonly CommerceCommentModule commerceCommentModule = new CommerceCommentModule();
        /// <summary>
        /// 认证对象
        /// </summary>
        private readonly AuthenticationModule authenticationModule = new AuthenticationModule();
        /// <summary>
        /// 小程序
        /// </summary>
        private readonly Module.User.MiniProgramModule programModule = new Module.User.MiniProgramModule();

        #region 公司信息管理

        /// <summary>
        /// 新增修改公司信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCompany()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var extModel = new RB_Company_Extend()
            {
                CompanyId = parms.GetInt("CompanyId"),
                CompanyName = parms.GetStringValue("CompanyName"),
                BusinessLicense = parms.GetStringValue("BusinessLicense"),
                // Principal = parms.GetStringValue("Principal"),
                Mobile = parms.GetStringValue("Mobile"),
                UnifiedCode = parms.GetStringValue("UnifiedCode"),
                LegalPerson = parms.GetStringValue("LegalPerson"),
                // CompanyIntro = parms.GetStringValue("CompanyIntro"),
            };
            if (string.IsNullOrWhiteSpace(extModel.BusinessLicense))
            {
                return ApiResult.Failed("请上传公司营业执照");
            }
            if (string.IsNullOrWhiteSpace(extModel.CompanyName))
            {
                return ApiResult.Failed("请输入企业名称");
            }
            if (string.IsNullOrWhiteSpace(extModel.UnifiedCode))
            {
                return ApiResult.Failed("请输入统一社会信用代码");
            }

            if (string.IsNullOrWhiteSpace(extModel.LegalPerson))
            {
                return ApiResult.Failed("请输入法人代表");
            }
            if (string.IsNullOrWhiteSpace(extModel.Mobile))
            {
                return ApiResult.Failed("请输入联系电话");
            }

            var userInfo = AppletUserInfo;
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            extModel.MallBaseId = userInfo.MallBaseId;
            extModel.TenantId = userInfo.TenantId;
            Int32.TryParse(userInfo.UserId.ToString(), out int Uid);
            extModel.CreateBy = Uid;
            extModel.CreateDate = DateTime.Now;
            extModel.UpdateBy = Uid;
            extModel.UpdateDate = DateTime.Now;
            extModel.CompanyStatus = 0;
            int ID = companyModule.SetCompanyModule(extModel);
            if (ID > 0)
            {
                //获取订阅消息
                var miniModel = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

                List<string> template_message_list = new List<string>();

                if (miniModel != null)
                {
                    if (!string.IsNullOrWhiteSpace(miniModel.HatchExamineTpl))
                    {
                        template_message_list.Add(miniModel.HatchExamineTpl);
                    }
                }
                return ApiResult.Success("", new { CompanyId = ID, template_message_list });
            }
            return ApiResult.Failed();

        }

        /// <summary>
        /// 获取当前用户的公司信息实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserCompany()
        {
            var userInfo = AppletUserInfo;
            var model = companyModule.GetCompanyByUserIdModule(userInfo.UserId);
            return ApiResult.Success(data: model);
        }

        #endregion

        #region 新闻管理

        /// <summary>
        /// 获取新闻前几条
        /// </summary>
        /// <returns></returns>
        public ApiResult GetNewsPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Commerce_News_Extend()
            {
                Title = parms.GetStringValue("Title"),
                Type = parms.GetInt("Type")
            };
            var userInfo = AppletUserInfo;
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = userInfo?.TenantId ?? 0;
            var list = commerceNewsModule.GetCommerceNewsPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取新闻信息详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetCommerceNews()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = commerceNewsModule.GetCommerceNewsModule(Id);
            return ApiResult.Success(data: extModel);
        }
        #endregion

        #region 投资采购管理

        /// <summary>
        /// 获取投资采购分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetInvestmentProcurementPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_InvestmentProcurement_Extend()
            {
                CompanyName = parms.GetStringValue("CompanyName"),
                Type = parms.GetInt("Type"),
            };
            var userInfo = AppletUserInfo;
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = userInfo?.TenantId ?? 0;
            query.CreateBy = userInfo.UserId;
            var list = procurementModule.GetInvestmentProcurementPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 新增修改投资采购
        /// </summary>
        /// <returns></returns>
        public ApiResult SetInvestmentProcurement()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var extModel = new RB_InvestmentProcurement_Extend()
            {
                Id = parms.GetInt("Id"),
                Type = parms.GetInt("Type"),
                GoodsCategory = parms.GetStringValue("GoodsCategory"),
                Investment = parms.GetStringValue("Investment"),
                ImportNum = parms.GetInt("ImportNum"),
                Describe = parms.GetStringValue("Describe"),
                CompanyName = parms.GetStringValue("CompanyName"),
                CompanyEnName = parms.GetStringValue("CompanyEnName"),
                Mobile = parms.GetStringValue("Mobile"),
                EMail = parms.GetStringValue("EMail"),
                LegalPerson = parms.GetStringValue("LegalPerson"),
                Principal = parms.GetStringValue("Principal"),
                WechatNo = parms.GetStringValue("WechatNo"),
                DomainUrl = parms.GetStringValue("DomainUrl"),
                Industry = parms.GetStringValue("Industry"),
                FoundingTime = parms.GetDateTime("FoundingTime"),
                EmployeeNum = parms.GetInt("EmployeeNum"),
                AnnualSales = parms.GetDecimal("AnnualSales"),
                Address = parms.GetStringValue("Address"),
                EnAddress = parms.GetStringValue("EnAddress"),
                AnnualImport = parms.GetDecimal("AnnualImport"),
                ImportCategory = parms.GetStringValue("ImportCategory"),
                ImportCountry = parms.GetStringValue("ImportCountry"),
                ExportCountry = parms.GetStringValue("ExportCountry"),
                CompanyIntro = parms.GetStringValue("CompanyIntro"),
                OtherInfo = parms.GetStringValue("OtherInfo"),
            };
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            var userInfo = AppletUserInfo;
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = userInfo?.TenantId ?? 0;
            extModel.CreateBy = userInfo?.UserId ?? 0;
            extModel.CreateDate = DateTime.Now;
            extModel.UpdateBy = userInfo?.UserId ?? 0; ;
            extModel.UpdateDate = DateTime.Now;
            var flag = procurementModule.SetInvestmentProcurementModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取投资采购详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetInvestmentProcurement()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = procurementModule.GetInvestmentProcurementModule(Id);
            return ApiResult.Success(data: extModel);
        }

        #endregion

        #region Fat咨询管理

        /// <summary>
        /// 新增修改Fat咨询
        /// </summary>
        /// <returns></returns>
        public ApiResult SetCommerceAsk()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var extModel = new RB_Commerce_Ask_Extend()
            {
                Id = parms.GetInt("Id"),
                CompanyName = parms.GetStringValue("CompanyName"),
                Principal = parms.GetStringValue("Principal"),
                Mobile = parms.GetStringValue("Mobile"),
                EMail = parms.GetStringValue("EMail"),
                FatCode = parms.GetStringValue("FatCode"),
                FatTitle = parms.GetStringValue("FatTitle"),
                FatQuestion = parms.GetStringValue("FatQuestion"),
                FatContent = parms.GetStringValue("FatContent")
            };
            var userInfo = AppletUserInfo;
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            extModel.MallBaseId = userInfo.MallBaseId;
            extModel.TenantId = userInfo.TenantId;
            Int32.TryParse(userInfo.UserId.ToString(), out int Uid);
            extModel.CreateBy = Uid;
            extModel.CreateDate = DateTime.Now;
            extModel.UpdateBy = Uid;
            extModel.UpdateDate = DateTime.Now;
            var flag = askModule.SetCommerceAskModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取投资采购分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetCommerceAskPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Commerce_Ask_Extend()
            {
                CompanyName = parms.GetStringValue("CompanyName"),
            };
            var userInfo = AppletUserInfo;
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = userInfo?.TenantId ?? 0;
            query.CreateBy = userInfo.UserId;
            var list = askModule.GetCommerceAskPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 获取咨询详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetCommerceAsk()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = askModule.GetCommerceAskModule(Id);
            return ApiResult.Success(data: extModel);
        }
        #endregion

        #region 活动管理

        /// <summary>
        /// 获取商会活动类型列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ApiResult GetCommerceActivityTypeList()
        {
            var query = new RB_Commerce_ActivityType_Extend();
            var userInfo = AppletUserInfo;
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = userInfo?.TenantId ?? 0;
            var list = activityModule.GetCommerceActivityTypeListModule(query);
            return ApiResult.Success(data: list.Select(qitem => new { qitem.Id, qitem.CoverImage, qitem.TypeName, LableNameList = string.IsNullOrWhiteSpace(qitem.LableName) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(qitem.LableName) }));
        }

        /// <summary>
        /// 获取商会活动分页列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ApiResult GetCommerceActivityPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Commerce_Activity_Extend()
            {
                ActivityType = jObj.GetInt("ActivityType")
            };
            query.MallBaseId = RequestParm.MallBaseId;
            var list = activityModule.GetCommerceActivityPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 获取商会活动详情
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ApiResult GetCommerceActivity()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = activityModule.GetCommerceActivityModule(Id);
            var userInfo = AppletUserInfo;
            if (extModel != null && extModel.CreateBy > 0)
            {
                extModel.CreateByName = UserReidsCache.GetUserLoginInfo(extModel.CreateBy)?.Name ?? "";
                extModel.IsJoinActivity = 0;
                if (userInfo != null && userInfo.UserId > 0)
                {
                    var list = consultModule.GetCommerceConsultListModule(new RB_Commerce_Consult_Extend() { ActivityId = Id, UserId = userInfo.UserId });
                    if (list != null && list.Count > 0)
                    {
                        extModel.IsJoinActivity = 1;
                    }
                    else
                    {
                        extModel.IsJoinActivity = 0;
                    }
                }
            }
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 获取当前用户参加的活动
        /// </summary>
        /// <returns></returns>
        public ApiResult GetUserActivityPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Commerce_Activity_Extend()
            {
            };
            var userInfo = AppletUserInfo;
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = userInfo?.TenantId ?? 0;
            query.CreateBy = userInfo.UserId;
            var list = activityModule.GetUserCommerceActivityPageModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取活动报名列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserJoinActivityPageList()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Commerce_Consult_Extend dmodel = JsonConvert.DeserializeObject<RB_Commerce_Consult_Extend>(RequestParm.msg.ToString());
            var userInfo = AppletUserInfo;
            dmodel.MallBaseId = RequestParm.MallBaseId;
            dmodel.TenantId = userInfo?.TenantId ?? 0;
            dmodel.UserId = userInfo.UserId;
            var list = consultModule.GetUserJoinActivityPageList(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, dmodel);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list.Select(x => new
            {
                x.Id,
                x.ActivityId,
                x.UserId,
                x.LinkMan,
                x.LinkTel,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                x.Status,
                x.PeopleNum,
                x.Money,
                x.Remark,
                x.IsApplyForCancel,
                x.CancelRemark,
                x.ApplyForCancelStatus,
                x.RejectRemark,
                x.ActivityName,
                x.CoverImg,
                StartTime = x.StartTime.HasValue ? x.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                EndTime = x.EndTime.HasValue ? x.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.TypeName
            });
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 新增修改商会活动报名
        /// </summary>
        /// <returns></returns>
        public ApiResult SetCommerceConsult()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var extModel = new RB_Commerce_Consult_Extend()
            {
                Id = jObj.GetInt("Id"),
                ActivityId = jObj.GetInt("ActivityId"),
                UserId = jObj.GetInt("UserId"),
                LinkMan = jObj.GetStringValue("LinkMan"),
                LinkTel = jObj.GetStringValue("LinkTel"),
                PeopleNum = jObj.GetInt("PeopleNum", 0),
                UnitPrice = jObj.GetInt("UnitPrice", 0),
                Money = jObj.GetInt("Money", 0),
                Remark = jObj.GetStringValue("Remark"),
            };
            var userInfo = AppletUserInfo;
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = userInfo?.TenantId ?? 0;
            extModel.UserId = userInfo?.UserId ?? 0;
            extModel.CreateTime = DateTime.Now;
            string msg = consultModule.SetCommerceConsultModule(extModel);
            return msg == "" ? ApiResult.Success() : ApiResult.Failed(msg);
        }

        /// <summary>
        /// 取消报名
        /// </summary>
        /// <returns></returns>
        public ApiResult CancelCommerceConsult()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var ActivityId = jObj.GetInt("ActivityId");
            string CancelRemark = jObj.GetStringValue("CancelRemark");
            var userInfo = AppletUserInfo;
            var flag = consultModule.CancelCommerceConsultModule(ActivityId, CancelRemark, out int IsCancelConfirm, userInfo.UserId);
            return flag ? ApiResult.Success("", IsCancelConfirm) : ApiResult.Failed();
        }

        /// <summary>
        /// 新增活动评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddCommerceComment()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var extModel = new RB_Commerce_Comment_Extend()
            {
                Id = jObj.GetInt("Id"),
                ActivityId = jObj.GetInt("ActivityId"),
                CommentScore = jObj.GetInt("CommentScore"),
                CommentGrade = (GoodsCommentTypeEnum)jObj.GetInt("CommentGrade"),
                CommentImage = jObj.GetStringValue("CommentImage"),
                PlatformSource = (UserSourceEnum)jObj.GetInt("PlatformSource"),
                Content = jObj.GetStringValue("Content")
            };
            var userInfo = AppletUserInfo;
            extModel.UserName = userInfo.Name;
            extModel.UserPhoto = userInfo.Photo;
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = userInfo?.TenantId ?? 0;
            extModel.UserId = userInfo?.UserId ?? 0;
            extModel.CreateDate = DateTime.Now;
            extModel.UpdateDate = DateTime.Now;
            var flag = commerceCommentModule.SetCommerceCommentModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 删除评论
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveCommerceComment()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var Id = jObj.GetInt("Id");
            var flag = commerceCommentModule.RemoveCommerceCommentModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion

        #region 认证申请

        /// <summary>
        /// 申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAuthenticationInfo()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Authentication_Extend demodel = JsonConvert.DeserializeObject<RB_Authentication_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请传递首店名称");
            }
            if (string.IsNullOrEmpty(demodel.Address))
            {
                return ApiResult.ParamIsNull("请输入地址");
            }
            if (string.IsNullOrEmpty(demodel.Description))
            {
                return ApiResult.ParamIsNull("请输入简介");
            }
            if (string.IsNullOrEmpty(demodel.Contact))
            {
                return ApiResult.ParamIsNull("请输入联系人");
            }
            if (string.IsNullOrEmpty(demodel.ContactMobile))
            {
                return ApiResult.ParamIsNull("请输入联系电话");
            }

            demodel.ImageList ??= new List<string>();
            demodel.Images = JsonConvert.SerializeObject(demodel.ImageList);
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Status = 0;
            demodel.CreateBy = userInfo.UserId;
            demodel.CreateDate = DateTime.Now;
            demodel.AuditState = 1;
            bool flag = authenticationModule.SetActivityDiscussInfo(demodel);
            if (flag)
            {
                //获取订阅消息
                var miniModel = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

                List<string> template_message_list = new List<string>();

                if (miniModel != null)
                {
                    if (!string.IsNullOrWhiteSpace(miniModel.HatchExamineTpl))
                    {
                        template_message_list.Add(miniModel.HatchExamineTpl);
                    }
                }
                return ApiResult.Success("", template_message_list);
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取认证分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAuthenticationPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Authentication_Extend demodel = JsonConvert.DeserializeObject<RB_Authentication_Extend>(parms.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.CreateBy = userInfo.UserId;
            var list = authenticationModule.GetAuthenticationPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.CoverImage,
                x.ImageList,
                x.VideoUrl,
                x.Type,
                TypeName = x.Type.GetEnumName(),
                x.BrandType,
                BrandTypeName = x.BrandType.GetEnumName(),
                OpenTime = x.OpenTime.ToString("yyyy-MM-dd HH:mm"),
                x.Address,
                x.TradingArea,
                x.BusinessType,
                BusinessTypeName = x.BusinessType.GetEnumName(),
                x.BusinessDetail,
                x.Description,
                x.County,
                x.Category,
                CategoryName = x.Category.GetEnumName(),
                x.Contact,
                x.ContactMobile,
                x.AuditState,
                x.AuditRemark,
                AuditDate = x.AuditDate.HasValue ? x.AuditDate.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取认证详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAuthenticationInfo()
        {
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int AuthenticationId = parms.GetInt("AuthenticationId", 0);
            if (AuthenticationId <= 0)
            {
                return ApiResult.ParamIsNull("请传递认证id");
            }
            var model = authenticationModule.GetAuthenticationInfo(AuthenticationId);
            if (model == null) { return ApiResult.Failed("认证不存在"); }
            if (userInfo.UserId != model.CreateBy) { return ApiResult.Failed("无法查看"); }
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.CoverImage,
                model.ImageList,
                model.VideoUrl,
                model.Type,
                TypeName = model.Type.GetEnumName(),
                model.BrandType,
                BrandTypeName = model.BrandType.GetEnumName(),
                OpenTime = model.OpenTime.ToString("yyyy-MM-dd HH:mm"),
                model.Address,
                model.TradingArea,
                model.BusinessType,
                BusinessTypeName = model.BusinessType.GetEnumName(),
                model.BusinessDetail,
                model.Description,
                model.County,
                model.Category,
                CategoryName = model.Category.GetEnumName(),
                model.Contact,
                model.ContactMobile,
                model.AuditState,
                model.AuditRemark,
                AuditDate = model.AuditDate.HasValue ? model.AuditDate.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateDate = model.CreateDate.ToString("yyyy-MM-dd HH:mm")
            });
        }

        /// <summary>
        /// 删除认证
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelAuthenticationInfo()
        {
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int AuthenticationId = parms.GetInt("AuthenticationId", 0);
            if (AuthenticationId <= 0)
            {
                return ApiResult.ParamIsNull("请传递认证id");
            }
            bool flag = authenticationModule.DelAuthenticationInfo(AuthenticationId, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取认证分类枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetAuthenticationCategoryEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.TradePavilion.AuthenticationCategoryEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取认证类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetAuthenticationTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.TradePavilion.AuthenticationTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取品牌归属地枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetBrandTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.TradePavilion.BrandTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取行业枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetBusinessTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.TradePavilion.BusinessTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        #endregion

        #region 载体管理

        /// <summary>
        /// 获取商会活动类型列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetCarrierPageList()
        {
            var userInfo = AppletUserInfo;
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Carrier_Extend()
            {
                MetroName = parms.GetStringValue("MetroName"),
                CarrierName = parms.GetStringValue("CarrierName"),
                MetroNum = parms.GetInt("MetroNum", 0),
                Developers = parms.GetStringValue("Developers"),
                StartOpenTime = parms.GetStringValue("StartOpenTime"),
                EndOpenTime = parms.GetStringValue("EndOpenTime"),
                ProjectType = (Common.Enum.TradePavilion.ProjectTypeEnum)parms.GetInt("ProjectType", 0),
                OrderBy = parms.GetInt("OrderBy", 0)
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = userInfo?.TenantId ?? 0;

            var list = carrierModule.GetCarrierPageList(pageModel.pageIndex, pageModel.pageSize, out long count, query);
            foreach (var item in list)
            {
                if (!string.IsNullOrWhiteSpace(item.Banner))
                {
                    item.BannerList = JsonConvert.DeserializeObject<List<string>>(item.Banner);
                }
                else {
                    item.BannerList = new List<string>();
                }
            }
            pageModel.count = Convert.ToInt32(count);
            pageModel.pageData = list.Select(x => new
            {
                x.ID,
                x.CarrierName,
                x.Logo,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm"),
                x.Address,
                x.LatAndLon,
                x.Developers,
                OpenTime = x.OpenTime.HasValue ? x.OpenTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                x.ProjectType,
                ProjectTypeName = x.ProjectType.GetEnumName(),
                x.CarrierSize,
                x.LayersNum,
                x.CarNum,
                x.CarrierPlan,
                x.CarrierTarget,
                x.Location,
                x.Crowd,
                x.VideoUrl,
                x.CarrierMetroList,
                x.BannerList
            });
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取载体实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetCarrierDetails()
        {
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Carrier_Extend()
            {
                ID = parms.GetInt("ID", 0),
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = userInfo?.TenantId ?? 0;
            var extModel = carrierModule.GetCarrierModel(query);
            if (userInfo == null)
            {
                userInfo = new AppletUserInfo
                {
                    UserId = RequestParm.UserId,
                    MallBaseId = RequestParm.MallBaseId,
                    TenantId = RequestParm.TenantId
                };
            }
            if (userInfo.UserId > 0 && extModel.ID > 0)
            {                //判断是否已经关注过
                var collectModel = carrierModule.GetList(new RB_Collect_Extend { Status = 0, Type = 1, UserId = userInfo.UserId, SourceId = extModel.ID, MallBaseId = query.MallBaseId, TenantId = query.TenantId }).FirstOrDefault();
                extModel.CollectId = collectModel?.Id ?? 0;
            }
            return ApiResult.Success(data: new
            {
                extModel.ID,
                extModel.CarrierName,
                extModel.Logo,
                CreateDate = extModel.CreateDate.ToString("yyyy-MM-dd HH:mm"),
                extModel.Address,
                extModel.LatAndLon,
                extModel.Developers,
                OpenTime = extModel.OpenTime.HasValue ? extModel.OpenTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                extModel.ProjectType,
                ProjectTypeName = extModel.ProjectType.GetEnumName(),
                extModel.CarrierSize,
                extModel.LayersNum,
                extModel.CarNum,
                extModel.CarrierPlan,
                extModel.CarrierTarget,
                extModel.Location,
                extModel.Crowd,
                extModel.VideoUrl,
                extModel.CarrierMetroList,
                extModel.BannerList,
                extModel.CollectId
            });
        }

        #endregion

        #region 公司品牌
        /// <summary>
        /// 新增修改品牌信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetBrand()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            RB_CompanyBrand_Extend extModel = JsonConvert.DeserializeObject<RB_CompanyBrand_Extend>(RequestParm.msg.ToString());

            if (string.IsNullOrWhiteSpace(extModel.BrandName))
            {
                return ApiResult.Failed("品牌名称必填");
            }
            if (extModel.ShopNum == 0)
            {
                return ApiResult.Failed("店铺数量必须大于0");
            }
            if (extModel.BuiltUpArea == 0)
            {
                return ApiResult.Failed("店铺面积必填");
            }
            if (extModel.EndBuiltUpArea == 0)
            {
                return ApiResult.Failed("店铺面积必填");
            }
            if (string.IsNullOrWhiteSpace(extModel.FullBrandName))
            {
                return ApiResult.Failed("店铺定位必填");
            }
            if (string.IsNullOrWhiteSpace(extModel.CustomerType))
            {
                return ApiResult.Failed("请选择客户群体");
            }
            if (!string.IsNullOrWhiteSpace(extModel.CustomerType) && extModel.CustomerType.Split(",").ToList().Any(x => x.Contains("5")))
            {
                if (string.IsNullOrWhiteSpace(extModel.CustomerOtherType))
                {
                    return ApiResult.Failed("请输入客户群体");
                }
            }


            var userInfo = AppletUserInfo;
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            extModel.MallBaseId = userInfo.MallBaseId;
            extModel.TenantId = userInfo.TenantId;
            var oldBrandModel = carrierModule.GetBrandRepository(new RB_CompanyBrand_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, CompanyId = extModel.CompanyId });
            if (oldBrandModel != null && oldBrandModel.ID > 0)
            {
                extModel.ID = oldBrandModel.ID;
            }
            var flag = carrierModule.SetCompanyBrand(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 获取当前用户的公司品牌信息实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserCompanyBrand()
        {
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var CompanyId = parms.GetInt("CompanyId", 0);
            var model = carrierModule.GetBrandRepository(new RB_CompanyBrand_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, CompanyId = CompanyId });
            return ApiResult.Success(data: model);
        }


        /// <summary>
        /// 获取客户群体枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetCustomerTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.TradePavilion.CustomerTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取商品性质枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetProjectTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.TradePavilion.ProjectTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        #endregion


        #region 品牌
        /// <summary>
        /// 获取品牌分页列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetBrandPageList()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Brand_Extend()
            {
                BrandName = parms.GetStringValue("BrandName"),
                ProjectType = (Common.Enum.TradePavilion.ProjectTypeEnum)parms.GetInt("ProjectType", 0),
                BrandClassId = parms.GetInt("BrandClassId", 0),
                RanQi = parms.GetInt("RanQi", -1),
                KongTiao = parms.GetInt("KongTiao", -1),
                XinFeng = parms.GetInt("XinFeng", -1),
                Plumbing = parms.GetInt("Plumbing", -1),
                Caliber = parms.GetInt("Caliber", -1),
                Sewage = parms.GetInt("Sewage", -1),
                PaiYan = parms.GetInt("PaiYan", -1),
                DianLiang = parms.GetStringValue("DianLiang"),
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = carrierModule.GetBrandPageList(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (!string.IsNullOrWhiteSpace(item.Banner))
                {
                    item.BannerList = JsonConvert.DeserializeObject<List<string>>(item.Banner);
                }
                else
                {
                    item.BannerList = new List<string>();
                }
            }
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }



        /// <summary>
        /// 获取品牌实体
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetBrandDetails()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            var query = new RB_Brand_Extend()
            {
                ID = parms.GetInt("ID", 0),

            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;

            var extModel = carrierModule.GetBrand(query);

            if (!string.IsNullOrWhiteSpace(extModel.Banner))
            {
                extModel.BannerList = JsonConvert.DeserializeObject<List<string>>(extModel.Banner);
            }
            else
            {
                extModel.BannerList = new List<string>();
            }

            extModel.ProjectName = extModel.ClassName;
            if (req.UserId > 0 && extModel.ID > 0)
            {                //判断是否已经关注过
                var collectModel = carrierModule.GetList(new RB_Collect_Extend { Status = 0, Type = 2, UserId = req.UserId, SourceId = extModel.ID, MallBaseId = query.MallBaseId, TenantId = query.TenantId }).FirstOrDefault();
                extModel.CollectId = collectModel?.Id ?? 0;
            }
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 获取品牌分类分页列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetBrandClassList()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_BrandClass_Extend();
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = carrierModule.GetBrandClassList(query);
            return ApiResult.Success(data: list);
        }
        #endregion

        #region 关注
        /// <summary>
        /// 关注品牌/载体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCollect()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Collect_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;

            bool isUpdate = true;

            if (query == null)
            {
                return ApiResult.Failed("请传入我关注的信息");
            }
            else
            {

                //判断是否已经关注过
                var oldList = carrierModule.GetList(new RB_Collect_Extend { Status = -1, Type = query.Type, UserId = query.UserId, SourceId = query.SourceId, MallBaseId = query.MallBaseId, TenantId = query.TenantId }); ;
                if (query.Id == 0)
                {
                    isUpdate = false;
                    query.CreateDate = System.DateTime.Now;
                    if (query.SourceId <= 0)
                    {
                        return ApiResult.Failed("请传入我关注的信息");
                    }
                    if (query.Type <= 0)
                    {
                        return ApiResult.Failed("请传入我关注的类型");
                    }
                    if (oldList != null && oldList.Any(x => x.Status == 0))
                    {
                        return ApiResult.Failed("您已关注，请勿重复操作");
                    }
                    else
                    {
                        if (oldList != null && oldList.Any())
                        {
                            query.Id = oldList.OrderByDescending(x => x.CreateDate).FirstOrDefault().Id;
                        }
                        query.Status = 0;
                    }
                }
                else
                {
                    query.Status = 1;
                }

                bool result = carrierModule.AddOrUpdateCollect(query);
                if (isUpdate)
                {
                    if (result)
                    {
                        return ApiResult.Success("取消关注成功");
                    }
                    else
                    {
                        return ApiResult.Failed("取消关注成功");
                    }
                }
                else
                {
                    if (result)
                    {
                        return ApiResult.Success("关注成功");
                    }
                    else
                    {
                        return ApiResult.Failed("关注成功");
                    }
                }
            }
        }
        #endregion
    }
}
