using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using Znyc.Cloudcar.Admin.AspNetCore.Controllers;
using Znyc.Cloudcar.Admin.AspNetCore.Entitys;
using Znyc.Cloudcar.Admin.AspNetCore.Mvc;
using Znyc.Cloudcar.Admin.AspNetCore.ViewModel;
using Znyc.Cloudcar.Admin.Commons.Cache;
using Znyc.Cloudcar.Admin.Commons.Entitys;
using Znyc.Cloudcar.Admin.Commons.Extensions;
using Znyc.Cloudcar.Admin.Commons.Log;
using Znyc.Cloudcar.Admin.Commons.Mapping;
using Znyc.Cloudcar.Admin.Security.Dtos;
using Znyc.Cloudcar.Admin.Security.Entitys;
using Znyc.Cloudcar.Admin.Security.IServices;

namespace Znyc.Cloudcar.Admin.WebApi.Controllers
{
    /// <summary>
    ///     行业岗位
    /// </summary>
    [ApiController]
    [Route("api/Security/[controller]")]
    public class
        IndustryJobsController : AreaApiController<IndustryJobsEntity, IndustryJobsOutputDto, IndustryJobsInputDto,
            IIndustryJobsService, long>
    {
        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="service"></param>
        public IndustryJobsController(IIndustryJobsService service) : base(service)
        {
            _service = service;
        }

        /// <summary>
        ///     新增前处理数据
        /// </summary>
        /// <param name="info"></param>
        protected override void OnBeforeInsert(IndustryJobsEntity info)
        {
            info.Id = 0;
            info.IsEnabled = true;
            info.CreatedTime = DateTime.Now;
            info.CreatedUserId = CurrentUser.UserId;
            info.IsDeleted = false;
        }

        /// <summary>
        ///     在更新数据前对数据的修改操作
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        protected override void OnBeforeUpdate(IndustryJobsEntity info)
        {
            info.ModifiedUserId = CurrentUser.UserId;
            info.ModifiedTime = DateTime.Now;
        }

        /// <summary>
        ///     在软删除数据前对数据的修改操作
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        protected override void OnBeforeSoftDelete(IndustryJobsEntity info)
        {
            info.IsDeleted = true;
        }

        /// <summary>
        ///     异步新增数据
        /// </summary>
        /// <param name="tinfo"></param>
        /// <returns></returns>
        [HttpPost("Insert")]
        [FunctionAuthorize("Add")]
        public async Task<IActionResult> InsertAsync(IndustryJobsInputDto tinfo)
        {
            CommonResult result = new CommonResult();
            CacheHelper cacheHelper = new CacheHelper();
            IndustryJobsEntity info = tinfo.MapTo<IndustryJobsEntity>();
            OnBeforeInsert(info);
            info.Id = YitIdHelper.NextId();
            int bl = await _service.InsertAsync(info).ConfigureAwait(false);
            if (bl > 0)
            {
                cacheHelper.Remove("industryjobs:list");
                cacheHelper.Remove("allindustryjobs:list");
                result.ErrCode = ErrCode.successCode;
                result.ErrMsg = ErrCode.err0;
            }
            else
            {
                result.ErrMsg = ErrCode.err43002;
                result.ErrCode = "43002";
            }

            return ToJsonContent(result);
        }

        /// <summary>
        ///     异步更新数据
        /// </summary>
        /// <param name="tinfo"></param>
        /// <returns></returns>
        [HttpPost("UpdateAsync")]
        [FunctionAuthorize("Edit")]
        public async Task<IActionResult> UpdateAsync(IndustryJobsInputDto tinfo)
        {
            CommonResult result = new CommonResult();
            CacheHelper cacheHelper = new CacheHelper();
            IndustryJobsEntity info = _service.Get(tinfo.Id);
            info.ParentId = tinfo.ParentId;
            info.Name = tinfo.Name;
            info.Sort = tinfo.Sort;
            info.IsEnabled = tinfo.IsEnabled;
            OnBeforeUpdate(info);
            bool bl = await _service.UpdateAsync(info, tinfo.Id).ConfigureAwait(false);
            if (bl)
            {
                cacheHelper.Remove("industryjobs:list");
                cacheHelper.Remove("allindustryjobs:list");
                result.ErrCode = ErrCode.successCode;
                result.ErrMsg = ErrCode.err0;
            }
            else
            {
                result.ErrMsg = ErrCode.err43002;
                result.ErrCode = "43002";
            }

            return ToJsonContent(result);
        }

        /// <summary>
        ///     获取行业岗位适用于Vue 树形列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllIndustryJobsTreeTable")]
        [FunctionAuthorize("")]
        public async Task<IActionResult> GetAllIndustryJobsTreeTable()
        {
            CommonResult result = new CommonResult();
            try
            {
                System.Collections.Generic.List<IndustryJobsTreeTableDto> list = await _service.GetAllIndustryJobsTreeTable();
                result.Success = true;
                result.ErrCode = ErrCode.successCode;
                result.ResData = list;
            }
            catch (Exception ex)
            {
                Log4NetHelper.Error("获取组织结构异常", ex);
                result.ErrMsg = ErrCode.err40110;
                result.ErrCode = "40110";
            }

            return ToJsonContent(result);
        }

        /// <summary>
        ///     异步批量禁用数据
        /// </summary>
        /// <param name="info"></param>
        [HttpPost("SetEnabledMarktBatchAsync")]
        [FunctionAuthorize("")]
        public async Task<IActionResult> SetEnabledMarktBatchAsync(UpdateEnableViewModel info)
        {
            CommonResult result = new CommonResult();
            CacheHelper cacheHelper = new CacheHelper();
            string where = string.Empty;
            if (typeof(int) == typeof(string))
            {
                @where = "id in ('" + info.Ids.Join(",").Trim(',').Replace(",", "','") + "')";
            }
            else if (typeof(int) == typeof(int))
            {
                @where = "id in (" + info.Ids.Join(",") + ")";
            }

            if (!string.IsNullOrEmpty(where))
            {
                bool bl = false;
                if (info.Flag == "1")
                {
                    bl = true;
                }

                bool blResult = await _service.SetEnabledMarkByWhereAsync(bl, where, CurrentUser.UserId);
                if (blResult)
                {
                    cacheHelper.Remove("industryjobs:list");
                    cacheHelper.Remove("allindustryjobs:list");
                    result.ErrCode = ErrCode.successCode;
                    result.ErrMsg = ErrCode.err0;
                }
                else
                {
                    result.ErrMsg = ErrCode.err43002;
                    result.ErrCode = "43002";
                }
            }

            return ToJsonContent(result);
        }

        /// <summary>
        ///     异步软删除信息
        /// </summary>
        /// <param name="id">主键Id</param>
        /// <param name="bltag">删除标识,默认为1:即设为删除,0:未删除</param>
        [HttpDelete("DeleteSoftAsync")]
        [FunctionAuthorize("DeleteSoft")]
        public async Task<IActionResult> DeleteSoftAsync(long id, string bltag = "1")
        {
            CommonResult result = new CommonResult();
            System.Collections.Generic.IEnumerable<IndustryJobsEntity> IndustryJobList = await _service.GetListWhereAsync($" ParentId={id} and IsDeleted=0 and IsEnabled=1");
            if (IndustryJobList != null && IndustryJobList.Count() > 0)
            {
                result.ErrMsg = "行业存在启用岗位,不能删除";
                return ToJsonContent(result);
            }
            CacheHelper cacheHelper = new CacheHelper();
            bool bl = false;
            if (bltag == "0")
            {
                bl = true;
            }

            bool blResult = await _service.DeleteSoftAsync(bl, id, CurrentUser.UserId);
            if (blResult)
            {
                cacheHelper.Remove("industryjobs:list");
                cacheHelper.Remove("allindustryjobs:list");
                result.ErrCode = ErrCode.successCode;
                result.ErrMsg = ErrCode.err0;
            }
            else
            {
                result.ErrMsg = ErrCode.err43002;
                result.ErrCode = "43002";
            }

            return ToJsonContent(result);
        }

        /// <summary>
        ///     异步批量软删除信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpDelete("DeleteSoftBatchAsync")]
        [FunctionAuthorize("DeleteSoft")]
        public async Task<IActionResult> DeleteSoftBatchAsync(UpdateEnableViewModel info)
        {
            CommonResult result = new CommonResult();
            CacheHelper cacheHelper = new CacheHelper();
            string where = string.Empty;
            string key = string.Empty;
            if (typeof(int) == typeof(string))
            {
                @where = "id in ('" + info.Ids.Join(",").Trim(',').Replace(",", "','") + "')";
                @key = " ParentId in ('" + info.Ids.Join(",").Trim(',').Replace(",", "','") + "') and IsDeleted=0 and IsEnabled=1";
            }
            else if (typeof(int) == typeof(int))
            {
                @where = "id in (" + info.Ids.Join(",") + ")";
                @key = " ParentId in (" + info.Ids.Join(",") + ") and IsDeleted=0 and IsEnabled=1";
            }
            if (!string.IsNullOrEmpty(key))
            {
                System.Collections.Generic.IEnumerable<IndustryJobsEntity> IndustryJobList = await _service.GetListWhereAsync(key);
                if (IndustryJobList != null && IndustryJobList.Count() > 0)
                {
                    result.ErrMsg = "行业存在启用岗位,不能删除";
                    return ToJsonContent(result);
                }
            }
            if (!string.IsNullOrEmpty(where))
            {
                bool bl = false;
                if (info.Flag == "0")
                {
                    bl = true;
                }

                bool blResult = await _service.DeleteSoftBatchAsync(bl, where, CurrentUser.UserId);
                if (blResult)
                {
                    cacheHelper.Remove("industryjobs:list");
                    cacheHelper.Remove("allindustryjobs:list");
                    result.ErrCode = ErrCode.successCode;
                    result.ErrMsg = ErrCode.err0;
                }
                else
                {
                    result.ErrMsg = ErrCode.err43002;
                    result.ErrCode = "43002";
                }
            }

            return ToJsonContent(result);
        }
    }
}