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

namespace CallCenterApi.Interface.Controllers.tel
{
    public class CallInScreenController : BaseController
    {
        private BLL.T_Sys_DictionaryValue dictionaryValueBLL = new BLL.T_Sys_DictionaryValue();
        /// <summary>
        /// 添加黑名单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddBlack()
        {
            string tel = HttpUtility.UrlDecode(RequestString.GetFormString("tel"));
            string callid = HttpUtility.UrlDecode(RequestString.GetFormString("callid"));
            int n = RequestString.GetInt("num", 0);
            int type = RequestString.GetInt("type", 0);
            Model.T_Call_Blacklist dModel = new BLL.T_Call_Blacklist().GetModelList(" F_TelPhone='" + tel + "' ").FirstOrDefault();

            var date = DateTime.Now;
            var enddate = date;
            switch (type)
            {
                case 1: enddate = enddate.AddDays(n); break;
                case 2: enddate = enddate.AddHours(n); break;
                case 3: enddate = enddate.AddMinutes(n); break;
                case 4: enddate = DateTime.MaxValue; break;
            }
            if (dModel == null)
            {
                dModel = new Model.T_Call_Blacklist();
                dModel.F_CallId = callid;
                dModel.F_TelPhone = tel.Trim();
                dModel.F_SetTime = date;
                dModel.F_RemoveTime = enddate;
                dModel.F_InterceptNum = 1;
                dModel.F_UserId = CurrentUser.UserData.F_UserId;
                int b = new BLL.T_Call_Blacklist().Add(dModel);
                if (b > 0)
                {
                    return Success("添加成功", enddate.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else
                {
                    return Error("添加失败");
                }
            }
            else
            {

                dModel.F_RemoveTime = enddate;
                if (new BLL.T_Call_Blacklist().Update(dModel))
                {
                    return Success("修改成功", enddate.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else
                {
                    return Error("修改失败");
                }
            }
        }

        /// <summary>
        /// 取消黑名单
        /// </summary>
        /// <returns></returns>
        public ActionResult DelBlack()
        {
            string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            Model.T_Call_Blacklist dModel = new BLL.T_Call_Blacklist().GetModelList(" F_TelPhone='" + tel + "' ").FirstOrDefault();

            if (dModel != null)
            {
                bool bl = new BLL.T_Call_Blacklist().Delete(dModel.F_BlackId);
                if (bl)
                {
                    return Success("取消成功");
                }
                else
                { return Error("取消失败"); }
            }
            else
            { return Error("取消失败"); }
        }

        /// <summary>
        /// 根据来电号码获取客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCustomerByTel(string tel)
        {
            BLL.T_Cus_CustomerBase bll = new BLL.T_Cus_CustomerBase();
            var cusmodel = bll.GetModelByTel(tel);
            CustomerDto cusdto = new CustomerDto();
            if (cusmodel != null)
            {
                cusdto.id = cusmodel.F_CustomerId;
                cusdto.cusname = cusmodel.F_CustomerName;
                cusdto.mobile = cusmodel.F_Mobile;
                cusdto.telphone = cusmodel.F_Telephone;
                cusdto.countryid = cusmodel.F_CityID.Value;
                cusdto.country = cusmodel.F_City;
                cusdto.address = cusmodel.F_Address;
            
                return Success("获取成功", cusdto);
            }
            else
                return Success("获取失败", null);

        }

        #region 20180509调整前
        //public ActionResult GetCustomerByTel()
        //{
        //    ActionResult return NoToken("未知错误，请重新登录");
        //    if (Request.IsAuthenticated)
        //    {
        //        DataTable dt = new DataTable();

        //        string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
        //        BLL.T_Cus_CustomerBase bll = new BLL.T_Cus_CustomerBase();
        //        dt = bll.GetList(" F_Telephone like '%" + tel + "%' or F_Mobile like '%" + tel + "%' ").Tables[0];

        //        return Success("客户信息加载成功", dt);

        //    }
        //    return res;
        //}
        #endregion

        /// <summary>
        /// 根据来电号码获取最近的callid
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCallIdByPhone()
        {
            DataTable dt = new DataTable();

            string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            Model.T_Call_CallRecords model = new BLL.T_Call_CallRecords().GetModelByTelphone(tel);

            return Success("加载成功", model);

        }

        /// <summary>
        /// 根据callid获取最近的通话记录
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTelRecordByCallid()
        {
            DataTable dt = new DataTable();

            string callid = HttpUtility.UrlDecode(RequestString.GetQueryString("callid"));
            Model.T_Call_CallRecords model = new BLL.T_Call_CallRecords().GetModelByCallId(callid);

            return Success("通话记录加载成功", model);

        }

        /// <summary>
        /// 来电归属地查询
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPhoneLocation()
        {
            string location = "未知";

            string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            if (tel.Trim().Length == 11 && tel.Substring(0, 1) != "0")
            {
                BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModelList(" F_MobileNum='" + tel.Substring(0, 7) + "'").FirstOrDefault();

                if (mobileModel != null)
                {
                    location = mobileModel.F_CityDes + mobileModel.F_CardDes;
                }
            }
            else
            {
                BLL.T_Sys_TelTitleData numbBll = new BLL.T_Sys_TelTitleData();
                List<Model.T_Sys_TelTitleData> mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + tel.Substring(0, 4) + "'");
                if (mobileModel == null || mobileModel.Count <= 0)
                {
                    mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + tel.Substring(0, 3) + "'");
                }
                if (mobileModel.Count > 0)
                {
                    location = mobileModel[0].F_TitleName;
                }
            }

            return Success("归属地加载成功", location);

        }

        /// <summary>
        /// 历史记录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOldList()
        {
            string sql = "";
            string sqlcount = "";
            DataTable dt = new DataTable();

            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strcalltype = HttpUtility.UrlDecode(RequestString.GetQueryString("calltype"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            if (strcalltype.Trim() != "" && strcalltype != "undefined")
            {
                sql += " and CallType=" + strcalltype + " ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and CallNumber= '" + strtel.Trim() + "' ";
                sqlcount += " and CallNumber= '" + strtel.Trim() + "' ";
            }
            //else
            //{
            //    sql += " and 1=0 ";
            //}
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,BeginTime,'" + strstarttime + "')<=0 ";
                sqlcount += " and datediff(day,BeginTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,BeginTime,'" + strendtime + "')>=0   ";
                sqlcount += " and datediff(day,BeginTime,'" + strendtime + "')>=0   ";
            }

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Call_CallRecords",
                "CallRecordsId",
                "*",
                sql,
                "ORDER BY CallRecordsId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            foreach (DataRow dr in dt.Rows)
            {
                string path = dr["FilePath"] != null ? dr["FilePath"].ToString() : "";
                if (path != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                {
                    var ym = config.F_ParamValue;
                    if (ym.Substring(ym.Length - 1) == "/")
                    {
                        ym = ym.Substring(0, ym.Length - 1);
                    }
                    dr["FilePath"] = ym + path.Substring(path.IndexOf(':') + 1).Replace('\\', '/');
                }
            }

            int hrcount = new BLL.T_Call_CallRecords().GetRecordCount(" calltype=0 " + sqlcount);
            int hccount = new BLL.T_Call_CallRecords().GetRecordCount(" calltype=1 " + sqlcount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount,
                hrcount = hrcount,
                hccount = hccount,
            };

            return Content(obj.ToJson());

        }

        /// <summary>
        /// 获取最新知识库
        /// </summary>
        /// <returns></returns>
        public ActionResult GetZSKList()
        {

            DataTable dt = new DataTable();
            string pid = HttpUtility.UrlDecode(RequestString.GetQueryString("pid"));
            string keywords = HttpUtility.UrlDecode(RequestString.GetQueryString("keywords"));

            string sql = " F_DeleteFlag=0";
            if (pid.Trim() != "")
            {
                sql += " and F_CategoryId=" + pid.Trim();
            }
            if (keywords.Trim() != "")
            {
                sql += " and (F_Content like '%" + keywords.Trim() + "%' or F_Title like '%"
                    + keywords.Trim() + "%' or F_KeyWords like '%" + keywords.Trim() + "%')";
            }

            dt = new BLL.T_RepositoryInformation().GetList(8, sql, " F_RepositoryId desc").Tables[0];

            return Success("加载成功", dt);

        }

        /// <summary>
        /// 振铃事件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateZL()
        {
            var ua = CurrentUser.UserData;
            Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
            model.CallId = RequestString.GetFormString("callid");
            model.UserId = ua.F_UserId;
            model.UserCode = ua.F_UserCode;
            model.UserName = ua.F_UserName;
            //model.ExtNumber = ua.F_WorkNumber;
            model.ExtNumber = CurrentUser.UserData.F_ExtensionNumber;

            model.DealType = 5;
            bool bl = new BLL.T_Call_CallRecords().UpdateCallInRingTelRecord(model);
            if (bl)
            {
                return Success("更新振铃状态成功");
            }
            else
            {
                return Success("更新振铃状态失败");
            }
        }

        /// <summary>
        /// 摘机事件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateZJ()
        {
            Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
            model.CallId = RequestString.GetFormString("callid");
            model.CallState = 1;
            model.DealType = 6;
            bool bl = new BLL.T_Call_CallRecords().UpdateCallInAnswerTelRecord(model);
            if (bl)
            {
                Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(model.CallId);
                string type = vmodel.OperateType.ToString();
                if (type == "7")
                {
                    new BLL.T_Call_TaskTelNum().UpdateYJ(Convert.ToInt32(vmodel.OperateObject.ToString()), 1);
                }

                return Success("更新摘机状态成功");
            }
            else
            {
                return Success("更新摘机状态失败");
            }

        }

        /// <summary>
        /// 挂机事件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateGJ()
        {
            string strid = RequestString.GetFormString("callid");
            bool bl = new BLL.T_Call_CallRecords().UpdateCallInHookTelRecord(strid);
            if (bl)
            {
                return Success("更新挂机状态成功");
            }
            else
            {
                return Success("更新挂机状态失败");
            }

        }

        /// <summary>
        /// 录音事件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateLY()
        {
            Model.T_Call_CallRecords model = new Model.T_Call_CallRecords();
            model.CallId = RequestString.GetFormString("callid");
            model.CallState = 1;
            model.DealType = 6;
            model.FilePath = RequestString.GetFormString("path");
            bool bl = new BLL.T_Call_CallRecords().UpdateCallInPathTelRecord(model);
            if (bl)
            {
                Model.T_Call_CallRecords vmodel = new BLL.T_Call_CallRecords().GetModelByCallId(model.CallId);
                string type = vmodel.OperateType.ToString();
                if (type == "7")
                {
                    new BLL.T_Call_TaskTelNum().UpdateYJ(Convert.ToInt32(vmodel.OperateObject.ToString()), 1);
                }

                return Success("更新挂机状态成功");
            }
            else
            {
                return Success("更新挂机状态失败");
            }

        }

        #region 创建工单
        //zhengbingbing 20180503 根据息县工单调整
        /// <summary>
        /// 创建工单
        /// </summary>
        /// <returns></returns>
        //public ActionResult AddWorkOrder(string callid, string source, string file
        //    , string customer, string custel, string country, string address, string inqtime, string inquser
        //   , string detail, string cont, string answer, string remark, string wjid
        //    , string infotype, string unit, string clbm, string clr, int khid = 0,
        //     int infotypeid = 0, int unitid = 0, int clid = 0)
        //{
        //    var ua = CurrentUser.UserData;
        //    Model.T_Wo_WorkOrder model = new Model.T_Wo_WorkOrder();
        //    model.WorkOrderID = DateTime.Now.ToString("yyyyMMddHHmmss");//工单编号
        //    model.CallID = callid;
        //    model.CustomerID = khid;
        //    model.CustomerTel = custel;
        //    #region 息县工单
        //    if (!string.IsNullOrWhiteSpace(customer))
        //        model.Customer = customer;
        //    if (!string.IsNullOrWhiteSpace(inqtime))
        //        model.Inqtime = DateTime.Parse(inqtime);
        //    if (!string.IsNullOrWhiteSpace(inquser))
        //        model.Inquser = inquser;
        //    if (!string.IsNullOrWhiteSpace(country))
        //        model.County = country;
        //    if (!string.IsNullOrWhiteSpace(address))
        //        model.Address = address;
        //    if (!string.IsNullOrWhiteSpace(detail))
        //        model.Detail = detail;
        //    if (!string.IsNullOrWhiteSpace(answer))
        //        model.Answer = answer;
        //    if (!string.IsNullOrWhiteSpace(cont))
        //        model.Clcontent = cont;
        //    if (!string.IsNullOrWhiteSpace(remark))
        //        model.Remark = remark;
        //    if (!string.IsNullOrWhiteSpace(wjid))
        //        model.WjID = int.Parse(wjid);
        //    #endregion
        //    #region 信息分类和交办单位
        //    model.InfoType = infotype;
        //    model.Unit = unit;
         
        //    #endregion
        //    model.Files = file;
        //    model.Source = "手工制单";

        //    //if (source.Trim() == "1")
        //    //    model.Source = "手工制单";
        //    //else if (source.Trim() == "2")
        //    //    model.Source = "电话";
        //    //else if (source.Trim() == "3")
        //    //    model.Source = "微信";
        //    #region 无需参数字段
        //    model.Type = 3;//默认为投诉工单
        //                   //model.WjID = 0;
        //    model.State = 0;
        //    model.IsDel = 0;
        //    model.IsReturn = 0;
        //    model.IsReturnBak = 0;
        //    model.IsTimeOut = 0;
        //    model.IsUserSend = 0;
        //    model.IsAdminSend = 0;
        //    model.CreateUser = ua.F_UserCode;
        //    model.CreateTime = DateTime.Now;
        //    #endregion

        //    #region 工单明细
            
        //    int depid = 0; //部门id
        //    var model_Dep = new BLL.T_Sys_Department().GetModel(clbm);
        //    depid = model_Dep != null ? model_Dep.F_DeptId : 0;

        //    Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
        //    item.WorkOrderID = model.WorkOrderID;
        //    item.ToDept = depid; //部门clbm
        //    item.Type = 1;

        //    if (!string.IsNullOrEmpty(clr))  //if (clid != 0)
        //    {
        //        Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModelByName(clr);
        //        if (clus != null)
        //        {
        //            item.ToUser = clus.F_UserCode;
        //        }
        //    }
        //    else
        //    {
        //        string users = string.Empty;
        //        var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
        //        foreach (var l in list)
        //        {
        //            if (string.IsNullOrEmpty(users))
        //            {
        //                users = l.F_UserCode;
        //            }
        //            else
        //            {
        //                users = users + "," + l.F_UserCode;
        //            }
        //        }
        //        item.ToUser = users;
        //    }

        //    if (item.ToUser != "")
        //    {
        //        item.SureUser = ua.F_UserCode;
        //        item.State = 1;
        //        item.SureTime = DateTime.Now;
        //        item.IsStart = 1;
        //    }
        //    else
        //    {
        //        item.State = 0;
        //        item.IsStart = 0;
        //    }
        //    item.Detail = model.Detail;
        //    item.IsLast = 0;
        //    item.IsTimeOut = 0;
        //    item.IsDel = 0;
        //    item.CreateUser = ua.F_UserCode;
        //    item.CreateTime = DateTime.Now;

        //    long itemid = new BLL.T_Wo_WorkOrderItem().Add(item);
        //    if (itemid > 0)
        //    {
        //        model.State = 1;//已指派
        //        model.AppointTime = DateTime.Now;

        //    }
        //    //}
        //    #endregion
        //    #region 插入操作记录
        //    Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //    oper.F_WorkOrderId = model.WorkOrderID;
        //    oper.F_State = model.State;
        //    oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
        //    oper.F_File = model.Files;

        //    string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
        //    if (model.State == 0)
        //    {
        //        oper.F_Message = userinfo + " 登记了工单,工单编号：" + model.WorkOrderID;
        //    }
        //    if (model.State == 1)
        //    {
        //        oper.F_Message = userinfo + " 登记并提交了工单,工单编号：" + model.WorkOrderID;
        //    }
        //    if (model.State == 2)
        //    {
        //        oper.F_Message = userinfo + " 登记并完结了工单,工单编号：" + model.WorkOrderID;
        //    }

        //    oper.F_CreateUser = ua.F_UserCode;
        //    oper.F_CreateTime = DateTime.Now;
        //    oper.F_IsDelete = 0;

        //    new BLL.T_Wo_Operation().Add(oper);
        //    #endregion
        //    if (new BLL.T_Wo_WorkOrder().Add(model) > 0)
        //    {
        //        if (!string.IsNullOrEmpty(callid))
        //        {
        //            var rec = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
        //            if (rec != null)
        //            {
        //                rec.IsExitWorkOrder = true;
        //                new BLL.T_Call_CallRecords().Update(rec);
        //            }
        //        }
        //        return Success("新增成功！", model.WorkOrderID);
        //    }
        //    else
        //    {
        //        return Error("新增失败！");
        //    }



        //}
        //#endregion
        #region 创建工单调整前
        /// <summary>
        /// 创建工单
        /// </summary>
        /// <returns></returns>
        //public ActionResult AddWorkOrder()
        //{
            
        //    if (Request.IsAuthenticated)
        //    {
        //        #region 获取参数
        //        int type = RequestString.GetInt("type", 0);
        //        //int tslx = RequestString.GetInt("tslx", 0);
        //        string callid = RequestString.GetFormString("callid");
        //        int khid = RequestString.GetInt("khid", 0);
        //        string tskh = RequestString.GetFormString("tskh");
        //        string tsdh = RequestString.GetFormString("tsdh");
        //        //int zrbm = RequestString.GetInt("zrbm", 0);
        //        //int zrid = RequestString.GetInt("zrid", 0);
        //        string cont = RequestString.GetFormString("cont");
        //        //string answer = RequestString.GetFormString("answer");
        //        string clcont = RequestString.GetFormString("clcont");

        //        int clbm = RequestString.GetInt("clbm", 0);
        //        int clid = RequestString.GetInt("clid", 0);
        //        string source = RequestString.GetFormString("source");
        //        //string address = RequestString.GetFormString("address");
        //        #region 新增字段
        //        int infotypeid = RequestString.GetInt("infotypeid", 0);//信息分类
        //        //int isreward = RequestString.GetInt("isreward", 0);//上报奖励
        //        //string reamount = RequestString.GetFormString("reamount");//奖励金额
        //        //string retime = RequestString.GetFormString("retime");//奖励时间
        //        int unitid = RequestString.GetInt("unitid", 0);//交办单位
        //        int isaudit = RequestString.GetInt("isaudit", 0);//0未审核，1无效，2有效
        //        #endregion
        //        #endregion

        //        #region 判断输入数据类型
        //        if (!Validate.IsNumber(tsdh))
        //        {
        //            return Error("电话必须为数字");
        //            return res;
        //        }
        //        #endregion

        //        int userId = CurrentUser.UserData.F_UserId;
        //        if (userId != 0)
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
        //            if (ua != null)
        //            {
        //                Model.T_Wo_WorkOrder model = new Model.T_Wo_WorkOrder();
        //                model.WorkOrderID = DateTime.Now.ToString("yyyyMMddHHmmssmsfff");//工单编号
        //                model.CallID = callid;
        //                model.Customer = tskh;
        //                model.CustomerID = khid;
        //                model.CustomerTel = tsdh;
        //                model.Detail = cont;
        //                model.Clcontent = clcont;
        //                model.Type = type;
        //                //model.TypeClass = tslx;

        //                if (type == 1)
        //                {
        //                    model.State = 2;
        //                }
        //                else
        //                    model.State = 0;
        //                model.IsDel = 0;
        //                model.IsReturn = 0;
        //                model.IsReturnBak = 0;
        //                //model.ResponDept = zrbm;
        //                //model.Answer = answer;
        //                model.IsTimeOut = 0;
        //                model.IsUserSend = 0;
        //                model.IsAdminSend = 0;
        //                model.IsAudit = isaudit;//0未审核，1无效，2有效

        //                if (source.Trim() == "1")
        //                    model.Source = "手工制单";
        //                else if (source.Trim() == "2")
        //                    model.Source = "电话";
        //                else if (source.Trim() == "3")
        //                    model.Source = "微信";

        //                #region 新增字段
        //                model.InfoTypeID = infotypeid;
        //                if (infotypeid != 0)
        //                {
        //                    Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(infotypeid);
        //                    if (dicVModel != null)
        //                    {
        //                        model.InfoType = dicVModel.F_Name;
        //                    }
        //                }
        //                model.ISReward = 0;
        //                //model.RewardAmount = reamount;
        //                //model.RewardTime = retime;
        //                model.UnitID = unitid;
        //                if (unitid != 0)
        //                {
        //                    Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(unitid);
        //                    if (dicVModel != null)
        //                    {
        //                        model.Unit = dicVModel.F_Name;
        //                    }
        //                }
        //                #endregion

        //                #region 工单超时
        //                Model.T_Wo_WorkOrderTimeOut to = new BLL.T_Wo_WorkOrderTimeOut().GetModel(type);
        //                if (to != null)
        //                {
        //                    model.LimitTime = to.MainTime;
        //                }
        //                #endregion
        //                model.CreateUser = ua.F_UserCode;
        //                model.CreateTime = DateTime.Now;
        //                #region 工单明细
        //                if (clbm != 0 || clid != 0)
        //                {
        //                    Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
        //                    item.WorkOrderID = model.WorkOrderID;
        //                    item.ToDept = clbm;
        //                    item.Type = 1;

        //                    if (clid != 0)
        //                    {
        //                        Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModel(clid);
        //                        if (clus != null)
        //                        {
        //                            item.ToUser = clus.F_UserCode;
        //                        }
        //                    }
        //                    else
        //                    {
        //                        string users = string.Empty;
        //                        var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
        //                        foreach (var l in list)
        //                        {
        //                            if (string.IsNullOrEmpty(users))
        //                            {
        //                                users = l.F_UserCode;
        //                            }
        //                            else
        //                            {
        //                                users = users + "," + l.F_UserCode;
        //                            }
        //                        }
        //                        item.ToUser = users;
        //                    }

        //                    if (to != null)
        //                    {
        //                        item.LimitTime = to.ItemTime;
        //                    }
        //                    if (item.ToUser != "")
        //                    {
        //                        item.SureUser = ua.F_UserCode;
        //                        item.State = 1;
        //                        item.SureTime = DateTime.Now;
        //                        item.IsStart = 1;
        //                    }
        //                    else
        //                    {
        //                        item.State = 0;
        //                        item.IsStart = 0;
        //                    }
        //                    item.Detail = clcont;
        //                    item.IsLast = 0;
        //                    //item.State = 0;
        //                    //item.IsStart = 0;
        //                    item.IsTimeOut = 0;
        //                    item.IsDel = 0;
        //                    item.CreateUser = ua.F_UserCode;
        //                    item.CreateTime = DateTime.Now;

        //                    long itemid = new BLL.T_Wo_WorkOrderItem().Add(item);
        //                    if (itemid > 0)
        //                    {
        //                        model.State = 1;//已指派
        //                        model.AppointTime = DateTime.Now;

        //                        #region 消息表
        //                        //foreach (string ur in item.ToUser.Split(','))
        //                        //{
        //                        //    Model.T_Msg_List msg = new Model.T_Msg_List();
        //                        //    msg.Type = 1;
        //                        //    msg.ToUser = ur;
        //                        //    msg.ToID = Int32.Parse(itemid.ToString());
        //                        //    msg.Detail = ua.F_UserName + "给你指派了工单，单号：" + model.WorkOrderID;
        //                        //    msg.State = 0;
        //                        //    msg.IsDel = 0;
        //                        //    msg.CreateUser = ua.F_UserCode;
        //                        //    msg.CreateDate = DateTime.Now;

        //                        //    new BLL.T_Msg_List().Add(msg);
        //                        //}
        //                        #endregion
        //                    }
        //                }
        //                #endregion
        //                #region 插入操作记录
        //                Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //                oper.F_WorkOrderId = model.WorkOrderID;
        //                oper.F_State = model.State;
        //                oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
        //                oper.F_File = model.Files;

        //                string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
        //                if (model.State == 0)
        //                {
        //                    oper.F_Message = userinfo + " 登记了工单,工单编号：" + model.WorkOrderID;
        //                }
        //                if (model.State == 1)
        //                {
        //                    oper.F_Message = userinfo + " 登记并提交了工单,工单编号：" + model.WorkOrderID;
        //                }
        //                if (model.State == 2)
        //                {
        //                    oper.F_Message = userinfo + " 登记并完结了工单,工单编号：" + model.WorkOrderID;
        //                }

        //                oper.F_CreateUser = ua.F_UserCode;
        //                oper.F_CreateTime = DateTime.Now;
        //                oper.F_IsDelete = 0;

        //                new BLL.T_Wo_Operation().Add(oper);
        //                #endregion
        //                if (new BLL.T_Wo_WorkOrder().Add(model) > 0)
        //                {
        //                    if (!string.IsNullOrEmpty(callid))
        //                    {
        //                        var rec = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
        //                        if (rec != null)
        //                        {
        //                            rec.IsExitWorkOrder = true;
        //                            new BLL.T_Call_CallRecords().Update(rec);
        //                        }
        //                    }
        //                    return Success("新增成功！");
        //                }
        //                else
        //                {
        //                    return Error("新增失败！");
        //                }

        //                #region no use
        //                //Model.T_Wo_WorkOrderBase model = new Model.T_Wo_WorkOrderBase();
        //                //model.F_CODE = DateTime.Now.ToString("yyyyMMddHHmmssms");//工单编号
        //                //model.F_WORKORDERTYPEID = type;
        //                //model.F_WORKORDERSTATEID = 0;
        //                //model.F_WORKORDERNAME = "";
        //                //model.F_WORKORDERFROM = "";
        //                //model.F_WORKORDERLEVELID = 0;
        //                //model.F_ADSLACCOUNT = callid;
        //                ////model.F_USERID = ua.F_UserId;
        //                ////model.F_USERNAME = ua.F_UserName;
        //                ////model.F_USERPHONE = ua.F_WorkNumber;
        //                //model.F_TypeName = "";
        //                //model.F_STARTTIME = DateTime.Now;
        //                //model.F_RETURNVISITFLAG = 0;
        //                //model.F_LINKMANTELEPHONE = tsdh;
        //                //model.F_LINKMAN = tskh;
        //                //model.F_DELETEFLAG = 0;
        //                //model.F_CUSTOMERTELEPHONE = tsdh;
        //                //model.F_CUSTOMERNAME = tskh;
        //                //model.F_CUSTOMERID = 0;//待实现
        //                //model.F_CREATEDATE = DateTime.Now;
        //                //model.F_CREATEBY = ua.F_UserId;
        //                //model.F_CONTENT = cont;
        //                //model.F_REPAIRMANNAME = tskh;
        //                //model.F_REPAIRMANPHONE = tsdh;

        //                //if (new BLL.T_Wo_WorkOrderBase().Add(model) > 0)
        //                //{
        //                //    return Success("新增成功！");
        //                //}
        //                //else
        //                //{
        //                //    return Error("新增失败！");
        //                //} 
        //                #endregion
        //            }
        //        }

        //    }
        //    return res;
        //}
        #endregion

        //根据部门id 获取处理人
        public ActionResult getUserListByDepartment(int deptid)
        {
            BLL.T_Sys_UserAccount bll = new BLL.T_Sys_UserAccount();
            DataTable dt=  bll.GetList(" F_DeptId='"+deptid+"'").Tables[0];
            
            return Success("获取userlist成功", dt);
        }


        /// <summary>
        /// 创建工单
        /// </summary>
        /// <param name="callid"></param>
        /// <param name="source"></param>
        /// <param name="file"></param>
        /// <param name="customer"></param>
        /// <param name="custel"></param>
        /// <param name="address"></param>
        /// <param name="inqtime"></param>
        /// <param name="inquser"></param>
        /// <param name="detail"></param>
        /// <param name="cont"></param>
        /// <param name="remark"></param>
        /// <param name="infotypedetail"></param>
        /// <param name="infotype"></param>
        /// <param name="clbm"></param>
        /// <param name="clr"></param>
        /// <param name="khid"></param>
        /// <param name="infotypeid"></param>
        /// <param name="infotypedetailid"></param>
        /// <param name="country"></param>
        /// <param name="state"></param>
        /// <param name="wjid"></param>
        /// <returns></returns>
        public ActionResult AddWorkOrder(string callid, string source, string file
          , string customer, string custel,  string address, string inqtime, string inquser
         , string detail, string cont,   string remark 
          , string infotypedetail, string infotype,   int clbm, string clr, int khid = 0,
           int infotypeid = 0, int infotypedetailid = 0, int country=0,int state=1, 
           
           int? wjid=null)
        //clr 是usercode
        {
            var ua = CurrentUser.UserData;
            Model.T_Wo_WorkOrder model = new Model.T_Wo_WorkOrder();
            model.WorkOrderID = DateTime.Now.ToString("yyyyMMddHHmmss");//工单编号
            model.CallID = callid;
            model.CustomerID = khid;
            model.CustomerTel = custel;
            #region 息县工单
            if (!string.IsNullOrWhiteSpace(customer))
                model.Customer = customer;
            if (!string.IsNullOrWhiteSpace(inqtime))
                model.Inqtime = DateTime.Parse(inqtime);
            if (!string.IsNullOrWhiteSpace(inquser))
                model.Inquser = inquser;

            if (country != 0)
            {
                //营业部
                 model.County = country.ToString();

            }
            if (!string.IsNullOrWhiteSpace(address))
                model.Address = address;
            if (!string.IsNullOrWhiteSpace(detail))
                model.Detail = detail;
            
            if (!string.IsNullOrWhiteSpace(cont))
                model.Clcontent = cont;
            if (!string.IsNullOrWhiteSpace(remark))
                model.Remark = remark;

            #endregion
           
                var model_Dep = new BLL.T_Sys_Department().GetModel(clbm);
                model.Unit = model_Dep != null ? model_Dep.F_DeptName : ""; 
           
                

            #region 问题分类和处理单位
           
            model.InfoTypeID = infotypeid;
            model.InfoType = infotype;

            model.InfoTypeDetail = infotypedetail;
            model.InfoTypeDetailID = infotypedetailid;

          
          
           
            #endregion
            model.Files = file;

            if (source.Trim() == "1")
                model.Source = "手工制单";
            else if (source.Trim() == "2")
                model.Source = "电话";

         //   model.Source = "电话";

       
            #region 无需参数字段
            model.Type = 3;//默认为投诉工单
                          
            model.State = 0;
            model.IsDel = 0;
            model.IsReturn = 0;
            model.IsReturnBak = 0;
            model.IsTimeOut = 0;
            model.IsUserSend = 0;
            model.IsAdminSend = 0;
            model.CreateUser = ua.F_UserCode;
            model.CreateTime = DateTime.Now;
            #endregion
            model.WjID = wjid;

            if (state == 2)
            {
                model.State = 2; // 2是已完结 1 是未完结
            }
            else
            {
                #region 工单明细

                int depid = 0; //部门id

                depid = model_Dep != null ? model_Dep.F_DeptId : 0;

                Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
                item.WorkOrderID = model.WorkOrderID;
                item.ToDept = Convert.ToInt32(clbm); //部门clbm   id
                model.UnitID = Convert.ToInt32(clbm);
                item.Type = 1;

                if (!string.IsNullOrEmpty(clr))  //if (clid != 0)
                {
                    Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModelByName(clr);
                    if (clus != null)
                    {
                        item.ToUser = clus.F_UserCode;
                    }
                }
                else
                {
                    string users = string.Empty;
                    var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
                    foreach (var l in list)
                    {
                        if (string.IsNullOrEmpty(users))
                        {
                            users = l.F_UserCode;
                        }
                        else
                        {
                            users = users + "," + l.F_UserCode;
                        }
                    }
                    item.ToUser = users;
                }

                if (item.ToUser != "")
                {
                    item.SureUser = ua.F_UserCode;
                    item.State = 1;
                    item.SureTime = DateTime.Now;
                    item.IsStart = 1;
                }
                else
                {
                    item.State = 0;
                    item.IsStart = 0;
                }
                item.Detail = model.Detail;
                item.IsLast = 0;
                item.IsTimeOut = 0;
                item.IsDel = 0;
                item.CreateUser = ua.F_UserCode;
                item.CreateTime = DateTime.Now;

                long itemid = new BLL.T_Wo_WorkOrderItem().Add(item);
                if (itemid > 0)
                {
                    model.State = 1;//已指派
                    model.AppointTime = DateTime.Now;

                }
                model.AuditUser = item.ToUser;

                //}
                #endregion
            }

           

            #region 插入操作记录
            Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
            oper.F_WorkOrderId = model.WorkOrderID;
            oper.F_State = model.State;
            oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
            oper.F_File = model.Files;

            string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
            if (model.State == 0)
            {
                oper.F_Message = userinfo + " 登记了工单,工单编号：" + model.WorkOrderID;
            }
            if (model.State == 1)
            {
                oper.F_Message = userinfo + " 登记并提交了工单,工单编号：" + model.WorkOrderID;
            }
            if (model.State == 2)
            {
                oper.F_Message = userinfo + " 登记并完结了工单,工单编号：" + model.WorkOrderID;
            }

            oper.F_CreateUser = ua.F_UserCode;
            oper.F_CreateTime = DateTime.Now;
            oper.F_IsDelete = 0;

            new BLL.T_Wo_Operation().Add(oper);
            #endregion
            if (new BLL.T_Wo_WorkOrder().Add(model) > 0)
            {
                if (!string.IsNullOrEmpty(callid))
                {
                    var rec = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
                    if (rec != null)
                    {
                        rec.IsExitWorkOrder = true;
                        new BLL.T_Call_CallRecords().Update(rec);
                    }
                }
                //处理内容不为空 说明是在问卷调查那添加的工单
                if (!string.IsNullOrEmpty(cont))
                {
                    var item = new Model.T_Wo_WorkOrderItem();
                    #region 获取接收人
                    int depid = 0; //部门id

                    depid = clbm;

                    if (!string.IsNullOrEmpty(clr))
                    {

                        Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModelByName(clr);
                        if (clus != null)
                        {
                            item.ToUser = clus.F_UserCode;
                        }
                    }
                    else
                    {
                        string users = string.Empty;
                        var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
                        foreach (var l in list)
                        {
                            if (string.IsNullOrEmpty(users))
                            {
                                users = l.F_UserCode;
                            }
                            else
                            {
                                users = users + "," + l.F_UserCode;
                            }
                        }
                        item.ToUser = users;
                    }
                    model.AuditUser = item.ToUser;
                    var rerere = new BLL.T_Wo_WorkOrder().Update(model);

                    #endregion
                    item.WorkOrderID = model.WorkOrderID;
                    item.Type = 1;      //处理
                    item.ToDept = depid; //部门clbm
                                         //item.ToUser = clus != null ? clus.F_UserCode : "";  //接收人
                    item.Detail = cont;
                    item.IsDel = 0;
                    //转派
                    if (state == 1) //页面选了未完结
                    {
                        item.State = 0;
                        item.IsLast = 0;
                        item.DealUser = CurrentUser.UserData.F_UserCode;
                        item.DealTime = DateTime.Now;
                    }
                    else//完结
                    {
                        item.State = 2;
                        item.IsLast = 1;
                        item.DealUser = CurrentUser.UserData.F_UserCode;
                        item.DealTime = DateTime.Now;
                    }
                    item.Detail = remark;
                    item.IsStart = 0;
                    item.IsTimeOut = 0;
                    item.CreateUser = CurrentUser.UserData.F_UserCode;
                    item.CreateTime = DateTime.Now;
                    long itemid = new BLL.T_Wo_WorkOrderItem().Add(item);

                }


                return Success("新增成功！", model.WorkOrderID);
            }
            else
            {
                return Error("新增失败！");
            }



        }


    }
}
#endregion