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

namespace CallCenterApi.Interface.Controllers
{
    public class APPController : BaseController
    {
        // GET: APP

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Login(string usercode, string password)
        {
            DateTime ExpiredTime = DateTime.Now.AddDays(1);
            bool appResult = DateTime.Now < ExpiredTime;// Convert.ToDateTime(ReadFile(HttpRuntime.AppDomainAppPath + "tools\\hykj.hy"));
            if (appResult)
            {
                DataTable dt = new DataTable();
                try
                {
                    Dictionary<string, string> paras = new Dictionary<string, string>();
                    string sql = " select * from T_Sys_Users where F_OpenId=@F_OpenId and F_Password=@F_Password";
                    paras.Add("@F_OpenId", usercode);
                    paras.Add("@F_Password", password);

                    dt = DbHelperSQL.Query(sql, paras).Tables[0];
                    if (dt != null)
                    {
                        //写入登录日志
                        new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                        {
                            F_LoginName = dt.Rows[0]["F_OpenId"].ToString(),
                            F_LoginId = Convert.ToInt32(dt.Rows[0]["F_Id"].ToString()),
                            F_Result = "APP市民登录成功",
                            F_LoginIP = Common.DTRequest.GetIP(),
                            F_Hostname = Common.DTRequest.GetIP(),
                            F_LoginDate = DateTime.Now,
                            F_Remark = "",
                            F_State = 0
                        });

                        return Success("登录成功", new
                        {
                            usercode = dt.Rows[0]["F_OpenId"].ToString(),
                            userid = dt.Rows[0]["F_Id"].ToString()
                        });
                    }
                    else
                    {
                        //写入登录日志
                        DataTable dt1 = new CallCenterApi.BLL.T_Sys_Users().GetList("F_OpenId='" + usercode + "'").Tables[0];
                        if (dt1.Rows.Count > 0)
                        {
                            int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt1.Rows[0]["F_OpenId"].ToString(),
                                F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_Id"].ToString()),
                                F_Result = "APP市民登录失败：帐号-" + usercode,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                        }
                        else
                        {
                            int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = usercode,
                                F_LoginId = -1,
                                F_Result = "APP市民登录失败：帐号-" + usercode,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                        }

                        return Error("账号或密码错误，请重新登录");
                    }
                }
                catch
                {
                    return Error("账号或密码错误，请重新登录");
                }
            }
            else
            {
                return Error("授权过期，请联系系统厂家。");
            }
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddUser()
        {
            string usercode = RequestString.GetFormString("usercode");
            string password = RequestString.GetFormString("password");
            string name = RequestString.GetFormString("name");
            string phone = RequestString.GetFormString("phone");
            int sex = RequestString.GetInt("sex", 0);
            string province = RequestString.GetFormString("province");
            string city = RequestString.GetFormString("city");
            string county = RequestString.GetFormString("county");
            string address = RequestString.GetFormString("address");

            Model.T_Sys_Users dModel = new Model.T_Sys_Users();

            var list = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + usercode + "' ");
            if (list.Count > 0)
            {
                return Error("已经存在此账号");
            }
            else
            {
                dModel.F_OpenId = usercode;
                dModel.F_Password = password;
                dModel.F_Name = name;
                dModel.F_Telphone = phone;
                dModel.F_Sex = sex;
                dModel.F_Type = 4;
                dModel.F_Province = province;
                dModel.F_City = city;
                dModel.F_County = county;
                dModel.F_Address = address;


                dModel.F_CreateTime = DateTime.Now;

                long n = new BLL.T_Sys_Users().Add(dModel);
                if (n > 0)
                    return Success("添加成功", n);
                else
                    return Error("添加失败");
            }
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [APPActionFilter]
        [HttpPost]
        public ActionResult UpdateUser()
        {
            int id = RequestString.GetInt("id", 0);
            string usercode = RequestString.GetFormString("usercode");
            string password = RequestString.GetFormString("password");
            string name = RequestString.GetFormString("name");
            string phone = RequestString.GetFormString("phone");
            int sex = RequestString.GetInt("sex", 0);
            string province = RequestString.GetFormString("province");
            string city = RequestString.GetFormString("city");
            string county = RequestString.GetFormString("county");
            string address = RequestString.GetFormString("address");

            Model.T_Sys_Users dModel = new Model.T_Sys_Users();
            if (id == 0)
            {
                dModel = new BLL.T_Sys_Users().GetModel(id);
                if (dModel != null)
                {
                    var list = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + usercode + "' and F_Id!='" + id + "' ");
                    if (list.Count > 0)
                    {
                        return Error("已经存在此账号");
                    }
                    else
                    {
                        dModel.F_OpenId = usercode;
                        dModel.F_Name = name;
                        dModel.F_Telphone = phone;
                        dModel.F_Sex = sex;
                        dModel.F_Province = province;
                        dModel.F_City = city;
                        dModel.F_County = county;
                        dModel.F_Address = address;

                        if (new BLL.T_Sys_Users().Update(dModel))
                            return Success("修改成功");
                        else
                            return Error("修改失败");
                    }
                }
                else
                {
                    return Error("修改失败");
                }
            }
            else
            {
                return Error("修改失败");
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        [HttpPost]
        public ActionResult UpdatePassword()
        {
            string usercode = RequestString.GetFormString("usercode");
            string old = RequestString.GetFormString("old");
            string new1 = RequestString.GetFormString("new1");
            string new2 = RequestString.GetFormString("new2");
            if (string.IsNullOrEmpty(old) || string.IsNullOrEmpty(new1) || string.IsNullOrEmpty(new2))
            {
                return Error("请输入新旧密码");
            }
            if (new1 != new2)
            {
                return Error("两次输入的不一致");
            }

            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);
            if (old == userinfo.F_Password)
            {
                userinfo.F_Password = new1;
                new BLL.T_Sys_Users().Update(userinfo);

                return Success("修改成功");
            }
            else
            {
                return Error("原密码错误");
            }
        }

        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetWorkOrderList(int isdc = 0)
        {

            //string sql = " and F_IsDelete=0 ";
            string sql = " and (F_IsEnabled=0 or F_IsDelete=0) ";

            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));

