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

namespace CallCenterApi.Controllers
{
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class QCManageController : BaseController
    {
        private readonly ILogger<QCManageController> _logger;
        private readonly IQC_CheckTypeRepository _qc_checktypeRepository;
        private readonly IQC_CheckScoreRepository _qc_checkscoreRepository;
        private readonly IQC_CheckListRepository _qc_checklistRepository;
        private readonly ISys_User_AccountRepository _sys_useraccountRepository;
        private readonly ICall_RecordsRepository _call_recordsRepository;

        public QCManageController(ILogger<QCManageController> logger, IQC_CheckTypeRepository qc_checktypeRepository,
            IQC_CheckScoreRepository qc_checkscoreRepository, IQC_CheckListRepository qc_checklistRepository, ISys_User_AccountRepository sys_useraccountRepository, ICall_RecordsRepository call_recordsRepository)
        {
            _logger = logger;
            _qc_checktypeRepository = qc_checktypeRepository;
            _qc_checkscoreRepository = qc_checkscoreRepository;
            _qc_checklistRepository = qc_checklistRepository;
            _sys_useraccountRepository = sys_useraccountRepository;
            _call_recordsRepository = call_recordsRepository;
        }

        #region 质检分类
        /// <summary>
        /// 获取列表
        /// </summary>
        [HttpGet("gettypelist")]
        public async Task<IActionResult> GetTypeListAsync()
        {
            var list = await _qc_checktypeRepository.Get(p => p.isdelete == 0);

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

        /// <summary>
        /// 获取树结构
        /// </summary>
        [HttpGet("gettypetreelist")]
        public async Task<IActionResult> GetTypeTreeListAsync()
        {
            var list = (await _qc_checktypeRepository.Get(p => p.isdelete == 0)).ToList();

            return Success("获取成功", gettreeinfo(list, null));
        }

        /// <summary>
        /// 循环获取树结构
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public object gettreeinfo(List<QC_CheckType> list, string pid)
        {
            var children = list.Where(p => p.parentid == pid).Select(p => new
            {
                p.id,
                p.name,
                p.sort,
                p.parentid,
                children = gettreeinfo(list, p.id)
            });

            return children;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        [HttpGet("gettypesingle")]
        public async Task<IActionResult> GetTypeSingleAsync(string id)
        {
            var model = await _qc_checktypeRepository.GetSingle(id);

            var obj = new {
                model,
                levelid= (await GetTypeIDAsync(model.id)).Split(","),
                levelname= (await GetTypeNameAsync(model.id)).Split(",")
            };

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

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost("addtype")]
        public async Task<IActionResult> AddTypeAsync(string parentid, string name, string remark, int sort)
        {
            if (string.IsNullOrEmpty(name))
            {
                return Error("名称不能为空");
            }

            QC_CheckType clmodel = new QC_CheckType();

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

            clmodel.parentid = parentid;
            clmodel.name = name;
            clmodel.remark = remark;
            clmodel.sort = sort;

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

            bool bl = await _qc_checktypeRepository.Add(clmodel);

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

        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("updatetype")]
        public async Task<IActionResult> UpdateTypeAsync(string id, string parentid, string name, string remark, int sort)
        {
            if (string.IsNullOrEmpty(name))
            {
                return Error("名称不能为空");
            }

            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 _qc_checktypeRepository.Get(p => p.id == id && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();

            clmodel.parentid = parentid;
            clmodel.name = name;
            clmodel.remark = remark;
            clmodel.sort = sort;

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

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deletetype")]
        public async Task<IActionResult> RemoveTypeAsync(string[] ids, int channel = 1)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    if (await DeleteTypeAsync(id, optuser))
                    {
                        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="typeid"></param>
        /// <returns></returns>
        public async Task<bool> DeleteTypeAsync(string typeid, string usercode)
        {
            bool bl = false;
            var typeinfo = await _qc_checktypeRepository.GetSingle(typeid);
            if (typeinfo != null)
            {
                //if (typeinfo.parentid != null)
                //{
                //    await DeleteTypeAsync(typeinfo.parentid, usercode);
                //}

                var zlist = await _qc_checktypeRepository.Get(p => p.parentid == typeinfo.id && p.isdelete == 0);
                foreach (var z in zlist)
                {
                    await DeleteTypeAsync(z.id, usercode);
                }

                typeinfo.isdelete = 1;
                typeinfo.deleteuser = usercode;
                typeinfo.deletetime = DateTime.Now;
                bl = await _qc_checktypeRepository.UpdateOne(typeinfo);
            }

            return bl;
        }

        /// <summary>
        /// 循环获取分类名称
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public async Task<string> GetTypeNameAsync(string typeid)
        {
            string type = string.Empty;
            var typeinfo = await _qc_checktypeRepository.GetSingle(typeid);
            if (typeinfo != null)
            {
                if (typeinfo.parentid != null)
                {
                    type = await GetTypeNameAsync(typeinfo.parentid);
                }
                if (string.IsNullOrEmpty(type))
                {
                    type = typeinfo.name;
                }
                else
                {
                    type += "," + typeinfo.name;
                }
            }

            return type;
        }

        /// <summary>
        /// 循环获取分类id
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public async Task<string> GetTypeIDAsync(string typeid)
        {
            string type = string.Empty;
            var typeinfo = await _qc_checktypeRepository.GetSingle(typeid);
            if (typeinfo != null)
            {
                if (typeinfo.parentid != null)
                {
                    type = await GetTypeIDAsync(typeinfo.parentid);
                }
                if (string.IsNullOrEmpty(type))
                {
                    type = typeinfo.id;
                }
                else
                {
                    type += "," + typeinfo.id;
                }
            }

            return type;
        }

        #endregion

        #region 质检分类指标
        /// <summary>
        /// 获取列表
        /// </summary>
        [HttpGet("gettypescorelist")]
        public IActionResult GetTypeScoreList(string typeid, string key)
        {
            var list = _qc_checkscoreRepository.GetList(key.Trim (), typeid);

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

        /// <summary>
        /// 获取详情
        /// </summary>
        [HttpGet("gettypescoresingle")]
        public IActionResult GetTypeScoreSingle(string id)
        {
            var model = _qc_checkscoreRepository.GetDetails(id);
            var ml = _qc_checkscoreRepository.GetSingle(id).Result;
            var obj = new
            {
                model,
                levelid = GetTypeIDAsync(ml.typeid).Result.Split(","),
                levelname = GetTypeNameAsync(ml.typeid).Result.Split(",")
            };

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

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost("addtypescore")]
        public async Task<IActionResult> AddTypeScoreAsync(string typeid, string title, string content, int score, string remark, int sort)
        {
            if (string.IsNullOrEmpty(title))
            {
                return Error("标题不能为空");
            }

            QC_CheckScore clmodel = new QC_CheckScore();

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

            clmodel.typeid = typeid;
            clmodel.title = title;
            clmodel.content = content;
            clmodel.score = score;
            clmodel.remark = remark;
            clmodel.sort = sort;

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

            bool bl = await _qc_checkscoreRepository.Add(clmodel);

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

        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("updatetypescore")]
        public async Task<IActionResult> UpdateTypeScoreAsync(string id, string typeid, string title, string content, int score, string remark, int sort)
        {
            if (string.IsNullOrEmpty(title))
            {
                return Error("标题不能为空");
            }

            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 _qc_checkscoreRepository.Get(p => p.id == id && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();

            clmodel.typeid = typeid;
            clmodel.title = title;
            clmodel.content = content;
            clmodel.score = score;
            clmodel.remark = remark;
            clmodel.sort = sort;

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

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deletetypescore")]
        public async Task<IActionResult> RemoveTypeScoreAsync(string[] ids, int channel = 1)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    var modelinfo = await _qc_checkscoreRepository.GetSingle(id);
                    modelinfo.isdelete = 1;
                    modelinfo.deleteuser = optuser;
                    modelinfo.deletetime = DateTime.Now;

                    if (await _qc_checkscoreRepository.UpdateOne(modelinfo))
                    {
                        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>
        [HttpGet("gettypescoretreelist")]
        public async Task<IActionResult> GetTypeTreescoreList()
        {
            var typelist = (await _qc_checktypeRepository.Get(p => p.isdelete == 0)).ToList();
            var scorelist = (await _qc_checkscoreRepository.Get(p => p.isdelete == 0)).ToList();
            var list = typelist.Where(p => p.parentid == null).Select(p =>
            {
                var tlist = typelist.Where(s => s.parentid == p.id).Select(s =>
                 {
                     var slist = scorelist.Where(o => o.typeid == s.id);
                     return new
                     {
                         s.name,
                         s.sort,
                         score = slist.Sum(o => o.score),
                         qcscore = 0,
                         item = slist.Select(o => new
                         {
                             name = o.title,
                             o.sort,
                             o.score,
                             qcscore = 0
                         }).OrderBy(o => o.sort)
                     };
                 }).OrderBy(s => s.sort);

                return new
                {
                    p.name,
                    p.sort,
                    score = tlist.Sum(s => s.score),
                    qcscore = 0,
                    item = tlist
                };
            }).OrderBy(p => p.sort);

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

        /// <summary>
        /// 获取树结构
        /// </summary>
        [HttpGet("gettypescoretreelistbak")]
        public async Task<IActionResult> GetTypeTreescoreListbak()
        {
            var typelist = (await _qc_checktypeRepository.Get(p => p.isdelete == 0)).ToList();
            var scorelist = (await _qc_checkscoreRepository.Get(p => p.isdelete == 0)).ToList();

            return Success("获取成功", getscoretreeinfo(typelist, scorelist, null));
        }

        /// <summary>
        /// 循环获取树结构
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public object getscoretreeinfo(List<QC_CheckType> typelist, List<QC_CheckScore> scorelist, string pid)
        {
            var children = typelist.Where(p => p.parentid == pid).Select(p => new
            {
                p.id,
                p.name,
                p.sort,
                p.parentid,
                scoreitem = scorelist.Where(s => s.typeid == p.id),
                children = getscoretreeinfo(typelist, scorelist, p.id)
            });

            return children;
        }

        #endregion

        #region 质检通话记录

        /// <summary>
        /// 分页获取
        /// </summary>
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(string usercode, string telephone, string stime, string etime, int calltype = -1,
            int checktype = -1, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _qc_checklistRepository.GetListsByPage(usercode.Trim (), calltype, telephone.Trim (), checktype, stime, etime, pageindex, pagesize, out recordCount);

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

        /// <summary>
        /// 获取详情
        /// </summary>
        [HttpGet("getsingle")]
        public IActionResult GetSingle(string id)
        {
            var model = _qc_checklistRepository.GetDetails(id);

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

        /// <summary>
        /// 质检通话记录
        /// </summary>
        [HttpPost("setscore")]
        public async Task<IActionResult> SetScoreAsync(string recordid, List<result> result, string remark)
        //public async Task<IActionResult> SetScoreAsync(string recordid, string results, string remark)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //var result = results.ToList<result>();
            result.ForEach(x =>
            {
                x.item.ForEach(y =>
                {
                    y.qcscore = y.item.Sum(p => p.qcscore);
                    y.score = y.item.Sum(p => p.score);
                });
                x.qcscore = x.item.Sum(p => p.qcscore);
                x.score = x.item.Sum(p => p.score);
            });

            bool bl = false;

            QC_CheckList clmodel = (await _qc_checklistRepository.Get(p => p.recordid == recordid)).FirstOrDefault();
            if (clmodel == null)
            {
                clmodel = new QC_CheckList();
                clmodel.recordid = recordid;
                clmodel.result = result;
                clmodel.remark = remark;
                clmodel.totalscore = result.Sum(p => p.score);
                clmodel.qctotalscore = result.Sum(p => p.qcscore);

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

                bl = await _qc_checklistRepository.Add(clmodel);

            }
            else
            {
                clmodel.result = result;
                clmodel.remark = remark;
                clmodel.totalscore = result.Sum(p => p.score);
                clmodel.qctotalscore = result.Sum(p => p.qcscore);

                bl = await _qc_checklistRepository.UpdateOne(clmodel);
            }

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

        }

        #endregion

        #region 报表

        /// <summary>
        /// 获取坐席统计数据
        /// </summary>
        /// <param name="monthdate"></param>
        /// <param name="isadmin"></param>
        /// <returns></returns>
        [HttpGet("getseattotal")]
        public IActionResult GetSeatTotal(string monthdate, int isadmin = 1)
        {
            string optuser = isadmin != 1 ? User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value : string.Empty;

            string start = string.Empty;
            string end = string.Empty;
            if (string.IsNullOrEmpty(monthdate))
            {
                start = DateTime.Now.ToString("yyyy-MM") + "-01";
                end = DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {
                start = monthdate + "-01";
                end = DateTime.Parse(start).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            }

            var result = _qc_checklistRepository.GetSeatTotal(start, end, optuser);

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

        /// <summary>
        /// 获取坐席月度排行
        /// </summary>
        /// <param name="monthdate"></param>
        /// <returns></returns>
        [HttpGet("getseatmonthrank")]
        public IActionResult GetSeatMonthRank(string monthdate, int isadmin = 1)
        {
            string optuser = isadmin != 1 ? User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value : string.Empty;

            string start = string.Empty;
            string end = string.Empty;
            if (string.IsNullOrEmpty(monthdate))
            {
                start = DateTime.Now.ToString("yyyy-MM") + "-01";
                end = DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {
                start = monthdate + "-01";
                end = DateTime.Parse(start).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            }

            var result = _qc_checklistRepository.GetSeatMonthRank(start, end, optuser);

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

        /// <summary>
        /// 获取坐席月度分布图
        /// </summary>
        /// <param name="monthdate"></param>
        /// <returns></returns>
        [HttpGet("getseatmonthchart")]
        public IActionResult GetSeatMonthChart(string monthdate)
        {
            string start = string.Empty;
            string end = string.Empty;
            if (string.IsNullOrEmpty(monthdate))
            {
                start = DateTime.Now.ToString("yyyy-MM") + "-01";
                end = DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {
                start = monthdate + "-01";
                end = DateTime.Parse(start).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            }

            var result = _qc_checklistRepository.GetSeatMonthChart(start, end);

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

        #endregion

        #region 坐席质检数据报表
        List<string> arlist = new List<string>();
        DataTable dtNew = new DataTable();
        //获取表头
        [HttpGet("getcolumnlist")]
        public async Task<IActionResult> GetColumnList(string isext)
        {
            var res= Error("获取质检表头失败");
            List<QCModel> qclist = new List<QCModel>();

            #region 加载固定项
            DataColumn dc1 = new DataColumn("QCName", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("UserName", Type.GetType("System.String"));
            DataColumn dc3 = new DataColumn("UserCode", Type.GetType("System.String"));
            DataColumn dc4 = new DataColumn("ZJCount", Type.GetType("System.String"));
            dtNew.Columns.Add(dc1);
            dtNew.Columns.Add(dc2);
            dtNew.Columns.Add(dc3);
            dtNew.Columns.Add(dc4);
            QCModel qcm1 = new QCModel();
            qcm1.Qcid = "cpr1";
            qcm1.Qcname = "测评人";
            qcm1.Rowspan = "4";
            QCModel qcm2 = new QCModel();
            qcm2.Qcid = "xm2";
            qcm2.Qcname = "姓名";
            qcm2.Rowspan = "4";
            QCModel qcm3 = new QCModel();
            qcm3.Qcid = "gh3";
            qcm3.Qcname = "工号";
            qcm3.Rowspan = "4";
            QCModel qcm4 = new QCModel();
            qcm4.Qcid = "zjts4";
            qcm4.Qcname = "质检条数";
            qcm4.Rowspan = "4";
            qclist.Add(qcm1);
            qclist.Add(qcm2);
            qclist.Add(qcm3);
            qclist.Add(qcm4);
            #endregion
            QCModel qcmzf = new QCModel();
            qcmzf.Qcid = "zf999";
            qcmzf.Qcname = "总分";
            qcmzf.Rowspan = "3";

            object obj = null;

            #region
            //根据条件查询集合
            var list = new List<FilterDefinition<QC_CheckType>>();
            list.Add(Builders<QC_CheckType>.Filter.Eq("isdelete", 0));
            list.Add(Builders<QC_CheckType>.Filter.Where(s => s.parentid.Equals (null )));
            
            var filter = Builders<QC_CheckType>.Filter.And(list);
            var tasklist = await _qc_checktypeRepository.Get(filter, null, null );
            var tlist = tasklist.ToList();
            int ctsc = 0;//总分
            int i = 0;
            foreach (var item in tlist)
            {

                QCModel qcml = new QCModel();
                qcml.Qcid = item.id;
                qcml.Qcname = item.name;
                qcml.Colspan = _qc_checktypeRepository.Count(x => x.parentid == item.id && x.isdelete == 0).ToString();
                var list1 = await _qc_checktypeRepository.Get(x => x.parentid == item.id && x.isdelete == 0);
                var clist = list1.ToList();
                if (clist.Count > 0)
                {
                    List<QCModel> qcclist = new List<QCModel>();
                    int sc = 0;
                    string strCatid = "";
                    foreach (var citem in clist)
                    {

                        QCModel qccml = new QCModel();
                        qccml.Qcid = item.id + "-" + citem.id;
                        qccml.Qcname = citem.name;
                        qccml.Colspan = _qc_checkscoreRepository.Count(x => x.typeid == item.id && x.isdelete == 0).ToString();
                        var list2 = await _qc_checkscoreRepository.Get(x => x.typeid == item.id && x.isdelete == 0);
                        var cclist = list2.ToList();
                        List<QCModel> qccllist = new List<QCModel>();
                        foreach (var ccitem in cclist)
                        {

                            QCModel qcccml = new QCModel();
                            qcccml.Qcid = item.id + "-" + citem.id + "-" + ccitem.id;
                            qcccml.Qcname = ccitem.title;
                            qcccml.Qcscore = ccitem.score.ToString();
                            qcccml.Colspan = _qc_checkscoreRepository.Count(x => x.typeid == item.id && x.isdelete == 0).ToString();
                            if (!string.IsNullOrEmpty(ccitem.score.ToString()))
                            {
                                sc += int.Parse(ccitem.score.ToString());
                            }

                            strCatid += ccitem.id + ",";

                            DataColumn dc = new DataColumn("Q" + ccitem.id, Type.GetType("System.String"));
                            dtNew.Columns.Add(dc);

                            qccllist.Add(qcccml);

                        }
                    }
                    if (strCatid != "")
                    {
                        strCatid.Substring(0, strCatid.Length - 1);
                    }
                    arlist.Add(strCatid); //每一组的题id记下来，用在分数总和上。
                                          //strColom4 += "<td  align='center'style='border-top: 0px solid #CCCCCC; border-bottom: 1px solid #CCCCCC; border-left: 1px solid #CCCCCC; border-right: 1px solid #CCCCCC; padding-left: 2px; height: 18px; padding-top: 3px; padding-bottom: 3px;'>" + sc.ToString() + "</td>";
                    ctsc += sc;


                    qcml.Qclist = qcclist;
                    qclist.Add(qcml);

                    QCModel qcml1 = new QCModel();
                    qcml1.Qcid = "fx" + item.id;
                    qcml1.Qcname = "分项得分";
                    qcml1.Rowspan = "3";
                    qcml1.Qcscore = sc.ToString();
                    qclist.Add(qcml1);
                    DataColumn dcdf = new DataColumn("df" + i.ToString(), Type.GetType("System.String"));
                    dtNew.Columns.Add(dcdf);
                    i++;
                }
            }
            qcmzf.Qcscore = ctsc.ToString();
            #endregion

            qclist.Add(qcmzf);
            DataColumn dczf = new DataColumn("AllScore", Type.GetType("System.String"));
            dtNew.Columns.Add(dczf);
            if (isext != null && isext.Trim() != "")
            {
                //导出增加显示问题和建议
                QCModel qcmlzj1 = new QCModel();
                QCModel qcmlzj2 = new QCModel();
                qcmlzj1.Qcid = "wt99";
                qcmlzj1.Qcname = "问题";
                qcmlzj1.Rowspan = "4";
                qclist.Add(qcmlzj1);
                qcmlzj2.Qcid = "jy99";
                qcmlzj2.Qcname = "建议";
                qcmlzj2.Rowspan = "4";
                qclist.Add(qcmlzj2);
                DataColumn dcwt = new DataColumn("Question", Type.GetType("System.String"));
                dtNew.Columns.Add(dcwt);
                DataColumn dcjy = new DataColumn("Advise", Type.GetType("System.String"));
                dtNew.Columns.Add(dcjy);
            }
            if (qclist != null)
            {
                res = Success("获取质检表头成功", qclist);
            }
            return res;
            
        }

        //获取数据
        public async Task<IActionResult> GetDataList(string stime, string endtime,string dpt,string isext, int pageindex, int pagesize)
        {
            var res = Error("获取质检数据失败");
            //Model.PageData<object> pagedata = new Model.PageData<object>();

            //await GetColumnList(isext);

            string sqltimeCallRecords = "";
            string strsql = "";
            //排序字段
            var sort = Builders<Call_OutTask>.Sort.Descending("createtime");

            //根据条件查询集合
            var list = new List<FilterDefinition<Call_OutTask>>();
            list.Add(Builders<Call_OutTask>.Filter.Eq("deleteflag", 0));
            if (stime != null)
                list.Add(Builders<Call_OutTask>.Filter.Gt("createtime", stime.Trim() + " 00:00:01"));
            if (endtime != null)
                list.Add(Builders<Call_OutTask>.Filter.Lt("createtime", endtime.Trim() + " 23:59:59"));

            if (dpt != null && dpt.ToString() != "")
            {
                strsql = " and UserId in(select F_UserId from T_Sys_UserAccount where F_DeptId=" + dpt.ToString() + ") ";
            }
            int totalcount = 0;
            var result = _qc_checklistRepository.GetLists(dpt,stime ,endtime, pageindex,  pagesize, out totalcount);
            var lists = result.ToList();

            #region
            /*string strname = "";
            foreach (var item in lists)
            {
                DataRow drNew = dtNew.NewRow();
                drNew["QCName"] = ;
                drNew["UserName"] = dr["name"].ToString();
                drNew["UserCode"] = dr["wknmb"].ToString();

                int ct = 0;
                if (dr["ct"] != null && dr["ct"].ToString() != "")
                {
                    ct = int.Parse(dr["ct"].ToString());//评价数量
                }
                drNew["ZJCount"] = dr["ct"].ToString();

                double itemfs = 0;//每一大项分数和
                double ctfs = 0;//总分

                for (int i = 0; i < arlist.Count; i++)
                {
                    string strList = arlist[i];
                    string[] strTitleList = strList.Split(',');
                    foreach (string str in strTitleList)
                    {
                        if (str != "")
                        {
                            double fs = 0;//每一项分数
                            obj = DbHelperSQL.GetSingle("select sum(F_QCScore) from T_QC_IndexRes where CallRecordsId in (select CallRecordsId from T_Call_CallRecords where F_QCState=1 and UserId=" + dr["UserId"] + " " + sqltimeCallRecords + ") and F_IndexId=" + str);
                            if (obj != null && obj.ToString() != "")
                            {
                                if (ct != 0)
                                {//评价数量不为0
                                    if (int.Parse(obj.ToString()) % ct == 0)
                                    {
                                        fs = int.Parse(obj.ToString()) / ct; //每一项分数
                                    }
                                    else
                                    {
                                        fs = double.Parse(obj.ToString()) / double.Parse(ct.ToString());
                                    }
                                }
                            }
                            string mm = "";
                            if (fs.ToString().IndexOf('.') > -1 && fs.ToString().Substring(fs.ToString().IndexOf('.') + 1).Length > 2)
                            {
                                mm = fs.ToString("0.00");
                            }
                            else
                            {
                                mm = fs.ToString();
                            }
                            drNew["Q" + str] = mm;
                            itemfs += fs;
                        }
                    }
                    string imm = "";
                    if (itemfs.ToString().IndexOf('.') > -1 && itemfs.ToString().Substring(itemfs.ToString().IndexOf('.') + 1).Length > 2)
                    {
                        imm = itemfs.ToString("0.00");
                    }
                    else
                    {
                        imm = itemfs.ToString();
                    }
                    drNew["df" + i.ToString()] = imm;
                    ctfs += itemfs;
                    itemfs = 0;
                }
                //drNew["AllScore"] = ((int)ctfs).ToString();
                drNew["AllScore"] = ctfs.ToString();
                if (isext != null && isext.Trim() != "")
                {
                    string question = "";
                    string advise = "";
                    DataSet dss = DbHelperSQL.Query("select * from T_Call_CallRecords where UserId=" + dr["UserId"] + " and F_QCState=1 " + sqltimeCallRecords);
                    if (dss.Tables[0].Rows.Count > 0)
                    {
                        for (int ii = 0; ii < dss.Tables[0].Rows.Count; ii++)
                        {
                            question += dss.Tables[0].Rows[ii]["F_QCQuestion"].ToString() + ";";
                            advise += dss.Tables[0].Rows[ii]["F_QCAdvise"].ToString() + ";";
                        }
                    }
                    drNew["Question"] = question;
                    drNew["Advise"] = advise;
                }
                ctfs = 0;

                dtNew.Rows.Add(drNew);
            }*/
            #endregion

            res = Success("获取质检数据成功", lists);

            return res;
        }
    }
    #endregion
}
