UavProfitUserSettingService.cs 7.8 KB
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Extend.Interfaces.UavProfitUserSetting;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Extend.Entitys;
using NCC.Extend.Entitys.Dto.UavProfitUserSetting;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.System.Entitys.Permission;
using NCC.DataEncryption;
using NCC.Common.Const;
using NCC.System.Entitys.System;
using SqlSugar;


namespace NCC.Extend.UavProfitUserSetting
{
    /// <summary>
    /// 人员分润设置服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Extend", Name = "UavProfitUserSetting", Order = 200)]
    [Route("api/Extend/[controller]")]
    public class UavProfitUserSettingService : IUavProfitUserSettingService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<UavProfitUserSettingEntity> _uavProfitUserSettingRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="UavProfitUserSettingService"/>类型的新实例
        /// </summary>
        public UavProfitUserSettingService(
            ISqlSugarRepository<UavProfitUserSettingEntity> uavProfitUserSettingRepository,
            IUserManager userManager)
        {
            _uavProfitUserSettingRepository = uavProfitUserSettingRepository;
            _db = _uavProfitUserSettingRepository.Context;
            _userManager = userManager;
        }

        #region 获取人员分润设置信息
        /// <summary>
        /// 获取人员分润设置
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<UavProfitUserSettingEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<UavProfitUserSettingInfoOutput>();
            return output;
        }
        #endregion
        
        #region 获取人员分润设置列表
        /// <summary>
        /// 获取人员分润设置列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] UavProfitUserSettingListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            var data = await _db.Queryable<UavProfitUserSettingEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.userRoleName), setting => setting.UserRoleName == input.userRoleName)
                .WhereIF(!string.IsNullOrEmpty(input.agentId), setting => setting.AgentId == input.agentId)
                .Select(setting => new UavProfitUserSettingListOutput
                {
                    id = setting.Id,
                    profitUserId = setting.ProfitUserId,
                    profitUserName = SqlFunc.Subqueryable<UserEntity>() .Where(p => p.Id == setting.ProfitUserId).Select(user => user.RealName),
                    profitUserAccount = SqlFunc.Subqueryable<UserEntity>() .Where(p => p.Id == setting.ProfitUserId).Select(user => user.Account),
                    profitRatio = setting.ProfitRatio,
                    enabledMark = setting.EnabledMark,
                    userRoleName = setting.UserRoleName,
                    agentId = setting.AgentId,
                    agentName = SqlFunc.Subqueryable<UserEntity>() .Where(p => p.Id == setting.AgentId).Select(user => user.RealName),
                    description = setting.Description,
                    creatorTime = setting.CreatorTime,
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<UavProfitUserSettingListOutput>.SqlSugarPageResult(data);
        }
        #endregion

        #region 新建人员分润设置
        /// <summary>
        /// 新建人员分润设置
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] UavProfitUserSettingCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            // 判断账号密码必填
            if (string.IsNullOrEmpty(input.profitUserAccount) || string.IsNullOrEmpty(input.profitUserPassword))
            {
                throw NCCException.Oh(ErrorCode.COM1000);
            }
            // 检查用户是否已存在
            var existingUser = await _db.Queryable<UserEntity>()
                .Where(o => o.Account == input.profitUserAccount && o.ExtensionStr == "分润人员" && o.EnabledMark != 0 && o.DeleteMark == null)
                .FirstAsync();

            if (existingUser != null)
            {
                throw NCCException.Oh(ErrorCode.COM1000, "该账号已存在");
            }

            // 创建新用户
            var secretKey = Guid.NewGuid().ToString();
            var newUser = new UserEntity
            {
                Id = YitIdHelper.NextId().ToString(),
                Account = input.profitUserAccount,
                RealName = input.profitUserName,
                MobilePhone = input.profitUserPhone,
                EnabledMark = 1,
                Secretkey = secretKey,
                Password = MD5Encryption.Encrypt(MD5Encryption.Encrypt(input.profitUserPassword) + secretKey),
                ExtensionStr = "分润人员",
                OrganizeId = "17BEBDCB-248D-4668-B6CD-BF22A446BBD4"
            };

            // 插入用户
            var userInsertResult = await _db.Insertable<UserEntity>(newUser).ExecuteCommandAsync();
            if (!(userInsertResult > 0)) throw NCCException.Oh(ErrorCode.COM1000, "用户创建失败");

            // 创建人员分润设置
            var entity = input.Adapt<UavProfitUserSettingEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.ProfitUserId = newUser.Id; // 使用新创建的用户ID
            entity.CreatorUserId = _userManager.UserId;
            entity.CreatorTime = DateTime.Now;

            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
        }
        #endregion

        #region 更新人员分润设置
        /// <summary>
        /// 更新人员分润设置
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] UavProfitUserSettingUpInput input)
        {
            var entity = input.Adapt<UavProfitUserSettingEntity>();
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
        }
        #endregion

        #region 删除人员分润设置
        /// <summary>
        /// 删除人员分润设置
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<UavProfitUserSettingEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<UavProfitUserSettingEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
        }
        #endregion
    }
}