using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using AutoMapper.Configuration;
using ConfigurationApi.IRepositories;
using MadRunFabric.Model;
using System.Security.Claims;
using ConfigurationApi.Models;

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// 部门  本接口应该没有用   张琨20201115鉴定
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class DepartmentBaseController : BaseController
    {
        private readonly ILogger<DepartmentBaseController> _logger;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISys_DepartmentBaseRepository _sys_departmentbaserepository;
        public DepartmentBaseController(
            ILogger<DepartmentBaseController> logger,
            ISys_User_AccountRepository sys_user_accountRepository,
            ISys_DepartmentBaseRepository sys_departmentbaserepository
            )
        {
            _logger = logger;
            _sys_user_accountRepository = sys_user_accountRepository;
            _sys_departmentbaserepository = sys_departmentbaserepository;
        }

        /// <summary>
        /// 获取树结构
        /// </summary>
        [HttpGet("gettreelist")]
        public async Task<IActionResult> GetTreeListAsync()
        {
            var list = (await _sys_departmentbaserepository.Get(p => p.isdelete == 0)).ToList();
            return Success("获取成功", GetTreeList(list, null));
        }

        /// <summary>
        /// 循环获取树结构
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public object GetTreeList(List<Sys_DepartmentBase> list, string pid)
        {
            var children = list.Where(p => p.parentid == pid).Select(p => new
            {
                p.id,
                p.departmenname,
                p.sortnum,
                p.parentid,
                children = GetTreeList(list, p.id)
            });
            return children;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetTypeSingleAsync(string id)
        {
            var model = await _sys_departmentbaserepository.GetSingle(id);
            var names = await GetNameListAsync(model.id, "tts");    //获取名称
            var ids = await GetNameListAsync(model.id, "ids");      //获取ids
            var obj = new
            {
                model,
                depids = ids.Split(","),
                depnames = names.Split(",")
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 循环获取分类名称和id ("部门1", "部门2")
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type">type：tts获取名称,ids获取id</param>
        /// <returns></returns>
        public async Task<string> GetNameListAsync(string id, string type)
        {
            string str = string.Empty;
            var depinfo = await _sys_departmentbaserepository.GetSingle(id);
            if (depinfo != null)
            {
                if (depinfo.parentid != null)
                {
                    str = await GetNameListAsync(depinfo.parentid, type);
                }
                if (string.IsNullOrEmpty(str))
                {
                    if (type == "tts")
                        str = depinfo.departmenname;
                    else
                        str = depinfo.id;
                }
                else
                {
                    if (type == "tts")
                        str += "," + depinfo.departmenname;
                    else
                        str += "," + depinfo.id;
                }
            }
            return str;
        }

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(DepartmentBaseInput input)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            if (string.IsNullOrEmpty(input.departmenname))
            {
                return Error("名称不能为空");
            }
            var model = new Sys_DepartmentBase();
            model.departmenname = input.departmenname;
            model.code = input.code;
            model.parentid = input.parentid;
            model.mobile = input.mobile;
            model.telephone = input.telephone;
            model.remark = input.remark;
            model.sortnum = input.sortnum;

            model.createtby = optuser;
            model.createbyname = optusername;
            model.createtime = DateTime.Now;
            bool bl = await _sys_departmentbaserepository.Add(model);
            if (bl)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateTypeAsync(DepartmentBaseInput input)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            if (string.IsNullOrEmpty(input.departmenname))
            {
                return Error("名称不能为空");
            }
            var model = await _sys_departmentbaserepository.GetSingle(p => p.id == input.id && p.isdelete == 0);
            model.departmenname = input.departmenname;
            model.code = input.code;
            model.parentid = input.parentid;
            model.mobile = input.mobile;
            model.telephone = input.telephone;
            model.remark = input.remark;
            model.sortnum = input.sortnum;

            model.updateby = optuser;
            model.updatetime = DateTime.Now;
            bool bl = await _sys_departmentbaserepository.UpdateOne(model);
            if (bl)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");            
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveTypeAsync(string[] ids, int channel = 1)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    if (await DeleteTypeAsync(id, optuser))
                    {
                        res += 1;
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败");
                else
                    return Error("删除失败");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 循环删除分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteTypeAsync(string id, string usercode)
        {
            bool bl = false;
            var model = await _sys_departmentbaserepository.GetSingle(id);
            if (model != null)
            {
                var zlist = await _sys_departmentbaserepository.Get(p => p.parentid == model.id && p.isdelete == 0);
                foreach (var z in zlist)
                {
                    await DeleteTypeAsync(z.id, usercode);
                }
                model.isdelete = 1;
                model.deleteby = usercode;
                model.deletetime = DateTime.Now;
                bl = await _sys_departmentbaserepository.UpdateOne(model);
            }
            return bl;
        }
               
    }
}