using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.report
{
    /// [Authority]
    public class QCResultController : BaseController
    {
        //质检报表

        List<string> arlist = new List<string>();
        DataTable dtNew = new DataTable();
        //获取表头
        public ActionResult GetColumnList(string isext)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            List<Model.QCModel> qclist = new List<Model.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);
            Model.QCModel qcm1 = new Model.QCModel();
            qcm1.Qcid = "cpr1";
            qcm1.Qcname = "测评人";
            qcm1.Rowspan = "4";
            Model.QCModel qcm2 = new Model.QCModel();
            qcm2.Qcid = "xm2";
            qcm2.Qcname = "姓名";
            qcm2.Rowspan = "4";
            Model.QCModel qcm3 = new Model.QCModel();
            qcm3.Qcid = "gh3";
            qcm3.Qcname = "工号";
            qcm3.Rowspan = "4";
            Model.QCModel qcm4 = new Model.QCModel();
            qcm4.Qcid = "zjts4";
            qcm4.Qcname = "质检条数";
            qcm4.Rowspan = "4";
            qclist.Add(qcm1);
            qclist.Add(qcm2);
            qclist.Add(qcm3);
            qclist.Add(qcm4);
            #endregion
            Model.QCModel qcmzf = new Model.QCModel();
            qcmzf.Qcid = "zf999";
            qcmzf.Qcname = "总分";
            qcmzf.Rowspan = "3";

            object obj = null;

            DataSet ds = DbHelperSQL.Query("select F_CategoryId,F_CategoryName,F_ParentId from T_QC_IndexCategory where F_DeleteFlag=0 order by F_CategoryId asc");
            DataTable dsConten = DbHelperSQL.Query("select F_IndexId,F_Content,F_Title,F_Score,F_CategoryId from T_QC_IndexBase order by F_IndexId asc").Tables[0];
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                DataRow[] drlist = dt.Select("F_ParentId=0");
                if (drlist != null)
                {
                    int ctsc = 0;//总分
                    for (int i = 0; i < drlist.Length; i++)
                    {
                        obj = DbHelperSQL.GetSingle("select count(*) from T_QC_IndexBase where F_CategoryId in(select F_CategoryId from T_QC_IndexCategory where F_ParentId=" + drlist[i]["F_CategoryId"] + ")");

                        Model.QCModel qcml = new Model.QCModel();
                        qcml.Qcid = drlist[i]["F_CategoryId"].ToString();
                        qcml.Qcname = drlist[i]["F_CategoryName"].ToString();
                        qcml.Colspan = obj.ToString();

                        //strColom1 += "<td colspan='" + obj.ToString() + "' style='height: 18px; background-color: #D5EDFE; border-left: 1px solid #CCCCCC; border-right: 1px solid #CCCCCC; border-top: 1px solid #CCCCCC; border-bottom: 1px solid #CCCCCC; padding: 3px 3px 3px 3px; text-align: center;'>" + drlist[i]["F_CategoryName"] + "</td>";
                        //strColom1 += "<td rowspan='3' style='height: 18px; background-color: #D5EDFE; border-left: 1px solid #CCCCCC; border-right: 1px solid #CCCCCC; border-top: 1px solid #CCCCCC; border-bottom: 1px solid #CCCCCC; padding: 3px 3px 3px 3px; text-align: center;'>分项得分</td>";

                        DataRow[] drlistnew = dt.Select("F_ParentId=" + drlist[i]["F_CategoryId"]);
                        if (drlistnew != null && drlist.Length > 0)
                        {
                            List<Model.QCModel> qcclist = new List<Model.QCModel>();
                            int sc = 0;
                            string strCatid = "";
                            for (int n = 0; n < drlistnew.Length; n++)
                            {
                                Model.QCModel qccml = new Model.QCModel();
                                obj = DbHelperSQL.GetSingle("select count(*) from T_QC_IndexBase where F_CategoryId=" + drlistnew[n]["F_CategoryId"]);
                                //strColom2 += "<td colspan='" + obj + "' style='height: 18px; background-color: #D5EDFE; border-left: 1px solid #CCCCCC; border-right: 1px solid #CCCCCC; border-top: 1px solid #CCCCCC; border-bottom: 1px solid #CCCCCC; padding: 3px 3px 3px 3px; text-align: center;'>" + drlistnew[n]["F_CategoryName"] + "</td>";
                                qccml.Qcid = drlist[i]["F_CategoryId"].ToString() + "-" + drlistnew[n]["F_CategoryId"].ToString();
                                qccml.Qcname = drlistnew[n]["F_CategoryName"].ToString();
                                qccml.Colspan = obj.ToString();

                                DataRow[] drContent = dsConten.Select("F_CategoryId=" + drlistnew[n]["F_CategoryId"]);
                                if (drContent != null && drContent.Length > 0)
                                {
                                    List<Model.QCModel> qccllist = new List<Model.QCModel>();
                                    for (int m = 0; m < drContent.Length; m++)
                                    {
                                        Model.QCModel qccmll = new Model.QCModel();
                                        qccmll.Qcid = drlist[i]["F_CategoryId"].ToString() + "-" + drlistnew[n]["F_CategoryId"].ToString() + "-" + drContent[m]["F_IndexId"].ToString();
                                        qccmll.Qcname = drContent[m]["F_Title"].ToString();
                                        qccmll.Qcscore = drContent[m]["F_Score"].ToString();
                                        //strColom3 += "<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;'>" + drContent[m]["F_Title"] + "</td>";
                                        //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;'>" + drContent[m]["F_Score"] + "</td>";
                                        if (!string.IsNullOrEmpty(drContent[m]["F_Score"].ToString()))
                                        {
                                            sc += int.Parse(drContent[m]["F_Score"].ToString());
                                        }

                                        strCatid += drContent[m]["F_IndexId"] + ",";

                                        DataColumn dc = new DataColumn("Q" + drContent[m]["F_IndexId"].ToString(), Type.GetType("System.String"));
                                        dtNew.Columns.Add(dc);

                                        qccllist.Add(qccmll);
                                    }

                                    qccml.Qclist = qccllist;
                                }
                                qcclist.Add(qccml);
                            }

                            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);

                            Model.QCModel qcml1 = new Model.QCModel();
                            qcml1.Qcid = "fx" + drlist[i]["F_CategoryId"].ToString();
                            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);
                        }

                    }

                    qcmzf.Qcscore = ctsc.ToString();
                }

            }

            qclist.Add(qcmzf);
            DataColumn dczf = new DataColumn("AllScore", Type.GetType("System.String"));
            dtNew.Columns.Add(dczf);
            if (isext != null && isext.Trim() != "")
            {
                //导出增加显示问题和建议
                Model.QCModel qcmlzj1 = new Model.QCModel();
                Model.QCModel qcmlzj2 = new Model.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);
            }

            res = Success("获取质检表头成功", qclist);

            return res;
        }

        //获取数据
        public ActionResult GetDataList(string stime, string endtime)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            Model.PageData<object> pagedata = new Model.PageData<object>();

            string dpt = RequestString.GetQueryString("dpt");
            string isext = RequestString.GetQueryString("isext");

            GetColumnList(isext);

            string sqltimeCallRecords = "";
            string strsql = "";
            if (stime != null && stime.Trim() != "")
            {
                sqltimeCallRecords += $" and DATEDIFF(S,'{stime.Trim()} 00:00:01' ,BeginTime)>=0 ";
            }
            if (endtime != null && endtime.Trim() != "")
            {
                sqltimeCallRecords += $" and DATEDIFF(S,'{endtime.Trim()} 23:59:59',BeginTime)<=0 ";
            }
            if (dpt != null && dpt.ToString() != "")
            {
                strsql = " and UserCode in(select F_UserCode from T_Sys_UserAccount where F_DeptId=" + dpt.ToString() + ") ";
            }


            //17=系统管理员,36=客服,37=组长,38=组员,39=业主,40=话务员,41=客服主管,43=分公司市场部主任,45=业务稽核,46=集团客户部,
            //47 =网络部,48=市场部经理,50=业务支撑中心,51=市场部,52=客户服务中心,53=总经理,54=副总经理,55=业务负责人,56=投诉处理员,57=基础业务主管,


            var deptId = CurrentUser.UserData.F_DeptId;
            var roleId = CurrentUser.UserData.F_RoleId;
            var deptCode = CurrentUser.UserData.F_DeptCode;
            var usercode = CurrentUser.UserData.F_UserCode;
            int[] deptArr = new int[] { 1, 4, 19, 20, 21 };
            int[] roleArr = new int[] { 50, 53, 54, 59 };
            if (roleId != 0)
            {
                if (roleId != 17)
                {
                    if (roleId == 36 || roleId == 38 || roleId == 40)
                    {
                        strsql += $" and UserCode='{usercode}'";
                    }
                    else if (!deptArr.Contains(deptId))
                    {
                        strsql += $" and UserCode in(select F_UserCode from T_Sys_UserAccount where F_DeptId={deptId}) ";
                    }
                    else
                    {
                        if (!roleArr.Contains(roleId))
                        {
                            strsql += $" and UserCode in(select F_UserCode from T_Sys_UserAccount where F_DeptId={deptId}) ";
                        }

                    }

                }
            }



            DataSet ds = DbHelperSQL.Query("select *,(select F_UserName from  T_Sys_UserAccount as b where b.F_UserCode=a.UserCode) as name,(select F_WorkNumber from  T_Sys_UserAccount as b where b.F_UserCode=a.UserCode) as wknmb from (select COUNT(*) as ct,UserCode from T_Call_CallRecords where F_QCState=1 " + sqltimeCallRecords + strsql + " group by  UserCode) as a order by wknmb asc");
            DataTable dtTitle = DbHelperSQL.Query("select F_IndexId from T_QC_IndexBase where F_DeleteFlag=0").Tables[0];
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                string strname = "";
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow drNew = dtNew.NewRow();

                    object obj = DbHelperSQL.GetSingle("select F_QCUserName from T_Call_CallRecords where UserCode=" + dr["UserCode"] + " and F_QCState=1 " + sqltimeCallRecords);
                    if (obj != null)
                    {
                        strname = obj.ToString();
                    }
                    else
                    {
                        strname = "";
                    }
                    drNew["QCName"] = strname;
                    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 UserCode=" + dr["UserCode"] + " " + 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();
                    if (isext != null && isext.Trim() != "")
                    {
                        string question = "";
                        string advise = "";
                        DataSet dss = DbHelperSQL.Query("select * from T_Call_CallRecords where UserCode=" + dr["UserCode"] + " 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);
                }
            }

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

            return res;
        }
    }
}