using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers.System
{
    public class CustomerController : BaseController
    {
        // GET: Customer
        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(string name,string telephone,int page = 1, int pagesize = 10,int isdc = 0)
        {
            string sql = " and F_DeleteFlag=0";
            DataTable dt = new DataTable();

            if (name != null && name.Trim() != "")
            {
                sql += " and F_CustomerName like '%" + name + "%' ";
            }
            if (telephone != null && telephone.Trim() != "")
            {
                sql += " and (F_Telephone like '%" + telephone + "%' or F_Mobile like '%" + telephone + "%') ";
            }

            if (isdc > 0)
            {
                var dtdc = DB.DbHelperSQL.Query("SELECT F_CustomerName 联系人姓名,F_Mobile 联系人电话,F_Email 邮箱,F_Address 地址"
                 + " from T_Cus_Customer a WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("市民资料", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            string cols = "*,dbo.GetUserNameNew(F_CreateBy) F_CreateName";
            int recordCount = 0;
            dt = Bll.PagerBll.GetListPager(
                "T_Cus_Customer WITH(NOLOCK) ",
                "F_CustomerId",
                cols,
                sql,
                "ORDER BY F_CustomerId desc",
                pagesize,
                page,
                true,
                out recordCount);

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

            return Content(obj.ToJson());


        }

        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCustomer(int id = 0)
        {
            if (id > 0)
            {
                return Success("获取成功", new Bll.T_Cus_Customer().GetModel(id));
            }
            else
            {
                return Error("参数传输失败");
            }
        }

        /// <summary>
        /// 添加/修改客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddCustomer(string name, string telphone, string sex,string code,int? layer,string adddress,string idcard, string mobile="", string linkman="",string fax="", string email="", string province="", string city="", string county="", string postcode="",string remark="", int id =0)
        {

            #region 验证
            if (string.IsNullOrEmpty(name))
            {
                return Error("请输入客户名称");
            }
            #endregion

            Model.T_Cus_Customer model = new Model.T_Cus_Customer();
            Bll.T_Cus_Customer bll = new Bll.T_Cus_Customer();
            if (id == 0)
            {
                model.F_CustomerName = name;    //客户名称
                model.F_Mobile = mobile;        //联系人手机
                model.F_Telephone = telphone;   //联系人电话-单位电话
                model.F_Fax = fax;              //传真
                model.F_PostCode = postcode;    //邮编
                model.F_Email = email;          //邮件
                model.F_Province = province;      //省
                model.F_City = city;//市
                model.F_County = county;    //区
                model.F_Sex = sex;                  //性别
                model.F_IdCard = idcard;    //身份证号
                model.F_CustomerCode = code;//客户编码
                model.F_Layer = layer;//级别
                model.F_Address = adddress;//地址

                model.F_CreateBy = User.F_UserCode;          //创建人
                model.F_CreatedOn = DateTime.Now;   //创建时间
                model.F_DeleteFlag = 0;             //删除标志
                model.F_Remark = remark;
                model.F_AboutLinkMan = linkman;
                int n = bll.Add(model);
                if (n > 0)
                {
                    return Success("新增成功！", n);
                }
                else
                {
                    return Error("新增失败！");
                }

            }
            else
            {
                model = bll.GetModel(id);
                if (model != null)
                {
                    model.F_CustomerName = name;    //客户名称
                    model.F_Mobile = mobile;        //联系人手机
                    model.F_Telephone = telphone;   //联系人电话-单位电话
                    model.F_Fax = fax;              //传真
                    model.F_PostCode = postcode;    //邮编
                    model.F_Email = email;          //邮件
                    model.F_Province = province;      //省
                    model.F_City = city;//市
                    model.F_County = county;    //区
                    model.F_Sex = sex;                  //性别
                    model.F_IdCard = idcard;    //身份证号
                    model.F_CustomerCode = code;//客户编码
                    model.F_Layer = layer;//级别
                    model.F_Address = adddress;//地址
                    model.F_ModifiedOn = DateTime.Now;
                    model.F_ModifyBy = User.F_UserCode;
                    model.F_Remark = remark;
                    model.F_AboutLinkMan = linkman;
                    if (bll.Update(model))
                    {
                        return Success("修改成功！");
                    }
                    else
                    {
                        return Error("修改失败！");
                    }
                }
                else
                {
                    return Error("修改失败！");
                }
            }

        }

        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelCustomer(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = "";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                //string state = RequestString.GetQueryString("state");

                string sql = "update T_Cus_Customer set F_DeleteFlag=1,F_DeleteOn=getdate(),F_DeleteBy='" + User.F_UserCode + "' where F_CustomerId in(" + idd.TrimEnd(',') + ")";

                if (DB.DbHelperSQL.ExecuteSql(sql) > 0)
                {
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 导入客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportCustomer()
        {
            HttpPostedFileBase _upfile = Request.Files["upFile"] ;
            int headrow = 0;
            NPOIHelper npoi = new NPOIHelper();
            DataTable dt = npoi.ExcelToTable(_upfile, headrow);
            var bll = new Bll.T_Cus_Customer();
            foreach (DataRow dr in dt.Rows)
            {
                headrow = headrow + 1;
                if (dr[0].ToString() != "" && dr[1].ToString() != "")
                {
                    Model.T_Cus_Customer model = new Model.T_Cus_Customer();
                    model.F_CustomerName = dr[0].ToString();    //客户姓名
                    model.F_Sex = dr[1].ToString();   //性别
                    model.F_Mobile = dr[2].ToString();          //手机号码
                     model.F_IdCard = dr[3].ToString();           //身份证号
                    model.F_Address = dr[4].ToString();      //地址
                    model.F_AboutLinkMan = dr[5].ToString();
                    model.F_Remark = dr[6].ToString();

                    model.F_CreateBy = User.F_UserCode;
                    model.F_CreatedOn = DateTime.Now;
                    model.F_DeleteFlag = 0;
                    if (bll.Add(model) <= 0)
                    {
                        return Error("第" + headrow + "行，导入失败!");
                    }
                }
                else
                {
                    return Error("第" + headrow + "行，第1，2列信息不能为空，未导入");
                }
            }
            return Success("导入成功");
        }

        public ActionResult GetUserInfoByPhone(string phone)
        {
            string sql = "select * from T_Cus_Customer where  F_Telephone='"+phone+ "' or F_Mobile='"+phone+"'";
            DataTable dtcustomer = DB.DbHelperSQL.Query(sql).Tables[0];

            string sqluser = "  select * ,dbo.GetDepName(F_DeptId) deptname from T_Sys_UserAccount  where  F_Telephone='" + phone + "' or F_WorkPhone='" + phone + "'";
            DataTable dtuser = DB.DbHelperSQL.Query(sqluser).Tables[0];
            var obj = new
            {
                state = "success",
                message = "成功",
                dtcustomer = dtcustomer,
                dtuser = dtuser
            };

            return Success("根据电话号码获取信息成功", obj);

        }

    }
}