using Mall.Common.Plugin;
using Mall.Model.Extend.TradePavilion;
using Mall.Repository.TradePavilion;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Mall.Module.TradePavilion
{
    /// <summary>
    /// 公司信息处理类
    /// </summary>
    public class CompanyModule
    {
        private readonly RB_CompanyRepository companyRepository = new RB_CompanyRepository();
        private readonly RB_CompanyBrandRepository brandRepository = new RB_CompanyBrandRepository();
        /// <summary>
        /// 品牌申请
        /// </summary>
        private readonly RB_BrandApplyForRepository brandApplyForRepository = new RB_BrandApplyForRepository();
        /// <summary>
        /// 载体申请
        /// </summary>
        private readonly RB_CarrierApplyForRepository carrierApplyForRepository = new RB_CarrierApplyForRepository();
        /// <summary>
        /// 载体地铁
        /// </summary>
        private readonly RB_CarrierMetroApplyForRepository carrierMetroApplyForRepository = new RB_CarrierMetroApplyForRepository();
        /// <summary>
        /// 品牌
        /// </summary>
        private readonly RB_BrandRepository brand2Repository = new RB_BrandRepository();
        /// <summary>
        /// 载体
        /// </summary>
        private readonly RB_CarrierRepository carrierRepository = new RB_CarrierRepository();
        /// <summary>
        /// 载体地铁
        /// </summary>
        private readonly RB_CarrierMetroRepository carrierMetroRepository = new RB_CarrierMetroRepository();
        /// <summary>
        /// 用户
        /// </summary>
        private readonly Repository.User.RB_Member_UserRepository member_UserRepository = new Repository.User.RB_Member_UserRepository();

        /// <summary>
        /// 获取公司信息分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Company_Extend> GetCompanyPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Company_Extend query)
        {
            var list = companyRepository.GetCompanyPageListRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Any())
            {
                #region 屏蔽
                //string carrierIds = string.Join(",", list.Select(x => x.CompanyId));
                //if (!string.IsNullOrWhiteSpace(carrierIds))
                //{
                //    var metroList = brandRepository.GetBrandList(new RB_CompanyBrand_Extend { TenantId = query.TenantId, MallBaseId = query.MallBaseId, CompanyIds = carrierIds });
                //    if (metroList != null && metroList.Any())
                //    {
                //        foreach (var item in list)
                //        {
                //            item.BrandModel = new RB_CompanyBrand_Extend();
                //            item.BrandModel = metroList.Where(x => x.CompanyId == item.CompanyId).FirstOrDefault();
                //            if (item.BrandModel != null && !string.IsNullOrWhiteSpace(item.BrandModel.CustomerType))
                //            {
                //                item.BrandModel.CustomerTypeInfo = new List<string>();
                //                foreach (var itemCustomerType in item.BrandModel.CustomerType.Split(","))
                //                {
                //                    if (!string.IsNullOrWhiteSpace(itemCustomerType) && itemCustomerType != "5")
                //                    {
                //                        item.BrandModel.CustomerTypeInfo.Add(Common.Plugin.EnumHelper.GetEnumName((Common.Enum.TradePavilion.CustomerTypeEnum)System.Convert.ToInt32(itemCustomerType)));
                //                    }
                //                    else if (!string.IsNullOrWhiteSpace(itemCustomerType))
                //                    {
                //                        item.BrandModel.CustomerTypeInfo.Add(item.BrandModel.CustomerOtherType);
                //                    }
                //                }
                //            }
                //        }
                //    }
                //}
                #endregion
                //查询用户列表
                string userIds = string.Join(",", list.Select(x => x.CreateBy));
                var ulist = member_UserRepository.GetList(new Model.Extend.User.RB_Member_User_Extend() { MallBaseId = query.MallBaseId, UserIds = userIds });
                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.CreateBy).FirstOrDefault();
                    item.UserName = umodel.Name;
                    item.UserIcon = umodel.Photo;
                }
            }

            return list;
        }


        /// <summary>
        /// 获取公司信息实体
        /// </summary>
        /// <param name="CompanyId"></param>
        /// <returns></returns>
        public RB_Company_Extend GetCompanyEntity(object CompanyId)
        {
            var model = companyRepository.GetEntity<RB_Company_Extend>(CompanyId);

            return model;
        }

        /// <summary>
        /// 获取公司信息实体
        /// </summary>
        /// <param name="CompanyId"></param>
        /// <returns></returns>
        public RB_Company_Extend GetCompanyModule(object CompanyId)
        {
            var model = companyRepository.GetEntity<RB_Company_Extend>(CompanyId);
            if (model != null && model.CompanyId > 0)
            {
                model.BrandModel = new RB_BrandApplyFor_Extend();
                model.CarrierModel = new RB_CarrierApplyFor_Extend();

                if (model.FirstShopType == 1)
                {
                    var brandList = brandApplyForRepository.GetBrandListByWhere(new RB_BrandApplyFor_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CompanyId = model.CompanyId });
                    if (brandList != null && brandList.Any())
                    {
                        model.BrandModel = brandList.FirstOrDefault();
                        if (model.BrandModel != null && !string.IsNullOrWhiteSpace(model.BrandModel.CustomerType))
                        {
                            model.BrandModel.CustomerTypeInfo = new List<string>();
                            foreach (var itemCustomerType in model.BrandModel.CustomerType.Split(","))
                            {
                                model.BrandModel.CustomerTypeInfo.Add(Common.Plugin.EnumHelper.GetEnumName(itemCustomerType));
                            }
                        }

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

                        model.BrandModel.ProjectName = model.BrandModel.ProjectType.GetEnumName();
                    }
                }
                else
                {
                    var carrierList = carrierApplyForRepository.GetCarrierList(new RB_CarrierApplyFor_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CompanyId = model.CompanyId });
                    if (carrierList.Any())
                    {
                        model.CarrierModel = carrierList.FirstOrDefault();
                        var metroList = carrierMetroApplyForRepository.GetCarrierMetroList(new RB_CarrierMetroApplyFor_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CarrierId = model.CarrierModel.ID });
                        model.CarrierModel.CarrierMetroList = new List<RB_CarrierMetroApplyFor_Extend>();
                        if (metroList != null && metroList.Any())
                        {
                            model.CarrierModel.CarrierMetroList = metroList;
                        }
                        if (!string.IsNullOrWhiteSpace(model.CarrierModel.Banner))
                        {
                            model.CarrierModel.BannerList = JsonConvert.DeserializeObject<List<string>>(model.CarrierModel.Banner);
                        }
                        else
                        {
                            model.CarrierModel.BannerList = new List<string>();
                        }

                        model.CarrierModel.ProjectName = model.CarrierModel.ProjectType.GetEnumName();
                    }
                }
            }
            return model;
        }

        /// <summary>
        /// 获取认证状态
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public object GetCommpanyStatus(int userId)
        {
            var model = companyRepository.GetCompanyRepository(new RB_Company_Extend() { CreateBy = userId });
            if (model != null)
            {
                if (model.CompanyStatus == 1)
                {
                    return new
                    {
                        CompanyStatus = 5,//认证通过
                        model.FirstShopType,
                        model.CompanyName
                    };
                }
                else if (model.CompanyStatus == 0)
                {
                    if (model.IsComplete == 1)
                    {
                        return new
                        {
                            CompanyStatus = 3,//认证审核中
                            model.FirstShopType,
                            model.CompanyName
                        };
                    }
                    else
                    {
                        return new
                        {
                            CompanyStatus = 2,//认证待完善
                            model.FirstShopType,
                            model.CompanyName
                        };
                    }
                }
                else if (model.CompanyStatus == 2)
                {
                    return new
                    {
                        CompanyStatus = 4,//认证未通过
                        model.FirstShopType,
                        model.CompanyName
                    };
                }
            }
            else
            {
                return new
                {
                    CompanyStatus = 1,//未认证
                    FirstShopType = 0,
                    CompanyName = ""
                };
            }
            return model;
        }

        /// <summary>
        /// 获取公司信息实体
        /// </summary>
        /// <param name="CompanyId"></param>
        /// <returns></returns>
        public RB_Company_Extend GetCompanyByUserIdModule(int userId)
        {
            var model = companyRepository.GetCompanyRepository(new RB_Company_Extend() { CreateBy = userId });
            if (model != null && model.CompanyId > 0)
            {
                model.BrandModel = new RB_BrandApplyFor_Extend();
                model.CarrierModel = new RB_CarrierApplyFor_Extend();
                if (model.CompanyStatus == 1)
                {
                    if (model.FirstShopType == 1)
                    {
                        //审核通过了的  直接查询资料表
                        var blist = brand2Repository.GetBrandList(new RB_Brand_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, UserId = userId });
                        model.BrandModel = blist.FirstOrDefault().RefMapperTo<RB_BrandApplyFor_Extend>();


                        if (model.BrandModel != null)
                        {
                            if (!string.IsNullOrWhiteSpace(model.BrandModel.CustomerType))
                            {
                                model.BrandModel.CustomerTypeInfo = new List<string>();
                                foreach (var itemCustomerType in model.BrandModel.CustomerType.Split(","))
                                {
                                    model.BrandModel.CustomerTypeInfo.Add(Common.Plugin.EnumHelper.GetEnumName(itemCustomerType));
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(model.BrandModel.Banner))
                            {
                                model.BrandModel.BannerList = JsonConvert.DeserializeObject<List<string>>(model.BrandModel.Banner);
                            }
                            else
                            {
                                model.BrandModel.BannerList = new List<string>();
                            }
                        }
                        else
                        {
                            model.BrandModel = new RB_BrandApplyFor_Extend
                            {
                                BannerList = new List<string>(),
                                CustomerTypeInfo = new List<string>()
                            };
                        }
                    }
                    else
                    {
                        var clist = carrierRepository.GetCarrierList(new RB_Carrier_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, UserId = userId });
                        if (clist.Any())
                        {
                            model.CarrierModel = clist.FirstOrDefault().RefMapperTo<RB_CarrierApplyFor_Extend>();
                            var metroList = carrierMetroRepository.GetCarrierMetroList(new RB_CarrierMetro_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CarrierId = model.CarrierModel.ID });
                            model.CarrierModel.CarrierMetroList = new List<RB_CarrierMetroApplyFor_Extend>();
                            if (metroList != null && metroList.Any())
                            {
                                model.CarrierModel.CarrierMetroList = metroList.RefMapperToList<RB_CarrierMetroApplyFor_Extend>();
                            }
                            if (!string.IsNullOrWhiteSpace(model.CarrierModel.Banner))
                            {
                                model.CarrierModel.BannerList = JsonConvert.DeserializeObject<List<string>>(model.CarrierModel.Banner);
                            }
                            else
                            {
                                model.CarrierModel.BannerList = new List<string>();
                            }
                        }
                    }
                }
                else
                {
                    if (model.FirstShopType == 1)
                    {
                        var brandList = brandApplyForRepository.GetBrandListByWhere(new RB_BrandApplyFor_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CompanyId = model.CompanyId });
                        if (brandList != null && brandList.Any())
                        {
                            model.BrandModel = brandList.FirstOrDefault();
                            if (model.BrandModel != null)
                            {
                                if (!string.IsNullOrWhiteSpace(model.BrandModel.CustomerType))
                                {
                                    model.BrandModel.CustomerTypeInfo = new List<string>();
                                    foreach (var itemCustomerType in model.BrandModel.CustomerType.Split(","))
                                    {
                                        model.BrandModel.CustomerTypeInfo.Add(Common.Plugin.EnumHelper.GetEnumName(itemCustomerType));
                                    }
                                }
                                if (!string.IsNullOrWhiteSpace(model.BrandModel.Banner))
                                {
                                    model.BrandModel.BannerList = JsonConvert.DeserializeObject<List<string>>(model.BrandModel.Banner);
                                }
                                else
                                {
                                    model.BrandModel.BannerList = new List<string>();
                                }
                            }
                            else
                            {
                                model.BrandModel = new RB_BrandApplyFor_Extend
                                {
                                    BannerList = new List<string>(),
                                    CustomerTypeInfo = new List<string>()
                                };
                            }
                        }
                    }
                    else
                    {
                        var carrierList = carrierApplyForRepository.GetCarrierList(new RB_CarrierApplyFor_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CompanyId = model.CompanyId });
                        if (carrierList.Any())
                        {
                            model.CarrierModel = carrierList.FirstOrDefault();
                            var metroList = carrierMetroApplyForRepository.GetCarrierMetroList(new RB_CarrierMetroApplyFor_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CarrierId = model.CarrierModel.ID });
                            model.CarrierModel.CarrierMetroList = new List<RB_CarrierMetroApplyFor_Extend>();
                            if (metroList != null && metroList.Any())
                            {
                                model.CarrierModel.CarrierMetroList = metroList;
                            }
                            if (!string.IsNullOrWhiteSpace(model.CarrierModel.Banner))
                            {
                                model.CarrierModel.BannerList = JsonConvert.DeserializeObject<List<string>>(model.CarrierModel.Banner);
                            }
                            else
                            {
                                model.CarrierModel.BannerList = new List<string>();
                            }
                            if (!string.IsNullOrWhiteSpace(model.CarrierModel.Honor))
                            {
                                model.CarrierModel.HonorList = JsonConvert.DeserializeObject<List<string>>(model.CarrierModel.Honor);
                            }
                            else
                            {
                                model.CarrierModel.HonorList = new List<string>();
                            }
                            if (!string.IsNullOrWhiteSpace(model.CarrierModel.FirstShopNum))
                            {
                                model.CarrierModel.FirstShopNumList = JsonConvert.DeserializeObject<List<FirstShopNumModel>>(model.CarrierModel.FirstShopNum);
                            }
                            else
                            {
                                model.CarrierModel.FirstShopNumList = new List<FirstShopNumModel>();
                            }


                        }
                    }
                }
            }
            return model;
        }

        /// <summary>
        /// 设置用户为管理员
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isAdmin"></param>
        /// <returns></returns>
        public string SetMemberUserIsAdmin(int userId, int isAdmin)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(Model.Extend.User.RB_Member_User_Extend.IsAdmin),isAdmin}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(Model.Extend.User.RB_Member_User_Extend.Id),
                      FiledValue=userId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = member_UserRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 新增修改公司信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int SetCompanyModule(RB_Company_Extend model)
        {
            int ID;
            if (model.CompanyId > 0)
            {
                ID = model.CompanyId;
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Company_Extend.CompanyName),model.CompanyName },
                    {nameof(RB_Company_Extend.Principal),model.Principal },
                    {nameof(RB_Company_Extend.Mobile),model.Mobile },
                    {nameof(RB_Company_Extend.BusinessLicense),model.BusinessLicense },
                    {nameof(RB_Company_Extend.LegalPerson),model.LegalPerson },
                    {nameof(RB_Company_Extend.UnifiedCode),model.UnifiedCode },
                    {nameof(RB_Company_Extend.CompanyIntro),model.CompanyIntro },
                    {nameof(RB_Company_Extend.FirstShopType),model.FirstShopType },
                    {nameof(RB_Company_Extend.CompanyStatus),model.CompanyStatus },
                    {nameof(RB_Company_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Company_Extend.UpdateDate),model.UpdateDate },
                };
                companyRepository.Update(fileds, new WhereHelper(nameof(RB_Company_Extend.CompanyId), model.CompanyId));
            }
            else
            {
                var newId = companyRepository.Insert(model);
                model.CompanyId = newId;
                ID = newId;
            }
            return ID;
        }

        /// <summary>
        /// 设置认证为待完善状态
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public string SetCommpanyCompleteCorvidae(int companyId, int userId)
        {
            var model = companyRepository.GetEntity(companyId);
            if (model == null || model.CreateBy != userId) { return "认证不存在"; }
            if (model.CompanyStatus == 0 && model.IsComplete == 1)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Company_Extend.IsComplete),0}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Company_Extend.CompanyId),
                          FiledValue=companyId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = companyRepository.Update(keyValues, wheres);
                return flag ? "" : "修改失败";
            }
            else
            {
                return "认证状态不正确";
            }
        }

        /// <summary>
        /// 更新公司信息状态
        /// </summary>
        /// <param name="CompanyId"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveCompanyModule(int CompanyId, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Company_Extend.Status),Status },
            };
            bool flag = companyRepository.Update(fileds, new WhereHelper(nameof(RB_Company_Extend.CompanyId), CompanyId));
            return flag;
        }

        /// <summary>
        /// 更新公司审核状态
        /// </summary>
        /// <param name="CompanyId"></param>
        /// <param name="Status"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public string UpdateCompanyStatus(int CompanyId, int Status, string remark)
        {
            var trans = companyRepository.DbTransaction;
            try
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Company_Extend.CompanyStatus),Status },
                };
                if (Status == 2)
                {
                    fileds.Add(nameof(RB_Company_Extend.RejectRemark), remark);
                }
                List<WhereHelper> wheres = new List<WhereHelper>() {
                     new WhereHelper(){
                         FiledName=nameof(RB_Company_Extend.CompanyId),
                          FiledValue=CompanyId,
                           OperatorEnum=OperatorEnum.Equal
                     }
                };
                bool flag = companyRepository.Update(fileds, wheres, trans);
                if (flag)
                {
                    //新增 更新品牌 载体信息
                    if (Status == 1)
                    {
                        var cmodel = companyRepository.GetEntity(CompanyId);
                        if (cmodel.FirstShopType == 1)
                        {
                            //品牌
                            var brandList = brandApplyForRepository.GetBrandListByWhere(new RB_BrandApplyFor_Extend { MallBaseId = cmodel.MallBaseId, CompanyId = cmodel.CompanyId });
                            if (brandList != null && brandList.Any())
                            {
                                var BrandModel = brandList.FirstOrDefault();
                                if (BrandModel.ExistBrandId > 0)
                                {
                                    //修改
                                    #region 验证品牌是否已关联用户
                                    //var bmodel = brand2Repository.GetEntity(BrandModel.ExistBrandId);
                                    //if (bmodel.UserId > 0)
                                    //{
                                    //    companyRepository.DBSession.Rollback();
                                    //    return "该品牌已被其他用户认证，请核实后再试";
                                    //}
                                    #endregion
                                    Dictionary<string, object> filedsBrand = new Dictionary<string, object>()
                                    {
                                        {nameof(RB_Brand_Extend.UpdateDate),DateTime.Now },
                                        {nameof(RB_Brand_Extend.Logo),BrandModel.Logo },
                                        {nameof(RB_Brand_Extend.Banner),BrandModel.Banner },
                                        {nameof(RB_Brand_Extend.VideoUrl),BrandModel.VideoUrl },
                                        {nameof(RB_Brand_Extend.ShopNum),BrandModel.ShopNum },
                                        {nameof(RB_Brand_Extend.BuiltUpArea),BrandModel.BuiltUpArea },
                                        {nameof(RB_Brand_Extend.EndBuiltUpArea),BrandModel.EndBuiltUpArea },
                                        {nameof(RB_Brand_Extend.BrandType),BrandModel.BrandType },
                                        {nameof(RB_Brand_Extend.CustomerType),BrandModel.CustomerType },
                                        {nameof(RB_Brand_Extend.StoreExpansion),BrandModel.StoreExpansion },
                                        {nameof(RB_Brand_Extend.ProjectType),BrandModel.ProjectType },
                                        {nameof(RB_Brand_Extend.AreaRequirement),BrandModel.AreaRequirement },
                                        {nameof(RB_Brand_Extend.EndAreaRequirement),BrandModel.EndAreaRequirement },
                                        {nameof(RB_Brand_Extend.ShopSize),BrandModel.ShopSize },
                                        {nameof(RB_Brand_Extend.Plumbing),BrandModel.Plumbing },
                                        {nameof(RB_Brand_Extend.Caliber),BrandModel.Caliber },
                                        {nameof(RB_Brand_Extend.Sewage),BrandModel.Sewage },
                                        {nameof(RB_Brand_Extend.RanQi),BrandModel.RanQi },
                                        {nameof(RB_Brand_Extend.DianLiang),BrandModel.DianLiang },
                                        {nameof(RB_Brand_Extend.PaiYan),BrandModel.PaiYan },
                                        {nameof(RB_Brand_Extend.KongTiao),BrandModel.KongTiao },
                                        {nameof(RB_Brand_Extend.XinFeng),BrandModel.XinFeng },
                                        {nameof(RB_Brand_Extend.BrandClassId),BrandModel.BrandClassId },
                                        {nameof(RB_Brand_Extend.RanQiBZ),BrandModel.RanQiBZ },
                                        {nameof(RB_Brand_Extend.IsDianLiang),BrandModel.IsDianLiang },
                                        {nameof(RB_Brand_Extend.PaiYanBZ),BrandModel.PaiYanBZ },
                                        {nameof(RB_Brand_Extend.IsShopSize),BrandModel.IsShopSize },
                                        {nameof(RB_Brand_Extend.OpenShopWish),BrandModel.OpenShopWish },
                                        {nameof(RB_Brand_Extend.IsInChengdu),BrandModel.IsInChengdu },
                                        {nameof(RB_Brand_Extend.UserId),cmodel.CreateBy },
                                    };
                                    brand2Repository.Update(filedsBrand, new WhereHelper(nameof(RB_Brand_Extend.ID), BrandModel.ExistBrandId), trans);
                                }
                                else
                                {
                                    //新增
                                    #region 再次验证品牌名称
                                    //if (ValidateBrandName(BrandModel.BrandName, cmodel.MallBaseId))
                                    //{
                                    //    companyRepository.DBSession.Rollback();
                                    //    return "该品牌名称已存在,请确认品牌名称后再次审核";
                                    //}
                                    //if (ValidateFullBrandName(BrandModel.FullBrandName, cmodel.MallBaseId))
                                    //{
                                    //    companyRepository.DBSession.Rollback();
                                    //    return "该品牌全名已存在,请确认品牌全名后再次审核";
                                    //}
                                    #endregion

                                    #region 新增品牌
                                    var inserBModel = BrandModel.RefMapperTo<RB_Brand_Extend>();
                                    inserBModel.ID = 0;
                                    inserBModel.UserId = cmodel.CreateBy;
                                    brand2Repository.Insert(inserBModel, trans);
                                    #endregion
                                }
                            }
                        }
                        else
                        {
                            //载体
                            var carrierList = carrierApplyForRepository.GetCarrierList(new RB_CarrierApplyFor_Extend() { MallBaseId = cmodel.MallBaseId, CompanyId = cmodel.CompanyId });
                            if (carrierList != null && carrierList.Any())
                            {
                                var CarrierModel = carrierList.FirstOrDefault();
                                var MetroList = carrierMetroApplyForRepository.GetCarrierMetroList(new RB_CarrierMetroApplyFor_Extend { MallBaseId = cmodel.MallBaseId, CarrierId = CarrierModel.ID });

                                if (CarrierModel.ExistCarrierId > 0)
                                {
                                    //修改
                                    #region 验证品牌是否已关联用户
                                    var carrmodel = carrierRepository.GetEntity(CarrierModel.ExistCarrierId);
                                    //if (carrmodel.UserId > 0)
                                    //{
                                    //    companyRepository.DBSession.Rollback();
                                    //    return "该载体已被其他用户认证，请核实后再试";
                                    //}
                                    #endregion
                                    #region 修改载体
                                    int FirstStoreTest = 0;
                                    if (!string.IsNullOrWhiteSpace(CarrierModel.StartingInfo) )
                                    {
                                        FirstStoreTest = 1;
                                    }
                                    int OpeningStatus = 0;
                                    if (CarrierModel.OpenTime.HasValue)
                                    {
                                        if (CarrierModel.OpenTime.Value <= System.DateTime.Now)
                                        {
                                            OpeningStatus = 1;
                                        }
                                    }
                                    Dictionary<string, object> filedsCarrier = new Dictionary<string, object>()
                                    {
                                        {nameof(RB_Carrier_Extend.Logo),CarrierModel.Logo },
                                        {nameof(RB_Carrier_Extend.Banner),CarrierModel.Banner },
                                        {nameof(RB_Carrier_Extend.VideoUrl),CarrierModel.VideoUrl },
                                        {nameof(RB_Carrier_Extend.Address),CarrierModel.Address },
                                        {nameof(RB_Carrier_Extend.LatAndLon),CarrierModel.LatAndLon },
                                        {nameof(RB_Carrier_Extend.Developers),CarrierModel.Developers },
                                        {nameof(RB_Carrier_Extend.OpenTime),CarrierModel.OpenTime },
                                        {nameof(RB_Carrier_Extend.CarrierSize),CarrierModel.CarrierSize },
                                        {nameof(RB_Carrier_Extend.ProjectType),(int)CarrierModel.ProjectType },
                                        {nameof(RB_Carrier_Extend.LayersNum),CarrierModel.LayersNum },
                                        {nameof(RB_Carrier_Extend.CarNum),CarrierModel.CarNum },
                                        {nameof(RB_Carrier_Extend.CarrierPlan),CarrierModel.CarrierPlan },
                                        {nameof(RB_Carrier_Extend.CarrierTarget),CarrierModel.CarrierTarget },
                                        {nameof(RB_Carrier_Extend.Location),CarrierModel.Location },
                                        {nameof(RB_Carrier_Extend.Crowd),CarrierModel.Crowd },
                                        {nameof(RB_Carrier_Extend.UserId),cmodel.CreateBy },
                                        {nameof(RB_Carrier_Extend.Discount),CarrierModel.Discount },
                                        {nameof(RB_Carrier_Extend.Honor),CarrierModel.Honor },
                                        {nameof(RB_Carrier_Extend.YeJi),CarrierModel.YeJi },
                                        {nameof(RB_Carrier_Extend.ShopNum),CarrierModel.ShopNum },
                                        {nameof(RB_Carrier_Extend.AreaRequirement ),CarrierModel.AreaRequirement  },
                                        {nameof(RB_Carrier_Extend.EndAreaRequirement),CarrierModel.EndAreaRequirement },
                                        {nameof(RB_Carrier_Extend.BuiltUpArea),CarrierModel.BuiltUpArea },
                                        {nameof(RB_Carrier_Extend.EndBuiltUpArea),CarrierModel.EndBuiltUpArea },
                                        {nameof(RB_Carrier_Extend.FirstShopNum),CarrierModel.FirstShopNum },
                                        {nameof(RB_Carrier_Extend.StartingInfo),CarrierModel.StartingInfo },
                                          {nameof(RB_Carrier_Extend.FirstStoreTest),FirstStoreTest },
                                          {nameof(RB_Carrier_Extend.OpeningStatus),OpeningStatus }
                                    };
                                    flag = carrierRepository.Update(filedsCarrier, new WhereHelper(nameof(RB_Carrier_Extend.ID), carrmodel.ID), trans);
                                    if (flag)
                                    {
                                        var oldCarrierMetroList = carrierMetroRepository.GetCarrierMetroList(new RB_CarrierMetro_Extend { MallBaseId = CarrierModel.MallBaseId, CarrierId = carrmodel.ID });
                                        carrierMetroRepository.DeleteBatch(oldCarrierMetroList);
                                        var mlist = MetroList.RefMapperToList<RB_CarrierMetro_Extend>();
                                        mlist.ForEach(x =>
                                        {
                                            x.ID = 0;
                                            x.CarrierId = carrmodel.ID;
                                            x.Status = 0;
                                            x.TenantId = CarrierModel.TenantId;
                                            x.MallBaseId = CarrierModel.MallBaseId;
                                        });
                                        carrierMetroRepository.InsertBatch(mlist);
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //新增
                                    #region 再次验证载体名称
                                    //if (ValidateCarrierName(CarrierModel.CarrierName, CarrierModel.MallBaseId))
                                    //{
                                    //    return "该载体名称已存在,请确认载体名称后再次审核";
                                    //}
                                    #endregion
                                    #region 新增载体
                                    var inserCModel = CarrierModel.RefMapperTo<RB_Carrier_Extend>();
                                    inserCModel.ID = 0;
                                    inserCModel.UserId = cmodel.CreateBy;
                                    if (CarrierModel.OpenTime.HasValue)
                                    {
                                        if (CarrierModel.OpenTime.Value <= System.DateTime.Now)
                                        {
                                            inserCModel.OpeningStatus = 1;
                                        }
                                    }
                                    if (!string.IsNullOrWhiteSpace(CarrierModel.StartingInfo))
                                    {
                                        inserCModel.FirstStoreTest = 1;
                                    }
                                    int Id = carrierRepository.Insert(inserCModel, trans);
                                    if (Id > 0)
                                    {
                                        var mlist = MetroList.RefMapperToList<RB_CarrierMetro_Extend>();
                                        mlist.ForEach(x =>
                                        {
                                            x.ID = 0;
                                            x.CarrierId = Id;
                                            x.Status = 0;
                                            x.TenantId = CarrierModel.TenantId;
                                            x.MallBaseId = CarrierModel.MallBaseId;
                                        });
                                        carrierMetroRepository.InsertBatch(mlist, trans);
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                }
                companyRepository.DBSession.Commit();
                return flag ? "" : "出错了，请联系管理员";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "UpdateCompanyStatus");
                companyRepository.DBSession.Rollback();
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 验证品牌名称
        /// </summary>
        /// <param name="brandName"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool ValidateBrandName(string brandName, int mallBaseId)
        {
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Brand_Extend.BrandName),
                      FiledValue=brandName,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Brand_Extend.MallBaseId),
                      FiledValue=mallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            return brandRepository.Exists(wheres);
        }

        /// <summary>
        /// 验证品牌全称
        /// </summary>
        /// <param name="brandName"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool ValidateFullBrandName(string brandName, int mallBaseId)
        {
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Brand_Extend.FullBrandName),
                      FiledValue=brandName,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Brand_Extend.MallBaseId),
                      FiledValue=mallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            return brandRepository.Exists(wheres);
        }

        /// <summary>
        /// 验证载体名称
        /// </summary>
        /// <param name="carrierName"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool ValidateCarrierName(string carrierName, int mallBaseId)
        {
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Carrier_Extend.CarrierName),
                      FiledValue=carrierName,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Carrier_Extend.MallBaseId),
                      FiledValue=mallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            return carrierRepository.Exists(wheres);
        }
    }
}
