using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Sugar.Enties;
using Utils;
using Microsoft.Extensions.Caching.Memory;

namespace PMS.NetCore.Controllers
{
    /// <summary>
    /// 机构人员
    /// </summary>
    [Produces("application/json;charset=UTF-8")]
    [Route("api/Organization")]
    [ServiceFilter(typeof(Filter.TokenAuthorize))]
    public class OrganizationController :  BaseController
    {
        private IMemoryCache _memoryCache;
        public OrganizationController(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }
        #region 组织机构
        /// <summary>
        /// 获取组织机构列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetCorpsList")]
        public JsonResult GetCorpsList()
        {
            var manger = new corpsManager();
            var list = manger.GetList();
            logger.Info($"【GetCorpsList】接口输出：{JsonConvert.SerializeObject(list)}");

            return Json(list);
        }
        /// <summary>
        /// 根据单位编号获取组织机构实例
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetCorps")]
        public JsonResult GetCorps([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetCorps】接口输入：{JsonConvert.SerializeObject(dto)}");
            var manger = new corpsManager();
            var model = manger.GetList(m=>m.pk_corp==dto.value).FirstOrDefault();
            logger.Info($"【GetCorps】接口输出：{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }
        /// <summary>
        /// 添加组织机构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("CorpsAdd")]
        public JsonResult CorpsAdd([FromBody] corps model )
        {
            var manger = new corpsManager();
            if(!model.pk_corp.IsInteger())
            {
                return Json("单位编码必须是整数形式");
            }
            var mod = manger.GetById(model.pk_corp);
            if (mod != null)
            {
                return Json("该组织机构单位编码已经存在");
            }
            if(model.fathercode!="0")
            {
                var father = manger.GetById(model.fathercode);
                if(father==null)
                {
                    return Json("上级公司不存在，请重新选择");
                }
            }
            if(model.corpname.IsNullOrEmpty())
            {
                return Json("单位名称不能为空");
            }
            var model1 = manger.GetList(m => m.corpname == model.corpname).FirstOrDefault();
            if(model1!=null)
            {
                return Json("单位名称必须唯一");
            }
            if(model.sgn.IsNotNullAndEmpty())
            {
                var model2 = manger.GetList(m => m.sgn == model.sgn).FirstOrDefault();
                if (model2 != null)
                {
                    return Json("收据标识必须唯一");
                }
            }
            var success = manger.Insert(model);
            if(success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");
            }
        }
        /// <summary>
        /// 修改组织机构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("CorpsUpdate")]
        public JsonResult CorpsUpdate([FromBody] corps model)
        {
            logger.Info($"【CorpsUpdate】model:{JsonConvert.SerializeObject(model)}");
            var manger = new corpsManager();
            if (!model.pk_corp.IsInteger())
            {
                return Json("单位编码必须是整数形式");
            }
            var mod = manger.GetById(model.pk_corp);
            if (mod == null)
            {
                return Json("不存在的组织机构");
            }
            if (model.fathercode != "0")
            {
                var father = manger.GetById(model.fathercode);
                if (father == null)
                {
                    return Json("上级公司不存在，请重新选择");
                }
            }
            if (model.corpname.IsNullOrEmpty())
            {
                return Json("单位名称不能为空");
            }
            var model1 = manger.GetList(m => m.corpname == model.corpname&&m.pk_corp!=model.pk_corp).FirstOrDefault();
            if (model1 != null)
            {
                return Json("单位名称必须唯一");
            }
            if (model.sgn.IsNotNullAndEmpty())
            {
                var model2 = manger.GetList(m => m.sgn == model.sgn && m.pk_corp != model.pk_corp).FirstOrDefault();
                if (model2 != null)
                {
                    return Json("收据标识必须唯一");
                }
            }
            mod.corpname = model.corpname;
            mod.fathercode = model.fathercode;
            mod.unitshortname = model.unitshortname;
            mod.industry = model.industry;
            mod.legalbodycode = model.legalbodycode;
            mod.taxcode = model.taxcode;
            mod.saleaddr = model.saleaddr;
            mod.postaddr = model.postaddr;
            mod.phone1 = model.phone1;
            mod.createdate = model.createdate;
            mod.regcapital = model.regcapital;
            mod.idnumber = model.idnumber;
            mod.email1 = model.email1;
            mod.memo = model.memo;
            mod.sgn = model.sgn;
            var success = manger.Update(mod);
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");
            }
        }
        /// <summary>
        /// 删除组织机构
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("CorpsDelete")]
        public JsonResult CorpsDelete([FromBody] SingleParamDTO dto)
        {
            var manger = new corpsManager();
            var model = manger.GetById(dto.value);
            if(model==null)
            {
                return Json("该组织机构不存在，不能删除");
            }
            var success = manger.Delete(dto.value);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }
        }
        #endregion

