using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using CallCenterApi.IRepositories;
using Microsoft.Extensions.Logging;
using MadRunFabric.Model;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using MongoDB.Driver;
using MadRunFabric.Model.CallCenterApi;
using System.Security.Claims;
using SignTokenApi.IRepositories;
using CallCenterApi.Input;

namespace CallCenterApi.Controllers
{
    /// <summary>
    /// 客户控制器
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class CusUserController : BaseController
    {
        private readonly ILogger<CusUserController> _logger;
        private readonly ICus_User_BaseRepository _cus_user_baseRepository;

        public CusUserController(ILogger<CusUserController> logger, ICus_User_BaseRepository cus_user_baseRepository)
        {
            _logger = logger;
            _cus_user_baseRepository = cus_user_baseRepository;
        }

        /// <summary>
        /// 分页获取
        /// </summary>
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(string key, string typeid,string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _cus_user_baseRepository.GetListsByPage(key, typeid, stime, etime, pageindex, pagesize, out recordCount);

            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取客户
        /// </summary>
        [HttpGet("getsingle")]
        public IActionResult GetSingleAsync(string id)
        {
            var model = _cus_user_baseRepository.GetDetails(id);

            return Success("获取成功", model);
        }

        /// <summary>
        /// 添加客户
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(CusUserBaseInput input)
        {
            Cus_User_Base clmodel = new Cus_User_Base();

            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            clmodel.typeid = input.typeid;
            clmodel.province = input.province;//省
            clmodel.city = input.city;//市
            clmodel.name = input.name;
            clmodel.mobilephone = input.mobilephone;
            clmodel.telephone = input.telephone;
            clmodel.sex = input.sex;
            clmodel.address = input.address;
            clmodel.qq = input.qq;
            clmodel.email = input.email;
            clmodel.companyname = input.companyname;
            clmodel.companyphone = input.companyphone;
            clmodel.companyposition = input.companyposition;

            clmodel.createuser = optuser;
            clmodel.createusername = optusername;
            clmodel.isdelete = 0;
            clmodel.createtime = DateTime.Now;

            bool bl = await _cus_user_baseRepository.Add(clmodel);

            if (bl)
            {
                return Success("客户保存成功");
            }
            else
                return Error("客户保存失败");

        }

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

            var cls = await _cus_user_baseRepository.Get(p => p.id == input.id && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();

            clmodel.typeid = input.typeid;
            clmodel.province = input.province;//省
            clmodel.city = input.city;//市
            clmodel.name = input.name;
            clmodel.mobilephone = input.mobilephone;
            clmodel.telephone = input.telephone;
            clmodel.sex = input.sex;
            clmodel.address = input.address;
            clmodel.qq = input.qq;
            clmodel.email = input.email;
            clmodel.companyname = input.companyname;
            clmodel.companyphone = input.companyphone;
            clmodel.companyposition = input.companyposition;

            var res = await _cus_user_baseRepository.UpdateOne(clmodel);
            if (res)
            {
                return Success("客户保存成功");
            }
            else
                return Error("客户保存失败");
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(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)
                {
                    var ml = await _cus_user_baseRepository.GetSingle(id);
                    ml.isdelete = 1;
                    ml.deleteuser = optuser;
                    ml.deletetime = DateTime.Now;
                    if (await _cus_user_baseRepository.UpdateOne(ml))
                    {
                        res += 1;
                    }
                }
                if (res == ids.Length)
                    return Success("客户删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分客户删除失败");
                else
                    return Error("客户删除失败");
            }
            else
                return Error("请选择要删除的记录");
        }
    }
}
