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

namespace CallCenterApi.Interface.Controllers
{
    public class AppealController : BaseController
    {
        BLL.T_Bus_AppealInfo bll = new BLL.T_Bus_AppealInfo();
        private BLL.T_Sys_SystemConfig configBll = new BLL.T_Sys_SystemConfig();
        // GET: Appeal
        public ActionResult Index()
        {
            return View();
        }

        // 获取申诉列表
        public ActionResult GetList(string startdate, string enddate,string deptid)
        {
            DataTable dt = new DataTable();
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            string sql = " ";
            if (startdate != null && startdate.Trim() != "")
            {
                sql += " and Datediff(day,F_CreateTime,'" + startdate.Trim() + "')>=0";
            }
            if (enddate != null && enddate.Trim() != "")
            {
                sql += " and Datediff(day,F_CreateTime,'" + enddate.Trim() + "')<=0";
            }
            if (!string.IsNullOrEmpty(deptid))
            {
                sql += " and charindex(','+'"+deptid +"'+',',','+F_DeptIds+',')>0";
            }
            //sql += " and (F_WorkOrderId is null or F_WorkOrderId='')";
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_AppealInfo",
                "F_Id",
                "*,dbo.GetDeptNames(F_DeptIds) as NoticeDeptName",
                sql,
                "ORDER BY F_Id desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }

        //添加申诉接口
        public ActionResult AddAppeal(string deptids, string content,  string noticeinfo,string workorderid,string remark,string basis,string requirement,string files,int type=0,int typeid=0,int noticeid=0)
        {
            Model.T_Bus_AppealInfo modelT_Bus_AppealInfo = new Model.T_Bus_AppealInfo();
            modelT_Bus_AppealInfo.F_DeptIds = deptids;
            modelT_Bus_AppealInfo.F_WorkOrderId = workorderid;
            modelT_Bus_AppealInfo.F_Content = content;
            modelT_Bus_AppealInfo.F_State = 0;
            modelT_Bus_AppealInfo.F_IsDelete = 0;
            modelT_Bus_AppealInfo.F_CreateTime = DateTime.Now;
            modelT_Bus_AppealInfo.F_CreateUser = User.UserData["F_UserID"];
            modelT_Bus_AppealInfo.F_NoticeID = noticeid;
            modelT_Bus_AppealInfo.F_NoticeInfo = noticeinfo;
            modelT_Bus_AppealInfo.F_Remark = remark;
            modelT_Bus_AppealInfo.F_Basis = basis;
            modelT_Bus_AppealInfo.F_Requirement = requirement;
            modelT_Bus_AppealInfo.F_Files = files;
            modelT_Bus_AppealInfo.F_Type = type;
            modelT_Bus_AppealInfo.F_TypeID = typeid;

            int b = new BLL.T_Bus_AppealInfo().Add(modelT_Bus_AppealInfo);

            if (b > 0)
            {
                return Success("添加成功");
            }
            else
            {
                return Success("添加失败");
            }
        }

        //编辑
        public ActionResult EditAppeal(string nid, string deptids, string content, string noticeinfo, string remark, string basis, string requirement, string files, int type=0, int typeid = 0, int noticeid = 0)//,int state=0)
        {

            if (nid != null && nid.Trim() != "")
            {
                Model.T_Bus_AppealInfo dModel = bll.GetModel(int.Parse(nid.Trim()));
                if (dModel != null)
                {

                    dModel.F_DeptIds = deptids;
                    //dModel.F_WorkOrderId = "";
                    dModel.F_Content = content;
                    //dModel.F_State = state;
                    dModel.F_IsDelete = 0;
                    //dModel.F_CreateTime = DateTime.Now;
                    //dModel.F_CreateUser = User.UserData["F_UserID"];
                    dModel.F_NoticeID = noticeid;
                    dModel.F_NoticeInfo = noticeinfo;
                    dModel.F_Remark = remark;
                    if (!string.IsNullOrEmpty(basis))
                    {
                        dModel.F_Basis = basis;
                    }
                    if (!string.IsNullOrEmpty(requirement))
                    {
                        dModel.F_Requirement = requirement;
                    }
                    if (!string.IsNullOrEmpty(files))
                    {
                        dModel.F_Files = files;
                    }
                    dModel.F_Type = type;
                    dModel.F_TypeID = typeid;

                    bool b = bll.Update(dModel);
                    if (b)
                    {
                        return Success("编辑成功");
                    }
                    else
                    {
                        return Success("编辑失败");
                    }
                }
                else
                    return Error("获取信息失败");
            }
            else
            {
                return Error("id不能为空");
            }

        }
        [Authority]
        //删除
        public ActionResult DelAppeal(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idds = "";
                for (int i = 0; i < ids.Length; i++)
                {
                    idds += ids[i] + ",";
                }
                bool r = bll.DeleteList(idds.Trim(','));

                if (r)
                    return Success("删除成功");
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }


        //获取申诉详情
        public ActionResult GetAppeal(string nid)
        {
            DataTable  dt = bll.GetTB(int.Parse(nid.Trim()));
            if (dt != null&&dt.Rows .Count >0)
            {
                string NoticeDeptName = "";
                if (dt.Rows[0]["F_DeptIds"] != null && dt.Rows[0]["F_DeptIds"].ToString() != "")
                {
                    NoticeDeptName = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dt.Rows[0]["F_DeptIds"].ToString() + "')").ToString();
                }
                var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (configfj != null)
                {
                    dt = BindFileData(dt, configfj.F_ParamValue);
                }
                var obj = new
                {
                    dt,
                    NoticeDeptName
                };
                return Success("获取申诉详情成功", obj);
            }
            else
            {
                return Error("获取申诉详情失败");
            }

        }

        /// <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_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    dr["File"] = GetFileData(dr["F_Files"].ToString(), prefix);
                }
            }
            return dt;
        }
        /// <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;
        }
        

        //处理申诉
        public ActionResult DealAppeal(string nid, int state,string reason)
        {

            if (nid != null && nid.Trim() != "")
            {
                Model.T_Bus_AppealInfo dModel = bll.GetModel(int.Parse(nid.Trim()));
                if (dModel != null)
                {                   
                    dModel.F_State = state;
                    if (!string.IsNullOrEmpty(reason))
                    {
                        dModel.F_Reason = reason;
                    }
                    bool b = bll.Update(dModel);
                    if (b)
                    {
                        if(state ==1)
                        {
                            //更新通报列表状态
                            BLL.T_Bus_NoticeCriticism blln = new BLL.T_Bus_NoticeCriticism();
                            blln.UpdateState(dModel .F_NCId.ToString () ,0);

                        }
                        return Success("处理成功");
                        
                    }
                    else
                    {
                        return Success("处理失败");
                    }
                }
                else
                    return Error("获取信息失败");
            }
            else
            {
                return Error("id不能为空");
            }

        }

    }
}