using CallCenter.Utility;
using CallCenter.Utility.log;
using CallCenterApi.Interface.Controllers.Base;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.workorder
{
    public class ShangQiuWorkOrderController : BaseController
    {
        BLL.T_Bus_WorkOrder_GovernmentServiceWO_Map womapbll = new BLL.T_Bus_WorkOrder_GovernmentServiceWO_Map();
        Model.T_Bus_WorkOrder_GovernmentServiceWO_Map womapmodel = new Model.T_Bus_WorkOrder_GovernmentServiceWO_Map();

        private AjaxResult result = new AjaxResult();
        /// <summary>
        /// 添加工单接口（投诉/咨询）
        /// 商丘市政务服务网和12345系统对接接口
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        public ActionResult AddWorkOrder()
        {
            
            string message = string.Empty;
            string port_password = RequestString.GetFormString("port_password");   //加密信息(安全验证用)
            string uuid = RequestString.GetFormString("uuid");          //客户唯一标识（安全验证用）
            int source = RequestString.GetInt("source", 7);             //信息来源
            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");    //内容
            int sourcearea = RequestString.GetInt("sourcearea", 0);      //事发地域id
            string sourceaddress = RequestString.GetFormString("sourceaddress");    //事发详细地址
            string keys = RequestString.GetFormString("keys");          //关键词id(多个用英文逗号, 隔开)
            string splituser = RequestString.GetFormString("splituser");    //分管领导id(多个用英文逗号, 隔开)
            int type = RequestString.GetInt("type", 0);              //类型
            int bigtype = RequestString.GetInt("bigtype", 0);        //大类别
            int smalltype = RequestString.GetInt("smalltype", 0);    //小类别
            int isprotect = RequestString.GetInt("isprotect", 0);    //0普通1保密
            int level = RequestString.GetInt("level", 0);            //1普通2紧急3特急

            if (string.IsNullOrEmpty(uuid))
            {
                result.state = (int)CodeStatus.ID不存在;
                result.message = "客户唯一标识不能为空";
                return Process();
            }
            else if (uuid.Length > 50)
            {
                result.state = (int)CodeStatus.字符串超出长度;
                result.message = "客户唯一标识超出长度";
                return Process();
            }
            if (string.IsNullOrEmpty(cusphone))
            {
                result.state = (int)CodeStatus.必填字段为空;
                result.message = "投诉人电话不能为空";
                return Process();
            }
            if (!Common.CodeValidate.ICodeValidate(uuid + cusphone, port_password))
            {
                result.state = (int)CodeStatus.安全验证未通过;
                result.message = "安全验证未通过";
                return Process();
            }
            if (string.IsNullOrEmpty(cusname))
            {
                result.state = (int)CodeStatus.必填字段为空;
                result.message = "投诉人姓名不能为空";
                return Process();
            }
            if (string.IsNullOrEmpty(title))
            {
                result.state = (int)CodeStatus.必填字段为空;
                result.message = "标题不能为空";
                return Process();
            }
            WorkOrderController wo = new WorkOrderController();
            if (!womapbll.ExistsByGSWorkOrderId(uuid))  //uuid不存在时,防止重复添加
            {
                string WorkOrderId = wo.AddWorkOrderBySource(source, cusname, cussex, cusphone, cusaddress, email, zipcode, conname, conphone, title, content, sourcearea, sourceaddress, keys, splituser, type, bigtype, smalltype, isprotect, level);
                if (string.IsNullOrEmpty(WorkOrderId))
                {
                    result.state = (int)CodeStatus.异常结果类型;
                    result.message = "操作失败";
                    return Process();
                }

                womapmodel.F_WorkOrderId = WorkOrderId;
                womapmodel.F_GSWorkOrderId = uuid;
                womapmodel.F_AddTime = DateTime.Now;
                int n = womapbll.Add(womapmodel);
                if (n <= 0)
                {
                    result.state = (int)CodeStatus.异常结果类型;
                    result.message = "操作失败";
                    return Process();
                }

                result.state = (int)CodeStatus.SUCCESS;
                result.message = "操作成功";
                result.data = WorkOrderId;  //订单号
                return Process();
            }
            else {
                result.state = (int)CodeStatus.数据库错误;
                result.message = "操作失败,信息已存在";
                return Process();
            }
        }
        /// <summary>
        /// 成功的消息格式化
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected virtual ActionResult Process()
        {
            string methodName = new System.Diagnostics.StackTrace(true).GetFrame(1).GetMethod().Name;   //事件源
            LogInterface.WriteLog(this.GetType().ToString() + " -- " + methodName + "\r\n" + result.state + "|" + result.data + result.message); //日志
            var jsonMsg = new AjaxResult { state = result.state, message = result.message, data=result.data }.ToJson();
            return Content(jsonMsg);
        }


        /// <summary>
        /// 处理信息推送（咨询、投诉）
        /// </summary>
        /// <param name="WorkOrderId">唯一标识</param>
        /// <param name="operateUserName">处理人</param>
        /// <param name="operateOrgName">处理人单位</param>
        /// <param name="opinion">处理意见</param>
        /// <param name="operateFlag">处理状态（1: 未处理 2: 处理中 3: 已归档）</param>
        /// <param name="type">处理类型（0:咨询 1:投诉）</param>
        /// <returns>返回（true 成功 false 失败）</returns>
        public bool SaveReplyInfo(string WorkOrderId, string operateUserName,string operateOrgName,string opinion,string operateFlag,string type)
        {
            string methodName = new System.Diagnostics.StackTrace(true).GetFrame(1).GetMethod().Name;   //事件源
            //9咨询 11投诉
            if (type == "9") {                
                type = "0"; //0:咨询 1:投诉
            }
            else {
                type = "1";
            }
            if (womapbll.ExistsByWorkOrderId(WorkOrderId))    //WorkOrderId存在时,防止重复添加
            {
                var womap = womapbll.GetModelList(" F_WorkOrderId = " + WorkOrderId + "").FirstOrDefault();
                try
                {
                    string ReqURL = Configs.GetValue("ReplyInfoUrl");
                    string param = "id=" + womap.F_GSWorkOrderId
                        + "&operateUserName=" + operateUserName
                        + "&operateOrgName=" + operateOrgName
                        + "&opinion=" + opinion
                        + "&operateFlag=" + operateFlag
                        + "&type=" + type;
                    string resultReq = HttpMethods.HttpPost(ReqURL, param);
                    JObject result = JObject.Parse(resultReq);
                    if (result["flag"].ToString() == "true")
                    {
                        LogInterface.WriteLog(this.GetType().ToString() + " -- " + methodName + "\r\n" + "Success:订单" + WorkOrderId + "信息推送成功"); //日志
                        return true;
                    }
                    else
                    {
                        LogInterface.WriteLog(this.GetType().ToString() + " -- " + methodName + "\r\n" + "ERROR:订单" + WorkOrderId + "信息推送失败"); //日志
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    LogInterface.WriteLog(this.GetType().ToString() + " -- " + methodName + "\r\n" + "ERROR:订单" + WorkOrderId + "报错" + ex.Message); //日志
                    return false;
                }
            }
            else {
                LogInterface.WriteLog(this.GetType().ToString() + " -- " + methodName + "\r\n" + "ERROR:订单" + WorkOrderId + "信息推送失败"); //日志
                return false;
            }

            
        }

        /// <summary>
        /// 状态枚举
        /// </summary>
        enum CodeStatus
        {
            SUCCESS = 200,
            安全验证未通过 = 400,
            无法预测的程序错误 = 500,
            参数格式错误 = 100,
            必填字段为空 = 101,
            字符串超出长度 = 102,
            数据库错误 = 103,
            执行超时 = 104,
            参数逻辑错误 = 105,
            ID不存在 = 106,
            用户已禁用 = 120,
            异常结果类型 = 500
        }
    }
}