using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZXDT.CallCenter.Model;
using ZXDT.CallCenter.MVCWeb.Models;

namespace ZXDT.CallCenter.MVCWeb.Controllers
{


    public class CustomerController : BaseController
    {
        //
        // GET: /Customer/
        BLL.T_Cus_CustomerBase cusBLL = new BLL.T_Cus_CustomerBase();
        public ActionResult CustomerAllList(int cusType)
        {
            CusPageModel model = new CusPageModel();
            model.cusType = cusType;
            return View(model);
        }

        /// <summary>
        /// 添加修改 视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Add()
        {
            return View();
        }


        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public string AddData(T_Cus_CustomerBase CustomerBaseModel)
        {
            //客户属性
            bool bl = false;
            if (string.IsNullOrWhiteSpace(CustomerBaseModel.F_Telephone))
            {
                return Error("手机号不能为空");
            }
            if (string.IsNullOrEmpty(CustomerBaseModel.F_Kind))
            {
                CustomerBaseModel.F_Kind = "2";
            }
            if (string.IsNullOrEmpty(CustomerBaseModel.F_CustomerNature))
            {
                CustomerBaseModel.F_CustomerNature = "微信";
            }
            if (CustomerBaseModel.F_CustomerId > 0)
            {
                AddAction("t_cus_customerbase", CustomerBaseModel.F_CustomerId.ToMyString(), "更新客户信息", CustomerBaseModel.F_CustomerName.ToMyString());
                AddAction("t_cus_customerbase", CustomerBaseModel.F_CustomerId.ToMyString(), "更新客户信息", "数据：" + JsonConvert.SerializeObject(CustomerBaseModel), "关键信息");
            }
            else
            {
                ZXDT.CallCenter.Model.T_Cus_CustomerBase modelcus = cusBLL.GetCusInfoModel(CustomerBaseModel.F_Telephone);
                if (modelcus.F_CustomerId > 0)
                {
                    return Error("此手机号已存在，请进行查询修改");
                }
                AddAction("t_cus_customerbase", CustomerBaseModel.F_Telephone, "添加客户信息", CustomerBaseModel.F_CustomerName.ToMyString());
                AddAction("t_cus_customerbase", CustomerBaseModel.F_Telephone, "添加客户信息", "数据：" + JsonConvert.SerializeObject(CustomerBaseModel), "关键信息");
            }
            if (CustomerBaseModel.F_ScaleResume == "3")
            {
                #region 添加到黑名单表

                try
                {
                    string phone = CustomerBaseModel.F_Telephone;

                    Model.T_Call_Blacklist orderModel = new Model.T_Call_Blacklist();
                    orderModel.F_TelPhone = phone;
                    orderModel.F_CallId = CustomerBaseModel.F_CustomerId.ToMyString();
                    orderModel.F_SetTime = DateTime.Now;
                    orderModel.F_RemoveTime = DateTime.Now.AddYears(10);
                    orderModel.F_Describe = "客户id:" + CustomerBaseModel.F_CustomerId.ToMyString();
                    orderModel.F_InterceptNum = 0;
                    orderModel.F_UserId = F_UserID;
                    int count = new BLL.T_Call_Blacklist().Add(orderModel);

                }
                catch
                { }

                #endregion
            }
            else
            {
                new BLL.T_Call_Blacklist().DeleteBlack(CustomerBaseModel.F_Telephone.Trim());
            }

            if (CustomerBaseModel.F_CustomerId > 0)
            { }
            else
            {
                CustomerBaseModel.F_CreateBy = F_UserID;
            }

            bl = cusBLL.UpdateCusInfoModel(CustomerBaseModel);

            if (bl)
                return Success("成功");
            else
                return Error("失败");
        }

        /// <summary>
        /// 客户状态修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SaveReceivedData(string keyList, int status)
        {
            AddAction("t_cus_customerbase", keyList, "修改客户状态",status.ToMyString());
            AddAction("t_cus_customerbase", keyList, "修改客户状态", string.Format("修改{0}数据F_ScaleResume/F_CustomerClass状态为{1}" , keyList, status), "关键信息");
            return cusBLL.EditCustonStatus(keyList, status,F_UserID);
        }
        #region 加载客户列表

