using CallCenter.Utility;
using CallCenter.Utility.log;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.customer
{
    public class XLXCustomerController : BaseController
    {
        private AjaxResult ajresult = new AjaxResult();
        BLL.T_Cus_Customerrecords t_Cus_Customerrecords = new BLL.T_Cus_Customerrecords();
        public ActionResult AddCustomer()
        {
            Model.T_Cus_Customerrecords cusmodel = new Model.T_Cus_Customerrecords();
            string port_password = RequestString.GetFormString("port_password");   //加密信息(安全验证用)
            string uuid = RequestString.GetFormString("uuid");          //客户唯一标识（安全验证用）
               //信息来源
            string customercode = RequestString.GetFormString("customercode");   //客户code10位数字
            int  gender = RequestString.GetInt("gender", 1);     //客户性别1男2女
            string companyname = RequestString.GetFormString("companyname");    //公司名称
            string areaname = RequestString.GetFormString("areaname");    //大区名称
            string branchname = RequestString.GetFormString("branchname");    //分公司名称
            string salesman = RequestString.GetFormString("salesman");    //业务员
            string salesphone = RequestString.GetFormString("salesphone");    //业务员电话
            string channel = RequestString.GetFormString("channel");    //渠道类型
            string credit = RequestString.GetFormString("credit");    //信用等级
            string customername = RequestString.GetFormString("customername");    //客户姓名
            string customerphone = RequestString.GetFormString("customerphone");    //客户电话
            string province = RequestString.GetFormString("province");    //省份
            string city = RequestString.GetFormString("city");    //市
            string country  = RequestString.GetFormString("county");    //区/县
            string township = RequestString.GetFormString("township");    //乡镇
            string  addressfull = RequestString.GetFormString("addressfull");    //详细地址
            string brands = RequestString.GetFormString("brands");    //经营品牌
            string product = RequestString.GetFormString("product");    //产品
            string isrunxlx = RequestString.GetFormString("isrunxlx");     //是否经营心连心0否1是
            string annualsales = RequestString.GetFormString("annualsales");    //年销量
            string formula = RequestString.GetFormString("formula");    //配方
            string raisecrops = RequestString.GetFormString("raisecrops");    //种植作物
            string plantingarea = RequestString.GetFormString("plantingarea");    //种植面积
            string fertilizerbrand = RequestString.GetFormString("fertilizerbrand");    //用肥品牌
            string remark = RequestString.GetFormString("remark");    //备注
            if (string.IsNullOrEmpty(uuid))
            {
                ajresult.state = (int)CodeStatus.ID不存在;
                ajresult.message = "客户唯一标识不能为空";
                return Process();
            }
            else if (uuid.Length > 50)
            {
                ajresult.state = (int)CodeStatus.字符串超出长度;
                ajresult.message = "客户唯一标识超出长度";
                return Process();
            }
            Model.T_Cus_CustomerBaseNew _Customer = new Model.T_Cus_CustomerBaseNew();
            CustomerNewController cus = new CustomerNewController();
            if (!string.IsNullOrEmpty(customercode))
            {
                if (!cus.valcode(customercode))
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "客户编号必须是10位数字";
                    return Process();
                }
                  
                if (cus.getunique(0, customercode))
                {
                     _Customer = new BLL.T_Cus_CustomerBaseNew().GetModelList("F_IsDelete=0 and F_CustomerCode='" + customercode + "'")
              .FirstOrDefault();
                }
            }
            else
            {
                ajresult.state = (int)CodeStatus.必填字段为空;
                ajresult.message = "客户编号不能为空";
                return Process();
            }
            
            if (!Common.CodeValidate.ICodeValidate(uuid + customercode, port_password))
            {
                ajresult.state = (int)CodeStatus.安全验证未通过;
                ajresult.message = "安全验证未通过";
                return Process();
            }
         
       
            if (!string.IsNullOrEmpty(salesphone))
            {
                if (!IsNumeric(salesphone))
                   {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "请输入正确的业务员电话";
                    return Process();
                 }
            }
            if (gender>2|| gender<1)
            {
                ajresult.state = (int)CodeStatus.参数逻辑错误;
                ajresult.message = "性别错误！";
                return Process();
            }
            string  area="", branch = "";
            if (!string .IsNullOrEmpty (areaname))
            {
                if (cus .IsModelDeptment (areaname)==null )
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "大区名称错误！查找不到该大区";
                    return Process();
                }
                else
                {
                    area = cus.IsModelDeptment(areaname).F_DeptId.ToString ();
                }
            }
           
            if (!string.IsNullOrEmpty(branchname))
            {
                if (cus.IsModelDeptment(branchname) == null)
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "分公司名称错误！查找不到该分公司";
                    return Process();
                }
                else
                    branch = cus.IsModelDeptment(branchname).F_DeptId.ToString();
            }
          
            if (!t_Cus_Customerrecords.ExistsCuscodeuuid(uuid))  //uuid不存在时,防止重复添加
            {
                int cusid = 0;
                if (_Customer != null)
                {
                    cusid = cus.CustemweCode(customercode, gender.ToString(),
               companyname, area, branch, salesman, salesphone, channel, credit, customername
               , customerphone, province, city, country, township, addressfull, brands, product
               , isrunxlx, annualsales, formula, raisecrops, plantingarea, fertilizerbrand, remark, _Customer.F_CustomerId );
                }
                else
                {
                    cusid = cus.CustemweCode(customercode, gender.ToString(),
               companyname, area, branch, salesman, salesphone, channel, credit, customername
               , customerphone, province, city, country, township, addressfull, brands, product
               , isrunxlx, annualsales, formula, raisecrops, plantingarea, fertilizerbrand, remark);
                }
               
                if (cusid==0)
                {
                    ajresult.state = (int)CodeStatus.异常结果类型;
                    ajresult.message = "操作失败";
                    return Process();
                }

                cusmodel.F_Cuscode  = cusid.ToString ();
                cusmodel.F_Cuscodeuuid  = uuid;
                cusmodel.F_AddTime = DateTime.Now;
                cusmodel.F_Type = 0;
                int n = t_Cus_Customerrecords.Add(cusmodel);
                if (n <= 0)
                {
                    ajresult.state = (int)CodeStatus.异常结果类型;
                    ajresult.message = "操作失败";
                    return Process();
                }

                ajresult.state = (int)CodeStatus.SUCCESS;
                ajresult.message = "操作成功";
                ajresult.data = cusid;  //订单号
                return Process();
            }
            else
            {
                ajresult.state = (int)CodeStatus.数据库错误;
                ajresult.message = "操作失败,信息已存在";
                return Process();
            }

        }
        public ActionResult EditCustomer()
        {
            Model.T_Cus_Customerrecords cusmodel = new Model.T_Cus_Customerrecords();
            string port_password = RequestString.GetFormString("port_password");   //加密信息(安全验证用)
            string uuid = RequestString.GetFormString("uuid");          //客户唯一标识（安全验证用）
                                                                        //信息来源
            int  id = RequestString.GetInt("id",0);   //客户档案id
            string customercode = RequestString.GetFormString("customercode");   //客户code10位数字
            int gender = RequestString.GetInt("gender", 1);     //客户性别1男2女
            string companyname = RequestString.GetFormString("companyname");    //公司名称
            string areaname = RequestString.GetFormString("areaname");    //大区名称
            string branchname = RequestString.GetFormString("branchname");    //分公司名称
            string salesman = RequestString.GetFormString("salesman");    //业务员
            string salesphone = RequestString.GetFormString("salesphone");    //业务员电话
            string channel = RequestString.GetFormString("channel");    //渠道类型
            string credit = RequestString.GetFormString("credit");    //信用等级
            string customername = RequestString.GetFormString("customername");    //客户姓名
            string customerphone = RequestString.GetFormString("customerphone");    //客户电话
            string province = RequestString.GetFormString("province");    //省份
            string city = RequestString.GetFormString("city");    //市
            string country = RequestString.GetFormString("county");    //区/县
            string township = RequestString.GetFormString("township");    //乡镇
            string addressfull = RequestString.GetFormString("addressfull");    //详细地址
            string brands = RequestString.GetFormString("brands");    //经营品牌
            string product = RequestString.GetFormString("product");    //产品
            string isrunxlx = RequestString.GetFormString("isrunxlx");     //是否经营心连心0否1是
            string annualsales = RequestString.GetFormString("annualsales");    //年销量
            string formula = RequestString.GetFormString("formula");    //配方
            string raisecrops = RequestString.GetFormString("raisecrops");    //种植作物
            string plantingarea = RequestString.GetFormString("plantingarea");    //种植面积
            string fertilizerbrand = RequestString.GetFormString("fertilizerbrand");    //用肥品牌
            string remark = RequestString.GetFormString("remark");    //备注
            if (string.IsNullOrEmpty(uuid))
            {
                ajresult.state = (int)CodeStatus.ID不存在;
                ajresult.message = "客户唯一标识不能为空";
                return Process();
            }
            else if (uuid.Length > 50)
            {
                ajresult.state = (int)CodeStatus.字符串超出长度;
                ajresult.message = "客户唯一标识超出长度";
                return Process();
            }
            if (id <=0)
            {
                ajresult.state = (int)CodeStatus.ID不存在 ;
                ajresult.message = "请输入正确的ID";
                return Process();
            }
            Model .T_Cus_CustomerBaseNew _Customer=new BLL.T_Cus_CustomerBaseNew().GetModel(id);
            if (_Customer==null )
            {
                ajresult.state = (int)CodeStatus.ID不存在;
                ajresult.message = "请输入正确的ID";
                return Process();
            }
            CustomerNewController cus = new CustomerNewController();
            if (!string.IsNullOrEmpty(customercode))
            {
                if (!cus.valcode(customercode))
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "客户编号必须是10位数字";
                    return Process();
                }

                if (cus.getunique(id , customercode))
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "客户编号已被占用，请重新输入！";
                    return Process();
                }
            }
            else
            {
                ajresult.state = (int)CodeStatus.必填字段为空;
                ajresult.message = "客户编号不能为空";
                return Process();
            }
           
            if (!Common.CodeValidate.ICodeValidate(uuid + customercode, port_password))
            {
                ajresult.state = (int)CodeStatus.安全验证未通过;
                ajresult.message = "安全验证未通过";
                return Process();
            }
           
           
            if (!string.IsNullOrEmpty(salesphone))
            {
                if (!IsNumeric(salesphone))
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "请输入正确的业务员电话";
                    return Process();
                }
            }
            if (gender > 2 || gender < 1)
            {
                ajresult.state = (int)CodeStatus.参数逻辑错误;
                ajresult.message = "性别错误！";
                return Process();
            }
            string area = "", branch = "";
            if (!string.IsNullOrEmpty(areaname))
            {
                if (cus.IsModelDeptment(areaname) == null)
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "大区名称错误！查找不到该大区";
                    return Process();
                }
                else
                {
                    area = cus.IsModelDeptment(areaname).F_DeptId.ToString();
                }
            }

            if (!string.IsNullOrEmpty(branchname))
            {
                if (cus.IsModelDeptment(branchname) == null)
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "分公司名称错误！查找不到该分公司";
                    return Process();
                }
                else
                    branch = cus.IsModelDeptment(branchname).F_DeptId.ToString();
            }
            
            if (!t_Cus_Customerrecords.ExistsCuscodeuuid(uuid))  //uuid不存在时,防止重复添加
            {
                int cusid = cus.CustemweCode(customercode, gender.ToString(),
                companyname, area, branch, salesman, salesphone, channel, credit, customername
                , customerphone, province, city, country, township, addressfull, brands, product
                , isrunxlx, annualsales, formula, raisecrops, plantingarea, fertilizerbrand, remark,id );
                if (cusid == 0)
                {
                    ajresult.state = (int)CodeStatus.异常结果类型;
                    ajresult.message = "操作失败";
                    return Process();
                }
                cusmodel.F_Cuscode = cusid.ToString();
                cusmodel.F_Cuscodeuuid = uuid;
                cusmodel.F_AddTime = DateTime.Now;
                cusmodel.F_Type  = 1;
                int a = 0;
                int n = t_Cus_Customerrecords.Add(cusmodel);
                if (n <= 0)
                {
                    ajresult.state = (int)CodeStatus.异常结果类型;
                    ajresult.message = "操作失败";
                    return Process();
                }

                ajresult.state = (int)CodeStatus.SUCCESS;
                ajresult.message = "操作成功";
                ajresult.data = cusid;  //订单号
                return Process();
            }
            else
            {
                ajresult.state = (int)CodeStatus.数据库错误;
                ajresult.message = "操作失败,信息已存在";
                return Process();
            }

        }
        public ActionResult GetCustomer()
        {
            string port_password = RequestString.GetFormString("port_password");   //加密信息(安全验证用)
            string uuid = RequestString.GetFormString("uuid");          //客户唯一标识（安全验证用）
                                                                        //信息来源
            string customercode = RequestString.GetFormString("customercode");   //客户code10位数字
            if (string.IsNullOrEmpty(uuid))
            {
                ajresult.state = (int)CodeStatus.ID不存在;
                ajresult.message = "客户唯一标识不能为空";
                return Process();
            }
            else if (uuid.Length > 50)
            {
                ajresult.state = (int)CodeStatus.字符串超出长度;
                ajresult.message = "客户唯一标识超出长度";
                return Process();
            }

            if (!Common.CodeValidate.ICodeValidate(uuid + customercode, port_password))
            {
                ajresult.state = (int)CodeStatus.安全验证未通过;
                ajresult.message = "安全验证未通过";
                return Process();
            }
            CustomerNewController cus = new CustomerNewController();
            if (!string.IsNullOrEmpty(customercode))
            {
                if (!cus.valcode(customercode))
                {
                    ajresult.state = (int)CodeStatus.参数逻辑错误;
                    ajresult.message = "客户编号必须是10位数字";
                    return Process();
                }
               
            }
            else
            {
                ajresult.state = (int)CodeStatus.必填字段为空;
                ajresult.message = "客户编号不能为空";
                return Process();
            }
            Model.T_Cus_CustomerBaseNew _Customer = new BLL.T_Cus_CustomerBaseNew().GetModelList ("F_IsDelete=0 and F_CustomerCode='"+ customercode + "'")
                .FirstOrDefault ();
            if (_Customer==null )
            {
                ajresult.state = (int)CodeStatus.ID不存在;
                ajresult.message = "该客户不存在";
                return Process();
            }
            else
            {
                ajresult.state = (int)CodeStatus.SUCCESS;
                ajresult.message = "操作成功";
                ajresult.data = _Customer.F_CustomerId ;  //订单号
                return Process();
            }

        }
        public ActionResult DelCustomer( string uuid, string port_password, int  id =0)
        {
            Model.T_Cus_Customerrecords cusmodel = new Model.T_Cus_Customerrecords();
            if (string.IsNullOrEmpty(uuid))
            {
                ajresult.state = (int)CodeStatus.ID不存在;
                ajresult.message = "客户唯一标识不能为空";
                return Process();
            }
            else if (uuid.Length > 50)
            {
                ajresult.state = (int)CodeStatus.字符串超出长度;
                ajresult.message = "客户唯一标识超出长度";
                return Process();
            }
            if (id <=0)
            {
                ajresult.state = (int)CodeStatus.ID不存在 ;
                ajresult.message = "请输入正确的ID";
                return Process();
            }
            Model.T_Cus_CustomerBaseNew _Customer = new BLL.T_Cus_CustomerBaseNew().GetModel(id);
            if (_Customer == null)
            {
                ajresult.state = (int)CodeStatus.ID不存在;
                ajresult.message = "请输入正确的ID";
                return Process();
            }
            if (!Common.CodeValidate.ICodeValidate(uuid + _Customer.F_CustomerCode  , port_password))
            {
                ajresult.state = (int)CodeStatus.安全验证未通过;
                ajresult.message = "安全验证未通过";
                return Process();
            }
            CustomerNewController cus = new CustomerNewController();
            if (cus .DelCustomers(id .ToString ()))
            {
                cusmodel.F_Cuscode = id.ToString();
                cusmodel.F_Cuscodeuuid = uuid;
                cusmodel.F_AddTime = DateTime.Now;
                cusmodel.F_Type = 2;
                int n = t_Cus_Customerrecords.Add(cusmodel);
                if (n <= 0)
                {
                    ajresult.state = (int)CodeStatus.异常结果类型;
                    ajresult.message = "操作失败";
                    return Process();
                }
                ajresult.state = (int)CodeStatus.SUCCESS;
                ajresult.message = "操作成功";
                ajresult.data = "";  //订单号
                return Process();
            }
            else
            {
                ajresult.state = (int)CodeStatus.数据库错误;
                ajresult.message = "操作失败";
                return Process();
            }
        }


        public static bool IsNumeric(string value)
        {
            return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");

        }
        /// <summary>
        /// 验证物料编码为10位纯数字
        /// </summary>
        private bool valcode(string code)
        {
            var res = false;
            //11位数字
            if (code.Length == 10 && Regex.IsMatch(code, @"^\d{10}$"))
                res = true;
            return res;
        }
        /// <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" + ajresult.state + "|" + ajresult.data + ajresult.message); //日志
            var jsonMsg = new AjaxResult { state = ajresult.state, message = ajresult.message, data = ajresult.data }.ToJson();
            return Content(jsonMsg);
        }
        /// <summary>
        /// 状态枚举
        /// </summary>
        enum CodeStatus
        {
            SUCCESS = 200,
            安全验证未通过 = 400,
            无法预测的程序错误 = 501,
            参数格式错误 = 100,
            必填字段为空 = 101,
            字符串超出长度 = 102,
            数据库错误 = 103,
            执行超时 = 104,
            参数逻辑错误 = 105,
            ID不存在 = 106,
            执行失败 = 108,
            用户已禁用 = 120,
            异常结果类型 = 500

        }
    }
}