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 Api.SignToken;
using DistributionApi.IRepositories;
using System.Security.Claims;
using MadRunFabric.Model;
using Microsoft.Extensions.Configuration;

namespace DistributionApi.Controllers
{
    /// <summary>
    /// 配送物品分类 - 省三院
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class DistriGoodsTypeController : BaseController
    {
        private readonly ILogger<DistriGoodsTypeController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly IDistri_Goods_TypeRepository _distri_goods_typerepository;
        private readonly IDistri_GoodsRepository _distri_goodsrepository;
        public DistriGoodsTypeController(
           ILogger<DistriGoodsTypeController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
           ISignTokenService signTokenService,
           IDistri_Goods_TypeRepository distri_goods_typerepository,
           IDistri_GoodsRepository distri_goodsrepository
           )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _signTokenService = signTokenService;
            _distri_goods_typerepository = distri_goods_typerepository;
            _distri_goodsrepository = distri_goodsrepository;
        }


        /// <summary>
        /// 获取物品分类列表 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public IActionResult GetListByPageAsync(string keyword, string projectid, int pageindex = 1, int pagesize = 10)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //获取数据
            int recordCount = 0;
            var result = _distri_goods_typerepository.GetListsByPage(keyword, projectid, userinfo, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取物品分类列表 - 下拉
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public IActionResult GetListAsync(string keyword, string projectid, int pageindex = 1, int pagesize = 10)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //获取数据
            var list = _distri_goods_typerepository.GetLists(keyword, projectid, userinfo).ToList();
            var treeList = new List<TreeGridModel>();

            foreach (var item in list)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = list.Count(t => t.parent_id == item.id.ToString()) == 0 ? false : true;
                treeModel.id = item.id.ToString();
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = item.parent_id;
                treeModel.expanded = hasChildren;
                treeModel.entityJson = item.ToJson();
                treeList.Add(treeModel);
            }
            var treeListJson = treeList.TreeGridJsonByParentId(null);
            return Content(treeList.TreeGridJsonByParentId(null));
        }


        /// <summary>
        /// 获取所有物品分类列表 - 树形下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListdrop(string projectid)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var list = (await _distri_goods_typerepository.Get(p => p.isdelete == 0)).ToList();
            if (!string.IsNullOrEmpty(projectid))
                list = list.Where(x => x.projectid == projectid).ToList();
            if (!string.IsNullOrEmpty(projectid))
                list = list.Where(x => x.projectid == projectid).ToList();
            if (userinfo.isallproject == 0)
                list = list.Where(it => userinfo.projectlist.Contains(it.projectid)).ToList();
            return Success("获取成功", GetTreeList(list, null));
        }

        /// <summary>
        /// 循环获取树结构
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public object GetTreeList(List<Distri_Goods_Type> list, string depid)
        {
            var children = list.Where(p => p.parent_id == depid).Select(p => new
            {
                p.id,
                p.projectid,
                p.kindname,
                p.sortnum,
                p.remark,
                children = GetTreeList(list, p.id)
            });

            return children;
        }

        /// <summary>
        /// 获取物品分类详情 by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = await _distri_goods_typerepository.GetSingle(id);
            if (model != null)
            {
                var result = new
                {
                    id = model.id,
                    parent_id = model.parent_id,
                    projectid = model.projectid,
                    kindname = model.kindname,
                    sortnum = model.sortnum,
                    remark = model.remark,
                    createtby = model.createtby,
                    createtime = model.createtime,
                };
                return Success("获取成功！", result);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加物品分类
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string parentid, string projectid, string kindname, int sortnum, string remark)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (string.IsNullOrEmpty(kindname))
                return Error("物品分类名称不能为空");
            var model = new Distri_Goods_Type();
            model.parent_id = parentid;
            model.projectid = projectid;
            model.kindname = kindname;
            model.sortnum = sortnum;
            model.remark = remark;
            model.createtby = usercode;
            model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _distri_goods_typerepository.Add(model);
            if (b)
                return Success("添加成功");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改物品分类信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="provincecode"></param>
        /// <param name="provincename"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string parentid, string projectid, string kindname, int sortnum, string remark)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            if (string.IsNullOrEmpty(kindname))
                return Error("物品分类名称不能为空");

            var model = new Distri_Goods_Type();
            model = await _distri_goods_typerepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.parent_id = parentid;
            model.projectid = projectid;
            model.kindname = kindname;
            model.sortnum = sortnum;
            model.remark = remark;
            bool b = await _distri_goods_typerepository.Update(model);
            if (b)
                return Success("保存成功");
            return Error("保存失败");
        }

        /// <summary>
        /// 删除物品分类信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var modelSun = await _distri_goods_typerepository.GetSingle(x => x.parent_id == item && x.isdelete == 0);
                    if (modelSun != null)
                        return Error("删除失败，此栏目下有子级信息");
                    var ml = await _distri_goods_typerepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deleteby = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_distri_goods_typerepository.Update(ml).Result)
                        res += 1;
                    //物品列表
                    var list_goods = await _distri_goodsrepository.Get(x => x.kindid == item);
                    foreach (var item_goods in list_goods)
                    {
                        var model_goods = await _distri_goodsrepository.GetSingle(item_goods.id);
                        model_goods.isdelete = 1;
                        model_goods.deleteby = usercode;
                        model_goods.deletetime = DateTime.Now.ToLocalTime();
                        await _distri_goodsrepository.Update(model_goods);
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }
    }
}