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 DistributionApi.Models.Input;
using MadRunFabric.Model;
using DistributionApi.Model.Dto;

namespace DistributionApi.Controllers
{
    /// <summary>
    /// 配送地址管理 - 不用了
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class DistriAddressController : BaseController
    {
        private readonly ILogger<DistriAddressController> _logger;
        private readonly ISignTokenService _signTokenService;
        private readonly IDistri_AddressRepository _distri_adressrepository;
        private readonly ISys_DepartmentRepository _sys_departmentpository;
        public DistriAddressController(
           ILogger<DistriAddressController> logger,
           ISignTokenService signTokenService,
           IDistri_AddressRepository distri_adressrepository,
           ISys_DepartmentRepository sys_departmentpository
           )
        {
            _logger = logger;
            _signTokenService = signTokenService;
            _distri_adressrepository = distri_adressrepository;
            _sys_departmentpository = sys_departmentpository;
        }

        /// <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, string buildingid, string floorid,int addresstype = -1, 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>();

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

        /// <summary>
        /// 获取地址列表 - 下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlist")]
        public IActionResult GetListAsync(string keyword, string projectid, int addresstype = -1)
        {
            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 result = _distri_adressrepository.GetLists(keyword, projectid, userinfo, addresstype);

            #region 遍历计算 - 科室表不用，楼层备注为科室
            ////所有科室
            //var listDep = (await _sys_departmentpository.Get(x => x.isdelete == 0)).ToList();
            //var list = new List<Distri_AddressDto>();
            //foreach (var item in result)
            //{
            //    //初始化全局变量
            //    deptmentNames = string.Empty;
            //    var deptmentNames_Item = GetDeptmentNames(listDep, item.departmentid);
            //    #region 倒序排序
            //    //定义临时变量
            //    string strRestult = "";
            //    string[] split = deptmentNames_Item.Split(new char[] { '|' }, 2);
            //    for (int i = split.Length - 1; i >= 0; i--)
            //    {
            //        strRestult += split[i] + "|";
            //    }
            //    strRestult = strRestult.TrimEnd(new char[] { '|' });
            //    #endregion
            //    item.departmentname = strRestult;
            //    list.Add(item);
            //}
            #endregion
            return Success("获取成功", result.ToList());
        }

        /// <summary>
        /// 循环获取科室名称（一级|二级|三级...）
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        string deptmentNames = "";
        public string GetDeptmentNames(List<Sys_Department> list, string depid)
        {            
            string pid = "";
            var model = list.FirstOrDefault(x => x.id == depid);
            if (model != null)
            {
                pid = model.parent_id;
                deptmentNames += model.departmenname + "|";
                GetDeptmentNames(list, pid);
            }
            deptmentNames = deptmentNames.TrimEnd(new char[] { '|' });
            return deptmentNames;
        }

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

        /// <summary>
        /// 添加地址
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(DistriAddressInput input)
        {
            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(input.projectid))
                return Error("请选择项目");
            if (string.IsNullOrWhiteSpace(input.fullname))
                return Error("请输入客户姓名");
            if (string.IsNullOrEmpty(input.mobile))
                return Error("请输入来电电话");
            #endregion

            var model = new Distri_Address();
            //判断是否有默认地址，如果没有添加时设置为默认地址
            var list_addresstype = (await _distri_adressrepository.Get(x => x.addresstype == model.addresstype && x.createtby == usercode && x.isdefault == true && x.isdelete == 0)).ToList();    //x.createtby == usercode && 
            #region model 添加地址对象

            model.isdefault = input.isdefault;
            if (list_addresstype != null && list_addresstype.Count > 0)
            {
                if (input.isdefault)
                {
                    foreach (var item in list_addresstype)
                    {
                        item.isdefault = false;
                        await _distri_adressrepository.UpdateOne(item);
                    }
                }
            }
            else
            {
                model.isdefault = true;
            }
            model.addresstype = input.addresstype;
            model.projectid = input.projectid;
            model.buildingid = input.buildingid;
            model.floorid = input.floorid;
            //model.departmentid = input.departmentid;    //不用了
            model.fullname = input.fullname;
            model.mobile = input.mobile;
            model.remark = input.remark;
            model.sortnum = input.addresstype;
            model.createtby = usercode;
            #endregion
            bool bl = await _distri_adressrepository.Add(model);
            if (bl)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        /// <summary>
        /// 修改地址
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(DistriAddressInput input)
        {
            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_adressrepository.GetSingle(p => p.id == input.id));
            if (model != null)
            {
                #region 判断验证
                if (string.IsNullOrEmpty(input.projectid))
                    return Error("请选择项目");
                if (string.IsNullOrWhiteSpace(input.fullname))
                    return Error("请输入客户姓名");
                if (string.IsNullOrEmpty(input.mobile))
                    return Error("请输入来电电话");
                #endregion
                
                //判断是否有默认地址，如果没有添加时设置为默认地址
                var list_addresstype = (await _distri_adressrepository.Get(x => x.addresstype == model.addresstype && x.createtby == usercode && x.isdefault == true && x.isdelete == 0)).ToList();    //x.createtby == usercode && 
                #region model 添加地址对象

                model.isdefault = input.isdefault;
                if (input.isdefault)
                {
                    if (list_addresstype != null && list_addresstype.Count > 0)
                    {
                        foreach (var item in list_addresstype)
                        {
                            item.isdefault = false;
                            await _distri_adressrepository.UpdateOne(item);
                        }
                    }
                }
                model.addresstype = input.addresstype;
                model.projectid = input.projectid;
                model.buildingid = input.buildingid;
                model.floorid = input.floorid;
                //model.departmentid = input.departmentid;    //不用了
                model.fullname = input.fullname;
                model.mobile = input.mobile;
                model.remark = input.remark;
                model.sortnum = input.addresstype;
                #endregion

                bool b = await _distri_adressrepository.UpdateOne(model);
                if (b)
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
            return Error("操作失败");
        }
        
        /// <summary>
        /// 设置默认地址
        /// </summary>
        [HttpPost("UpdateDefault")]
        public async Task<IActionResult> UpdateDefaultAsync(string id)
        {
            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_adressrepository.GetSingle(p => p.id == id));

            var list_addresstype = (await _distri_adressrepository.Get(x => x.addresstype == model.addresstype && x.createtby == usercode && x.isdefault == true && x.isdelete == 0)).ToList();    //p.createtby == usercode &&
            if (list_addresstype != null && list_addresstype.Count>0)
            {
                foreach (var item in list_addresstype)
                {
                    item.isdefault = false;
                    bool b = await _distri_adressrepository.UpdateOne(item);
                }
            }
            if (model != null)
            {
                model.isdefault = true;
                bool b = await _distri_adressrepository.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_adressrepository.GetSingle(id);
                    model.isdelete = 1;
                    model.deleteby = usercode;
                    model.deletetime = DateTime.Now;
                    if (await _distri_adressrepository.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("请选择要删除的记录");
        }

    }
}