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

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

        /// <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 async Task<IActionResult> GetListByPageAsync(string keyword, string projectid, string kindid, 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());

            List<string> kindids = new List<string>();
            if (!string.IsNullOrEmpty(kindid))
            {
                //获取物品分类id list<string>
                var listGoodType = (await _distri_goods_typerepository.Get(x => x.isdelete == 0));  //.ToList();
                if (!string.IsNullOrEmpty(projectid))
                    listGoodType = listGoodType.Where(x => x.projectid == projectid);   //.ToList();
                kindids = GetGoodsTypeIds(listGoodType.ToList(), kindid);
            }
            //获取数据
            int recordCount = 0;
            var result = _distri_goodsrepository.GetListsByPage(keyword, projectid, userinfo, kindids, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取配送物品列表 - 下拉
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="projectid"></param>
        /// <param name="kindid">物品分类</param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListAsync(string keyword, string projectid,string kindid)
        {
            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>();

            //获取物品分类id list<string>
            var listGoodType = (await _distri_goods_typerepository.Get(x => x.projectid == projectid)).ToList();
            List<string> kindids = GetGoodsTypeIds(listGoodType, kindid);
            //获取数据
            var result = _distri_goodsrepository.GetLists(keyword, projectid, userinfo, kindids);
            return Success("获取成功", result.ToList());
        }       

        /// <summary>
        /// 获取配送物品详情
        /// </summary>
        [HttpGet("getsingle")]
        public IActionResult GetSingleAsync(string id)
        {
            var model = _distri_goodsrepository.GetDetails(id);
            return Success("获取成功", model);
        }

        /// <summary>
        /// 添加配送物品
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string projectid, string kindid, string buildingid, string floorid, string goodsname, int typeid, bool isremind, string remark, int sortnum)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            #region 判断验证
            if (string.IsNullOrEmpty(projectid))
                return Error("请选择项目");
            if (string.IsNullOrWhiteSpace(kindid))
                return Error("请选择物品种类");
            if (typeid == 0)
                return Error("请选择紧急程度");
            #endregion

            var model = new Distri_Goods();
            #region model 添加配送物品对象
            model.projectid = projectid;
            model.kindid = kindid;
            model.typeid = typeid;
            model.goodsname = string.IsNullOrEmpty(goodsname) ? "" : Regex.Replace(goodsname, @"\s", "");
            model.isremind = isremind;
            model.remark = string.IsNullOrEmpty(remark) ? "" : Regex.Replace(remark, @"\s", "");
            model.buildingid = buildingid;
            model.floorid = floorid;
            model.sortnum = sortnum;
            model.createtby = usercode;
            #endregion
            bool bl = await _distri_goodsrepository.Add(model);
            if (bl)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        /// <summary>
        /// 修改配送物品
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string projectid, string kindid, string buildingid, string floorid, string goodsname, int typeid, bool isremind, string remark, int sortnum)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var model = (await _distri_goodsrepository.GetSingle(p => p.id == id));
            if (model != null)
            {
                #region 判断验证
                if (string.IsNullOrEmpty(projectid))
                    return Error("请选择项目");
                if (string.IsNullOrWhiteSpace(kindid))
                    return Error("请选择物品种类");
                if (typeid == 0)
                    return Error("请选择紧急程度");
                #endregion
                
                #region model 添加配送物品对象
                model.projectid = projectid;
                model.kindid = kindid;
                model.typeid = typeid;
                model.goodsname = string.IsNullOrEmpty(goodsname) ? "" : Regex.Replace(goodsname, @"\s", "");
                model.isremind = isremind;
                model.remark = string.IsNullOrEmpty(remark) ? "" : Regex.Replace(remark, @"\s", "");
                model.buildingid = buildingid;
                model.floorid = floorid;
                model.sortnum = sortnum;
                model.createtby = usercode;
                #endregion

                bool b = await _distri_goodsrepository.UpdateOne(model);
                if (b)
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
            return Error("操作失败");
        }        

        /// <summary>
        /// 删除配送物品
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //使用逻辑删除
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    var model = await _distri_goodsrepository.GetSingle(id);
                    model.isdelete = 1;
                    model.deleteby = usercode;
                    model.deletetime = DateTime.Now;
                    if (await _distri_goodsrepository.UpdateOne(model))
                    {
                        res += 1;
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败");
                else
                    return Error("删除失败");
            }
            else
                return Error("请选择要删除的记录");
        }

        #region 方法
        /// <summary>
       /// 获取物品分类id list<string> - 递归
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        List<string> listIds = new List<string>();
        public List<string> GetGoodsTypeIds(List<Distri_Goods_Type> list, string kindid)
        {
            string kindid_init = kindid;
            var lists = list.Where(x => x.parent_id == kindid).ToList();
            if (lists != null && lists.Count > 0)
            {
                //有多级子级
                foreach (var item in lists)
                {
                    if (item != null)
                    {
                        string id = item.id;
                        listIds.Add(item.id);
                        GetGoodsTypeIds(list, id);
                    }
                }
            }
            else {
                listIds.Add(kindid_init);
            }
            return listIds;
        }
        #endregion

    }
}