using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum.Customer;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Customer;
using Edu.Module.Customer;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Edu.WebApi.Controllers.Customer
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class B2BCustomerController : BaseController
    {
        /// <summary>
        /// 同行管理处理类对象
        /// </summary>
        private readonly CustomerModule customerModule = new CustomerModule();

        /// <summary>
        /// 同行任务处理类对象
        /// </summary>
        private readonly CustomerTaskModule taskModule = new CustomerTaskModule();

        /// <summary>
        /// 客户幸福存折和返佣处理类对象
        /// </summary>
        private readonly CustomerBalanceDetailModule balanceDetailModule = new CustomerBalanceDetailModule();


        #region 同行管理

        /// <summary>
        /// 获取同行分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerPage()
        {
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Customer_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                ContactNumber = base.ParmJObj.GetStringValue("ContactNumber"),
                ApproveState = base.ParmJObj.GetInt("ApproveState"),
                QCustomerState = base.ParmJObj.GetInt("QCustomerState"),
                QApproveState=base.ParmJObj.GetInt("QApproveState")
            };
            var list = customerModule.GetCustomerPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);

            List<object> result = new List<object>();
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                result.Add(new
                {
                    item.CustomerId,
                    item.CustomerName,
                    item.ContactNumber,
                    item.EnterpriseName,
                    item.CustomerType,
                    CustomerTypeName = item.CustomerType.ToName(),
                    item.StuNum,
                    item.OrderNum,
                    item.OrderSales,
                    item.ApproveState,
                    item.ApproveStateStr,
                    item.CreateBy,
                    item.CreateByName,
                    item.CreateTimeStr,
                    item.CategoryName,
                    item.CategoryId,
                });
            }
            pageModel.PageData = result;
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 新增修改同业客户资料
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomer()
        {
            var model = new RB_Customer_Extend()
            {
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                ContactNumber = base.ParmJObj.GetStringValue("ContactNumber"),
                Fax = base.ParmJObj.GetStringValue("Fax"),
                QQ = base.ParmJObj.GetStringValue("QQ"),
                Email = base.ParmJObj.GetStringValue("Email"),
                Address = base.ParmJObj.GetStringValue("Address"),
                Sex = base.ParmJObj.GetInt("Sex"),
                Image = base.ParmJObj.GetStringValue("Image"),
                CustomerSourceType = base.ParmJObj.GetInt("CustomerSourceType"),
                CustomerSource = base.ParmJObj.GetStringValue("CustomerSource"),
                CountryId = base.ParmJObj.GetInt("CountryId"),
                ProvinceId = base.ParmJObj.GetInt("ProvinceId"),
                CityId = base.ParmJObj.GetInt("CityId"),
                DistrictId = base.ParmJObj.GetInt("DistrictId"),
                LngLat = base.ParmJObj.GetStringValue("LngLat"),
                Account = base.ParmJObj.GetStringValue("Account"),
                Remark = base.ParmJObj.GetStringValue("Remark"),
                EnterpriseName = base.ParmJObj.GetStringValue("EnterpriseName"),
                CustomerType = (CatetoryTypeEnum)base.ParmJObj.GetInt("CustomerType"),
                WeChatNo = base.ParmJObj.GetStringValue("WeChatNo"),
                CategoryId=base.ParmJObj.GetInt("CategoryId"),
            };
            if (string.IsNullOrEmpty(model.CustomerName))
            {
                return ApiResult.ParamIsNull(message: "请填写客户名称!");
            }

            if (string.IsNullOrEmpty(model.ContactNumber) && string.IsNullOrEmpty(model.QQ) && string.IsNullOrEmpty(model.WeChatNo))
            {
                return ApiResult.Failed("手机号码、QQ号码、微信号码至少填写一项!");
            }

            var categoryModel = new RB_Customer_Category_Extend()
            {
                CategoryId = 0,
                CatetoryType = (CatetoryTypeEnum)base.ParmJObj.GetInt("CustomerType"),
                CategoryName = base.ParmJObj.GetStringValue("CategoryName"),
                Status = Common.Enum.DateStateEnum.Normal,
                Group_Id = base.UserInfo.Group_Id,
                CreateBy = base.UserInfo.Id,
                CreateTime = DateTime.Now,
                UpdateBy = base.UserInfo.Id,
                UpdateTime = DateTime.Now,
                School_Id = base.UserInfo.School_Id,
            };
            if (!string.IsNullOrEmpty(categoryModel.CategoryName))
            {
                bool cflag = customerModule.SetCustomerCategoryModule(categoryModel);
                model.CategoryId = categoryModel.CategoryId;
            }

            model.Status = Common.Enum.DateStateEnum.Normal;
            model.CreateBy = base.UserInfo.Id;
            model.CreateTime = DateTime.Now;
            model.UpdateTime = DateTime.Now;
            model.Group_Id = base.UserInfo.Group_Id;
            model.School_Id = base.UserInfo.School_Id;
            model.ApproveState = 1;
            model.ApproveId = base.UserInfo.Id;
            model.ApproveTime = DateTime.Now;
            model.CustomerState = CustomerStateEnum.Normal;
            var flag = customerModule.SetCustomerModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据编号删除客户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveCustomer()
        {
            var CustomerId = base.ParmJObj.GetInt("CustomerId");
            var flag = customerModule.RemoveCustomerModule(CustomerId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据编号获取客户详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomer()
        {
            var CustomerId = base.ParmJObj.GetInt("CustomerId");
            var data = customerModule.GetCustomerModule(CustomerId);
            if (data != null && data.CreateBy > 0)
            {
                data.CreateByName = UserReidsCache.GetUserLoginInfo(data.CreateBy)?.AccountName ?? "";
            }
            return ApiResult.Success(data: data);
        }

        /// <summary>
        /// 客户审批
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AuditCustomer()
        {
            var model = new RB_Customer_Extend()
            {
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                ApproveState = base.ParmJObj.GetInt("ApproveState"),
                ApproveContent = base.ParmJObj.GetStringValue("ApproveContent"),
                ApproveId = base.UserInfo.Id,
                ApproveTime = DateTime.Now
            };
            var flag = customerModule.AuditCustomerModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        #endregion

        #region 任务管理

        /// <summary>
        /// 获取任务类型
        /// </summary>
        /// <returns></returns>
        public ApiResult GetTaskTypeList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(TaskTypeEnum));
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 获取同行任务分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerTaskPage()
        {
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Task_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                TaskName = base.ParmJObj.GetStringValue("TaskName"),
            };
            var list = taskModule.GetTaskPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
            }
            pageModel.PageData = list;
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 新增修改同业客户资料
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerTask()
        {
            var model = new RB_Task_Extend()
            {
                Id = base.ParmJObj.GetInt("Id"),
                TaskName = base.ParmJObj.GetStringValue("TaskName"),
                TaskSubTitle = base.ParmJObj.GetStringValue("TaskSubTitle"),
                TaskStartTime = base.ParmJObj.GetDateTime("TaskStartTime"),
                TaskEndTime = base.ParmJObj.GetDateTime("TaskEndTime"),
                TaskDesc = base.ParmJObj.GetStringValue("TaskDesc"),
                ExchangeEndTime = base.ParmJObj.GetDateTime("ExchangeEndTime"),
                TaskFinishType = base.ParmJObj.GetInt("TaskFinishType"),
            };
            if (string.IsNullOrEmpty(model.TaskName))
            {
                return ApiResult.ParamIsNull(message: "请填写任务名称!");
            }
            if (string.IsNullOrEmpty(base.ParmJObj.GetStringValue("TaskStartTime")))
            {
                return ApiResult.ParamIsNull(message: "请选择任务开始时间!");
            }
            if (string.IsNullOrEmpty(base.ParmJObj.GetStringValue("TaskEndTime")))
            {
                return ApiResult.ParamIsNull(message: "请选择任务结束时间!");
            }
            if (model.TaskStartTime > model.TaskEndTime)
            {
                return ApiResult.ParamIsNull(message: "开始时间不能大于结束时间!");
            }
            if (model.TaskFinishType <= 0)
            {
                return ApiResult.ParamIsNull(message: "请选择任务完成类型!");
            }
            string taskImageList = base.ParmJObj.GetStringValue("TaskImageList");
            List<string> imgList = new List<string>();
            if (!string.IsNullOrEmpty(taskImageList))
            {
                imgList = JsonHelper.DeserializeObject<List<string>>(taskImageList);
            }
            model.TaskImage = JsonHelper.Serialize(imgList);

            model.Status = Common.Enum.DateStateEnum.Normal;
            model.CreateBy = base.UserInfo.Id;
            model.CreateTime = DateTime.Now;
            model.UpdateTime = DateTime.Now;
            model.Group_Id = base.UserInfo.Group_Id;
            model.School_Id = base.UserInfo.School_Id;
            model.DetailsList = new List<RB_TaskDetails_Extend>();
            string details = base.ParmJObj.GetStringValue("DetailsList");
            if (!string.IsNullOrEmpty(details))
            {
                JArray jarray = JArray.Parse(details);
                if (jarray != null && jarray.Count > 0)
                {
                    foreach (var jItem in jarray)
                    {
                        JObject jobj = JObject.Parse(jItem.ToString());
                        var targetIdList = jobj.GetStringValue("TargetIdList");
                        List<string> targetIds = new List<string>();
                        if (!string.IsNullOrEmpty(targetIdList))
                        {
                            targetIds = JsonHelper.DeserializeObject<List<string>>(targetIdList);
                        }
                        string taskKudoImageList = jobj.GetStringValue("TaskKudoImgList");
                        List<string> imgKudoList = new List<string>();
                        if (!string.IsNullOrEmpty(taskKudoImageList))
                        {
                            imgKudoList = JsonHelper.DeserializeObject<List<string>>(taskKudoImageList);
                        }
                        model.DetailsList.Add(new RB_TaskDetails_Extend()
                        {
                            DetailId = jobj.GetInt("DetailId"),
                            TaskId = jobj.GetInt("TaskId"),
                            DetailsName = jobj.GetStringValue("DetailsName"),
                            TaskType = (TaskTypeEnum)jobj.GetInt("TaskType"),
                            TargetId = string.Join(",", targetIds),
                            TaskFinishValue = jobj.GetDecimal("TaskFinishValue"),
                            TaskKudo = jobj.GetStringValue("TaskKudo"),
                            TaskKudoImg = JsonHelper.Serialize(imgKudoList),
                            KudoDescription = jobj.GetStringValue("KudoDescription")
                        });
                    }
                }
            }
            if (model.DetailsList == null || (model.DetailsList != null && model.DetailsList.Count() == 0))
            {
                return ApiResult.ParamIsNull(message: "请添加任务完成条件!");
            }
            foreach (var item in model.DetailsList)
            {
                switch (item.TaskType)
                {
                    case TaskTypeEnum.Course:
                        if (item.TargetIdList == null || (item.TargetIdList != null && item.TargetIdList.Count == 0))
                        {
                            return ApiResult.ParamIsNull(message: $"请选择【{item.TaskType.ToName()}】类型的任务条件！");
                        }
                        break;
                    case TaskTypeEnum.CourseCate:
                        if (item.TargetIdList == null || (item.TargetIdList != null && item.TargetIdList.Count == 0))
                        {
                            return ApiResult.ParamIsNull(message: $"请选择【{item.TaskType.ToName()}】类型的任务条件！");
                        }
                        break;
                    case TaskTypeEnum.CourseSuject:
                        if (item.TargetIdList == null || (item.TargetIdList != null && item.TargetIdList.Count == 0))
                        {
                            return ApiResult.ParamIsNull(message: $"请选择【{item.TaskType.ToName()}】类型的任务条件！");
                        }
                        break;
                    case TaskTypeEnum.GlobalUse:
                        item.TargetId = "";
                        break;
                }
            }
            var flag = taskModule.SetCustomerTaskModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据任务编号删除任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveCustomerTask()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var flag = taskModule.RemoveCustomerTaskModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据任务编号获取任务实体类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerTask()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var data = taskModule.GetCustomerTaskModule(Id);
            return ApiResult.Success(data: data);
        }
        #endregion

        #region 客户幸福存折和返佣
        /// <summary>
        /// 获取同行任务分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerBalanceDetailPage()
        {
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Customer_BalanceDetail_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                RebateType = base.ParmJObj.GetInt("RebateType"),
                BalanceType = base.ParmJObj.GetInt("BalanceType"),
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                OrderId = base.ParmJObj.GetInt("OrderId"),
                Description = base.ParmJObj.GetStringValue("Description"),
            };
            var list = balanceDetailModule.GetCustomerBalanceDetailPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            pageModel.PageData = list;
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }

        #endregion

        #region 同行完成任务列表


        /// <summary>
        /// 获取客户完成任务分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerFinishtaskPage()
        {
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Customer_Finishtask_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                TaskName = base.ParmJObj.GetStringValue("TaskName"),
                ExchangeStatus = base.ParmJObj.GetInt("ExchangeStatus"),
                ExchangeCode = base.ParmJObj.GetStringValue("ExchangeCode"),
            };
            var list = taskModule.GetCustomerFinishtaskPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            pageModel.PageData = list;
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 根据编号获取任务完成详情列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerFinishtaskDetailsPage()
        {
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Customer_Finishdetails_Extend()
            {
                TaskId = base.ParmJObj.GetInt("TaskId"),
                DetailId = base.ParmJObj.GetInt("DetailId"),
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                FinishId = base.ParmJObj.GetInt("GetCustomerFinishtaskDetailsPage"),
            };
            var list = taskModule.GetCustomerFinishdetailsPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            pageModel.Count = rowsCount;
            pageModel.PageData = list;
            return ApiResult.Success(data: pageModel);
        }
        #endregion

        /// <summary>
        /// 兑换奖品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult ExchangeKudo()
        {
            var Id = base.ParmJObj.GetInt("Id");
            string exchangeCode = base.ParmJObj.GetStringValue("ExchangeCode");
            var CustomerId = base.ParmJObj.GetInt("CustomerId");
            bool flag = taskModule.ExchangeKudoModule(Id, out string message);
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }

        #region 同业调整

        /// <summary>
        /// 获取同行分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerPageList_V2()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Customer_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                ContactNumber = base.ParmJObj.GetStringValue("ContactNumber"),
                ApproveState = base.ParmJObj.GetInt("ApproveState"),
                QCustomerState = base.ParmJObj.GetInt("QCustomerState"),
                CategoryName=base.ParmJObj.GetStringValue("CategoryName"),
            };
            query.CreateBy = userInfo.Id;
            var list = customerModule.GetCustomerPageModule_V2(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
  
            pageModel.PageData = list.Select(x => new
            {
                x.CustomerId,
                x.CustomerName,
                x.ContactNumber,
                x.EnterpriseName,
                x.CustomerType,
                CustomerTypeName=x.CustomerType.ToName(),
                x.StuNum,
                x.OrderNum,
                x.OrderSales,
                x.ApproveState,
                x.ApproveStateStr,
                x.CreateBy,
                x.CreateByName,
                x.CreateTimeStr,
                x.CategoryName,
                x.CategoryId,
            });
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取同行分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllCustomerPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Customer_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                ContactNumber = base.ParmJObj.GetStringValue("ContactNumber"),
                ApproveState = base.ParmJObj.GetInt("ApproveState"),
                QCustomerState = base.ParmJObj.GetInt("QCustomerState"),
                CreateBy = base.ParmJObj.GetInt("CreateBy"),
                CategoryName=base.ParmJObj.GetStringValue("CategoryName"),
                CategoryId=base.ParmJObj.GetInt("CategoryId"),
            };
            var list = customerModule.GetCustomerPageModule_V2(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);

            pageModel.PageData = list.Select(x => new
            {
                x.CustomerId,
                x.CustomerName,
                x.ContactNumber,
                x.CustomerType,
                CustomerTypeName = x.CustomerType.ToName(),
                x.EnterpriseName,
                x.StuNum,
                x.OrderNum,
                x.OrderSales,
                x.ApproveState,
                x.ApproveStateStr,
                x.CreateBy,
                x.CreateByName,
                x.CreateTimeStr,
                x.QQ,
                x.WeChatNo,
                x.CategoryName,
                x.CategoryId,
            });
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 导出同行联系人信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public FileContentResult DownLoadCustomerLinkMan()
        {
            var query = new RB_Customer_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                ContactNumber = base.ParmJObj.GetStringValue("ContactNumber"),
                ApproveState = base.ParmJObj.GetInt("ApproveState"),
                QCustomerState = base.ParmJObj.GetInt("QCustomerState"),
                CreateBy = base.ParmJObj.GetInt("CreateBy"),
                CategoryName = base.ParmJObj.GetStringValue("CategoryName"),
                CategoryId = base.ParmJObj.GetInt("CategoryId"),
            };
            string excelName = "同行联系人.xls";
            Common.Plugin.StopwatchHelper stopwatch = new StopwatchHelper();
            stopwatch.Start();
            var list = customerModule.GetCustomerPageModule_V2(1, 100000, out long rowsCount, query);
            var xx = stopwatch.Stop();
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            try
            {
                ExcelDataSource header = new ExcelDataSource();
                header.ExcelRows = new List<ExcelColumn>()
                {
                    new ExcelColumn("联系人名称"){  CellWidth=20},
                    new ExcelColumn("类型"){  CellWidth=20},
                    new ExcelColumn("同行名称"){  CellWidth=20},
                    new ExcelColumn("电话"){  CellWidth=20},
                    new ExcelColumn("QQ号"){  CellWidth=20},
                    new ExcelColumn("微信号"){  CellWidth=20},
                    new ExcelColumn("客户数量"){  CellWidth=20},
                    new ExcelColumn("订单数量"){  CellWidth=20},
                    new ExcelColumn("交易额"){  CellWidth=20},
                    new ExcelColumn("审核状态"){  CellWidth=20},
                    new ExcelColumn("加入时间"){  CellWidth=20},
                    new ExcelColumn("负责人"){  CellWidth=20},
                };
                slist.Add(header);
                foreach (var item in list)
                {
                    var dataRow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>()
                         {
                            new ExcelColumn(item.CustomerName),
                            new ExcelColumn(item.CustomerType.ToName()),
                            new ExcelColumn(item.CategoryName),
                            new ExcelColumn(item.ContactNumber),
                            new ExcelColumn(item.QQ),
                            new ExcelColumn(item.WeChatNo),
                            new ExcelColumn(item.StuNum.ToString()),
                            new ExcelColumn(item.OrderNum.ToString()),
                            new ExcelColumn(item.OrderSales.ToString()),
                            new ExcelColumn(item.ApproveStateStr),
                            new ExcelColumn(item.CreateTimeStr),
                            new ExcelColumn(item.CreateByName),
                         }
                    };
                    slist.Add(dataRow);
                }
                stopwatch.Start();
                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                var yy = stopwatch.Stop();
                return  File(byteData, "application/octet-stream", excelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DownLoadCustomerLinkMan");
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", excelName);
            }
        }

        /// <summary>
        /// 获取同行佣金幸福存折
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerCommissionPassbook()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int CustomerId = parms.GetInt("CustomerId", 0);//同业ID
            int Type = parms.GetInt("Type", 1);//类型  1佣金  2幸福存折
            if (CustomerId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var RObj = customerModule.GetCustomerCommissionPassbook(CustomerId, Type, userInfo.Group_Id);
            return ApiResult.Success("", RObj);
        }

        /// <summary>
        /// 同行转交
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerCareOf()
        {
            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("请传递接收人ID");
            }

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

        /// <summary>
        /// 获取同业下所有学生阶段人数统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerStuStageStatistics()
        {
            var userInfo = base.UserInfo;
            int CustomerId = base.ParmJObj.GetInt("CustomerId", 0);//同业联系人编号ID
            int CategoryId = base.ParmJObj.GetInt("CategoryId", 0);//同业编号
            if (CustomerId <= 0&& CategoryId<=0)
            {
                return ApiResult.ParamIsNull();
            }

            var Robj = customerModule.GetCustomerStuStageStatistics(CustomerId, CategoryId, userInfo.Group_Id);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 获取我的同行列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyCustomerList()
        {
            var query = new RB_Customer_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CreateBy = base.UserInfo.Id,
                CustomerId = base.ParmJObj.GetInt("CustomerId"),
                CustomerName = base.ParmJObj.GetStringValue("CustomerName"),
                ContactNumber = base.ParmJObj.GetStringValue("ContactNumber"),
                ApproveState = 1,
                QCustomerState = 1,
            };
            var list = customerModule.GetCustomerListModule(query);
            return ApiResult.Success(data: list.Select(x => new
            {
                x.CustomerId,
                x.CustomerName,
                x.ContactNumber,
                x.EnterpriseName,
                x.CustomerType
            }));
        }

        #endregion

        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerList()
        {
            var query = new RB_Customer_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                ApproveState = 1,
                QCustomerState = 1,
            };
            query.QCreateBy = base.ParmJObj.GetInt("QCreateBy");
            if (query.QCreateBy > 0)
            {
                query.CreateBy = base.UserInfo.Id;
            }
            var list = customerModule.GetCustomerListModule(query);
            return ApiResult.Success(data: list);
        }

        #region 企业管理
        /// <summary>
        /// 获取企业分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEnterprisePage()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Enterprise_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                EnterpriseName = base.ParmJObj.GetStringValue("EnterpriseName")
            };
            query.CreateBy = userInfo.Id;
            var list = customerModule.GetEnterprisePageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            List<object> result = new List<object>();
            foreach (var item in list)
            {
                string CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                result.Add(new
                {
                    item.Id,
                    item.EnterpriseName,
                    CreateByName,
                    CreateTime = Common.ConvertHelper.FormatTime(item.CreateTime),
                });
            }
            pageModel.PageData = result;
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取企业列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEnterpriseList()
        {
            var userInfo = base.UserInfo;
            var query = new RB_Enterprise_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                EnterpriseName = base.ParmJObj.GetStringValue("EnterpriseName")
            };
            query.CreateBy = userInfo.Id;
            var list = customerModule.GetEnterpriseListModule(query);
            List<object> result = new List<object>();
            foreach (var item in list)
            {
                string CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                result.Add(new
                {
                    item.Id,
                    item.EnterpriseName,
                    CreateByName,
                    CreateTime = Common.ConvertHelper.FormatTime(item.CreateTime),
                });
            }
            return ApiResult.Success(data: result);
        }

        /// <summary>
        /// 新增修改企业
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetEnterprise()
        {
            var extModel = new RB_Enterprise_Extend()
            {
                Id = base.ParmJObj.GetInt("Id"),
                EnterpriseName = base.ParmJObj.GetStringValue("EnterpriseName")
            };
            extModel.Group_Id = base.UserInfo.Group_Id;
            extModel.CreateBy = base.UserInfo.Id;
            extModel.UpdateBy = base.UserInfo.Id;
            extModel.CreateTime = DateTime.Now;
            extModel.UpdateTime = DateTime.Now;
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            bool flag = customerModule.SetEnterpriseModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 根据编号获取企业信息
        /// </summary>
        /// <returns></returns>
        public ApiResult GetEnterprise()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var extModel = customerModule.GetEnterpriseModule(Id);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 根据编号删除企业信息
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveEnterprise()
        {
            var Id = base.ParmJObj.GetInt("Id");
            bool flag = customerModule.RemoveEnterpriseModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        #endregion

        #region 同行管理

        /// <summary>
        /// 获取同行分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerCategoryPage()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Customer_Category_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CategoryName = base.ParmJObj.GetStringValue("CategoryName"),
                CatetoryType=(CatetoryTypeEnum)base.ParmJObj.GetInt("CatetoryType"),
            };
            int IsQueryAll = base.ParmJObj.GetInt("IsQueryAll");
            if (IsQueryAll ==0)
            {
                query.CreateBy = userInfo.Id;
            }
            var list = customerModule.GetCustomerCategoryPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            List<object> result = new List<object>();
            foreach (var item in list)
            {

                result.Add(new
                {
                    item.CategoryId,
                    item.CategoryName,
                    CreateByName=item.CreateByName,
                    item.CatetoryType,
                    item.LinkManCount,
                    item.StudentCount,
                    item.OrderCount,
                    CatetoryTypeName = item.CatetoryType.ToName(),
                    CreateTime = Common.ConvertHelper.FormatTime(item.CreateTime),
                });
            }
            pageModel.PageData = result;
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 同行信息下载
        /// </summary>
        /// <returns></returns>

        [HttpPost]
        [Obsolete]
        public FileContentResult DownLoadCustomer()
        {
            var query = new RB_Customer_Category_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CategoryName = base.ParmJObj.GetStringValue("CategoryName"),
                CatetoryType = (CatetoryTypeEnum)base.ParmJObj.GetInt("CatetoryType"),
            };
            int IsQueryAll = base.ParmJObj.GetInt("IsQueryAll");
            if (IsQueryAll == 0)
            {
                query.CreateBy = base.UserInfo.Id;
            }
            var list = customerModule.GetCustomerCategoryPageModule(1, 100000, out long rowsCount, query);
            string excelName = "同行资料.xls";
            
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            try
            {
                ExcelDataSource header = new ExcelDataSource();
                header.ExcelRows = new List<ExcelColumn>()
                {
                    new ExcelColumn("同业名称"){  CellWidth=40},
                    new ExcelColumn("类型"){  CellWidth=20},
                    new ExcelColumn("联系人数量"){  CellWidth=20},
                    new ExcelColumn("客户数量"){  CellWidth=20},
                    new ExcelColumn("订单数量"){  CellWidth=20},
                    new ExcelColumn("加入时间"){  CellWidth=30},
                    new ExcelColumn("负责人"){  CellWidth=20},
                };
                slist.Add(header);
                foreach (var item in list)
                {

                    var dataRow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>()
                         {
                            new ExcelColumn(item.CategoryName),
                            new ExcelColumn(item.CatetoryType.ToName()),
                            new ExcelColumn(item.LinkManCount.ToString()),
                            new ExcelColumn(item.StudentCount.ToString()),
                            new ExcelColumn(item.OrderCount.ToString()),
                            new ExcelColumn(Common.ConvertHelper.FormatTime(item.CreateTime)),
                            new ExcelColumn(item.CreateByName),
                         }
                    };
                    slist.Add(dataRow);
                }
                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", excelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "OutToExcelOrderStudentClassHoursList");
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", excelName);
            }
        }

        /// <summary>
        /// 获取同行列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerCategoryList()
        {
            var userInfo = base.UserInfo;
            var query = new RB_Customer_Category_Extend()
            {
                Group_Id = base.UserInfo.Group_Id,
                CategoryName = base.ParmJObj.GetStringValue("CategoryName"),
                CatetoryType = (CatetoryTypeEnum)base.ParmJObj.GetInt("CatetoryType"),
            };
            query.CreateBy = userInfo.Id;
            var list = customerModule.GetCustomerCategoryListModule(query);
            List<object> result = new List<object>();
            foreach (var item in list)
            {
                string CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                result.Add(new
                {
                    item.CategoryId,
                    item.CategoryName,
                    CreateByName,
                    item.CatetoryType,
                    CatetoryTypeName = item.CatetoryType.ToName(),
                    CreateTime = Common.ConvertHelper.FormatTime(item.CreateTime),
                });
            }
            return ApiResult.Success(data: result);
        }

        /// <summary>
        /// 新增修改同行
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCustomerCategory()
        {
            int CategoryId = base.ParmJObj.GetInt("CategoryId");
            var extModel = new RB_Customer_Category_Extend()
            {
                CategoryId= CategoryId,
                CategoryName = base.ParmJObj.GetStringValue("CategoryName"),
                CatetoryType = (CatetoryTypeEnum)base.ParmJObj.GetInt("CatetoryType"),
            };
            var linkMan = base.ParmJObj.GetStringValue("linkMan");
            var linkTel = base.ParmJObj.GetStringValue("linkTel");
            extModel.Group_Id = base.UserInfo.Group_Id;
            extModel.CreateBy = base.UserInfo.Id;
            extModel.UpdateBy = base.UserInfo.Id;
            extModel.CreateTime = DateTime.Now;
            extModel.UpdateTime = DateTime.Now;
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            if (customerModule.CheckCustomerCategoryModule(extModel))
            {
                return ApiResult.Failed(message: "已存在此同行信息,请重新录入!");
            }
            bool flag = customerModule.SetCustomerCategoryModule(extModel);
            if (flag && CategoryId <= 0)
            {
                var customerModel = new RB_Customer_Extend()
                {
                    CustomerId = 0,
                    CustomerName = linkMan,
                    ContactNumber = linkTel,
                    Fax = "",
                    QQ = "",
                    Email = "",
                    Address = "",
                    Sex = 1,
                    Image = "",
                    CustomerSourceType = (int)extModel.CatetoryType,
                    CustomerSource = extModel.CategoryName,
                    CountryId = 0,
                    ProvinceId = 0,
                    CityId = 0,
                    DistrictId = 0,
                    LngLat = "",
                    Account = linkTel,
                    Remark = "",
                    EnterpriseName = "",
                    CustomerType = extModel.CatetoryType,
                    WeChatNo = "",
                    CategoryId= extModel.CategoryId,
                };
                if (string.IsNullOrEmpty(customerModel.CustomerName))
                {
                    return ApiResult.ParamIsNull(message: "请填写客户名称!");
                }
                if (string.IsNullOrEmpty(customerModel.ContactNumber) && string.IsNullOrEmpty(customerModel.QQ) && string.IsNullOrEmpty(customerModel.WeChatNo))
                {
                    return ApiResult.Failed("手机号码、QQ号码、微信号码至少填写一项!");
                }
                customerModel.Status = Common.Enum.DateStateEnum.Normal;
                customerModel.CreateBy = base.UserInfo.Id;
                customerModel.CreateTime = DateTime.Now;
                customerModel.UpdateTime = DateTime.Now;
                customerModel.Group_Id = base.UserInfo.Group_Id;
                customerModel.School_Id = base.UserInfo.School_Id;
                customerModel.ApproveState = 1;
                customerModel.ApproveId = base.UserInfo.Id;
                customerModel.ApproveTime = DateTime.Now;
                customerModel.CustomerState = CustomerStateEnum.Normal;
                customerModule.SetCustomerModule(customerModel);
            }
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 根据编号获取同行
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerCategory()
        {
            var CategoryId = base.ParmJObj.GetInt("CategoryId");
            var extModel = customerModule.GetCustomerCategoryModule(CategoryId);
            var obj = new
            {
                extModel?.CategoryId,
                extModel?.CategoryName,
                extModel?.CatetoryType,
                CatetoryTypeName=extModel?.CatetoryType.ToName()??"",
            };
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 根据编号删除同行信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveCustomerCategory()
        {
            var CategoryId = base.ParmJObj.GetInt("CategoryId");
            bool flag = customerModule.RemoveCustomerCategoryModule(CategoryId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取客户类型列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCatetoryTypeList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(CatetoryTypeEnum));
            return ApiResult.Success(data: list);
        }
        #endregion
    }
}