        #region 部门档案
        /// <summary>
        /// 获取部门档案列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetDeptsList")]
        public JsonResult GetDeptsList()
        {
            var manger = new deptsManager();
            var list = manger.GetList();
            logger.Info($"【GetDeptsList】接口输出：{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }
        /// <summary>
        /// 根据单位编号获取部门实例
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetDepts")]
        public JsonResult GetDepts([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetDepts】接口输入：{JsonConvert.SerializeObject(dto)}");
            var manger = new deptsManager();
            var model = manger.GetList(m => m.DeptCode == dto.value).FirstOrDefault();
            logger.Info($"【GetDepts】接口输出：{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }
        /// <summary>
        /// 添加部门档案
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("DeptsAdd")]
        public JsonResult DeptsAdd([FromBody] depts model)
        {
            var manger = new deptsManager();
            if (model.DeptCode.IsNullOrEmpty())
            {
                return Json("编码不能为空");
            }
            var mod = manger.GetList(m => m.DeptCode ==model.DeptCode).FirstOrDefault();
            if (mod != null)
            {
                return Json("该编码已经存在");
            }
            if (model.FatherCode != "0")
            {
                var father = new corpsManager().GetById(model.FatherCode);
                if (father == null)
                {
                    return Json("上级部门不存在，请重新选择");
                }
            }
            if (model.DeptName.IsNullOrEmpty())
            {
                return Json("部门名称不能为空");
            }
            var model1 = manger.GetList(m => m.DeptName == model.DeptName).FirstOrDefault();
            if (model1 != null)
            {
                return Json("部门名称必须唯一");
            }

            var success = manger.Insert(model);
            if (success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");
            }
        }
        /// <summary>
        /// 修改部门档案
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("DeptsUpdate")]
        public JsonResult DeptsUpdate([FromBody] depts model)
        {
            logger.Info($"【CorpsUpdate】model:{JsonConvert.SerializeObject(model)}");
            var manger = new deptsManager();
            if (model.DeptCode.IsNullOrEmpty())
            {
                return Json("编码不能为空");
            }
            var mod = manger.GetList(m=>m.DeptCode== model.DeptCode).FirstOrDefault();
            if (mod == null)
            {
                return Json("不存在的部门");
            }
            if (model.FatherCode != "0")
            {
                var father = new corpsManager().GetById(model.FatherCode);
                if (father == null)
                {
                    return Json("上级部门不存在，请重新选择");
                }
            }
            if (model.DeptName.IsNullOrEmpty())
            {
                return Json("部门名称不能为空");
            }
            var model1 = manger.GetList(m => m.DeptName == model.DeptName && m.DeptCode != model.DeptCode&&m.FatherCode==model.FatherCode).FirstOrDefault();
            if (model1 != null)
            {
                return Json("部门名称必须唯一");
            }

            mod.DeptCode = model.DeptCode;
            mod.DeptName = model.DeptName;
            mod.FatherCode = model.FatherCode;
            mod.Director = model.Director;
            mod.Tel = model.Tel;
            mod.Fax = model.Fax;
            mod.Email = model.Email;
            mod.PostCode = model.PostCode;
            mod.Addr = model.Addr;

            var rows = manger.Db.Updateable(mod).WhereColumns(m => new { m.DeptCode }).ExecuteCommand();
            if (rows==1)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");
            }
        }
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("DeptsDelete")]
        public JsonResult DeptsDelete([FromBody] SingleParamDTO dto)
        {
            var manger = new deptsManager();
            var model = manger.GetList(m=>m.DeptCode==dto.value).FirstOrDefault();
            if (model == null)
            {
                return Json("该部门不存在，不能删除");
            }
            var rows = manger.Db.Deleteable<depts>().Where(m=>m.DeptCode==dto.value).ExecuteCommand();
            if (rows == 1)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }
        }
        #endregion

