using CallCenter.Utility;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.callout
{
    public class PagerAnswerWXController : BaseController
    {
        private readonly BLL.T_Call_OutTask otBLL = new BLL.T_Call_OutTask();
        private readonly BLL.T_Call_OutTaskTelNum otnBLL = new BLL.T_Call_OutTaskTelNum();
        private readonly BLL.T_Call_OutAnswers ansBLL = new BLL.T_Call_OutAnswers();
        private readonly BLL.T_Ask_Question questionBLL = new BLL.T_Ask_Question();
        private readonly BLL.T_Ask_PagerInfo pagerInfoBLL = new BLL.T_Ask_PagerInfo();

        private readonly BLL.T_Ask_QuestionItems questionItemBLL = new BLL.T_Ask_QuestionItems();

        private readonly BLL.T_Call_OutTelNumWX otnwxBLL = new BLL.T_Call_OutTelNumWX();
        private readonly BLL.T_Call_OutTelNumWXRecords otrwxBLL = new BLL.T_Call_OutTelNumWXRecords();
        private readonly BLL.T_Call_OutAnswersWX answxBLL = new BLL.T_Call_OutAnswersWX();

        #region 获取微信提交的问卷列表
        public ActionResult GetWJList(string key, string sdate, string edate, int pagesize = 10, int pageindex = 1)
        {
            StringBuilder sb = new StringBuilder();
            #region
            sb.Append(" and F_DeleteFlag=0 ");
            if (!string.IsNullOrWhiteSpace(key))
            {
                sb.Append(" and (F_CusName like '%" + key.Trim() + "%' or F_Phone like '%" + key.Trim() + "%' or F_TelPhone like '%" + key.Trim() + "%')");
            }
            if (!string.IsNullOrWhiteSpace(sdate))
                sb.Append(" and DATEDIFF(day,F_CreateTime,'" + sdate.Trim() + "')<=0");
            if (!string.IsNullOrWhiteSpace(edate))
                sb.Append(" and DATEDIFF(day,F_CreateTime,'" + edate.Trim() + "')>=0");
            #endregion
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Call_OutTelNumWX",
                    "F_Id",
                    "*",
                    sb.ToString(),
                    "ORDER BY F_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        #endregion

        #region 获取微信提交的问卷详情
        public ActionResult GetWXTelInfo(int telid = 0)
        {
            if (telid <= 0)
                return Error("参数不正确");
            var model = otnwxBLL.GetModel(telid);

            var paperid = 0;
            if (model != null)
            {
                var taskmodel = new CallPlanNewDto();
                #region 绑定信息
                taskmodel.F_CusID = model.F_CusID.Value;//客户id                
                taskmodel.F_CityID = model.F_CountryId.Value;//乡镇id                
                taskmodel.F_CusName = model.F_CusName;//客户姓名                
                taskmodel.F_Phone = model.F_Phone;//号码                
                taskmodel.F_Telephone = model.F_TelPhone;//手机号码        
                taskmodel.F_City = model.F_Country;//乡镇   
                taskmodel.F_Address = model.F_Address;//住址
                taskmodel.F_Id = model.F_Id;//号码id

                #endregion

                var anslist = answxBLL.GetModelList(" F_CusTelID=" + telid + " ");
                paperid = model.F_PagerId.Value;
                #region 获取问卷试题信息以及答案
                var pmodel = pagerInfoBLL.GetModel(paperid);
                var qlist = questionBLL.GetModelList(" F_DeleteFlag=0 and F_QuestionId in (select F_QuestionId from T_Ask_PagerItems where F_PagerId=" + paperid + ")  order by F_QuestionId ");
                var qilist = questionItemBLL.GetModelList(" F_QuestionId in (select F_QuestionId from T_Ask_PagerItems where F_PagerId=" + paperid + ")  order by F_ItemId ");
                var newmodel = new
                {
                    F_Title = pmodel.F_Title,
                    F_Remark = pmodel.F_Remark,
                    F_StartText = pmodel.F_StartText,
                    F_EndText = pmodel.F_EndText,
                    F_Questions = qlist.Select(q =>
                    {
                        var answers = "";
                        var qalist = anslist.Where(al => al.F_QID.Value == q.F_QuestionId).ToList<Model.T_Call_OutAnswersWX>();
                        if (qalist.Count > 0)
                        {
                            if (q.F_Type > 1)
                            {
                                foreach (var item in qalist)
                                {
                                    answers += item.F_QIID + "|";
                                }
                            }
                            else
                            {
                                answers = qalist[0].F_Answer;
                            }
                        }
                        return new
                        {
                            quesid = q.F_QuestionId,
                            questitle = q.F_Title,
                            questype = q.F_Type,
                            quescontent = q.F_Content,
                            quesremark = q.F_Remark,
                            quesanswers = answers.Trim('|'),
                            quesitems = qilist.Where(qq => qq.F_QuestionId == q.F_QuestionId).Select(qi =>
                            {
                                return new
                                {
                                    itemid = qi.F_ItemId,
                                    itemname = qi.F_ItemName,
                                    itemremark = qi.F_Remark,
                                };
                            })
                        };
                    })
                };
                #endregion

                var objy = new
                {
                    taskModel = taskmodel,
                    paperModel = newmodel
                };
                return Success("获取详情成功", objy);
            }
            return Error("获取详情失败");
        }
        #endregion

        #region 微信端提交问卷
        /// <summary>
        /// 微信端提交问卷
        /// </summary>
        /// <param name="telphone"></param>
        /// <param name="openid"></param>
        /// <param name="ans"></param>
        /// <param name="name"></param>
        /// <param name="phone"></param>
        /// <param name="countryid"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        public bool AnswersWX(string telphone, string openid, string[] ans,
            string name, string phone, string countryid, string address,Model.T_Sys_Users users)
        {
            int cc = 0;int telid = 0;string dateflag = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            if (!string.IsNullOrWhiteSpace(telphone))
            {
                var otnModel = new Model.T_Call_OutTelNumWX();
                #region 添加问卷提交
                otnModel.F_TelPhone = telphone;
                otnModel.F_Phone = phone;
                otnModel.F_CusName = name;
                if (!string.IsNullOrWhiteSpace(countryid.Trim()))
                {
                    otnModel.F_CountryId = int.Parse(countryid.Trim());
                    var countryconfig = new BLL.T_Sys_DictionaryValue().GetModel(otnModel.F_CountryId.Value);
                    if (countryconfig != null)
                        otnModel.F_Country = countryconfig.F_Name;
                }
                otnModel.F_Address = address;
                otnModel.F_Openid = openid;
                otnModel.F_PagerId = int.Parse(Configs.GetValue("WXPagerID")); ;
                otnModel.F_DeleteFlag = 0;

                otnModel.F_CusID = 0;
                otnModel.F_CreateTime = DateTime.Now;
                telid = otnwxBLL.Add(otnModel);
                #endregion
                //微信端提交的问卷不做保存客户档案记录
                //int cusid = saveCus(otnModel.F_Phone, name, phone, countryid, address);

                #region 保存答案
                var ansModel = new Model.T_Call_OutAnswersWX();
                string askqids = "";
                string ansids = "";
                if (ans != null)
                {
                    ansModel.F_PagerID = otnModel.F_PagerId;
                    ansModel.F_CusID = 0;
                    ansModel.F_CusTelID = telid;
                    if (users != null)
                    {
                        ansModel.F_OptBy = users.F_Id;
                        ansModel.F_OptByOpenid = users.F_OpenId;
                    }
                    ansModel.F_OptOn = DateTime.Now;
                    ansModel.F_Expand1 = countryid.ToString();
                    ansModel.F_Expand3 = dateflag;
                    #region 循环保存
                    foreach (var item in ans)
                    {
                        var nn = 0;
                        var ii = item.Split('_');
                        ansModel.F_QID = int.Parse(ii[0]);

                        askqids += ii[0] + ",";
                        ansids += ii[1] + ",";

                        if (ii[1].IndexOf('|') > 0)
                        {
                            var iii = ii[1].Trim('|').Split('|');
                            var iia = ii[2].Trim('|').Split('|');
                            for (int i = 0; i < iii.Length; i++)
                            {
                                ansModel.F_QIID = int.Parse(iii[i]);
                                ansModel.F_Answer = iia[i];
                                if (answxBLL.Add(ansModel) > 0)
                                    nn++;
                            }
                            if (nn == iii.Length)
                                cc++;
                        }
                        else
                        {
                            ansModel.F_QIID = int.Parse(ii[1]);
                            ansModel.F_Answer = ii[2];
                            if (answxBLL.Add(ansModel) > 0)
                                cc++;
                        }
                    }
                    #endregion

                    #endregion
                    #region  保存日志

                    otnModel.F_AskRes = askqids;
                    otnModel.F_AskInfo = ansids;
                    otnwxBLL.Update(otnModel);

                    planrecord(otnModel);
                    #endregion
                }
            }
            if (ans != null)
            {
                if (cc == ans.Length)
                {
                    return true;
                }
                else
                {
                    answxBLL.DeleteByTelid(telid, dateflag);
                    //return Error("问卷提交失败！");
                    return false;
                }
            }
            else
            {
                return false;
                //return Error("没有问卷答案提交");
            }
        }
        #endregion

        #region 工单关联问卷多选题的内容
        public ActionResult GetSel(int telid)
        {
            if (telid <= 0)
                return Error("参数不正确");
            var model = otnBLL.GetModel(telid);

            var paperid = 0;
            if (model != null)
            {
                var anslist = ansBLL.GetModelList(" F_TaskID=" + model.F_TaskId.Value + " and F_CusTelID=" + telid + " ");
                var tmodel = otBLL.GetModel(model.F_TaskId.Value);
                if (tmodel != null)
                {
                    paperid = tmodel.F_PagerID.Value;
                    #region 获取多选题目以及答案
                    var qlist = questionBLL.GetModelList(" F_DeleteFlag=0 and F_QuestionId in (select F_QuestionId from T_Ask_PagerItems where F_PagerId=" + paperid + ") order by F_QuestionId ");

                    var newmodel = new
                    {
                        cusname = model.F_CusName,
                        telphone = model.F_Phone,
                        cusphone = model.ExpandVchField2,
                        countryid = model.ExpandIntField1,
                        country = model.ExpandVchField4,
                        address = model.ExpandVchField3,
                        queslist = qlist.Where(t => t.F_Type == 3).Select(q => {
                            //获取多选题目以及答案
                            var answers = "";
                            var qalist = anslist.Where(al => al.F_QID.Value == q.F_QuestionId).ToList<Model.T_Call_OutAnswers>();
                            if (qalist.Count > 0)
                            {
                                foreach (var item in qalist)
                                {
                                    answers += item.F_Answer + "；";
                                }
                            }
                            return new
                            {
                                questitle = q.F_Title,
                                quesanswers = answers.Trim('；'),
                            };
                        }),
                        textlist = qlist.Where(t => t.F_Type == 1).Select(t => {
                            //获取问答题以及答案
                            var answers = "";
                            var qalist = anslist.Where(al => al.F_QID.Value == t.F_QuestionId).ToList<Model.T_Call_OutAnswers>();
                            if (qalist.Count > 0)
                            {
                                foreach (var item in qalist)
                                {
                                    answers += item.F_Answer + "；";
                                }
                            }
                            return new
                            {
                                questitle = t.F_Title,
                                quesanswers = answers.Trim('；') ,
                            };
                        })
                    };
                    #endregion

                    return Success("获取多选题及答案成功", newmodel);
                }
            }
            return Error("获取多选题及答案失败");
        }

        public ActionResult GetSelWX(int telid)
        {
            if (telid <= 0)
                return Error("参数不正确");
            var model = otnwxBLL.GetModel(telid);

            if (model != null)
            {
                var anslist = answxBLL.GetModelList(" F_CusTelID=" + telid + " ");

                var qlist = questionBLL.GetModelList(" F_DeleteFlag=0 and F_QuestionId in (select F_QuestionId from T_Ask_PagerItems where F_PagerId="+model.F_PagerId+") order by F_QuestionId ");

                var newmodel = new
                {
                    cusname = model.F_UserName,
                    telphone = model.F_TelPhone,
                    cusphone = model.F_Phone,
                    countryid = model.F_CountryId,
                    country = model.F_Country,
                    address = model.F_Address,
                    queslist = qlist.Where(t => t.F_Type == 3).Select(q =>
                    {
                        ////获取多选题目以及答案
                        var answers = "";
                        var qalist = anslist.Where(al => al.F_QID.Value == q.F_QuestionId).ToList<Model.T_Call_OutAnswersWX>();
                        if (qalist.Count > 0)
                        {
                            foreach (var item in qalist)
                            {
                                answers += item.F_Answer + "；";
                            }
                        }
                        return new
                        {
                            questitle = q.F_Title,
                            quesanswers = answers.Trim('；') + "。",
                        };
                    }),
                    textlist = qlist.Where(t => t.F_Type == 1).Select(q =>
                    {
                        //获取问答题以及答案
                        var answers = "";
                        var qalist = anslist.Where(al => al.F_QID.Value == q.F_QuestionId).ToList<Model.T_Call_OutAnswersWX>();
                        if (qalist.Count > 0)
                        {
                            foreach (var item in qalist)
                            {
                                answers += item.F_Answer + "；";
                            }
                        }
                        return new
                        {
                            questitle = q.F_Title,
                            quesanswers = answers.Trim('；') + "。",
                        };
                    })
                };

                return Success("获取多选题及答案成功", newmodel);
            }
            return Error("获取多选题及答案失败");
        }
        #endregion

        #region 记录日志
        private void planrecord(Model.T_Call_OutTelNumWX tnModel)
        {
            Model.T_Call_OutTelNumWXRecords trModel = new Model.T_Call_OutTelNumWXRecords();
            trModel.F_TelId = tnModel.F_Id;
            trModel.F_TelPhone = tnModel.F_TelPhone;
            trModel.F_Phone = tnModel.F_Phone;
            trModel.F_CusName = tnModel.F_CusName;
            trModel.F_CountryId = tnModel.F_CountryId;
            trModel.F_Country = tnModel.F_Country;
            trModel.F_Address = tnModel.F_Address;
            trModel.F_Openid = tnModel.F_Openid;
            trModel.F_PagerId = tnModel.F_PagerId;
            trModel.F_DeleteFlag = 0;
            trModel.F_AskRes = tnModel.F_AskRes;
            trModel.F_AskInfo = tnModel.F_AskInfo;
            trModel.F_CusID = tnModel.F_CusID;
            trModel.F_CreateTime = DateTime.Now;
            trModel.F_UserId = tnModel.F_UserId;
            new BLL.T_Call_OutTelNumWXRecords().Add(trModel);
        }
        #endregion
    }
}