using System;
using System.Linq;
using Mall.Common.API;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Mall.Common;
using Mall.Module.Property;
using Mall.Model.Extend.Property;

namespace Mall.WebApi.Controllers.Property
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AuthorizeController : BaseController
    {
        private readonly AuthorizeModule authorizeModule = new AuthorizeModule();



        /// <summary>
        /// 获取人员授权分页信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAuthorizePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_ERP_Authorize_Extend demodel = JsonConvert.DeserializeObject<RB_ERP_Authorize_Extend>(parms.msg.ToString());
            demodel.Type = 1;
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = authorizeModule.GetAuthorizePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.Type,
                x.Status,
                x.TenantId,
                x.MallBaseId,
                x.CreateBy,
                x.EmpName,
                x.DomainName,
                x.Account,
                x.MallUserName,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : "",
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取集团授权信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAuthorizeModel()
        {
            var parms = RequestParm;
            RB_ERP_Authorize_Extend demodel = JsonConvert.DeserializeObject<RB_ERP_Authorize_Extend>(parms.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var authorizeModel = authorizeModule.GetAuthorizeList(demodel).FirstOrDefault();

            return ApiResult.Success("", authorizeModel);
        }





        /// <summary>
        /// 新增授权信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAuthorize()
        {
            var parms = RequestParm;
            RB_ERP_Authorize_Extend demodel = JsonConvert.DeserializeObject<RB_ERP_Authorize_Extend>(parms.msg.ToString());

            demodel.UpdateDate = System.DateTime.Now;
            demodel.Status = 1;
            if (demodel.ID == 0)
            {
                demodel.TenantId = UserInfo.TenantId;
                demodel.MallBaseId = parms.MallBaseId;
                demodel.CreateBy = UserInfo.EmpId;
                demodel.CreateDate = System.DateTime.Now;
            }
            if (string.IsNullOrWhiteSpace(demodel.DomainName))
            {
                return ApiResult.Failed("请填写需要绑定集团的域名");
            }
            if (demodel.Type == 1)
            {
                if (demodel.MallUserId == 0)
                {
                    return ApiResult.Failed("请选择您要绑定的用户");
                }
                if (string.IsNullOrWhiteSpace(demodel.Account))
                {
                    return ApiResult.Failed("请填写需要绑定的账号");
                }
                if (demodel.ID == 0)
                {
                    if (string.IsNullOrWhiteSpace(demodel.Password))
                    {
                        return ApiResult.Failed("请填写需要绑定的账户密码");
                    }
                }
            }
            RB_ERP_Authorize_Extend groupAuthorize = JsonConvert.DeserializeObject<RB_ERP_Authorize_Extend>(parms.msg.ToString());
            groupAuthorize.Type = 0;
            groupAuthorize.TenantId = UserInfo.TenantId;
            groupAuthorize.MallBaseId = parms.MallBaseId;
            groupAuthorize.MallUserId = 0;
            groupAuthorize.ID = 0;
            var authorizeModel = authorizeModule.GetAuthorizeList(groupAuthorize).FirstOrDefault();

            //判断集团域名是否存在
            var groupModel = authorizeModule.GetGroupList(new RB_Group_Extend { Domain = demodel.DomainName, IsEquit = 1 }).FirstOrDefault();
            if (groupModel == null || groupModel.Id == 0)
            {
                return ApiResult.Failed("集团域名不存在，请确认后再绑定");
            }
            demodel.ERPGroupId = groupModel.Id;
            if (demodel.Type == 1)
            {
                //判断集团是否授权
                if (authorizeModel == null || authorizeModel.ID == 0)
                {
                    return ApiResult.Failed("集团暂未授权");
                }
                if (authorizeModel.Status != 2)
                {
                    return ApiResult.Failed("集团未通过审核，不能授权用户");
                }
                //判断人员账号是否存在
                demodel.Password = Common.DES.Encrypt(demodel.Password, Common.Config.WebApiKey, Common.Config.WebApiIV);
                var employeeModel = authorizeModule.ValidateAdmin(new RB_Employee_Extend { RB_Group_id = groupModel.Id, EmAccount = demodel.Account, EmPassword = demodel.Password }).FirstOrDefault();
                if (employeeModel == null || employeeModel.EmployeeId == 0)
                {
                    return ApiResult.Failed("账号不存在，请确认后再绑定");
                }
                if (employeeModel.IsLeave == 1)
                {
                    return ApiResult.Failed("账号已离职");
                }
            }
            else
            {
                if (demodel.ID == 0 && authorizeModel != null && authorizeModel.Status != 4)
                {
                    return ApiResult.Failed("集团已申请授权");
                }
            }
            bool result = authorizeModule.AddERPAuthorize(demodel);

            if (result)
            {
                return ApiResult.Success("申请绑定ERP信息，请等待审核");
            }
            else
            {
                return ApiResult.Failed("申请绑定ERP信息失败");

            }
        }


        /// <summary>
        /// 删除授权
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelERPAuthorize()
        {
            var parms = RequestParm;
            RB_ERP_Authorize_Extend demodel = JsonConvert.DeserializeObject<RB_ERP_Authorize_Extend>(parms.msg.ToString());

            bool result = authorizeModule.DelERPAuthorize(demodel);
            if (result)
            {
                return ApiResult.Success("删除授权成功");
            }
            else
            {
                return ApiResult.Failed("删除授权失败");
            }

        }

    }

}