        /// <summary>
        /// 加载客户列表
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页数据量</param>
        /// <param name="sqlWhere">查询条件</param>
        /// <returns></returns>
        [ActionName("LoadCustomerALLList")]
        [HttpGet]
        public string LoadCustomerALLList(DateTime? NowDateTime, string cusType, int page, int limit, string cusName, string cusNum)
        {
            //数据结果集
            ResponseData dataModel = new ResponseData();

            string sql = "";



            sql += " and F_DeleteFlag=0 ";

            //语音客户
            if (cusType == "1")
            {
                sql += " and F_Kind=1 ";
            }
            //微信客户
            if (cusType == "2")
            {
                sql += " and F_Kind=2 ";
            }
            //微博客户
            if (cusType == "3")
            {
                sql += " and F_Kind=3 ";
            }
            //特别客户
            if (cusType == "4")
            {
                sql += " and F_ScaleResume=2";
            }
         
            //白名单客户
            if (cusType == "6")
            {
                sql += " and F_ScaleResume=4";
            }


            if (!string.IsNullOrEmpty(cusName))
            {
                sql += " and F_CustomerName like '%" + cusName.Trim() + "%' ";
            }

            if (!string.IsNullOrEmpty(cusNum))
            {
                // sql += " and( F_Telephone like '%" + cusNum + "%' or F_Mobile like '%" + cusNum + "%' )";
                sql += " and F_Telephone like '%" + cusNum.Trim() + "%'";
            }
            //黑名单客户
            if (cusType == "5")
            {
                // sql += " and F_ScaleResume=3";
                int recordCountblack = 0;
                DataTable dtblack = new DataTable();
                //Model.PageData<Model.T_Cus_CustomerBase> pageModelblack = new Model.PageData<Model.T_Cus_CustomerBase>();
                string table = " (select t1.*,t2.F_UserId from T_Cus_CustomerBase  t1 left join  T_Call_Blacklist t2 on t1.F_CustomerId = t2.F_CallId  where t1.F_DeleteFlag = 0 and t2.F_IsDelete = 0) t";
                dtblack = BLL.PagerBLL.GetListPager(
                    table,
                    "F_CustomerId",
                 "*,CONVERT(varchar,F_ModifiedOn, 120 ) as F_ModifiedOnNew ,[dbo].[GetUserNameByUserID](F_UserId) F_CreateUserName",
                    sql,
                    "ORDER BY F_CustomerId desc",
                    limit,
                    page,
                    true,
                    out recordCountblack);


                dataModel.code = 0;
                dataModel.count = recordCountblack;
                dataModel.data = dtblack;

                return JsonConvert.SerializeObject(dataModel);


            }


            DataTable dt = new DataTable();
            int recordCount = 0;
            Model.PageData<Model.T_Cus_CustomerBase> pageModel = new Model.PageData<Model.T_Cus_CustomerBase>();
            dt = BLL.PagerBLL.GetListPager(
                "T_Cus_CustomerBase",
                "F_CustomerId",
             "*,CONVERT(varchar,F_ModifiedOn, 120 ) as F_ModifiedOnNew ,[dbo].[GetUserNameByUserID](F_CreateBy) F_CreateUserName" ,


                sql,
                "ORDER BY F_CustomerId desc",
                limit,
                page,
                true,
                out recordCount);


            dataModel.code = 0;
            dataModel.count = recordCount;
            dataModel.data = dt;

            return JsonConvert.SerializeObject(dataModel);
        }



        [ActionName("GetCustomerModel")]
        [HttpGet]
        public string GetCustomerModel(int id)
        {
            if (id == 0)
            {
                return Error("id不能为空");
            }
            BLL.T_Cus_CustomerBase busCus_CustomerBase = new BLL.T_Cus_CustomerBase();
            Model.T_Cus_CustomerBase model= busCus_CustomerBase.GetModel(id);
            int count = 0;
            if (model != null)
                count = 1;
            return Success("成功", model, count);
        }


