using System;
using System.Collections.Generic;
using System.Common;
using System.Common.Helpers;
using System.IRepositories;
using System.Linq;
using System.Linq.Expressions;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.Traffic
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SetMobileDataController : BaseController
    {
        private readonly ISys_MobileDataRepository _sys_mobiledataRepository;
        public SetMobileDataController(ISys_MobileDataRepository sys_mobiledataRepository)
        {
            _sys_mobiledataRepository = sys_mobiledataRepository;
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string key, int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });

            if (!string.IsNullOrEmpty(key))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_MobileNum", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_ZipCode", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_CityDes", ConditionalType = ConditionalType.Like, FieldValue = key }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_CardDes", ConditionalType = ConditionalType.Like, FieldValue = key })
                    }
                });
            }
            #endregion
            int recordCount = 0;
            var list = await _sys_mobiledataRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "F_CreateOn desc");

            return Success("成功", list);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetails(int id)
        {
            if (id > 0)
            {
                var dModel = await _sys_mobiledataRepository.GetSingle(x => x.F_Id == id && x.F_State == (int)EnumUserCountState.Enabled);

                if (dModel != null)
                {
                    return Success("获取基础数据成功", dModel);
                }
                else
                {
                    return Error("获取基础数据失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 添加基础数据
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> Add(MobileDataInput input)
        {
            #region 验证
            if (string.IsNullOrEmpty(input.mobilenum))
            {
                return Error("号段不能为空");
            }
            if (string.IsNullOrEmpty(input.zipcode))
            {
                return Error("区号不能为空");
            }
            if (string.IsNullOrEmpty(input.citydes))
            {
                return Error("城市不能为空");
            }
            if (string.IsNullOrEmpty(input.carddes))
            {
                return Error("卡类型不能为空");
            }
            if (await GetExistByCodeAsync(input.mobilenum, 0))
                return Error("已存在此号段的记录，请重新输入！");
            #endregion
            T_Sys_MobileData clmodel = new T_Sys_MobileData();
            clmodel.F_MobileNum = input.mobilenum.Trim();
            clmodel.F_ZipCode = input.zipcode.Trim();
            clmodel.F_CityDes = input.citydes.Trim();
            clmodel.F_CardDes = input.carddes.Trim();

            clmodel.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
            clmodel.F_CreateOn = DateTime.Now;
            clmodel.F_State = (int)EnumUserCountState.Enabled;

            var res = await _sys_mobiledataRepository.Add(clmodel);
            if (res > 0)
                return Success("保存成功");
            else
            {
                return Error("保存失败");
            }
        }

        /// <summary>
        /// 修改基础数据
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> Edit(MobileDataInput input)
        {
            #region
            if (input.id <= 0)
                return Error("请选择要编辑的数据");
            if (string.IsNullOrEmpty(input.mobilenum))
            {
                return Error("号段不能为空");
            }
            if (string.IsNullOrEmpty (input.zipcode))
            {
                return Error("区号不能为空");
            }
            if (string.IsNullOrEmpty(input.citydes))
            {
                return Error("城市不能为空");
            }
            if (string.IsNullOrEmpty(input.carddes))
            {
                return Error("卡类型不能为空");
            }
            if (await GetExistByCodeAsync(input.mobilenum, input.id))
                return Error("已存在此号段的记录，请重新输入！");
            #endregion

            var clmodel = await _sys_mobiledataRepository.GetSingle(x => x.F_Id == input.id && x.F_State == (int)EnumUserCountState.Enabled);
            if (clmodel == null)
                return Error("信息获取失败");
            clmodel.F_MobileNum = input.mobilenum.Trim();
            clmodel.F_ZipCode = input.zipcode.Trim();
            clmodel.F_CityDes = input.citydes.Trim();
            clmodel.F_CardDes = input.carddes.Trim();

            clmodel.F_LastModifyBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            clmodel.F_LastModifyOn = DateTime.Now;

            var res = await _sys_mobiledataRepository.Update(clmodel);

            if (res)
                return Success("基础数据保存成功");
            else
            {
                return Error("基础数据保存失败");
            }
        }

        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_mobiledataRepository.GetSingle(x => x.F_Id == item);
                    ml.F_State = (int)EnumUserCountState.Delete;
                    ml.F_DeleteBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    ml.F_DeleteOn = DateTime.Now;
                    if (await _sys_mobiledataRepository.Update(ml))
                        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="input"></param>
        /// <returns></returns>
        [HttpPost("importmobile")]
        public async Task<IActionResult> ImportMobile()
        {
            Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
            if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={_upfile.ContentType}");

            //将数据导入数据库
            int headrow = 0;
            NPOIHelper npoi = new NPOIHelper();
            var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            if (dtExcel.Rows.Count <= 0)
                return Error("请选择要导入的文件");

            IList<MobileDataInput> IMobileDatas = ModelConvertHelper<MobileDataInput>.ConvertToModel(dtExcel);
            List<MobileDataInput> MobileDatas = ModelConvertHelper<MobileDataInput>.ConvertIListToList(IMobileDatas);
            int num = MobileDatas.Count;
            List<MobileDataInput> inputlist = new List<MobileDataInput>();

            foreach (MobileDataInput input in MobileDatas)
            {
                Expression<Func<T_Sys_MobileData, bool>> eq = a => a.F_MobileNum == input.mobilenum;
                eq = eq.Or(b => b.F_ZipCode == input.zipcode);
                //eq = eq.Or(b => b.F_ZipCode == input.zipcode);
                //eq = eq.Or(b => b.F_CityDes == input.citydes);
                //eq = eq.Or(b => b.F_CardDes == input.carddes);
                if (await _sys_mobiledataRepository.GetCount(eq) > 0)
                {
                    return Error("号段 有重复:" + input.mobilenum);
                }
                inputlist.Add(input);
            }
            if (await AddForInput(inputlist))
            {
                return Success("已导入数据");
            }
            else
            {
                return Error("导入失败");
            }

        }

        #region 私有方法
        /// <summary>
        /// 根据基础数据编号查询是否存在此基础数据编号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private async Task<bool> GetExistByCodeAsync(string code, int id)
        {
            long c = 0;
            if (id > 0)
                c = await _sys_mobiledataRepository.GetCount(x => x.F_MobileNum.Equals(code) && x.F_Id != id && x.F_State == (int)EnumUserCountState.Enabled);
            else
                c = await _sys_mobiledataRepository.GetCount(x => x.F_MobileNum.Equals(code) && x.F_State == (int)EnumUserCountState.Enabled);

            return c > 0;
        }

        private async Task<bool> AddForInput(List<MobileDataInput> inputs)
        {
            List<T_Sys_MobileData> inputlist = new List<T_Sys_MobileData>();
            foreach (var input in inputs)
            {
                T_Sys_MobileData clmodel = new T_Sys_MobileData();
                clmodel.F_MobileNum = input.mobilenum.Trim();
                clmodel.F_ZipCode = input.zipcode.Trim();
                clmodel.F_CityDes = input.citydes.Trim();
                clmodel.F_CardDes = input.carddes.Trim();

                clmodel.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                clmodel.F_CreateOn = DateTime.Now;
                clmodel.F_State = (int)EnumUserCountState.Enabled;
                inputlist.Add(clmodel);
            }
            if (await _sys_mobiledataRepository.AddMany(inputlist))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
    }
}