        #region 人员档案
        /// <summary>
        /// 用户信息查询
        /// </summary>
        /// <param name="DeptCode">部门代码</param>
        /// <param name="staffcode">用户唯一标识码</param>
        /// <param name="username">用户名</param>
        /// <param name="station">岗位代码</param>
        /// <param name="issystem">是否系统管理员</param>
        /// <param name="islock">用户是否锁定</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUsersList")]
        public JsonResult GetUsersList(string DeptCode, string staffcode, string username, string station, string issystem, string islock)
        {
            logger.Info($"【GetUsersList】DeptCode:{DeptCode},staffcode:{staffcode},username:{username},station:{station},issystem:{issystem},islock:{islock}");
            //logger.Info($"cookie:{GetCookies("userid")}");
            var user = JsonConvert.DeserializeObject<users>(GetCookies("userid"));
            var manager = new usersManager();
            issystem = user.IsSystem?.ToString();
            logger.Info($"issystem:{issystem}");
            var list = manager.GetUsersList(DeptCode, staffcode, username, station, issystem, islock);
            return Json(list);
        }

        /// <summary>
        /// 获取工号最大值
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetMaxStaffCode")]
        public JsonResult GetMaxStaffCode()
        {
            logger.Info($"【GetMaxStaffCode】获取工号最大值");
            var manager = new usersManager();
            var code = manager.GetMaxStaffCode();
            logger.Info($"【GetMaxStaffCode】MaxStaffCode:{code}");
            return Json(code);
        }

        /// <summary>
        /// 员工添加
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UsersAdd")]
        public JsonResult UsersAdd([FromBody] users users)
        {
            logger.Info($"【UsersAdd】users:{JsonConvert.SerializeObject(users)}");
            if (users.StaffCode.IsNullOrEmpty())
            {
                return Json("工号不能为空");
            }
            if (users.UserName.IsNullOrEmpty())
            {
                return Json("姓名不能为空");
            }
            if (users.Mobile.IsNullOrEmpty())
            {
                return Json("手机号不能为空");
            }
            if(!users.Mobile.IsCellPhone())
            {
                return Json("手机号格式不正确");
            }
            var success = new usersManager().Insert(users);
            logger.Info($"【UsersAdd】success:{success}");
            if (success)
            {
                return Json("插入成功");
            }
            else
            {
                return Json("插入失败");
            }
        }

        /// <summary>
        /// 根据工号获取单个员工信息
        /// </summary>
        /// <param name="staffcode">工号</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUsers")]
        public JsonResult GetUsers(string staffcode)
        {
            logger.Info($"【GetUsers】staffcode:{staffcode}");
            if(staffcode.IsNullOrEmpty())
            {
                return Json("工号不能为空");
            }
            var users = new usersManager().GetById(staffcode);
            if(users==null)
            {
                return Json("不存在的员工");
            }
            logger.Info($"【GetUsers】users:{JsonConvert.SerializeObject(users)}");
            return Json(users);
        }

        /// <summary>
        /// 员工修改
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UsersUpdate")]
        public JsonResult UsersUpdate([FromBody] users users)
        {
            logger.Info($"【UsersUpdate】users:{JsonConvert.SerializeObject(users)}");
            if (users.StaffCode.IsNullOrEmpty())
            {
                return Json("工号不能为空");
            }
            if (users.UserName.IsNullOrEmpty())
            {
                return Json("姓名不能为空");
            }
            if (users.Mobile.IsNullOrEmpty())
            {
                return Json("手机号不能为空");
            }
            if (!users.Mobile.IsCellPhone())
            {
                return Json("手机号格式不正确");
            }
            var manager = new usersManager();
            var users1 = manager.GetById(users.StaffCode);
            if(users1==null)
            {
                return Json("员工信息不存在，不能修改");
            }
            users1 = users;
            var success = manager.Update(users1);
            logger.Info($"【UsersUpdate】success:{success}");
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");
            }
        }

        /// <summary>
        /// 删除员工
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UsersDelete")]
        public JsonResult UsersDelete([FromBody] SingleParamDTO dto)
        {
            var manger = new usersManager();
            var model = manger.GetById( dto.value);
            if (model == null)
            {
                return Json("该员工不存在，不能删除");
            }
            var success = manger.Delete(model);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }
        }

        /// <summary>
        /// 设置员工状态
        /// </summary>
        /// <param name="staffcode">工号</param>
        /// <param name="status">状态：在岗，待岗，休班</param>
        /// <returns></returns>
        [HttpGet]
        [Route("SetStaffStatus")]
        public JsonResult SetStaffStatus(string staffcode,string status)
        {
            if(staffcode.IsNullOrEmpty())
            {
                return Json("工号不能为空");
            }
            string[] array = { "在岗", "待岗", "休班" };
            if (!array.Contains(status))
            {
                return Json("员工状态设置不正确");
            }
            var rows = new usersManager().SetStaffStatus(staffcode, status);
            if(rows>0)
            {
                return Json("状态设置成功");
            }
            else
            {
                return Json("状态设置失败");
            }
        }
        #endregion
    }
}
