using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace TVShoppingCallCenter_ZLJ.Controllers.IndexCategory
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class IndexBaseController : BaseController
    {
        private readonly IQC_IndexCategoryReposytory _qc_indexcategoryreposytory;
        private readonly IQC_IndexBaseReposytory _qc_indexbasereposytory;
        public IndexBaseController(IQC_IndexCategoryReposytory qc_indexcategoryreposytory, IQC_IndexBaseReposytory qc_indexbasereposytory)
        {
            _qc_indexcategoryreposytory = qc_indexcategoryreposytory;
            _qc_indexbasereposytory = qc_indexbasereposytory;
        }
        /// <summary>
        /// 添加指标
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(T_QC_IndexBase input)
        {
            if (input.F_Sort > 100000)
            {
                return Error("排序过大，请重新输入");
            }
            if (input.F_CategoryId <= 0)
            {
                return Error("请选择指标分类");
            }
            if (input.F_Score <= 0)
            {
                return Error("请输入分值");
            }
          //  string user = "8000";
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            input.F_CreateOn = DateTime.Now;
            input.F_CreateBy = user;
            input.F_DeleteFlag = 0;
            var res = await _qc_indexbasereposytory.Add(input);
            if (res > 0)
            {
                SetScoreByCategory((int )input.F_CategoryId, (int) input.F_Score, 0);
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }
        /// <summary>
        /// 修改指标
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(T_QC_IndexBase input)
        {
            if (input.F_IndexId <=0)
            {
                return Error("请选择指标");
            }
            if (input.F_Sort > 100000)
            {
                return Error("排序过大，请重新输入");
            }
            if (input.F_CategoryId <= 0)
            {
                return Error("请选择指标分类");
            }
            if (input.F_Score <= 0)
            {
                return Error("请输入分值");
            }
             string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var model = await _qc_indexbasereposytory.GetSingle(x => x.F_IndexId  == input.F_IndexId);

            if (model == null)
                return Error("操作失败");
            input.F_DeleteFlag = 0;
            input.F_CreateBy = model.F_CreateBy;
            input.F_CreateOn = model.F_CreateOn;
            input.F_ModifyBy = user;
            input.F_ModifyOn = DateTime .Now ;
            var b = await _qc_indexbasereposytory.Update(input);
            if (b)
            {
                try
                {
                    SetScoreByCategory((int)input.F_CategoryId, (int)input.F_Score, 1, (int)model.F_Score);
                }
                catch
                {

                }
                return Success("修改成功");
            }
            return Error("修改失败");
        }
       
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int id = 0)
        {

            var model = _qc_indexbasereposytory.GetSingle(x => x.F_IndexId  == id).Result;
            if (model == null)
                return Error("该指标不存在");
            model.F_DeleteFlag = (int)EnumUserCountState.Delete;

            bool n = _qc_indexbasereposytory.Update(model).Result;
            if (n)
            {
                try
                {
                    SetScoreByCategory((int)model.F_CategoryId, (int)model.F_Score, 2);
                }
              catch
                {

                }
                return Success("删除成功");
            }
               
            else
                return Error("删除失败");
        }
        /// <summary>
        /// 获取指标列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListMark(string keyword,int pid=-1,int  pageindex = 0, int pagesize = 0)
        {
            // string user = "8000";

            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_DeleteFlag", ConditionalType = ConditionalType.Equal, FieldValue = "0" });
            if (!string.IsNullOrEmpty(keyword))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_Title", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_Content", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                         new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_Remark", ConditionalType = ConditionalType.Like, FieldValue = keyword })
                    }
                });
            }
            if (pid > -1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_CategoryId", ConditionalType = ConditionalType.In, FieldValue = CategoryId(pid) });
            }
            #endregion
            int recordCount = 0;
            if (pageindex > 0 && pagesize > 0)
            {
                var list = await _qc_indexbasereposytory.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "  F_CreateOn  desc")  ;
                var result = list.Rows .Select(x => new {

                    x.F_CategoryId,
                    F_CategoryName = _qc_indexcategoryreposytory.GetSingle(z => z.F_CategoryId == x.F_CategoryId).Result
                   != null ? _qc_indexcategoryreposytory.GetSingle(z => z.F_CategoryId == x.F_CategoryId).Result.F_CategoryName : "",
                    x.F_Content,
                    x.F_Remark,
                    x.F_Title,
                    x.F_Score,
                    x.F_Sort ,
                    x.F_IndexId,
                });
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = result,
                    total = list.Totals,
                };
                return Content(obj.ToJson());
            }
            else
            {
                var list = await _qc_indexbasereposytory.GetListALL(conModels, " F_CreateOn  desc");
                var result = list.Select(x => new {

                    x.F_CategoryId ,
                    F_CategoryName= _qc_indexcategoryreposytory.GetSingle (z =>z .F_CategoryId == x.F_CategoryId).Result 
                    !=null ? _qc_indexcategoryreposytory.GetSingle(z => z.F_CategoryId == x.F_CategoryId).Result.F_CategoryName :"",
                    x.F_Content ,
                    x.F_Remark ,
                    x.F_Title ,
                    x.F_Score ,
                    x.F_Sort,
                    x.F_IndexId ,
                });
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = result,
                    total = list.Count(),
                };
                return Content(obj.ToJson());
            }
        }
       
      
        private string CategoryId(int parentid)
        {
            var iv = _qc_indexcategoryreposytory.GetSingle (x => x.F_CategoryId  == parentid && x.F_DeleteFlag == 0).Result;
            string modelList = parentid + "";
            if (iv != null)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                conModels.Add(new ConditionalModel() { FieldName = "F_DeleteFlag", ConditionalType = ConditionalType.Equal, FieldValue = "0" });
                conModels.Add(new ConditionalModel() { FieldName = "F_Expand2", ConditionalType = ConditionalType.Like, FieldValue = iv .F_Expand2  });
                var list = _qc_indexcategoryreposytory.GetListALL(conModels, " F_CreateOn  desc").Result ;
                if (list !=null )
                {
                    foreach (var it in list)
                    {
                        modelList += "," + it.F_CategoryId;
                    }
                }
            }
            return modelList;
        }

        /// <summary>
        /// 获取指标详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _qc_indexbasereposytory.GetSingle(x => x.F_IndexId  == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            List<string> CategoryId = new List<string>();
            List<string> F_CategoryName = new List<string>();
            var result =new {

                CategoryId = Category(model.F_CategoryId, 0, CategoryId),
                F_CategoryName = Category(model.F_CategoryId, 1, F_CategoryName),
                model.F_Content,
                model.F_Remark,
                model.F_Title,
                model.F_Score,
                model .F_Sort ,
                model.F_IndexId,
            };
           
            return Success("获取成功！", result);
        }
        public List<string> Category(int? CategoryId, int type, List<string> key)
        {
            var model = _qc_indexcategoryreposytory.GetSingle(x => x.F_CategoryId == CategoryId).Result;
            if (model != null)
            {
                if (type == 0)
                {
                    key.Add("" + CategoryId);
                    if (model.F_ParentId > 0)
                    {
                        key = Category((int)model.F_ParentId, 0, key);
                    }
                }
                else
                {
                    key.Add(model.F_CategoryName);
                    if (model.F_ParentId > 0)
                    {
                        key = Category((int)model.F_ParentId, 1, key);
                    }
                }
            }
            return key;
        }
        //设置指标分数
        private void SetScoreByCategory(int  categoryid, int source, int type=0,int F_Score=0)
        {
          
            try
            {
                var model = _qc_indexcategoryreposytory.GetSingle(x => x.F_CategoryId == categoryid).Result;

                if (model != null)
                {
                    if (type ==0)
                    {
                        int a = int.Parse(model.F_Expand1) + source;
                        model.F_Expand1 += a.ToString();
                    }
                    else if (type == 1)
                    {
                        int a = int.Parse(model.F_Expand1)- F_Score + source;
                        model.F_Expand1 += a.ToString();
                    }
                    else
                    {
                        int a = int.Parse(model.F_Expand1) -source;
                        model.F_Expand1 += a.ToString();
                    }
                    int parentid = 0;
                    if (model.F_ParentId!=null )
                        parentid = (int )model.F_ParentId;
                   
                    int score = 0;
                   
                    model.F_Expand1 = score.ToString();
                    if (_qc_indexcategoryreposytory.Update(model).Result )
                    {
                        if (parentid != 0)
                        {
                            SetScoreByCategory(parentid, source, type);
                        }
                    }
                }
            }
            catch { }
        }

    }
}