            var ouid = DbHelperSQL.GetSingle(" select F_ID from T_Sys_Users where F_OpenId ='" + strusercode + "'");

            string sqlwhere = "select F_WorkOrderID FROM T_Bus_UserWorkOrder where F_UserId = '" + ouid.ToString() + "' ";
            sql += " and F_WorkOrderID in (" + sqlwhere + ")";


            DataTable dt = new DataTable();

            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));

            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);

            int deptid = RequestString.GetInt("deptid", 0);
            int dealtype = RequestString.GetInt("dealtype", -1);
            int issend = RequestString.GetInt("issend", -1);

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

            #region sql 语句相关处理
            if (strstate.Trim() != "" && strstate != "undefined")
            {
                sql += " and F_WorkState = '" + strstate.Trim() + "' ";
            }
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and F_WorkOrderId like '%" + strworkid + "%' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }

            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }

            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }

            if (deptid != 0)
            {
                string sqlwhere1 = "select F_WorkOrderID from T_Bus_AssignedInfo where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                sql += " and F_WorkOrderID in(" + sqlwhere1 + ")";
            }
            if (dealtype != -1)
            {
                sql += " and isnull(F_IsResult,0) = '" + dealtype + "' ";
            }
            if (issend != -1)
            {
                sql += " and isnull(F_IsRelease,0) = '" + issend + "' ";
            }

            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            #endregion

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";

            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder",
                "F_WorkOrderId",
                cols,
                sql,
                "ORDER BY F_CreateTime DESC",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }

        /// <summary>
        /// 获取工单数量
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetWorkOrderCount()
        {
            string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            int type = RequestString.GetInt("type", 0);

            var wxuser = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + stropenid.Trim() + "' and F_Type=4 ").FirstOrDefault();

            string where = " F_WorkOrderId in (select F_WorkOrderId from T_Bus_UserWorkOrder where F_UserId='" + wxuser.F_Id + "') ";


            string sql = " select count(1) from T_Bus_UserWorkOrder where F_UserId='" + wxuser.F_Id + "' ";
            string sqlblz = " select count(1) from T_Bus_WorkOrder where " + where + " and F_WorkState!=9 and (F_IsEnabled=0 or F_IsDelete=0)";
            string sqlybl = " select count(1) from T_Bus_WorkOrder where " + where + " and F_WorkState =9 and (F_IsEnabled=0 or F_IsDelete=0)";

            string sqltype = " select F_ValueId,F_Value,(select COUNT(1) from T_Bus_WorkOrder where (F_IsEnabled=0 or F_IsDelete=0) ";
            if (type == 1)
            {
                sqltype += " and F_WorkState!=9";
            }
            else if (type == 2)
            {
                sqltype += " and F_WorkState=9";
            }
            sqltype += " and  F_InfoType=F_ValueId and " + where + ") Count from  dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";

            DataTable dt = DbHelperSQL.Query(sqltype).Tables[0];

            var obj = new
            {
                total = DbHelperSQL.GetSingle(sql).ToString(),
                blzcount = DbHelperSQL.GetSingle(sqlblz).ToString(),
                yblcount = DbHelperSQL.GetSingle(sqlybl).ToString(),
                typedata = dt
            };

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

        /// <summary>
        /// APP上传图片
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult Upload64()
        {
            //string dataurl = HttpUtility.UrlDecode(RequestString.GetFormString("dataurl"));
            string dataurl = RequestString.GetFormString("dataurl");
            string filename = RequestString.GetFormString("filename");
            if (!string.IsNullOrEmpty(dataurl))
            {
                string path = "/Upload/APP/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";

                ImageUpload iu = new ImageUpload();
                iu.SavePath = path;
                iu.DataUrl = dataurl;
                //iu.SaveType = 1;
                iu.InFileName = filename;
                iu.Upload64();

                int n = iu.Error;
                if (n == 0)
                {
                    path = path + iu.OutFileName;

                    Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    model_T_Sys_Accessories.F_FileName = iu.OutFileName;//附件名称
                    model_T_Sys_Accessories.F_FileType = ".jpg";//附件类型
                    model_T_Sys_Accessories.F_FileUrl = path;//附件地址
                    model_T_Sys_Accessories.F_Size = iu.FileSize;
                    //model_T_Sys_Accessories.F_UserCode = userModel.F_UserCode;//上传人  
                    int id = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    model_T_Sys_Accessories.F_FileId = id;

                    return Success("成功", model_T_Sys_Accessories);
                }
                else
                {
                    string msg = string.Empty;
                    switch (n)
                    {
                        case 1: msg = "请选择要上传的文件"; break;
                        case 2: msg = "上传的文件类型不支持"; break;
                        case 3: msg = "上传的文件过大"; break;
                        case 4: msg = "未知错误"; break;
                    }
                    return Error(msg);
                }
            }
            else
            {
                return Error("请选择要上传的文件");
            }
        }

        /// <summary>
        /// 添加工单信息
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult AddWorkOrder()
        {

            string usercode = RequestString.GetFormString("usercode");

            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);

            int source = RequestString.GetInt("source", 6);

            string cusname = RequestString.GetFormString("cusname");
            string cussex = RequestString.GetFormString("cussex");
            string cusphone = RequestString.GetFormString("cusphone");
            string cusaddress = RequestString.GetFormString("cusaddress");
            string email = RequestString.GetFormString("email");
            string zipcode = RequestString.GetFormString("zipcode");
            string conname = RequestString.GetFormString("conname");
            string conphone = RequestString.GetFormString("conphone");

            string title = RequestString.GetFormString("title");
            string content = RequestString.GetFormString("content");
            string files = RequestString.GetFormString("files");
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            string sourceaddress = RequestString.GetFormString("sourceaddress");

            int isresult = RequestString.GetInt("isresult", 0);
            string result = RequestString.GetFormString("result");

            string keys = RequestString.GetFormString("keys");
            string splituser = RequestString.GetFormString("splituser");

            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);

            int isprotect = RequestString.GetInt("isprotect", 0);
            int level = RequestString.GetInt("level", 0);

            WorkOrderController woc = new WorkOrderController();
            string workorderid = woc.AddWorkOrderBySource(6, cusname, cussex, cusphone, cusaddress, email, zipcode, conname,
                    conphone, title, content, sourcearea, sourceaddress, keys, splituser, type, bigtype, smalltype, isprotect, level);
            if (!string.IsNullOrEmpty(workorderid))
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存用户工单信息
                    Model.T_Bus_UserWorkOrder tbu = new Model.T_Bus_UserWorkOrder();
                    tbu.F_UserId = userinfo.F_Id;
                    tbu.F_WorkOrderId = workorderid;
                    new BLL.T_Bus_UserWorkOrder().Add(tbu);
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }
        }

        /// <summary>
        /// 市民催单
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult AdditionalWorkOrder()
        {
            string usercode = RequestString.GetFormString("usercode");
            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);

            string workorderid = RequestString.GetFormString("workorderid");
            string title = RequestString.GetFormString("title");
            string content = RequestString.GetFormString("content");
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new BLL.T_Bus_WorkOrder().GetModel(workorderid);
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {

                    #region 插入附加记录
                    //批示记录
                    Model.T_Bus_Additional model_T_Bus_Additional = new Model.T_Bus_Additional();
                    model_T_Bus_Additional.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单流水号
                    model_T_Bus_Additional.F_Title = title;
                    model_T_Bus_Additional.F_Content = content;
                    model_T_Bus_Additional.F_CreateTime = DateTime.Now;
                    model_T_Bus_Additional.F_IsDelete = 0;
                    model_T_Bus_Additional.F_State = 1;
                    new BLL.T_Bus_Additional().Add(model_T_Bus_Additional);
                    #endregion

                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                    oper.F_Message = "市民（" + userinfo.F_OpenId + "）催单，内容：" + content;
                    //oper.F_CreateUser = userModel.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    new BLL.T_Bus_Operation().Add(oper);
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }
        }

        /// <summary>
        /// 获取工单信息
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetWorkOrder()
        {
            string usercode = RequestString.GetFormString("usercode");
            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);

            string workorderid = RequestString.GetFormString("workorderid");

            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            //int type = RequestString.GetInt("type", 0);//0基本信息1监察意见2领导批示3办理情况4回访信息5督办信息6办理过程
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                string sql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName1,"
                    + "dbo.GetAreaName(F_SourceArea) as AreaName,dbo.GetDictionaryName(F_InfoSource) as SourceName "
                    + " from T_Bus_WorkOrder where F_WorkOrderId ='" + strworkorderid + "'";
                var dt = DbHelperSQL.Query(sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                    string jcsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_DeptId) as DeptName "
                                    + "from T_Bus_RemindRecord where F_Type=2 and F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string dbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_DeptId) as DeptName "
                                    + "from T_Bus_RemindRecord where F_Type=1 and F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string pssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper where F_State=1 and F_IsDelete=0 and F_Type=1 and F_WorkOrderId ='" + strworkorderid + "'";
                    string zssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper where F_State=1 and F_IsDelete=0 and F_Type=2 and F_WorkOrderId ='" + strworkorderid + "'";
                    string htsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper where F_State=1 and F_IsDelete=0 and F_Type=3 and F_WorkOrderId ='" + strworkorderid + "'";
                    string jbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_MainDeptId) as DeptName,dbo.GetDeptNames(F_OtherDeptIds) as OtherDeptName "
                                    + "from T_Bus_AssignedInfo where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string thsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_CreateDeptId) as DeptName "
                                    + "from T_Bus_Feedback where F_State=1 and F_Type=3 and F_IsDelete=0 and  F_WorkOrderId ='" + strworkorderid + "'";
                    string yssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_DelayTime where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string blsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_CreateDeptId) as DeptName "
                                    + "from T_Bus_Feedback where F_State=1 and F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId ='" + strworkorderid + "'";
                    string hfsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_VisitResult where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string gcsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_Operation where F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string cbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_Additional where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";


                    #region 附件
                    if (configfj != null)
                    {
                        dt = BindFileData(dt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 监察信息
                    var jcdt = DbHelperSQL.Query(jcsql).Tables[0];
                    if (configfj != null)
                    {
                        jcdt = BindFileData(jcdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 批示信息
                    var psdt = DbHelperSQL.Query(pssql).Tables[0];
                    if (configfj != null)
                    {
                        psdt = BindFileData(psdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 指示信息
                    var zsdt = DbHelperSQL.Query(zssql).Tables[0];
                    if (configfj != null)
                    {
                        zsdt = BindFileData(zsdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 回退信息
                    var htdt = DbHelperSQL.Query(htsql).Tables[0];
                    #endregion

                    #region 督办信息
                    var dbdt = DbHelperSQL.Query(dbsql).Tables[0];
                    if (configfj != null)
                    {
                        dbdt = BindFileData(dbdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 交办信息
                    var jbdt = DbHelperSQL.Query(jbsql).Tables[0];
                    if (configfj != null)
                    {
                        jbdt = BindFileData(jbdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 退回信息
                    var thdt = DbHelperSQL.Query(thsql).Tables[0];
                    #endregion

                    #region 延时信息
                    var ysdt = DbHelperSQL.Query(yssql).Tables[0];
                    #endregion

                    #region 办理情况
                    var bldt = DbHelperSQL.Query(blsql).Tables[0];
                    if (configfj != null)
                    {
                        bldt = BindFileData(bldt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 回访信息
                    var hfdt = DbHelperSQL.Query(hfsql).Tables[0];
                    #endregion

                    #region 市民催单
                    var cbdt = DbHelperSQL.Query(cbsql).Tables[0];
                    #endregion

                    #region 办理过程
                    var gcdt = DbHelperSQL.Query(gcsql).Tables[0];
                    gcdt.Columns.Add("File", typeof(object));
                    if (configfj != null)
                    {
                        foreach (DataRow bldr in gcdt.Rows)
                        {
                            if (bldr["F_File"] != null && bldr["F_File"].ToString() != "" && configfj != null)
                            {
                                bldr["File"] = GetFileData(bldr["F_File"].ToString(), configfj.F_ParamValue);
                            }
                        }
                    }
                    #endregion


                    var obj = new
                    {
                        data = dt,
                        jcdata = jcdt,
                        psdata = psdt,
                        zsdata = zsdt,
                        htdata = htdt,
                        dbdata = dbdt,
                        jbdata = jbdt,
                        thdata = thdt,
                        ysdata = ysdt,
                        bldata = bldt,
                        hfdata = hfdt,
                        cbdata = cbdt,
                        gcdata = gcdt
                    };
                    return Success("获取成功", obj);
                }
                else
                {
                    return Error("获取失败");
                }
            }
            else
            {
                return Error("参数传输失败");
            }
        }

        /// <summary>
        /// 获取附件数据
        /// </summary>
        /// <param name="ids">附件id，多个用英文逗号,隔开</param>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public DataTable GetFileData(string ids, string prefix)
        {
            DataTable dt = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + ids + ")").Tables[0];

            foreach (DataRow dr in dt.Rows)
            {
                dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
            }

            return dt;
        }

        /// <summary>
        /// 绑定附件信息
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public DataTable BindFileData(DataTable dt, string prefix)
        {
            dt.Columns.Add("File", typeof(object));
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["F_File"] != null && dr["F_File"].ToString() != "")
                {
                    dr["File"] = GetFileData(dr["F_File"].ToString(), prefix);
                }
            }
            return dt;
        }

        /// <summary>
        /// 修改工单信息
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult EditWorkOrder()
        {
            string usercode = RequestString.GetFormString("usercode");
            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);

            string workorderid = RequestString.GetFormString("workorderid");

            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new BLL.T_Bus_WorkOrder().GetModel(workorderid);
            Model.T_Bus_UserWorkOrder modelT_Bus_UserWorkOrder = new BLL.T_Bus_UserWorkOrder().GetModelList(" F_WorkOrderId='" + workorderid + "' ").FirstOrDefault();
            if (modelT_Bus_WorkOrder != null && modelT_Bus_UserWorkOrder != null && modelT_Bus_UserWorkOrder.F_UserId == userinfo.F_Id)
            {
                string cusname = RequestString.GetFormString("cusname");
                string cussex = RequestString.GetFormString("cussex");
                string cusphone = RequestString.GetFormString("cusphone");
                string cusaddress = RequestString.GetFormString("cusaddress");
                string email = RequestString.GetFormString("email");
                string zipcode = RequestString.GetFormString("zipcode");
                string conname = RequestString.GetFormString("conname");
                string conphone = RequestString.GetFormString("conphone");

                string title = RequestString.GetFormString("title");
                string content = RequestString.GetFormString("content");
                string files = RequestString.GetFormString("files");
                int sourcearea = RequestString.GetInt("sourcearea", 0);
                string sourceaddress = RequestString.GetFormString("sourceaddress");

                string keys = RequestString.GetFormString("keys");

                int type = RequestString.GetInt("type", 0);
                int bigtype = RequestString.GetInt("bigtype", 0);
                int smalltype = RequestString.GetInt("smalltype", 0);

                int isprotect = RequestString.GetInt("isprotect", 0);
                int level = RequestString.GetInt("level", 0);
                int issubmit = RequestString.GetInt("issubmit", 0);


                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息

                    modelT_Bus_WorkOrder.F_InfoType = type;//信息类别
                    modelT_Bus_WorkOrder.F_InfoConBigType = bigtype;//内容大类
                    modelT_Bus_WorkOrder.F_InfoConSmallType = smalltype;//内容小类
                    modelT_Bus_WorkOrder.F_SourceArea = sourcearea;//反映地域
                    modelT_Bus_WorkOrder.F_SourceAddress = sourceaddress;//事发地址

                    modelT_Bus_WorkOrder.F_CusName = cusname;//投诉人姓名
                    modelT_Bus_WorkOrder.F_CusSex = cussex;//性别
                    modelT_Bus_WorkOrder.F_CusPhone = cusphone;//来电号码
                    modelT_Bus_WorkOrder.F_CusAddress = cusaddress;//地址
                    modelT_Bus_WorkOrder.F_ZipCode = zipcode;//邮编
                    modelT_Bus_WorkOrder.F_ConName = conname;//联系人姓名
                    modelT_Bus_WorkOrder.F_ConPhone = conphone;//联系人电话
                    modelT_Bus_WorkOrder.F_Email = email;//E-mail

                    modelT_Bus_WorkOrder.F_ComTitle = title;//标题
                    modelT_Bus_WorkOrder.F_ComContent = content;//情况摘要（投诉内容）
                    modelT_Bus_WorkOrder.F_File = files;//附件
                    modelT_Bus_WorkOrder.F_IsProtect = isprotect;//保密方式0否1是

                    modelT_Bus_WorkOrder.F_Key = keys;
                    modelT_Bus_WorkOrder.F_Level = level;

                    new BLL.T_Bus_WorkOrder().Update(modelT_Bus_WorkOrder);
                    #endregion

                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    oper.F_CallRecordId = modelT_Bus_WorkOrder.F_CallRecordId;
                    oper.F_File = modelT_Bus_WorkOrder.F_File;

                    oper.F_Message = "市民（" + userinfo.F_OpenId + "） 修改了工单";


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

                    new BLL.T_Bus_Operation().Add(oper);

                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");

            }
            else
            {
                return Error("操作失败");
            }
        }



        /// <summary>
        /// 获取区域列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAreaList()
        {
            DataTable dt = new BLL.T_Sys_Area().GetList(0, "", " F_Sort").Tables[0];
            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取字典值列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDicValueList(int id = 0)
        {
            DataTable dt = new DataTable();
            dt = new BLL.T_Sys_DictionaryValue().GetList(" F_ItemId='" + id + "' and F_State=0 ").Tables[0];
            return Success("列表加载成功", dt);
        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDeptList()
        {
            DataTable dt = new DataTable();
            dt = new BLL.T_Sys_Department().GetList(0, "F_State=0", " F_Sort").Tables[0];
            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取坐席列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSeatList()
        {
            DataTable dt = new DataTable();
            dt = new BLL.T_Sys_UserAccount().GetList(0, "f_seatflag=1", " f_userid desc").Tables[0];
            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取工单日周月报表
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetAPPWorkReport(int datetype , string date)
        {
            DateTime dttime = DateTime.Now;
            if (!string.IsNullOrEmpty(date))
            {
                if (!DateTime.TryParse(date, out dttime))
                {
                    dttime = DateTime.Now;
                }
            }
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@date", dttime.ToString("yyyy-MM-dd"));
            paras.Add("@datetype", datetype.ToString());
            var obj = DbHelperSQL.RunProcedure("P_APPDayWeekMonthReport", paras, "APPDayWeekMonthReport");
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取工单日周月报表
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetAPPWorkReportSingle(int datetype, string date, int dataid, int datatype)
        {
            DateTime dttime = DateTime.Now;
            if (!string.IsNullOrEmpty(date))
            {
                if (!DateTime.TryParse(date, out dttime))
                {
                    dttime = DateTime.Now;
                }
            }
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@date", dttime.ToString("yyyy-MM-dd"));
            paras.Add("@datetype", datetype.ToString());
            paras.Add("@dataid", dataid.ToString());
            paras.Add("@datatype", datatype.ToString());
            var obj = DbHelperSQL.RunProcedure("P_APPDayWeekMonthReportSingle", paras, "APPDayWeekMonthReportSingle");
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取坐席工作报表
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetAPPSeatReport(string sdate, string edate,string seatcode)
        {
            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;

            if (!string.IsNullOrEmpty(sdate))
            {
                stime = DateTime.Parse(sdate);
            }
            if (!string.IsNullOrEmpty(edate))
            {
                etime = DateTime.Parse(edate);
            }
            if (string.IsNullOrEmpty(sdate) && string.IsNullOrEmpty(edate))
            {
                stime = new DateTime(stime.Year, stime.Month, 1);
            }
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@sdate", stime.ToString("yyyy-MM-dd"));
            paras.Add("@edate", etime.ToString("yyyy-MM-dd"));
            paras.Add("@usercode", seatcode);
            var obj = DbHelperSQL.RunProcedure("P_APPSeatReport", paras, "APPSeatReport");
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取单位工作报表
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetAPPDeptReport(string sdate, string edate,int id=0)
        {
            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;

            if (!string.IsNullOrEmpty(sdate))
            {
                stime = DateTime.Parse(sdate);
            }
            if (!string.IsNullOrEmpty(edate))
            {
                etime = DateTime.Parse(edate);
            }
            if (string.IsNullOrEmpty(sdate) && string.IsNullOrEmpty(edate))
            {
                stime = new DateTime(stime.Year, stime.Month, 1);
            }
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@sdate", stime.ToString("yyyy-MM-dd"));
            paras.Add("@edate", etime.ToString("yyyy-MM-dd"));
            paras.Add("@id", id.ToString());
            var obj = DbHelperSQL.RunProcedure("P_APPDeptReport", paras, "APPDeptReport");
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取单位未签收报表
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetAPPDeptNoSureReport(string sdate, string edate, int id = 0)
        {
            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;

            if (!string.IsNullOrEmpty(sdate))
            {
                stime = DateTime.Parse(sdate);
            }
            if (!string.IsNullOrEmpty(edate))
            {
                etime = DateTime.Parse(edate);
            }
            if (string.IsNullOrEmpty(sdate) && string.IsNullOrEmpty(edate))
            {
                stime = new DateTime(stime.Year, stime.Month, 1);
            }
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@sdate", stime.ToString("yyyy-MM-dd"));
            paras.Add("@edate", etime.ToString("yyyy-MM-dd"));
            paras.Add("@id", id.ToString());
            var obj = DbHelperSQL.RunProcedure("P_APPDeptNoSureReport", paras, "APPDeptNoSureReport");
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取单位已签收报表
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetAPPDeptSureReport(string sdate, string edate, int id = 0)
        {
            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;

            if (!string.IsNullOrEmpty(sdate))
            {
                stime = DateTime.Parse(sdate);
            }
            if (!string.IsNullOrEmpty(edate))
            {
                etime = DateTime.Parse(edate);
            }
            if (string.IsNullOrEmpty(sdate) && string.IsNullOrEmpty(edate))
            {
                stime = new DateTime(stime.Year, stime.Month, 1);
            }
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@sdate", stime.ToString("yyyy-MM-dd"));
            paras.Add("@edate", etime.ToString("yyyy-MM-dd"));
            paras.Add("@id", id.ToString());
            var obj = DbHelperSQL.RunProcedure("P_APPDeptSureReport", paras, "APPDeptSureReport");
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取单位已办理报表
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetAPPDeptDealReport(string sdate, string edate, int id = 0)
        {
            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;

            if (!string.IsNullOrEmpty(sdate))
            {
                stime = DateTime.Parse(sdate);
            }
            if (!string.IsNullOrEmpty(edate))
            {
                etime = DateTime.Parse(edate);
            }
            if (string.IsNullOrEmpty(sdate) && string.IsNullOrEmpty(edate))
            {
                stime = new DateTime(stime.Year, stime.Month, 1);
            }
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("@sdate", stime.ToString("yyyy-MM-dd"));
            paras.Add("@edate", etime.ToString("yyyy-MM-dd"));
            paras.Add("@id", id.ToString());
            var obj = DbHelperSQL.RunProcedure("P_APPDeptDealReport", paras, "APPDeptDealReport");
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetUserInfo()
        {
            string usercode = RequestString.GetQueryString("usercode");
            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);
            return Success("获取成功", userinfo);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [APPActionFilter]
        public ActionResult EditUser()
        {
            string usercode = RequestString.GetFormString("usercode");
            var dModel = new BLL.T_Sys_Users().GetModel(usercode);

            string name = RequestString.GetFormString("name");
            string phone = RequestString.GetFormString("phone");
            int sex = RequestString.GetInt("sex", 0);
            string province = RequestString.GetFormString("province");
            string city = RequestString.GetFormString("city");
            string county = RequestString.GetFormString("county");
            string address = RequestString.GetFormString("address");

            var list = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + usercode + "' and F_Id!='" + dModel.F_Id + "' ");
            if (list.Count > 0)
            {
                return Error("已经存在此账号");
            }
            else
            {
                dModel.F_Name = name;
                dModel.F_Telphone = phone;
                dModel.F_Sex = sex;
                dModel.F_Province = province;
                dModel.F_City = city;
                dModel.F_County = county;
                dModel.F_Address = address;

                bool n = new BLL.T_Sys_Users().Update(dModel);
                if (n)
                    return Success("修改成功", n);
                else
                    return Error("修改失败");
            }
        }
    }
}