using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.Finance;
using Edu.Common.Enum.WeChat;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.WeChat;
using Edu.Module.QYWeChat;
using Edu.Module.User;
using Edu.ThirdCore.QYWinXin;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.QYWeChat
{
    /// <summary>
    /// 企业微信接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class QYWeChatController : BaseController
    {
        /// <summary>
        /// 企业微信处理类对象
        /// </summary>
        private readonly QYWeChatModule weChatModule = new QYWeChatModule();

        private readonly GroupModule groupModule = new GroupModule();

        #region 微信配置
        /// <summary>
        /// 获取活动配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatConfigInfo() {
            var userInfo = base.UserInfo;

            var model = weChatModule.GetWeChatConfigModel(new RB_WeChat_Config_ViewModel() { Group_Id = userInfo.Group_Id });
            if (model == null) { model = new Model.CacheModel.WorkChatConfig(); }
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.WX_CorpId,
                model.Social_Code,
                model.Employee_Secret,
                model.Contact_Secret,
                model.TelEvent_CallBack,
                model.Token,
                model.Encoding_Aes_Key,
                model.EmpEvent_CallBack,
                model.Enable,
                model.DeptEmpEnable,
                model.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(model.UpdateBy)?.AccountName ?? "",
                UpdateTime = model.UpdateTime.ToString("yyyy-MM-dd HH:mm")
            });
        }

        /// <summary>
        /// 新增/修改 活动配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWeChatConfig() {
            var userInfo = base.UserInfo;
            RB_WeChat_Config_ViewModel demdoel = JsonHelper.DeserializeObject<RB_WeChat_Config_ViewModel>(RequestParm.Msg.ToString());

            demdoel.Group_Id = userInfo.Group_Id;
            demdoel.CreateBy = userInfo.Id;
            demdoel.CreateTime = DateTime.Now;
            demdoel.UpdateBy = userInfo.Id;
            demdoel.UpdateTime = DateTime.Now;
            demdoel.Token = Config.ReadConfigKey("QYWeiChatToken");
            demdoel.Encoding_Aes_Key = Config.ReadConfigKey("QYWeiChatEncodingAESKey");

            string msg = weChatModule.SetWeChatConfig(demdoel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        #endregion


        #region 同步部门

        /// <summary>
        /// 同步教育部门
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSyncEduDepartment() {
            var userInfo = base.UserInfo;

            string msg = weChatModule.SetSyncEduDepartment(userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 同步人员

        /// <summary>
        /// 同步教育人员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSynvEduEmployee() {
            var userInfo = base.UserInfo;

            string msg = weChatModule.SetSynvEduEmployee(userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 客户转移

        /// <summary>
        /// 客户继承
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserCoustomerTransfer() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int TransferUserId = parms.GetInt("TransferUserId", 0);//转交人
            int ReceiveUserId = parms.GetInt("ReceiveUserId", 0);//接收人
            int CustomerTransfer = parms.GetInt("CustomerTransfer", 0);//是否客户转移
            int ChannelTransfer = parms.GetInt("ChannelTransfer", 0);//是否转移渠道码用户配置
            if (TransferUserId <= 0) {
                return ApiResult.ParamIsNull("请传递转交人");
            }
            if (ReceiveUserId <= 0) {
                return ApiResult.ParamIsNull("请传递接收人");
            }
            if (CustomerTransfer != 1 && ChannelTransfer != 1) {
                return ApiResult.ParamIsNull("请选择需要转移的对象");
            }

            string msg = weChatModule.SetUserCoustomerTransfer(TransferUserId, ReceiveUserId, CustomerTransfer, ChannelTransfer, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取离职用户客服列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetLeaveUserClientList() {
            var userInfo = base.UserInfo;

            var RList = weChatModule.GetLeaveUserClientList(userInfo);
            return ApiResult.Success("", RList);
        }

        /// <summary>
        /// 离职用户 客户转移
        /// </summary>
        /// <returns></returns>
        public ApiResult SetLeaveUserCustomerTransfer() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int TransferUserId = parms.GetInt("TransferUserId", 0);//转交人
            int ReceiveUserId = parms.GetInt("ReceiveUserId", 0);//接收人
            string ClientList = parms.GetStringValue("ClientList");//客户Id列表
            if (TransferUserId <= 0)
            {
                return ApiResult.ParamIsNull("请传递转交人");
            }
            if (ReceiveUserId <= 0)
            {
                return ApiResult.ParamIsNull("请传递接收人");
            }
            if (string.IsNullOrEmpty(ClientList))
            {
                return ApiResult.ParamIsNull("请传递客户列表");
            }

            string msg = weChatModule.SetLeaveUserCustomerTransfer(TransferUserId, ReceiveUserId, ClientList, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }
        #endregion

        #region 素材管理

        /// <summary>
        /// 获取素材分组分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatMediumGroupPageList() {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_MediumGroup_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = weChatModule.GetWeChatMediumGroupPageList(pageModel.PageIndex, pageModel.PageSize, out long count, demodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取素材分组列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatMediumGroupList()
        {
            var userInfo = base.UserInfo;
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_MediumGroup_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = weChatModule.GetWeChatMediumGroupList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
            }));
        }

        /// <summary>
        /// 新增修改素材分组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWeChatMediumGroup() {
            var userInfo = base.UserInfo;
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_MediumGroup_ViewModel>(base.RequestParm.Msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name)) {
                return ApiResult.ParamIsNull("请传递分组名称");
            }

            demodel.Group_Id = userInfo.Group_Id;
            demodel.Status = 0;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            string msg = weChatModule.SetWeChatMediumGroup(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除素材分组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelWeChatMediumGroup() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int MediumId = parms.GetInt("MediumId", 0);
            if (MediumId <= 0) {
                return ApiResult.ParamIsNull();
            }

            string msg = weChatModule.DelWeChatMediumGroup(MediumId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取素材分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatMediumPageList() {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_Medium_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = weChatModule.GetWeChatMediumPageList(pageModel.PageIndex, pageModel.PageSize, out long count, demodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.MediaGroupId,
                x.MediumGroupName,
                x.Media_Id,
                x.Type,
                TypeName = x.Type.ToName(),
                x.Is_Sync,
                x.TextModel,
                x.ImageModel,
                x.ImgTextModel,
                x.AudioModel,
                x.VideoModel,
                x.AppletModel,
                x.FileModel,
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 保存素材
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWeChatMediumInfo() {
            var userInfo = base.UserInfo;
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_Medium_ViewModel>(base.RequestParm.Msg.ToString());
            if (demodel.MediaGroupId < 0)
            {
                return ApiResult.ParamIsNull("请传递分组id");
            }
            switch (demodel.Type) {
                case Common.Enum.WeChat.MediumTypeEnum.Text:
                    if (demodel.TextModel == null) { return ApiResult.ParamIsNull("请传递文本信息"); }
                    demodel.Content = JsonHelper.Serialize(demodel.TextModel);
                    break;
                case Common.Enum.WeChat.MediumTypeEnum.Image:
                    if (demodel.ImageModel == null) { return ApiResult.ParamIsNull("请传递图片信息"); }
                    demodel.Content = JsonHelper.Serialize(demodel.ImageModel);
                    break;
                case Common.Enum.WeChat.MediumTypeEnum.ImgText:
                    if (demodel.ImgTextModel == null) { return ApiResult.ParamIsNull("请传递图文信息"); }
                    demodel.Content = JsonHelper.Serialize(demodel.ImgTextModel);
                    break;
                case Common.Enum.WeChat.MediumTypeEnum.Audio:
                    if (demodel.AudioModel == null) { return ApiResult.ParamIsNull("请传递音频信息"); }
                    demodel.Content = JsonHelper.Serialize(demodel.AudioModel);
                    break;
                case Common.Enum.WeChat.MediumTypeEnum.Video:
                    if (demodel.VideoModel == null) { return ApiResult.ParamIsNull("请传递视频信息"); }
                    demodel.Content = JsonHelper.Serialize(demodel.VideoModel);
                    break;
                case Common.Enum.WeChat.MediumTypeEnum.Applet:
                    if (demodel.AppletModel == null) { return ApiResult.ParamIsNull("请传递小程序信息"); }
                    demodel.Content = JsonHelper.Serialize(demodel.AppletModel);
                    break;
                case Common.Enum.WeChat.MediumTypeEnum.File:
                    if (demodel.FileModel == null) { return ApiResult.ParamIsNull("请传递文件信息"); }
                    demodel.Content = JsonHelper.Serialize(demodel.FileModel);
                    break;
            }

            if (demodel.Id > 0) {
                if (demodel.Type != Common.Enum.WeChat.MediumTypeEnum.Text && demodel.Type != Common.Enum.WeChat.MediumTypeEnum.ImgText && demodel.Type != Common.Enum.WeChat.MediumTypeEnum.Applet) {
                    return ApiResult.Failed("无法修改");
                }
            }

            demodel.Group_Id = userInfo.Group_Id;
            demodel.Status = 0;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            string msg = weChatModule.SetWeChatMediumInfo(demodel, out int MediumId);
            if (msg == "")
            {
                return ApiResult.Success("", MediumId);
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 移动素材
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWecharMediumMore() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            string MediumIds = parms.GetStringValue("MediumIds");//素材ids
            int MediumGroupId = parms.GetInt("MediumGroupId", 0);//新分组id

            if (string.IsNullOrEmpty(MediumIds))
            {
                return ApiResult.ParamIsNull("请传递素材ids");
            }
            List<int> MediumIdList = JsonHelper.DeserializeObject<List<int>>("[" + MediumIds + "]");
            if (MediumGroupId <= 0)
            {
                return ApiResult.ParamIsNull("请传递分组id");
            }

            string msg = weChatModule.SetWecharMediumMore(MediumIdList, MediumGroupId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 删除素材
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelWecharMediumInfo()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            string MediumIds = parms.GetStringValue("MediumIds");//素材ids

            if (string.IsNullOrEmpty(MediumIds))
            {
                return ApiResult.ParamIsNull("请传递素材ids");
            }
            List<int> MediumIdList = JsonHelper.DeserializeObject<List<int>>("[" + MediumIds + "]");

            string msg = weChatModule.DelWecharMediumMore(MediumIdList, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMediumTypeEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(MediumTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => x.Id).Select(x => new
            {
                x.Name,
                x.Id
            }));
        }
        #endregion

        #region 欢迎语管理

        /// <summary>
        /// 获取欢迎语分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatWelcomesPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_Welcomes_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = weChatModule.GetWeChatWelcomesPageList(pageModel.PageIndex, pageModel.PageSize, out long count, demodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.UserIdList,
                x.Content,
                x.MediumIds,
                x.Type,
                MediumList = x.MediumList?.Select(x => new
                {
                    x?.Id,
                    x?.Type,
                    TypeName = x?.Type.ToName(),
                    x?.ImageModel,
                    x?.ImgTextModel,
                    x?.AppletModel,
                    x?.VideoModel,
                    x?.FileModel
                }),
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取欢迎语详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatWelcomesInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int WelcomeId = parms.GetInt("WelcomeId", 0);

            var model = weChatModule.GetWeChatWelcomesInfo(WelcomeId, userInfo.Group_Id);
            if (model == null) { return ApiResult.Failed("欢迎语不存在，请核实后再试"); }
            return ApiResult.Success("", new
            {
                model.Id,
                model.UserIdList,
                model.Content,
                model.MediumIds,
                model.Type,
                MediumList = model.MediumList?.Select(x => new
                {
                    x?.Id,
                    x?.Type,
                    TypeName = x?.Type.ToName(),
                    x?.ImageModel,
                    x?.ImgTextModel,
                    x?.AppletModel,
                    x?.VideoModel,
                    x?.FileModel
                }),
                model.UpdateBy
            });
        }

        /// <summary>
        /// 保存欢迎语
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWeChatWelcomesInfo()
        {
            var userInfo = base.UserInfo;
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_Welcomes_ViewModel>(base.RequestParm.Msg.ToString());
            if (demodel.UserIdList == null || !demodel.UserIdList.Any())
            {
                return ApiResult.ParamIsNull("请选择人员");
            }

            if (demodel.Type > 1)
            {
                if (string.IsNullOrEmpty(demodel.MediumIds)) {
                    return ApiResult.ParamIsNull("请传递素材Id");
                }
            }

            demodel.UserIds = string.Join(",", demodel.UserIdList);
            demodel.Group_Id = userInfo.Group_Id;
            demodel.Status = 0;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            string msg = weChatModule.SetWeChatWelcomesInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除欢迎语
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelWechatWelcomesInfo()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int WelcomesId = parms.GetInt("WelcomesId", 0);//欢迎语id

            if (WelcomesId <= 0)
            {
                return ApiResult.ParamIsNull("请传递欢迎语id");
            }

            string msg = weChatModule.DelWechatWelcomesInfo(WelcomesId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 客户标签

        /// <summary>
        /// 根据多个ID获取对应的标签信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ApiResult GetLabelListByIds()
        {
            var param = JObject.Parse(base.RequestParm.Msg.ToString());
            string ids = param.GetStringValue("ids");
            if (!string.IsNullOrEmpty(ids))
            {
                var result = weChatModule.GetLabelListByIds(ids);
                return ApiResult.Success(message: "OK", data: result);
            }
            else 
            {
                return ApiResult.Failed("参数信息错误");
            }
        }

        /// <summary>
        /// 获取企业标签列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatLableList() {
            var userInfo = base.UserInfo;
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_Lable_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = weChatModule.GetWeChatLableList(demodel);
            return ApiResult.Success("", list.OrderByDescending(x => x.Sort).ThenBy(x => x.Id).Select(x => new
            {
                x.Id,
                x.WXLableId,
                x.ParentId,
                x.Name,
                x.Sort,
                ChildList = x.ChildList.OrderByDescending(x => x.Sort).ThenBy(x => x.Id).Select(z => new
                {
                    z.Id,
                    z.WXLableId,
                    z.ParentId,
                    z.Name,
                    z.Sort
                })
            }));
        }

        /// <summary>
        /// 新增修改标签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWeChatLable() {
            var userInfo = base.UserInfo;
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_Lable_ViewModel>(base.RequestParm.Msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入分组/标签名称");
            }
            if (demodel.Id == 0 && demodel.ParentId == 0) {
                if (demodel.ChildList == null || !demodel.ChildList.Any()) {
                    return ApiResult.ParamIsNull("新增分组必须至少添加一个标签");
                }
                foreach (var item in demodel.ChildList) {
                    if (string.IsNullOrEmpty(item.Name)) {
                        return ApiResult.ParamIsNull("请输入标签名称");
                    }
                }
            }

            demodel.Group_Id = userInfo.Group_Id;
            demodel.Status = 0;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            string msg = weChatModule.SetWeChatLable(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelWeChatLable() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int LableId = parms.GetInt("LableId", 0);
            if (LableId <= 0) {
                return ApiResult.ParamIsNull("请传递标签Id");
            }

            string msg = weChatModule.DelWeChatLable(LableId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 同步企业微信标签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSyncWeChatLable() {
            var userInfo = base.UserInfo;

            string msg = weChatModule.SetSyncWeChatLable(userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 渠道活码
        #region 渠道分组
        /// <summary>
        /// 获取渠道分组分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelGroupPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_ChannelGroup_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = weChatModule.GetWeChatChannelGroupPageList(pageModel.PageIndex, pageModel.PageSize, out long count, demodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取渠道分组列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelGroupList()
        {
            var userInfo = base.UserInfo;
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_ChannelGroup_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = weChatModule.GetWeChatChannelGroupList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
            }));
        }

        /// <summary>
        /// 新增修改渠道分组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWeChatChannelGroup()
        {
            var userInfo = base.UserInfo;
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_ChannelGroup_ViewModel>(base.RequestParm.Msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请传递分组名称");
            }

            demodel.Group_Id = userInfo.Group_Id;
            demodel.Status = 0;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            string msg = weChatModule.SetWeChatChannelGroup(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 删除渠道分组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelWeChatChannelGroup()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int MediumId = parms.GetInt("GroupId", 0);
            if (MediumId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = weChatModule.DelWeChatChannelGroup(MediumId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }
        #endregion



        /// <summary>
        /// 获取渠道活码分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            var demodel = JsonHelper.DeserializeObject<RB_WeChat_Channel_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = weChatModule.GetWeChatChannelPageList(pageModel.PageIndex, pageModel.PageSize, out long count, demodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Type,
                x.WXQRCode,
                x.ChannelGroupId,
                x.ChannelGroupName,
                x.CustomerNum,
                x.LabelList,
                x.SkipVerify,
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取渠道活码详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int ChannelId = parms.GetInt("ChannelId", 0);
            if (ChannelId <= 0) {
                return ApiResult.ParamIsNull("请传递活码Id");
            }

            var rmodel = weChatModule.GetWeChatChannelInfo(ChannelId, userInfo);
            if (rmodel == null) { return ApiResult.Failed("渠道活码不存在"); }

            return ApiResult.Success("", new
            {
                rmodel.Id,
                rmodel.ChannelGroupId,
                rmodel.ChannelGroupName,
                rmodel.Name,
                rmodel.SkipVerify,
                rmodel.LableIds,
                rmodel.LabelIdList,
                rmodel.Type,
                WeekList = rmodel.WeekList?.Select(z => new
                {
                    z.Id,
                    z.Week,
                    z.IsDefault,
                    z.StartHours,
                    z.EndHours,
                    z.EmpList,
                    z.DeptList
                }),
                rmodel.SpecialDateEnable,
                SpecialWeekList = rmodel.SpecialWeekList?.Select(z => new
                {
                    z.Id,
                    StartDate = z.StartDate.Value.ToString("yyyy-MM-dd"),
                    EndDate = z.EndDate.Value.ToString("yyyy-MM-dd"),
                    z.IsDefault,
                    z.StartHours,
                    z.EndHours,
                    z.EmpList,
                    z.DeptList
                }),
                rmodel.EmpAddLimit,
                LimitList = rmodel.LimitList?.Select(x => new
                {
                    x.Id,
                    x.EmpId,
                    x.EmpName,
                    x.LimitNum
                }),
                rmodel.EmpBackUp,
                rmodel.EmpBackUpList,
                rmodel.WelcomeEnable,
                WelcomeList = rmodel.WelcomeList?.Select(x => new
                {
                    x.Id,
                    x.Content,
                    x.MediumIds,
                    MediumList = x.MediumList?.Select(x => new
                    {
                        x?.Id,
                        x?.Type,
                        TypeName = x?.Type.ToName(),
                        x?.ImageModel,
                        x?.ImgTextModel,
                        x?.AppletModel,
                        x?.VideoModel,
                        x?.FileModel
                    })
                }),
                rmodel.WelcomeWeekEnable,
                WelcomeWeekList = rmodel.WelcomeWeekList?.Select(x => new
                {
                    x.Id,
                    x.Weeks,
                    x.StartHours,
                    x.EndHours,
                    x.Content,
                    x.MediumIds,
                    MediumList = x.MediumList?.Select(x => new
                    {
                        x?.Id,
                        x?.Type,
                        TypeName = x?.Type.ToName(),
                        x?.ImageModel,
                        x?.ImgTextModel,
                        x?.AppletModel,
                        x?.VideoModel,
                        x?.FileModel
                    })
                }),
                rmodel.WelcomeSpecialEnable,
                WelcomeSpecialList = rmodel.WelcomeSpecialList?.Select(x => new
                {
                    x.Id,
                    StartDate = x.StartDate.Value.ToString("yyyy-MM-dd"),
                    EndDate = x.EndDate.Value.ToString("yyyy-MM-dd"),
                    x.StartHours,
                    x.EndHours,
                    x.Content,
                    x.MediumIds,
                    MediumList = x.MediumList?.Select(x => new
                    {
                        x?.Id,
                        x?.Type,
                        TypeName = x?.Type.ToName(),
                        x?.ImageModel,
                        x?.ImgTextModel,
                        x?.AppletModel,
                        x?.VideoModel,
                        x?.FileModel
                    })
                })
            });
        }

        /// <summary>
        /// 获取渠道活码详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelInfo_V2()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int ChannelId = parms.GetInt("ChannelId", 0);
            if (ChannelId <= 0)
            {
                return ApiResult.ParamIsNull("请传递活码Id");
            }

            var rmodel = weChatModule.GetWeChatChannelInfo(ChannelId, userInfo);
            if (rmodel == null) { return ApiResult.Failed("渠道活码不存在"); }

            return ApiResult.Success("", new
            {
                rmodel.Id,
                rmodel.ChannelGroupId,
                rmodel.ChannelGroupName,
                rmodel.Name,
                rmodel.SkipVerify,
                rmodel.LableIds,
                rmodel.LabelIdList,
                rmodel.Type,
                WeekList = rmodel.WeekList?.OrderBy(x => x.StartHours).Select(z => new
                {
                    z.Id,
                    z.Week,
                    z.IsDefault,
                    z.StartHours,
                    z.EndHours,
                    z.EmpList,
                    z.DeptList
                }),
                rmodel.SpecialDateEnable,
                SpecialWeekList = rmodel.SpecialWeekList?.GroupBy(x => new { x.StartDate, x.EndDate }).OrderBy(x => x.Key.StartDate).Select(z => new
                {
                    StartDate = z.Key.StartDate.Value.ToString("yyyy-MM-dd"),
                    EndDate = z.Key.EndDate.Value.ToString("yyyy-MM-dd"),
                    ChlidList = z.OrderBy(x => x.StartHours).Select(q => new
                    {
                        q.Id,
                        q.IsDefault,
                        q.StartHours,
                        q.EndHours,
                        q.EmpList,
                        q.DeptList
                    })
                }),
                rmodel.EmpAddLimit,
                LimitList = rmodel.LimitList?.OrderBy(x => x.Id).Select(x => new
                {
                    x.Id,
                    x.EmpId,
                    x.EmpName,
                    x.LimitNum
                }),
                rmodel.EmpBackUp,
                rmodel.EmpBackUpList,
                rmodel.WelcomeEnable,
                WelcomeList = rmodel.WelcomeList?.Select(x => new
                {
                    x.Id,
                    x.Content,
                    x.MediumIds,
                    MediumList = x.MediumList?.Select(x => new
                    {
                        x?.Id,
                        x?.Type,
                        TypeName = x?.Type.ToName(),
                        x?.ImageModel,
                        x?.ImgTextModel,
                        x?.AppletModel,
                        x?.VideoModel,
                        x?.FileModel
                    })
                }),
                rmodel.WelcomeWeekEnable,
                WelcomeWeekList = rmodel.WelcomeWeekList?.GroupBy(x => new { x.Weeks }).Select(x => new
                {
                    x.Key.Weeks,
                    ChildList = x.OrderBy(x => x.StartHours).Select(x => new
                    {
                        x.Id,
                        x.StartHours,
                        x.EndHours,
                        x.Content,
                        x.MediumIds,
                        MediumList = x.MediumList?.Select(x => new
                        {
                            x?.Id,
                            x?.Type,
                            TypeName = x?.Type.ToName(),
                            x?.ImageModel,
                            x?.ImgTextModel,
                            x?.AppletModel,
                            x?.VideoModel,
                            x?.FileModel
                        })
                    })
                }),
                rmodel.WelcomeSpecialEnable,
                WelcomeSpecialList = rmodel.WelcomeSpecialList?.GroupBy(x => new { x.StartDate, x.EndDate }).OrderBy(x => x.Key.StartDate).Select(x => new
                {
                    StartDate = x.Key.StartDate.Value.ToString("yyyy-MM-dd"),
                    EndDate = x.Key.EndDate.Value.ToString("yyyy-MM-dd"),
                    ChildList = x.OrderBy(x => x.StartHours).Select(x => new
                    {
                        x.Id,
                        x.StartHours,
                        x.EndHours,
                        x.Content,
                        x.MediumIds,
                        MediumList = x.MediumList?.Select(x => new
                        {
                            x?.Id,
                            x?.Type,
                            TypeName = x?.Type.ToName(),
                            x?.ImageModel,
                            x?.ImgTextModel,
                            x?.AppletModel,
                            x?.VideoModel,
                            x?.FileModel
                        })
                    })
                })
            });
        }

        /// <summary>
        /// 保存修改渠道活码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWeChatChannelInfo() {
            var userInfo = base.UserInfo;
            RB_WeChat_Channel_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_Channel_ViewModel>(base.RequestParm.Msg.ToString());
            if (demodel.ChannelGroupId <= 0) {
                return ApiResult.ParamIsNull("请传递分组Id");
            }
            if (string.IsNullOrEmpty(demodel.Name)) {
                return ApiResult.ParamIsNull("请输入渠道码的名称");
            }
            if (demodel.SkipVerify <= 0) {
                return ApiResult.ParamIsNull("请选择自动添加好友类型");
            }
            demodel.LableIds = "";
            if (demodel.LabelIdList != null && demodel.LabelIdList.Any()) {
                demodel.LableIds = string.Join(",", demodel.LabelIdList);
            }
            if (demodel.Type <= 0) {
                return ApiResult.ParamIsNull("请选择渠道码类型");
            }
            if (demodel.WeekList == null || !demodel.WeekList.Any()) {
                return ApiResult.ParamIsNull("请传递周期数据");
            }
            foreach (var item in demodel.WeekList) {
                if ((item.EmpList == null || !item.EmpList.Any()) && (item.DeptList == null || !item.DeptList.Any())) {
                    return ApiResult.Failed("周期数据传递有误");
                }
            }
            for (int i = 0; i < 7; i++) {
                var nlist = demodel.WeekList.Where(x => x.Week == i).ToList();
                if (!nlist.Any()) { return ApiResult.ParamIsNull("周期成员设置有误，亲核实后再试"); }
                if (!nlist.Where(x => x.IsDefault == 1).Any()) { return ApiResult.ParamIsNull("周期成员默认数据不存在，请核实后再试"); }
            }
            if (demodel.SpecialDateEnable == 1) {
                //启用特殊日期
                if (demodel.SpecialWeekList == null || !demodel.SpecialWeekList.Any())
                {
                    return ApiResult.ParamIsNull("请传递特殊日期数据");
                }
                foreach (var item in demodel.SpecialWeekList)
                {
                    if ((item.EmpList == null || !item.EmpList.Any()) && (item.DeptList == null || !item.DeptList.Any()))
                    {
                        return ApiResult.Failed("特殊日期数据传递有误");
                    }
                }
            }
            if (demodel.EmpAddLimit == 1) {
                if (demodel.LimitList == null || !demodel.LimitList.Any()) {
                    return ApiResult.ParamIsNull("请传递人员添加上限数据");
                }
                if (string.IsNullOrEmpty(demodel.EmpBackUp)) {
                    return ApiResult.ParamIsNull("请选择备用人员");
                }
            }

            if (demodel.WelcomeEnable == 1) {
                if (demodel.WelcomeList == null || !demodel.WelcomeList.Any()) {
                    return ApiResult.ParamIsNull("请传递通用欢迎语");
                }
            }
            if (demodel.WelcomeWeekEnable == 1)
            {
                if (demodel.WelcomeWeekList == null || !demodel.WelcomeWeekList.Any())
                {
                    return ApiResult.ParamIsNull("请传递周期欢迎语");
                }
            }
            if (demodel.WelcomeSpecialEnable == 1)
            {
                if (demodel.WelcomeSpecialList == null || !demodel.WelcomeSpecialList.Any())
                {
                    return ApiResult.ParamIsNull("请传递特殊日期欢迎语");
                }
            }

            demodel.Group_Id = userInfo.Group_Id;
            demodel.Status = 0;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            string msg = weChatModule.SetWeChatChannelInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 修改渠道分组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateWeChatChannelGroup() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int ChannelId = parms.GetInt("ChannelId", 0);
            int GroupId = parms.GetInt("GroupId", 0);
            if (ChannelId <= 0 || GroupId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = weChatModule.UpdateWeChatChannelGroup(ChannelId, GroupId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取渠道码添加的客户分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelCoustomerPageList() {
            var userInfo = base.UserInfo;
            ResultPageModel pageModel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_ChannelRecord_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_ChannelRecord_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            demodel.Type = 1;

            var list = weChatModule.GetWeChatChannelCoustomerPageList(pageModel.PageIndex, pageModel.PageSize, out long count, demodel);
            pageModel.Count = Convert.ToInt32(count);
            int num = 1;
            pageModel.PageData = list.Select(x => new
            {
                Id = num++,
                x.EmpId,
                x.EmpName,
                x.DeptName,
                x.WorkEmpId,
                x.ExternalUserId,
                x.CustomerName,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pageModel);
        }
        #endregion

        #region 渠道码统计

        /// <summary>
        /// 获取渠道码今日统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelStatisticsForDay()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int ChannelId = parms.GetInt("ChannelId", 0);
            if (ChannelId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var robj = weChatModule.GetWeChatChannelStatisticsForDay(ChannelId, userInfo);
            return ApiResult.Success("", robj);
        }

        /// <summary>
        /// 渠道码曲线图统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelStatistics()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int ChannelId = parms.GetInt("ChannelId", 0);
            int Type = parms.GetInt("Type", 0);//类型  1按日  2按周  3按月  (周：最近一周   月：最近一年)
            string StartTime = parms.GetStringValue("StartTime");
            string EndTime = parms.GetStringValue("EndTime");
            if (ChannelId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            if (Type == 1) {
                if (string.IsNullOrEmpty(StartTime)) {
                    return ApiResult.ParamIsNull("请传递开始时间");
                }
                if (string.IsNullOrEmpty(EndTime)) {
                    return ApiResult.ParamIsNull("请传递结束时间");
                }
            }

            var robj = weChatModule.GetWeChatChannelStatistics(ChannelId, Type, StartTime, EndTime, userInfo);
            return ApiResult.Success("", robj);
        }

        /// <summary>
        /// 获取统计详细数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeChatChannelStatisticsPageList() {
            var userInfo = base.UserInfo;
            ResultPageModel pageModel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int ChannelId = parms.GetInt("ChannelId", 0);
            int Type = parms.GetInt("Type", 0);//类型  1按日  2按周  3按月  (周：最近一周   月：最近一年)
            string StartTime = parms.GetStringValue("StartTime");
            string EndTime = parms.GetStringValue("EndTime");
            if (ChannelId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            if (Type == 1)
            {
                if (string.IsNullOrEmpty(StartTime))
                {
                    return ApiResult.ParamIsNull("请传递开始时间");
                }
                if (string.IsNullOrEmpty(EndTime))
                {
                    return ApiResult.ParamIsNull("请传递结束时间");
                }
            }

            var list = weChatModule.GetWeChatChannelStatisticsPageList(pageModel.PageIndex, pageModel.PageSize, out long count, ChannelId, Type, StartTime, EndTime, userInfo);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.DateStr,
                x.AddNum,
                x.DelNum,
                x.BlacklistNum,
                NetNum = x.AddNum - x.DelNum - x.BlacklistNum
            });
            return ApiResult.Success("", pageModel);
        }

        #endregion

        #region 企业微信客户端API

        /// <summary>
        /// 获取企业微信TOKEN
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetWorkToken()
        {
            var referer = Request.Headers["Origin"].ToString().Replace("http://", "");
            if (!string.IsNullOrEmpty(referer))
            {
                var group = groupModule.GetGroupEntityModule(referer);
                if (group.GId != 0)
                {
                    var config = Cache.WeChat.WeChatReidsCache.GetWorkChatConfig(group.GId);
                    var query = QYWeiXinHelper.GetToken(config?.WX_CorpId ?? "", config?.Employee_Secret ?? "", false);
                    if (!string.IsNullOrEmpty(query))
                    {
                        return ApiResult.Success(data: query);
                    }
                    else
                    {
                        return ApiResult.Failed(message: "解析用户信息失败");
                    }

                }
                else
                {
                    return ApiResult.Failed(message: "未知的集团信息");
                }

            }
            else
            {
                return ApiResult.Failed(message: "未找到域名来源");
            }
        }

        /// 获取登录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetLoginUserInfo()
        {
            var mark = JObject.FromObject(RequestParm.Msg).GetStringValue("mark");
            mark += "_Finish";
            if (UserReidsCache.Exists(mark))
            {
                var cacheObj = UserReidsCache.Get(mark);
                var cacheContent = JObject.FromObject(cacheObj);
                return ApiResult.Success(data: cacheContent["user"].ToString());
            }
            else
            {
                return ApiResult.Success(data: "");
            }
        }

        /// <summary>
        /// 获取用户Code
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult SetUserCodeCallBack()
        {
            var referer = Request.Headers["Origin"].ToString().Replace("http://", "");
            if (!string.IsNullOrEmpty(referer))
            {
                var group = groupModule.GetGroupEntityModule(referer);
                if (group.GId != 0)
                {
                    var parm = JObject.FromObject(RequestParm.Msg);
                    var appcode = parm.GetStringValue("appcode");
                    var code = parm.GetStringValue("code");

                    var config = Cache.WeChat.WeChatReidsCache.GetAppConfig(group.GId, appcode);
                    var token = QYWeiXinHelper.GetToken(config?.CropId ?? "", config?.Secret ?? "", false);
                    var userInfo = new QYWeiXinHelper().GetLoginWorkUserInfo(group.GId, code, appcode, token);
                    if (userInfo.status)
                    {
                        return ApiResult.Success(data: userInfo.result);
                    }
                    else
                    {
                        return ApiResult.Failed(message: "解析用户信息失败");
                    }
                }
                else
                {
                    return ApiResult.Failed(message: "未知的集团信息");
                }

            }
            else
            {
                return ApiResult.Failed(message: "未找到域名来源");
            }
        }

        /// 发起登录请求
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult SetUserAutoLogin()
        {
            var referer = Request.Headers["Origin"].ToString().Replace("http://", "");
            if (!string.IsNullOrEmpty(referer))
            {
                var group = groupModule.GetGroupEntityModule(referer);
                if (group.GId != 0)
                {
                    var query = JObject.Parse(RequestParm.Msg.ToString());
                    var mark = query.GetStringValue("mark");

                    var config = Cache.WeChat.WeChatReidsCache.GetAppConfig(group.GId, mark);
                    var token = QYWeiXinHelper.GetToken(config?.CropId ?? "", config?.Secret ?? "", false);
                    var path = new QYWeiXinHelper().GetUserAuthorizationCodePath(mark, config?.CropId ?? "", config?.AppId ?? "", token);
                    if (!string.IsNullOrEmpty(path))
                    {
                        HttpHelper.HttpGet(path);
                        return ApiResult.Success(data: path);
                    }
                    else
                    {
                        return ApiResult.Failed(message: "获取登录信息失败");
                    }

                }
                else
                {
                    return ApiResult.Failed(message: "未知的集团信息");
                }

            }
            else
            {
                return ApiResult.Failed(message: "未找到域名来源");
            }
        }
        #endregion
    }
}
