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.Entity.WeChat;
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 QYCustomerController : BaseController
    {
        /// <summary>
        /// 企业微信客户处理对象
        /// </summary>
        private readonly QYCustomerModule customerModule = new QYCustomerModule();


        #region 客户字段

        /// <summary>
        /// 获取客户字段列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerFiledList() {
            var userInfo = base.UserInfo;
            var req = base.RequestParm;
            RB_WeChat_CustomerField_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerField_ViewModel>(req.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = customerModule.GetCustomerFieldList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Type,
                TypeName = x.Type.ToName(),
                x.Name,
                x.Required,
                x.DeptId,
                x.DeptName,
                x.WordNum,
                x.InputType,
                x.Options,
                x.OptionsList,
                x.Digits,
                x.Sort,
                x.Enable,
                x.UpdateBy,
                x.IsSystem,
                x.IsDefault,
                x.IsLock,
                UpdateByName = Cache.User.UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName??"",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"),
            }));
        }

        /// <summary>
        /// 保存客户字段
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerFiledInfo() {
            var userInfo = base.UserInfo;
            var req = base.RequestParm;
            RB_WeChat_CustomerField_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerField_ViewModel>(req.Msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name)) {
                return ApiResult.ParamIsNull("请传递字段名称");
            }

            if (demodel.OptionsList != null && demodel.OptionsList.Any()) {
                demodel.Options = JsonHelper.Serialize(demodel.OptionsList);
            }
            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;
            demodel.IsSystem = 0;
            demodel.IsDefault = 0;
            demodel.IsLock = 0;

            string msg = customerModule.SetCustomerFiledInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 设置客户字段状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerFiledState() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int Type = parms.GetInt("Type", 1);//类型  1启用  2是否必填  3删除   4排序
            int FiledId = parms.GetInt("FiledId", 0);//字段id
            int SortFiledId = parms.GetInt("SortFiledId", 0);
            if (FiledId <= 0) {
                return ApiResult.ParamIsNull("请传递字段id");
            }

            string msg = customerModule.SetCustomerFiledState(Type, FiledId, SortFiledId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取客户子段类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerFieldTypeEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(CustomerFieldTypeEnum));
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 获取客户子段输入类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerFieldInputTypeEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(CustomerFieldInputTypeEnum));
            return ApiResult.Success("", list);
        }

        #endregion

        #region 客户阶段

        /// <summary>
        /// 获取客户阶段列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerStageList() {
            var userInfo = base.UserInfo;
            RB_WeChat_CustomerStage_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerStage_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = customerModule.GetCustomerStageList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Type,
                x.Name,
                x.Sort,
                x.OptionsList,
                x.IsDefault
            }));
        }

        /// <summary>
        /// 新增修改客户阶段
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerStageInfo() {
            var userInfo = base.UserInfo;
            List<RB_WeChat_CustomerStage_ViewModel> delist = JsonHelper.DeserializeObject<List<RB_WeChat_CustomerStage_ViewModel>>(base.RequestParm.Msg.ToString());
            if (delist == null || !delist.Any()) {
                return ApiResult.ParamIsNull("数据为空");
            }
            foreach (var item in delist) {
                if (string.IsNullOrEmpty(item.Name)) {
                    return ApiResult.ParamIsNull("请输入阶段名称");
                }
                item.Options = "";
                if (item.Type == 2) {
                    if (item.OptionsList == null || !item.OptionsList.Any()) {
                        return ApiResult.ParamIsNull("原因选项不能为空");
                    }
                    item.Options = JsonHelper.Serialize(item.OptionsList);
                }
            }

            string msg = customerModule.SetCustomerStageInfo(delist, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 验证该阶段是否可以删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult ValidataCustomerStageDel() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int StageId = parms.GetInt("StageId", 0);
            if (StageId <= 0) {
                return ApiResult.ParamIsNull();
            }

            bool flag = customerModule.ValidataCustomerStageDel(StageId, userInfo.Group_Id);
            return ApiResult.Success("", new
            {
                UseState = flag
            });
        }

        /// <summary>
        /// 验证该阶段原因选项是否可以删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult ValidataCustomerCauseDel()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int CauseId = parms.GetInt("CauseId", 0);
            int Type = parms.GetInt("Type", 1);//类型  1输单   2无效
            if (CauseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = customerModule.ValidataCustomerCauseDel(CauseId, Type, userInfo.Group_Id);
            return ApiResult.Success("", new
            {
                UseState = flag
            });
        }

        #region 客户阶段流程

        /// <summary>
        /// 获取客户阶段流程
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerStageFlowList() {
            var userInfo = base.UserInfo;
            RB_WeChat_CustomerStageFlow_ViewModel demdoel = JsonHelper.DeserializeObject<RB_WeChat_CustomerStageFlow_ViewModel>(base.RequestParm.Msg.ToString());
            demdoel.Group_Id = userInfo.Group_Id;

            var list = customerModule.GetCustomerStageFlowList(demdoel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.FlowName,
                x.DeptIds,
                x.EmpIds,
                x.DeptEmpList,
                x.UseStage,
                x.StageList,
                x.LoseCause,
                x.InvalidCause,
                x.IsDefault,
                x.Enable,
                UpdateByName = Cache.User.UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"),
            }));
        }

        /// <summary>
        /// 获取客户阶段流程详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerStageFlowInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int FlowId = parms.GetInt("FlowId", 0);//流程id
            if (FlowId <= 0) {
                return ApiResult.ParamIsNull();
            }

            var model = customerModule.GetCustomerStageFlowInfo(FlowId);
            if (model == null || model.Group_Id != userInfo.Group_Id) { return ApiResult.Failed("流程不存在"); }
            return ApiResult.Success("", new
            {
                model.Id,
                model.FlowName,
                model.DeptIds,
                model.EmpIds,
                model.DeptEmpList,
                model.UseStage,
                model.LoseCause,
                model.InvalidCause,
                model.IsDefault,
                model.Enable,
            });
        }

        /// <summary>
        /// 保存客户阶段流程
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerStageFlowInfo() {
            var userInfo = base.UserInfo;
            RB_WeChat_CustomerStageFlow_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerStageFlow_ViewModel>(base.RequestParm.Msg.ToString());
            if (string.IsNullOrEmpty(demodel.FlowName)) {
                return ApiResult.ParamIsNull("请输入流程名称");
            }
            if (demodel.DeptEmpList == null || !demodel.DeptEmpList.Any()) {
                return ApiResult.ParamIsNull("请选择适用的部门/成员");
            }
            demodel.DeptIds = "-1";
            demodel.EmpIds = "-1";
            
            if (demodel.DeptEmpList.Where(x => x.Type == 1).Any()) {
                demodel.DeptIds = string.Join(",", demodel.DeptEmpList.Where(x => x.Type == 1).Select(x => x.Id));
            }
            if (demodel.DeptEmpList.Where(x => x.Type == 2).Any()) {
                demodel.EmpIds = string.Join(",", demodel.DeptEmpList.Where(x => x.Type == 2).Select(x => x.Id));
            }
            
            if (string.IsNullOrEmpty(demodel.UseStage)) {
                return ApiResult.ParamIsNull("请选择适用阶段");
            }

            demodel.LoseCause ??= "";
            demodel.InvalidCause ??= "";
            demodel.IsDefault = 2;
            demodel.Enable = 2;
            demodel.Status = 0;
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;

            string msg = customerModule.SetCustomerStageFlowInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 设置客户阶段流程状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerStageFlowState() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int FlowId = parms.GetInt("FlowId", 0);//流程id
            int Type = parms.GetInt("Type", 1);//类型  1启用禁用   2删除
            if (FlowId <= 0) {
                return ApiResult.ParamIsNull("请传递流程ID");
            }

            string msg = customerModule.SetCustomerStageFlowState(FlowId, Type, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #endregion

        #region 客户操作

        /// <summary>
        /// 获取客户操作配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerConfig() {
            var userInfo = base.UserInfo;

            var model = customerModule.GetCustomerConfig(userInfo.Group_Id);
            return ApiResult.Success("", new
            {
                model?.Id,
                model?.IsPublicAudit,
                model?.PublicGetDept,
                model?.AbandonType,
                model?.LableIds,
                model?.StageIds,
                model?.AbandonDept,
                model?.AbandonAudit,
                model?.AbandonReason,
                model?.ApplyForTeamDept,
                model?.AddTeamDept,
                model?.TransferCustomerDept,
                PublicGetDeptList = model?.PublicGetDeptList?.Select(x=>new { 
                    x.DeptId,
                    x.DeptName
                }),
                AbandonDeptList = model?.AbandonDeptList?.Select(x => new {
                    x.DeptId,
                    x.DeptName
                }),
                ApplyForTeamDeptList = model?.ApplyForTeamDeptList?.Select(x => new {
                    x.DeptId,
                    x.DeptName
                }),
                AddTeamDeptList = model?.AddTeamDeptList?.Select(x => new {
                    x.DeptId,
                    x.DeptName
                }),
                TransferCustomerDeptList = model?.TransferCustomerDeptList?.Select(x => new {
                    x.DeptId,
                    x.DeptName
                }),
                model?.AbandonReasonList,
                model?.LableList,
                model?.StageList,
                model?.AbandonSelectType,
                model?.AbandonKHSelect,
                PublicGetEmpList = model?.PublicGetEmpList?.Select(x => new
                {
                    x.Id,
                    x.EmployeeName
                }),
                AbandonEmpList = model?.AbandonEmpList?.Select(x => new
                {
                    x.Id,
                    x.EmployeeName
                }),
                ApplyForTeamEmpList = model?.ApplyForTeamEmpList?.Select(x => new
                {
                    x.Id,
                    x.EmployeeName
                }),
                AddTeamEmpList = model?.AddTeamEmpList?.Select(x => new
                {
                    x.Id,
                    x.EmployeeName
                }),
                TransferCustomerEmpList = model?.TransferCustomerEmpList?.Select(x => new
                {
                    x.Id,
                    x.EmployeeName
                })
            });
        }

        /// <summary>
        /// 保存客户操作配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerConfig() {
            var userInfo = base.UserInfo;
            RB_WeChat_CustomerConfig_ViewModel demdoel = JsonHelper.DeserializeObject<RB_WeChat_CustomerConfig_ViewModel>(base.RequestParm.Msg.ToString());

            if (demdoel.AbandonType == 2) {
                if (demdoel.AbandonKHSelect == null || !demdoel.AbandonKHSelect.Any())
                {
                    return ApiResult.ParamIsNull("请选择部分客户筛选条件");
                }
                demdoel.AbandonSelectValue = JsonHelper.Serialize(demdoel.AbandonKHSelect);
            }
            if (demdoel.AbandonReasonList != null && demdoel.AbandonReasonList.Any())
            {
                demdoel.AbandonReason = JsonHelper.Serialize(demdoel.AbandonReasonList);
            }
            demdoel.Group_Id = userInfo.Group_Id;
            demdoel.Status = 0;
            demdoel.CreateBy = userInfo.Id;
            demdoel.CreateTime = DateTime.Now;
            demdoel.UpdateBy = userInfo.Id;
            demdoel.UpdateTime = DateTime.Now;
            string msg = customerModule.SetCustomerConfig(demdoel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取放弃进入公海原因
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerConfigAbandonReason() {
            var userInfo = base.UserInfo;

            var list = customerModule.GetCustomerConfigAbandonReason(userInfo.Group_Id);
            return ApiResult.Success("", list);
        }

        #endregion

        #region 客户管理

        /// <summary>
        /// 获取客户信息分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerInfoPageList() {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_CustomerInfo_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerInfo_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CustomerState = 1;//客户列表

            var list = customerModule.GetCustomerInfoPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = Convert.ToInt32(count);
            pmodel.PageData = list.Select(x => new
            {
                x.Id,
                x.EmpId,
                x.EmpName,
                x.WorkEmpId,
                x.WorkEmpName,
                x.ExternalUserId,
                x.CustomerName,
                x.WeChatName,
                x.WeChatPhoto,
                x.CorpName,
                x.CorpFullName,
                x.CustomerType,
                x.StageId,
                x.StageName,
                x.LableIds,
                LableList = x.LableList?.Select(z => new
                {
                    z.Id,
                    z.Name
                }),
                x.PersonLable,
                x.Source,
                x.CustomContent,
                x.CustomFiledList,
                x.FriendState,
                LastFollowUpTime = x.LastFollowUpTime.HasValue ? x.LastFollowUpTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                x.CheckInNum,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                FriendTime = x.FriendTime.HasValue ? x.FriendTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int CustomerId = parms.GetInt("CustomerId", 0);//客户Id
            if (CustomerId <= 0) { return ApiResult.ParamIsNull(); }

            var model = customerModule.GetCustomerInfo(CustomerId, userInfo);
            if (model == null || model.Group_Id != userInfo.Group_Id) { return ApiResult.Failed("客户不存在，请核实后再试"); }
            return ApiResult.Success("", new
            {
                model.Id,
                model.EmpId,
                model.EmpName,
                model.WorkEmpId,
                model.WorkEmpName,
                model.ExternalUserId,
                model.CustomerName,
                model.WeChatName,
                model.WeChatPhoto,
                model.CorpName,
                model.CorpFullName,
                model.CustomerType,
                model.StageId,
                model.StageName,
                model.LableIds,
                LableList = model.LableList?.Select(z => new
                {
                    z.Id,
                    z.Name
                }),
                model.PersonLable,
                model.Source,
                model.CustomContent,
                FiledDetailList = model.FiledDetailList.OrderBy(x=>x.Sort).Select(x=>new {
                    x.Id,
                    x.Type,
                    TypeName = x.Type.ToName(),
                    x.Name,
                    x.Required,
                    x.WordNum,
                    x.InputType,
                    x.Options,
                    x.OptionsList,
                    x.Digits,
                    x.Sort,
                    x.Value
                }),
                model.FriendState,
                LastFollowUpTime = model.LastFollowUpTime.HasValue ? model.LastFollowUpTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                model.CheckInNum,
                CreateTime = model.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                FriendTime = model.FriendTime.HasValue ? model.FriendTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
            });
        }

        /// <summary>
        /// 修改客户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int Type = parms.GetInt("Type", 0);//类型  1客户阶段  2自定义字段  3客户企业标签
            int CustomId = parms.GetInt("CustomId", 0);//自定义字段ID
            int CustomerId = parms.GetInt("CustomerId", 0);//客户Id
            string Value = parms.GetStringValue("Value");//值  多选的话  英文逗号分隔
            if (CustomerId <= 0) {
                return ApiResult.ParamIsNull("请传递客户ID");
            }
            if (Type == 2 && CustomId <= 0) {
                return ApiResult.ParamIsNull("请传递自定义字段ID");
            }

            string msg = customerModule.SetCustomerInfo(CustomerId, Type, CustomId, Value, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取客户旅程分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerTripPageList() {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_CustomerTrip_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerTrip_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = customerModule.GetCustomerTripPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = Convert.ToInt32(count);
            pmodel.PageData = list.Select(x => new
            {
                x.Id,
                x.Type,
                TypeName = x.Type.ToName(),
                x.CustomerId,
                x.Description,
                x.Remark,
                x.ImageList,
                x.FileList,
                x.UpdateBy,
                x.UpdateByName,
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 企业微信旅程类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerTripTypeEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(CustomerTripTypeEnum));
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 新增客户跟进记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerTripFollowUpInfo() {
            var userInfo = base.UserInfo;
            RB_WeChat_CustomerTrip_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerTrip_ViewModel>(base.RequestParm.Msg.ToString());
            if (demodel.CustomerId <= 0) {
                return ApiResult.ParamIsNull("请传递客户id");
            }
            if (string.IsNullOrEmpty(demodel.Remark)) {
                return ApiResult.ParamIsNull("请输入跟进记录");
            }
            if (demodel.ImageList != null && demodel.ImageList.Any()) {
                demodel.Images = JsonHelper.Serialize(demodel.ImageList);
            }
            if (demodel.FileList != null && demodel.FileList.Any()) {
                demodel.Files = JsonHelper.Serialize(demodel.FileList);
            }
            demodel.Type = CustomerTripTypeEnum.FollowUp;
            demodel.Description = "添加了跟进记录:";
            demodel.Status = 0;
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;

            string msg = customerModule.SetCustomerTripFollowUpInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 删除客户旅程
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelCustomerTripInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int TripId = parms.GetInt("TripId", 0);//
            if (TripId <= 0) {
                return ApiResult.ParamIsNull();
            }

            string msg = customerModule.DelCustomerTripInfo(TripId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取客户添加方式枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerAddWayEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(CustomerAddWayEnum));
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 初始化客户信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult InitializeCustomerInfoList() {
            var userInfo = base.UserInfo;

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


        /// <summary>
        /// 批量设置客户标签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerLabelBatch()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            string CustomerIds = parms.GetStringValue("CustomerIds");//客户ids 英文逗号分隔
            string LableIds = parms.GetStringValue("LableIds");//标签ids

            if (string.IsNullOrEmpty(CustomerIds))
            {
                return ApiResult.ParamIsNull("请传递客户ID");
            }
            if (string.IsNullOrEmpty(LableIds))
            {
                return ApiResult.ParamIsNull("请传递标签ID");
            }

            string msg = customerModule.SetCustomerLabelBatch(CustomerIds, LableIds, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 单客户标签设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerLabelSingle()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int CustomerId = parms.GetInt("CustomerId", 0);//客户id
            string LableIds = parms.GetStringValue("LableIds");//标签ids

            if (CustomerId <= 0)
            {
                return ApiResult.ParamIsNull("请传递客户ID");
            }
            if (string.IsNullOrEmpty(LableIds))
            {
                return ApiResult.ParamIsNull("请传递标签ID");
            }

            string msg = customerModule.SetCustomerLabelSingle(CustomerId, LableIds, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 客户转移（在职，离职
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerTransfer() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            string CustomerIds = parms.GetStringValue("CustomerIds");//客户ids
            int EmpId = parms.GetInt("EmpId", 0);//转入销售的id

            if (string.IsNullOrEmpty(CustomerIds))
            {
                return ApiResult.ParamIsNull("请传递客户ID");
            }
            if (EmpId <= 0) {
                return ApiResult.ParamIsNull("请现在转移销售");
            }

            string msg = customerModule.SetCustomerTransfer(CustomerIds, EmpId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 客户放弃（放弃至公海）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerAbandon() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            string CustomerIds = parms.GetStringValue("CustomerIds");//客户ids
            string Reason = parms.GetStringValue("Reason");//放弃原因

            if (string.IsNullOrEmpty(CustomerIds))
            {
                return ApiResult.ParamIsNull("请传递客户ID");
            }
            if (string.IsNullOrEmpty(Reason))
            {
                return ApiResult.ParamIsNull("请选择放弃原因");
            }

            string msg = customerModule.SetCustomerAbandon(CustomerIds, Reason, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

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

            if (string.IsNullOrEmpty(CustomerIds))
            {
                return ApiResult.ParamIsNull("请传递客户ID");
            }

            string msg = customerModule.DelCustomerInfo(CustomerIds, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        //修改客户企业标签(批量处理)
        //批量转移 导出

        #endregion

        #region 客户线索

        #region 线索分配规则
        /// <summary>
        /// 获取线索规则配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerClueRuleConfig() {
            var userInfo = base.UserInfo;

            var model = customerModule.GetCustomerClueRule(userInfo.Group_Id);
            return ApiResult.Success("", new
            {
                model?.Id,
                model?.ClueType,
                model?.ClueAllotWay
            });
        }

        /// <summary>
        /// 保存线索规则配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerClueRuleConfig() {
            var userInfo = base.UserInfo;

            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int ClueType = parms.GetInt("ClueType", 1);//线索类型   1手动分配   2自动分配
            int ClueAllotWay = parms.GetInt("ClueAllotWay", 1);//线索手动分配方式   1依次轮流   2随机分配
            if (ClueType <= 0) {
                return ApiResult.ParamIsNull();
            }
            if (ClueAllotWay <= 0) {
                return ApiResult.ParamIsNull();
            }

            string msg = customerModule.SetCustomerClueRuleConfig(ClueType, ClueAllotWay, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取客户线索规则列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerClueRuleList() {
            var userInfo = base.UserInfo;

            var list = customerModule.GetCustomerClueRuleList(userInfo.Group_Id);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.RuleSelectType,
                x.IsDefault,
                DeptList = x.DeptList.Select(z => new
                {
                    z.DeptId,
                    z.DeptName
                }),
                EmpList = x.EmpList.Select(z => new
                {
                    z.Id,
                    z.EmployeeName
                }),
                x.RuleAllotWay,
                x.Sort,
                x.ConditionList,
                x.ConditionStrList
            }));
        }

        /// <summary>
        /// 获取客户线索规则信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerClueRuleInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int RuleId = parms.GetInt("RuleId", 0);
            if (RuleId <= 0) {
                return ApiResult.ParamIsNull("请传递规则ID");
            }

            var model = customerModule.GetCustomerClueRuleInfo(RuleId, userInfo.Group_Id);
            return ApiResult.Success("", new
            {
                model.Id,
                model.RuleSelectType,
                model.IsDefault,
                DeptList = model.DeptList.Select(z => new
                {
                    z.DeptId,
                    z.DeptName
                }),
                EmpList = model.EmpList.Select(z => new
                {
                    z.Id,
                    z.EmployeeName
                }),
                model.RuleAllotWay,
                model.Sort,
                model.ConditionList,
                model.ConditionStrList
            });
        }

        /// <summary>
        /// 新增修改线索规则
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerClueRuleInfo() {
            var userInfo = base.UserInfo;
            RB_WeChat_CustomerClueRule_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerClueRule_ViewModel>(base.RequestParm.Msg.ToString());
            if (demodel.ConditionList == null || !demodel.ConditionList.Any()) {
                return ApiResult.ParamIsNull("请选择条件");
            }
            if ((demodel.DeptList == null || !demodel.DeptList.Any()) && (demodel.EmpList == null || !demodel.EmpList.Any())) {
                return ApiResult.ParamIsNull("请选择适用部门/成员");
            }
            demodel.RuleSelectValue = JsonHelper.Serialize(demodel.ConditionList);
            demodel.DeptIds = "-1";
            demodel.EmpIds = "-1";
            if (demodel.DeptList != null || demodel.DeptList.Any())
            {
                demodel.DeptIds = string.Join(",", demodel.DeptList.Select(x => x.DeptId));
            }
            if (demodel.EmpList != null || demodel.EmpList.Any())
            {
                demodel.EmpIds = string.Join(",", demodel.EmpList.Select(x => x.Id));
            }

            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;
            demodel.IsDefault = 2;

            string msg = customerModule.SetCustomerClueRuleInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 设置线索规则状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerClueRuleState() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int RuleId = parms.GetInt("RuleId", 0);//规则ID
            int Type = parms.GetInt("Type", 1);//类型  1移动规则  2删除
            int TargetId = parms.GetInt("TargetId", 0);//移动至目标的后面   0 表示移动至第一个
            if (RuleId <= 0) {
                return ApiResult.ParamIsNull("请传递规则Id");
            }

            if (Type == 1 && TargetId <0) {
                return ApiResult.ParamIsNull("请传递目标ID");
            }

            string msg = customerModule.SetCustomerClueRuleState(RuleId, Type, TargetId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }
        #endregion

        #region 客户线索
        /// <summary>
        /// 获取客户线索分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerCluePageList() {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_CustomerInfo_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerInfo_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CustomerState = 2;

            var list = customerModule.GetCustomerInfoPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = Convert.ToInt32(count);
            pmodel.PageData = list.Select(x => new
            {
                x.Id,
                x.EmpId,
                x.EmpName,
                x.WorkEmpId,
                x.WorkEmpName,
                x.ExternalUserId,
                x.CustomerName,
                x.WeChatName,
                x.WeChatPhoto,
                x.CorpName,
                x.CorpFullName,
                x.CustomerType,
                x.StageId,
                x.StageName,
                x.LableIds,
                LableList = x.LableList?.Select(z => new
                {
                    z.Id,
                    z.Name
                }),
                x.Source,
                x.CustomContent,
                x.CustomFiledList,
                x.FriendState,
                LastFollowUpTime = x.LastFollowUpTime.HasValue ? x.LastFollowUpTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 新增线索
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerClueInfo() {
            var userInfo = base.UserInfo;
            RB_WeChat_CustomerInfo_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerInfo_ViewModel>(base.RequestParm.Msg.ToString());
            if (demodel.CustomFiledList == null || !demodel.CustomFiledList.Any()) {
                return ApiResult.ParamIsNull("请传递字段内容");
            }

            #region 验证自定义字段
            if (demodel.CustomFiledList.Where(x => x.Id <= 0).Any()) {
                return ApiResult.ParamIsNull("请传递客户字段ID");
            }
            string xName = demodel.CustomFiledList.Where(x => x.Name == "姓名").FirstOrDefault()?.Value ?? "";
            string mobile = demodel.CustomFiledList.Where(x => x.Name == "电话").FirstOrDefault()?.Value ?? "";
            if (string.IsNullOrEmpty(xName)) {
                return ApiResult.ParamIsNull("请输入客人姓名");
            }
            if (string.IsNullOrEmpty(mobile)) {
                return ApiResult.ParamIsNull("请输入客人电话");
            }

            Dictionary<string, string> CustomContentKV = new Dictionary<string, string>();
            foreach (var qitem in demodel.CustomFiledList)
            {
                CustomContentKV.Add("z" + qitem.Id, qitem.Value);
            }
            demodel.CustomContent = JsonHelper.Serialize(CustomContentKV);
            demodel.CustomerMobile = mobile;
            demodel.CustomerName = xName;
            #endregion

            #region 基本信息
            demodel.Status = 0;
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            demodel.AddWay = CustomerAddWayEnum.Person;
            demodel.CustomerState = 2;//线索
            demodel.ClueState = 1;//未处理
            demodel.AllotState = 0;//分配状态
            
            demodel.EmpId = 0;
            demodel.WorkEmpId = "";
            demodel.WorkEmpName = "";
            demodel.ExternalUserId = "";
            demodel.CustomerType = 1;//微信用户
            demodel.StageId = 0;//阶段 根据领用用户来判断
            demodel.FriendState = 2;
            #endregion

            string msg = customerModule.SetCustomerClueInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 批量设置线索状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerClueState() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            string CustomerIds = parms.GetStringValue("CustomerIds");//客户ids
            int Type = parms.GetInt("Type", 1);//类型  1有效线索  2无效线索  3待回访  4直接分配（员工ID） 5重置无效线索
            string EmpIds = parms.GetStringValue("EmpIds");//分配员工
            if (string.IsNullOrEmpty(CustomerIds)) {
                return ApiResult.ParamIsNull("请传递客户ids");
            }
            if (Type == 4 && string.IsNullOrEmpty(EmpIds)) {
                return ApiResult.ParamIsNull("请传递分配员工");
            }

            string msg = customerModule.SetCustomerClueState(CustomerIds, Type, EmpIds, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.ParamIsNull(msg);
            }
        }

        /// <summary>
        /// 获取客户线索已转客户分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerClueToPassPageList()
        {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_CustomerInfo_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerInfo_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            demodel.ClueState = 4;//已转客户

            var list = customerModule.GetCustomerInfoPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = Convert.ToInt32(count);
            pmodel.PageData = list.Select(x => new
            {
                x.Id,
                x.EmpId,
                x.EmpName,
                x.WorkEmpId,
                x.WorkEmpName,
                x.ExternalUserId,
                x.CustomerName,
                x.WeChatName,
                x.WeChatPhoto,
                x.CorpName,
                x.CorpFullName,
                x.CustomerType,
                x.StageId,
                x.StageName,
                x.LableIds,
                LableList = x.LableList?.Select(z => new
                {
                    z.Id,
                    z.Name
                }),
                x.Source,
                x.CustomContent,
                x.CustomFiledList,
                x.FriendState,
                TurnCustomerTime = x.TurnCustomerTime.HasValue ? x.TurnCustomerTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取客户线索导入文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerClueExportFile() {
            var userInfo = base.UserInfo;

            string FliePath = customerModule.GetCustomerClueExportFile(userInfo);
            return ApiResult.Success("", new { Path = FliePath });
        }
        #endregion

        #endregion

        #region 待分配客户

        /// <summary>
        /// 获取客户待分配分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerClueWaitDistributionPageList()
        {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_CustomerInfo_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerInfo_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CustomerState = 2;//还是线索
            demodel.ClueState = 4;//已转客户
            demodel.AllotState = 1;//待分配

            var list = customerModule.GetCustomerInfoPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = Convert.ToInt32(count);
            pmodel.PageData = list.Select(x => new
            {
                x.Id,
                x.EmpId,
                x.EmpName,
                x.WorkEmpId,
                x.WorkEmpName,
                x.ExternalUserId,
                x.CustomerName,
                x.WeChatName,
                x.WeChatPhoto,
                x.CorpName,
                x.CorpFullName,
                x.CustomerType,
                x.StageId,
                x.StageName,
                x.LableIds,
                LableList = x.LableList?.Select(z => new
                {
                    z.Id,
                    z.Name
                }),
                x.Source,
                x.CustomContent,
                x.CustomFiledList,
                x.FriendState,
                LastFollowUpTime = x.LastFollowUpTime.HasValue ? x.LastFollowUpTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pmodel);
        }


        /// <summary>
        /// 获取客户已分配分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerClueAssignedPageList()
        {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_CustomerInfo_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerInfo_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            demodel.ClueState = 4;//已转客户
            demodel.AllotState = 2;//已分配

            var list = customerModule.GetCustomerInfoPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = Convert.ToInt32(count);
            pmodel.PageData = list.Select(x => new
            {
                x.Id,
                x.EmpId,
                x.EmpName,
                x.WorkEmpId,
                x.WorkEmpName,
                x.ExternalUserId,
                x.CustomerName,
                x.WeChatName,
                x.WeChatPhoto,
                x.CorpName,
                x.CorpFullName,
                x.CustomerType,
                x.StageId,
                x.StageName,
                x.LableIds,
                LableList = x.LableList?.Select(z => new
                {
                    z.Id,
                    z.Name
                }),
                x.Source,
                x.CustomContent,
                x.CustomFiledList,
                x.FriendState,
                AllotCustomerTime = x.AllotCustomerTime.HasValue ? x.AllotCustomerTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pmodel);
        }

        #endregion

        #region 公海

        #region 客户库

        /// <summary>
        /// 获取客户库 查重规则
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerLibraryLookRepeat() {
            var userInfo = base.UserInfo;

            int lookRepeat = customerModule.GetCustomerLibraryLookRepeat(userInfo.Group_Id);
            return ApiResult.Success("", lookRepeat);
        }

        /// <summary>
        /// 设置客户库 查重规则
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerLibraryLookRepeat() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int LookRepeat = parms.GetInt("LookRepeat", 1);//查重规则
            if (LookRepeat <= 0) {
                return ApiResult.ParamIsNull();
            }

            string msg = customerModule.SetCustomerLibraryLookRepeat(userInfo.Group_Id, LookRepeat);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取客户库列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerLibraryList() {
            var userInfo = base.UserInfo;

            var list = customerModule.GetCustomerLibraryList(userInfo.Group_Id);
            return ApiResult.Success("", list.OrderBy(x => x.IsDefault).ThenByDescending(x => x.Id).Select(x => new
            {
                x.Id,
                x.Name,
                x.IsDefault,
                x.IsAllowRepeat,
                DeptList = x.DeptList.Select(z => new
                {
                    z.DeptId,
                    z.DeptName
                }),
                EmpList = x.EmpList.Select(z => new
                {
                    z.Id,
                    z.EmployeeName
                }),
                x.RecyclingType,
                x.ConditionList,
                x.NotRecycleTimeList,
                x.RemindDay,
                x.RemindType,
                x.LimitDay,
                LimitList = x.LimitList.Select(z => new
                {
                    z.IsDefault,
                    z.LimitNum,
                    z.LockNum,
                    DeptList = z.DeptList.Select(y => new
                    {
                        y.DeptId,
                        y.DeptName
                    }),
                    EmpList = z.EmpList.Select(y => new
                    {
                        y.Id,
                        y.EmployeeName
                    })
                }),
                x.PrivateLibraryType,
                x.PrivateLibraryTypeStr,
                UpdateByName = Cache.User.UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"),
            }));
        }

        /// <summary>
        /// 获取客户库详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerLibraryInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int LibraryId = parms.GetInt("LibraryId", 0);//客户库ID
            if (LibraryId <= 0) {
                return ApiResult.ParamIsNull();
            }

            var model = customerModule.GetCustomerLibraryInfo(LibraryId, userInfo.Group_Id);
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.IsDefault,
                model.IsAllowRepeat,
                DeptList = model.DeptList.Select(z => new
                {
                    z.DeptId,
                    z.DeptName
                }),
                EmpList = model.EmpList.Select(z => new
                {
                    z.Id,
                    z.EmployeeName
                }),
                model.RecyclingType,
                model.ConditionList,
                model.NotRecycleTimeList,
                model.RemindDay,
                model.RemindType,
                model.LimitDay,
                LimitList = model.LimitList.Select(z => new
                {
                    z.IsDefault,
                    z.LimitNum,
                    z.LockNum,
                    DeptList = z.DeptList.Select(y => new
                    {
                        y.DeptId,
                        y.DeptName
                    }),
                    EmpList = z.EmpList.Select(y => new
                    {
                        y.Id,
                        y.EmployeeName
                    })
                }),
                model.PrivateLibraryType
            });
        }

        /// <summary>
        /// 新增修改客户库信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerLibraryInfo() {
            var userInfo = base.UserInfo;
            RB_WeChat_CustomerLibrary_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerLibrary_ViewModel>(base.RequestParm.Msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name)) {
                return ApiResult.ParamIsNull("请输入客户库名称");
            }
            if (demodel.RecyclingType == 2) {
                if (demodel.ConditionList == null || !demodel.ConditionList.Any()) {
                    return ApiResult.ParamIsNull("请传递条件列表");
                }
                demodel.RecycleCondition = JsonHelper.Serialize(demodel.ConditionList);
            }
            if (demodel.IsDefault == 1)
            {
                demodel.DeptIds = "";
                demodel.EmpIds = "";
            }
            else {
                if ((demodel.DeptList == null || !demodel.DeptList.Any()) && (demodel.EmpList == null || !demodel.EmpList.Any())) {
                    return ApiResult.ParamIsNull("请选择部门/员工");
                }
                demodel.DeptIds = string.Join(",", demodel.DeptList.Select(x => x.DeptId));
                demodel.EmpIds = string.Join(",", demodel.EmpList.Select(x => x.Id));
            }

            demodel.PrivateLibraryLimit = "";
            if (demodel.LimitList != null && demodel.LimitList.Any()) {
                foreach (var item in demodel.LimitList) {
                    if (item.IsDefault == 1)
                    {
                        item.DeptIds = "";
                        item.EmpIds = "";
                    }
                    else {
                        if ((item.DeptList == null || !item.DeptList.Any()) && (item.EmpList == null || !item.EmpList.Any()))
                        {
                            return ApiResult.ParamIsNull("请选择部门/员工");
                        }
                        item.DeptIds = string.Join(",", item.DeptList.Select(x => x.DeptId));
                        item.EmpIds = string.Join(",", item.EmpList.Select(x => x.Id));
                    }
                }
                demodel.PrivateLibraryLimit = JsonHelper.Serialize(demodel.LimitList);
            }
            demodel.NotRecycleTime = "";
            if (demodel.NotRecycleTimeList != null && demodel.NotRecycleTimeList.Any()) {
                demodel.NotRecycleTime = JsonHelper.Serialize(demodel.NotRecycleTimeList);
            }

            demodel.Status = 0;
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;

            string msg = customerModule.SetCustomerLibraryInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        /// <summary>
        /// 获取公海客户分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerPublicPageList()
        {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_CustomerInfo_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerInfo_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CustomerState = 3;//公海客户            

            //这里有个放弃的原因   放弃时间   前负责人
            var list = customerModule.GetCustomerInfoPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = Convert.ToInt32(count);
            pmodel.PageData = list.Select(x => new
            {
                x.Id,
                x.OldEmpId,
                x.OldEmpName,
                x.ExternalUserId,
                x.CustomerName,
                x.WeChatName,
                x.WeChatPhoto,
                x.CorpName,
                x.CorpFullName,
                x.CustomerType,
                x.StageId,
                x.StageName,
                x.LableIds,
                LableList = x.LableList?.Select(z => new
                {
                    z.Id,
                    z.Name
                }),
                x.Source,
                x.CustomContent,
                x.CustomFiledList,
                x.FriendState,
                x.AbandonReason,
                AbandonTime = x.AbandonTime.HasValue ? x.AbandonTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                LastFollowUpTime = x.LastFollowUpTime.HasValue ? x.LastFollowUpTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pmodel);
        }

        #endregion

        #region 重复跟进

        /// <summary>
        /// 获取重复跟进客户分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerRepeatToFollowUpPageList() {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_WeChat_CustomerInfo_ViewModel demodel = JsonHelper.DeserializeObject<RB_WeChat_CustomerInfo_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;

            var list = customerModule.GetCustomerRepeatToFollowUpPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = Convert.ToInt32(count);
            pmodel.PageData = list.GroupBy(x => x.ExternalUserId).Select(x => new
            {
                x.Key,
                x.FirstOrDefault()?.WeChatName,
                x.FirstOrDefault()?.WeChatPhoto,
                List = x.Select(z => new
                {
                    z.Id,
                    z.EmpId,
                    z.EmpName,
                    z.WorkEmpId,
                    z.WorkEmpName,
                    z.ExternalUserId,
                    z.CustomerName,
                    z.WeChatName,
                    z.WeChatPhoto,
                    z.CorpName,
                    z.CorpFullName,
                    z.CustomerType,
                    z.StageId,
                    z.StageName,
                    z.LableIds,
                    LableList = z.LableList?.Select(y => new
                    {
                        y.Id,
                        y.Name
                    }),
                    z.PersonLable,
                    z.Source,
                    z.CustomContent,
                    z.CustomFiledList,
                    z.FriendState,
                    LastFollowUpTime = z.LastFollowUpTime.HasValue ? z.LastFollowUpTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                    z.CheckInNum,
                    CreateTime = z.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                    FriendTime = z.FriendTime.HasValue ? z.FriendTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
                })
            });
            return ApiResult.Success("", pmodel);
        }
        #endregion

        #region 自定义查询

        [HttpPost]
        public ApiResult SaveCustomQuery()
        {
            RB_CustomQuery model = JsonHelper.DeserializeObject<RB_CustomQuery>(base.RequestParm.Msg.ToString());
            if (model != null) 
            {
                if (string.IsNullOrEmpty(model.Name) || string.IsNullOrEmpty(model.SelectList) || string.IsNullOrEmpty(model.Code) || model.AddCondition == 0)
                {
                    return ApiResult.Failed("参数信息不完整");
                }
                else 
                {
                    model.CreateBy = base.UserInfo.AccountId;
                    if (customerModule.SaveCustomQuery(model))
                    {
                        return ApiResult.Success("保存成功");
                    }
                    else 
                    {
                        return ApiResult.Failed("保存失败，请联系技术管理员");
                    }
                }
            }
            else
            {
                return ApiResult.Failed("未获取到有效参数信息，请重新发起保存或刷新页面");
            }
        }

        [HttpPost]
        public ApiResult DeleteCustomQuery()
        {
            int uid = base.UserInfo.AccountId;
            var parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int id = parms.GetInt("id", 0);
            if (id != 0 && customerModule.DeleteCustomQuery(id, uid))
            {
                return ApiResult.Success("删除成功");
            }
            else 
            {
                return ApiResult.Failed("删除失败");
            }
        }

        [HttpPost]
        public ApiResult GetUserCustomQuery()
        {
            int uid = base.UserInfo.AccountId;
            var parms = JObject.Parse(base.RequestParm.Msg.ToString());
            var code = parms.GetStringValue("code");
            if (!string.IsNullOrEmpty(code)) 
            {
                var data = customerModule.GetUserCustomQuery(uid,code);
                return ApiResult.Success(message: "查询成功", data: data);
            }

            return ApiResult.Failed("缺失必要的参数");
        }

        [HttpPost]
        public ApiResult GetCustomQueryById()
        {
            int uid = base.UserInfo.AccountId;
            var parms = JObject.Parse(base.RequestParm.Msg.ToString());
            var id = parms.GetInt("id",0);
            if (id!=0)
            {
                var data = customerModule.GetCustomQueryById(id, uid);
                return ApiResult.Success(message: "查询成功", data: data);
            }

            return ApiResult.Failed("缺失必要的参数");
        }


        #endregion
    }
}