        #endregion


        #region 客户工单信息
        /// <summary>
        /// 获取所有工单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult CusOrderList(string callNumber)
        {
            ViewCusOrderModel cusModel = new ViewCusOrderModel();
            cusModel.F_Telephone = callNumber;
            cusModel.SeatFlag = F_SeatFlag;
           
            return View(cusModel);
        }

        /// <summary>
        /// 获取工单信息
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页数据量</param>
        /// <param name="sqlWhere">查询条件</param>
        /// <returns></returns>
        [ActionName("CusOrderData")]
        [HttpGet]
        public string CusOrderData(int page, int limit, string cusNumber)
        {

            //数据结果集
            ResponseData dataModel = new ResponseData();

            string sql = "";


            //客户电话
            if (!string.IsNullOrEmpty(cusNumber))
            {
                sql += " and t.F_CUSTOMERTELEPHONE = '" + cusNumber.Trim() + "'";
            }
            else
            {
                sql += " and t.F_CUSTOMERTELEPHONE='-1'";
            }
            string tableNew = string.Format("(select DISTINCT t.*  from T_Wo_WorkOrderBase t LEFT JOIN T_Wo_WorkOrderHistory h ON t.F_WORKORDERID=h.F_INSTANCEID LEFT JOIN T_Sys_UserAccount u ON  t.F_USERID= u.F_UserId  where  (u.F_DeptId={0} OR  h.F_OPTBTNID={0})) as t", F_DeptId);
            DataTable dt = new DataTable();
            int recordCount = 0;
            Model.PageData<Model.T_Wo_WorkOrderBase> pageModel = new Model.PageData<Model.T_Wo_WorkOrderBase>();
            dt = BLL.PagerBLL.GetListPager(
                tableNew,
                "F_WORKORDERID",
                " t.*,CONVERT(varchar,t.F_CREATEDATE, 120 ) as F_CREATEDATENew"
                  + " ,(CASE F_WORKORDERFROM WHEN '留言工单' THEN (SELECT F_RecFileUrl FROM dbo.T_Call_LeaveRecord  WHERE F_CallId=t.F_KSHADDRESSCODE) WHEN '语音工单' THEN (SELECT FilePath FROM dbo.T_Call_CallRecords WHERE CallId=t.F_KSHADDRESSCODE) ELSE NULL END ) as FilePath",
                sql,
                "ORDER BY t.F_CREATEDATE desc",
                limit,
                page,
                true,
                out recordCount);


            dataModel.code = 0;
            dataModel.count = recordCount;
            dataModel.data = dt;

            return JsonConvert.SerializeObject(dataModel);
        }


        [ActionName("GetCusDatabyNumber")]
        [HttpGet]
        public string GetCusDatabyNumber( string cusNumber)
        {

            //数据结果集
            ResponseData dataModel = new ResponseData();

           // cusBLL.GetCusInfoModel(cusNumber);

            return JsonConvert.SerializeObject(cusBLL.GetCusInfoModel(cusNumber));
        }


        //
        /// <summary>
        /// 保存编辑客户
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        //[AcceptVerbs(HttpVerbs.Post)]
        //public bool SaveRepositoryCategoryContentData(T_RepositoryInformation categoryContentModel)
        //{

        //    categoryContentModel.F_CreateBy = F_UserID;
        //    if (categoryContentModel.F_RepositoryId > 0)
        //    {
        //        return reposCategoryContentBLL.Update(categoryContentModel);
        //    }
        //    else
        //    {

        //        return reposCategoryContentBLL.Add(categoryContentModel) > 0;
        //    }
        //}
        #endregion

    }
    public class ViewCusOrderModel
    {
        public string F_Telephone
        {
            get;
            set;
        }


        public bool SeatFlag
        {
            get;
            set;
        }

    }

}
