using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Model;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.customer
{
    public class CustomerNewController : BaseController
    {
        BLL.T_Cus_CustomerBaseNew cusbll = new BLL.T_Cus_CustomerBaseNew();
        BLL.T_Cus_ContactPersonNew conbll = new BLL.T_Cus_ContactPersonNew();
        BLL.T_Sys_Department deptbll = new BLL.T_Sys_Department();
        BLL.T_Sys_RoleInfo rolebll = new BLL.T_Sys_RoleInfo();
        BLL.T_Cus_CustomerFinance finbll = new BLL.T_Cus_CustomerFinance();
        BLL.T_Sys_Department departmentBLL = new BLL.T_Sys_Department();
        #region 客户管理
        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <param name="code">客户编号</param>
        /// <param name="cmpname">公司名称</param>
        /// <param name="cmpaddress">公司地址</param>
        /// <param name="legname">法人姓名</param>
        /// <param name="legtel">法人电话</param>
        /// <param name="subtrade">所属行业</param>
        /// <param name="layer">客户信誉等级</param>
        /// <param name="bedept">客户归属部门</param>
        /// <param name="bereladd">客户归属涉税会计</param>
        /// <param name="beaudacc">客户归属审核会计</param>
        /// <param name="bemakeacc">客户归属做账会计</param>
        /// <param name="conname">联系人姓名</param>
        /// <param name="contel">联系人电话</param>
        /// <returns></returns>
        public ActionResult GetList(string keywords, string channel,string code, string cmpname, string legname, string legtel, string province, string city,
            string country, string township, int areaid = 0, int branchid = 0, int pageindex = 1, int pagesize = 10,int isdc=0)
        {
            string sql = $" and F_IsDelete=0";
            DataTable dt = new DataTable();
            #region 筛选条件
            if (areaid > 0)//大区
                sql += $" and F_AreaID=" + areaid;
            if (branchid > 0)//分公司
                sql += $" and F_BranchID=" + branchid;
            if (!string.IsNullOrWhiteSpace(code))//客户编号
            {
                if (valcode(code))
                    sql += $" and F_CustomerCode like '%" + code.Trim() + "%'";
            }
            if (!string.IsNullOrWhiteSpace(channel))//渠道类型
                sql += $" and F_Channel like '%" + channel.Trim() + "%'";
            if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                sql += $"  and  (F_AddressCity like '%" + keywords.Trim()
                         + "%' or F_AddressCountry like '%" + keywords.Trim() + "%' or F_AddressFull like '%" + keywords.Trim()
                         + "%' or F_AddressProvince like '%" + keywords.Trim() + "%' or F_AddressTownship like '%" + keywords.Trim()
                          + "%' or F_CompanyName like '%" + keywords.Trim()
                           + "%' or F_Legal like '%" + keywords.Trim()
                            + "%'or F_Salesman like '%" + keywords.Trim() + "%')  ";
            if (!string.IsNullOrWhiteSpace(cmpname))//公司名称
                sql += $" and F_CompanyName like '%" + cmpname.Trim() + "%'";
            if (!string.IsNullOrWhiteSpace(legname))//法人姓名
                sql += $" and F_Legal like '%" + legname.Trim() + "%'";
            if (!string.IsNullOrWhiteSpace(legtel))//法人电话
                sql += $" and F_LegalPhone like '%" + legtel.Trim() + "%'";
            if (!string.IsNullOrWhiteSpace(province))//省
                sql += $" and F_AddressProvince like '%" + province.Trim() + "%'";
            if (!string.IsNullOrWhiteSpace(city))//市
                sql += $" and F_AddressCity like '%" + city.Trim() + "%'";
            if (!string.IsNullOrWhiteSpace(country))//县
                sql += $"  and  (F_AddressCountry like '%" + country.Trim()
                        + "%' or F_Legal like '%" + country.Trim() + "%'  ) ";
            if (!string.IsNullOrWhiteSpace(township))//乡
                sql += $" and F_AddressTownship like '%" + township.Trim() + "%'";
            #endregion

            int recordCount = 0;
            if (isdc>0)
            {
                dt = new BLL.T_Cus_CustomerBaseNew().GetExpt(sql).Tables[0];
                NPOIHelper npoi = new NPOIHelper();
                if (npoi.ExportToExcel("客户档案", dt, cjcol()) == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(sql))
                {
                    dt = BLL.PagerBLL.GetListPager(
                        "T_Cus_CustomerBaseNew",
                        "F_CustomerId",
                        "*",
                        sql,
                        "ORDER BY F_CustomerId desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount);
                }
                List<Model.T_Cus_CustomerBaseNew> modlelist = new BLL.T_Cus_CustomerBaseNew().DataTableToList(dt);
                List<CustomerBaseNewInput> Input = modeltooip(modlelist);
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = Input,
                    total = recordCount
                };

                return Content(obj.ToJson());
            }
       

        }
        private string[] cjcol()
        {

            string[] ccc = {
                   "客户编号","公司名称","大区名称","分公司名称","业务员","业务员电话","渠道类型","信用等级","客户",
                  "客户电话","性别","省","市","县","乡","详细地址","经营品牌"
                  ,"产品" ,"是否经营心连心","年销量","配方","种植作物","种植面积","用肥品牌","备注"
            };
            return ccc;
        }
        /// <summary>
        /// 通过来电号码获取来电弹屏左侧客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCustomerLeft(string tel,int page = 1, int pagesize = 2)
        {
         
                
              
                DataTable dt = new DataTable();
                int recordCount = 0;
                var sql = $" and  F_LegalPhone  = '" + tel.Trim() + "'";
                 sql +=" and F_IsDelete=0";
                if (!string.IsNullOrWhiteSpace(sql))
                {
                    dt = BLL.PagerBLL.GetListPager(
                        "T_Cus_CustomerBaseNew",
                        "F_CustomerId",
                        "*,dbo.GetUserName(F_CreateBy) as F_CreateByName",
                        sql,
                        "ORDER BY F_CustomerId desc",
                        pagesize,
                        page,
                        true,
                        out recordCount);
                }
                List<Model.T_Cus_CustomerBaseNew> modlelist = new BLL.T_Cus_CustomerBaseNew().DataTableToList(dt);
                List<CustomerBaseNewInput> Input = modeltooip(modlelist);
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = Input,
                    total = recordCount
                };

                return Content(obj.ToJson());

          
        }
        /// <summary>
        /// 根据关键字搜索公司
        /// </summary>
        public ActionResult GetListByKey(string keywords)
        {
            string sql = "";
            if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                sql += $" ( F_CompanyName like '%" + keywords.Trim() + "%' or F_CustomerCode like '%" + keywords.Trim() + "%' ) ";
            var list = new List<Model.T_Cus_CustomerBaseNew>();
            if (!string.IsNullOrWhiteSpace(sql))
            {
                sql += " and F_IsDelete=0";
                list = cusbll.GetModelList(sql);
            }
            if (list.Count > 0)
            {
                List<CustomerBaseNewInput> Input = modeltooip(list);
                if (Input != null)
                    return Success("根据关键字获取公司信息", Input.FirstOrDefault());
                else
                    return Error("没有获取到相关公司，请重新搜索");
            }
            else
                return Error("没有获取到相关公司，请重新搜索");

        }
        /// <summary>
        ///根据客户编码获取客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCodeCustomer(string code)
        {
            var list = new List<Model.T_Cus_CustomerBaseNew>(); DataTable dt = new DataTable();
            string sql = "  F_IsDelete=0";
            if (!string.IsNullOrWhiteSpace(code))//客户编号
            {
                if (valcode(code))
                {
                    sql += " and F_CustomerCode='" + code.Trim() + "'";
                    list = cusbll.GetModelList(sql);
                }
                if (list.Count > 0)
                {
                    List<CustomerBaseNewInput> Input = modeltooip(list);
                    if (Input != null)
                        return Success("获取成功", Input.FirstOrDefault());
                    else
                        return Success("没有获取到客户信息，请检查客户编号", null);
                }
                else
                {
                    return Success("没有获取到客户信息，请检查客户编号", null);
                }
            }
            else
            {
                return Success("请输入客户编号", null);

            }
        }
        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCustomer(int cusid)
        {
            if (cusid != 0)
            {
                Model.T_Cus_CustomerBaseNew userModel = cusbll.GetModel(cusid);
                List<Model.T_Cus_CustomerBaseNew> model = new List<T_Cus_CustomerBaseNew>();
                if (userModel != null)
                {
                    model.Add(userModel);
                    List<CustomerBaseNewInput> Input = modeltooip(model);
                    return Success("获取成功", Input.FirstOrDefault());
                }
                else
                {
                    return Error("获取失败");
                }
            }
            else
            {
                return Error("参数传输失败");
            }
        }
        public class Sales
        {
            public string name;
        }
        public class Salesman
        {
            public string name;
            public string phone;
            public int  areaid;
            public string area;
            public int branchid;
            public string branch;
            public List<Salesmanproduct> product;
        }
        public class Salesmanproduct
        {
            public string product;
        }
        public ActionResult GetSalesman(string Salesman)
        {
            string sql = " F_IsDelete = 0 ";

            if (!string.IsNullOrEmpty(Salesman))
            {
                sql += $" and  F_Salesman  = '" + Salesman.Trim() + "'";
            }
            var userModel = new BLL.T_Cus_CustomerBaseNew().GetModelList(sql);
            
            Salesman salesmen = new Salesman();
            salesmen.product  = new List<Salesmanproduct>();
            foreach (var it in userModel)
            {
                 salesmen.name = it.F_Salesman;
                if (string.IsNullOrEmpty (salesmen.phone))
                {
                    if (!string.IsNullOrEmpty(it.F_SalesPhone))
                    {
                        salesmen.phone = it.F_SalesPhone;
                    }
                }
                if (string.IsNullOrEmpty(salesmen.area))
                {
                    if (!string.IsNullOrEmpty(it.F_AreaID))
                    {
                        var area = deptbll.GetModel(it.F_AreaID);
                        if (area !=null )
                        {
                            salesmen.areaid = area.F_DeptId ;
                            salesmen.area = area.F_DeptName;
                        }
                       
                    }
                }
                if (string.IsNullOrEmpty(salesmen.branch))
                {
                    if (!string.IsNullOrEmpty(it.F_BranchID))
                    {
                        var branch = deptbll.GetModel(it.F_BranchID);
                        if (branch != null)
                        {
                            salesmen.branchid = branch.F_DeptId;
                            salesmen.branch = branch.F_DeptName;
                        }
                    }
                }
                if (salesmen.product.Exists(x => x.product == it.F_Product) == false && !string.IsNullOrEmpty(it.F_Product))
                {
                    Salesmanproduct model = new Salesmanproduct();
                    model.product = it.F_Product;
                    salesmen.product.Add(model);
                }
            }
            return Success("获取成功", salesmen);
        }
        public ActionResult GetSales(string Province, string City, string Country)
        {
            string sql = " F_IsDelete = 0 ";

            if (!string .IsNullOrEmpty (Province))
            {
                sql += $" and  F_AddressProvince  = '" + Province.Trim() + "'";
            }
            if (!string.IsNullOrEmpty(City))
            {
                sql += $" and  F_AddressCity  = '" + City.Trim() + "'";
            }
            if (!string.IsNullOrEmpty(Country))
            {
                sql += $" and  F_AddressCountry  = '" + Country.Trim() + "'"; ;
            }
                var userModel = new BLL.T_Cus_CustomerBaseNew().GetModelList( sql);
                List<Sales> salesmen = new List<Sales>();
                foreach (var  it  in userModel)
                {
                    if (salesmen.Exists(x => x.name == it.F_Salesman) == false&&!string .IsNullOrEmpty (it.F_Salesman))
                    {
                      Sales model = new Sales();
                        model.name = it.F_Salesman;
                        salesmen.Add(model);
                    }
                }
                return Success("获取成功", salesmen);
        }
        /// <summary>
        /// 通过来电号码获取来电弹屏左侧客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCustomerByTel(string tel)
        {
            if (!string.IsNullOrWhiteSpace(tel))
            {
                string Province = "", City="";
                var model = new object();
                var sql = $" and  F_LegalPhone  = '" + tel.Trim() + "'";
                var userModel = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_IsDelete = 0 " + sql);
                if (tel.Trim().Length == 11 && tel.Substring(0, 1) != "0")
                {
                    BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                    Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModelList(" F_MobileNum='" + tel.Substring(0, 7) + "' ").FirstOrDefault();

                    if (mobileModel != null)
                    {
                        if (!string.IsNullOrEmpty(mobileModel.F_CityDes))
                        {
                            try
                            {
                                var CityDes = mobileModel.F_CityDes.Split('-');
                                Province = CityDes[0].ToString() + "省";
                                City = CityDes[1].ToString() + "市";
                            }
                            catch
                            {

                            }
                        }
                    }
                }
                else
                {
                    BLL.T_Sys_TelTitleData numbBll = new BLL.T_Sys_TelTitleData();
                    List<Model.T_Sys_TelTitleData> mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + tel.Substring(0, 4) + "'");
                    if (mobileModel == null || mobileModel.Count <= 0)
                    {
                        mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + tel.Substring(0, 3) + "'");
                    }
                    if (mobileModel.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(mobileModel[0].F_TitleName))
                        {
                            try
                            {
                                var CityDes = mobileModel[0].F_TitleName.Split('-');
                                Province = CityDes[0].ToString() ;
                                City = CityDes[1].ToString();
                            }
                            catch
                            {

                            }
                        }
                    }
                }
                if (userModel.Count() > 0)
                {
                    List<CustomerBaseNewInput> Input = modeltooip(userModel);

                     model = Input.Last();
                }
                var obj = new
                {
                    model = model,
                    Province = Province,
                    City = City
                };
                return Success("获取成功", obj);
                //}
                //else
                //{
                //    return Success("获取成功");
                //}
            }
            else
            {
                return Error("参数传输失败");
            }
        }
        private string GetIntCode(int i)
        {
            DateTime times = DateTime.Now.AddMinutes(i);
            string time = times.ToString("yyMMddhhmm");
            return time;
        }
        public ActionResult CallAdd(CustomerBaseNewInput input)
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            if (string.IsNullOrEmpty(input.F_LegalPhone))
                return Error("请输入客户电话");
            var sql = $" and  F_LegalPhone ='" + input.F_LegalPhone.Trim() + "'";
            var userModel = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_IsDelete = 0 " + sql);
            if (userModel.Count() > 0)
            {
                var model = cusbll.GetModel(userModel[0].F_CustomerId);
                #region 保存客户基本信息
                model = inputtoobj(model, input);
                #endregion
                bool n = cusbll.Update(model);
                if (n)
                {
                    return Success("保存成功！",model.F_CustomerId);
                }
                else
                    return Error("保存失败！");
            }
            else
            {
                int i = 0;
                if (string.IsNullOrEmpty(input.F_CustomerCode))
                {
                    while (true)
                    {
                        if (!getunique(0, GetIntCode(i)))
                        {
                            input.F_CustomerCode = GetIntCode(i);
                            break;
                        }
                        else
                        {
                            i++;
                        }
                    }
                }
                var model = new Model.T_Cus_CustomerBaseNew();
                #region 保存客户基本信息
                model = inputtoobj(model, input);
                model.F_CreateBy = usercode;
                model.F_CreateOn = DateTime.Now;
                model.F_IsDelete = 0;
                #endregion
                int n = cusbll.Add(model);
                if (n > 0)
                {
                    return Success("新增成功！",n);
                }
                else
                    return Error("新增失败！");

            }

        }

        /// <summary>
        /// 通过区县获取关联业务员
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult GetCusYWY(int CustomerId = 0)
        {
            if (CustomerId == 0)
                return Error("客户信息不存在！");
            var model = cusbll.GetModel(CustomerId);
            if (model == null)
                return Error("客户不存在");
            string sql = $" F_DeleteFlag=0";
            if (!string.IsNullOrWhiteSpace(model.F_AddressCountry))//县
            {
                sql += $" and F_Remark like '%{ model.F_AddressCountry.Trim()}%'";
            }
            else if (!string.IsNullOrWhiteSpace(model.F_AddressCity))//市
                sql += $" and F_Remark like '%{model.F_AddressCity.Trim()}%'";
            else
                sql += $"and 1!=1 ";
            var modelist = new BLL.T_Sys_UserAccount().GetModelList(sql);
            var saleslist = modelist.Where(t => !string.IsNullOrEmpty(t.F_UserCode)).Select(p => new
            {
                Salesman = new BLL.T_Sys_Department().GetModel(p.F_DeptId).F_DeptName + "-" + p.F_UserName + "(" + p.F_UserCode + ")",              
                SalesPhone = p.F_Mobile
            });
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = saleslist.GroupBy(x => x.Salesman).Select(y => y.First()),
                customername = model.F_Legal,
                customerphon = model.F_LegalPhone

            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 添加客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult Add(CustomerBaseNewInput input)
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            #region 添加验证判断
            if (!string.IsNullOrEmpty(input.F_CustomerCode))
            {
                if (!valcode(input.F_CustomerCode))
                    return Error("编号必须是10位数字");
                if (getunique(0, input.F_CustomerCode))
                    return Error("编号已被占用，请重新输入！");
            }
            if (string.IsNullOrEmpty(input.F_LegalPhone))
                return Error("请输入客户电话");
            if (getunphone(0, input.F_LegalPhone.Trim()))
                return Error("已存在该客户请勿重复添加");
            if (!string.IsNullOrEmpty(input.F_SalesPhone))
            {
                if (!IsNumeric(input.F_SalesPhone))
                    return Error("请输入正确的业务员电话");
            }
            int i = 0;
            if (string.IsNullOrEmpty(input.F_CustomerCode))
            {
                while (true)
                {
                    if (!getunique(0, GetIntCode(i)))
                    {
                        input.F_CustomerCode = GetIntCode(i);
                        break;
                    }
                    else
                    {
                        i++;
                    }
                }
            }
            #endregion
            var model = new Model.T_Cus_CustomerBaseNew();
            #region 保存客户基本信息
            model = inputtoobj(model, input);
            model.F_CreateBy = usercode;
            model.F_CreateOn = DateTime.Now;
            model.F_IsDelete = 0;
            #endregion
            int n = cusbll.Add(model);
            if (n > 0)
            {
                return Success("新增成功！");
            }
            else
                return Error("新增失败！");
        }
        public int  CustemweCode(string customercode, string gender,
          string companyname, string area, string branch, string salesman
          , string salesphone, string channel, string credit, string customername,
          string customerphone, string province, string city, string country, string township
          , string addressfull, string brands, string product, string isrunxlx, string annualsales
          , string formula, string raisecrops, string plantingarea, string fertilizerbrand, string remark,int id=0)
        {
            
            var model = new Model.T_Cus_CustomerBaseNew();
            if (id >0)
            {
                model = new BLL.T_Cus_CustomerBaseNew().GetModel(id);
            }
            int i = 0;
            model.F_CustomerCode = customercode;//客户编号
            model.F_CompanyName = companyname;//公司名称
            model.F_AreaID = area;//大区
            model.F_BranchID = branch;//分公司
            model.F_Gender = gender;//性别
            model.F_Salesman = salesman;//业务员
            model.F_SalesPhone = salesphone;//业务员电话
            model.F_Channel = channel;// 渠道类型:总经销、二级商、种田大户、农户、化工客户、公司员工
            model.F_Credit = credit;//信用等级:一星、二星、三星、四星、五星、空
            model.F_Legal = customername;//法人 
            model.F_LegalPhone = customerphone;//法人电话
            model.F_AddressProvince = province;//省
            model.F_AddressCity = city;//市
            model.F_AddressCountry = country;
            model.F_AddressTownship = township;//乡
            model.F_AddressFull = addressfull;//详细地址
            model.F_Brands = brands;// 经营品牌:心连心、手拉手、沃利沃、双心、空
            model.F_Product = product;//产品:复合肥心连心、复合肥手拉手、复合肥沃利沃、复合肥双心、尿素心连心、尿素手拉手、尿素沃利沃、尿素双心
            model.F_IsRunXLX = isrunxlx;// 是否经营心连心:是、否
            model.F_AnnualSales = annualsales;//年销量
            model.F_Formula = formula;//配方
            model.F_RaiseCrops = raisecrops;//种植作物
            model.F_PlantingArea = plantingarea;//种植面积
            model.F_FertilizerBrand = fertilizerbrand;//用肥品牌
            model.F_Remark = remark;//备注
            model.F_FileId = 0;
            model.F_CreateBy = "系统外添加";
            model.F_CreateOn = DateTime.Now;
            model.F_IsDelete = 0;
            if (id >0)
            {
                bool  n = cusbll.Update (model);
                if (n)
                {
                    return id ;
                }
                else
                    return 0;
            }
            else
            {
                int n = cusbll.Add(model);
                if (n > 0)
                {
                    return n;
                }
                else
                    return 0;
            }
           
        }
        public static bool IsNumeric(string value)
        {
            return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");

        }
        /// <summary>
        /// 修改客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult Update(CustomerBaseNewInput input)
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            #region 添加验证判断
            if (input.F_CustomerId <= 0)
                return Error("参数错误！");
             if (string.IsNullOrEmpty(input.F_LegalPhone))
                return Error("请输入客户电话");
            if (getunique(input.F_CustomerId, input.F_CustomerCode))
                return Error("编号已被占用，请重新输入！");

            if (!string.IsNullOrEmpty(input.F_SalesPhone))
            {
                if (!IsNumeric(input.F_SalesPhone))
                    return Error("请输入正确的业务员电话");
            }
            #endregion
            var model = cusbll.GetModel(input.F_CustomerId);
            #region 保存客户基本信息
            model = inputtoobj(model, input);
            #endregion
            bool n = cusbll.Update(model);
            if (n)
            {
                return Success("保存成功！");
            }
            else
                return Error("保存失败！");
        }
        /// <summary>
        /// 根据model返回CustomerBaseNewInput对象
        /// </summary>
        private List<CustomerBaseNewInput> modeltooip(List<Model.T_Cus_CustomerBaseNew> model)
        {
            if (model != null && model.Count > 0)
            {
                List<CustomerBaseNewInput> Input = new List<CustomerBaseNewInput>(model.Count);
                for (int i = 0; i < model.Count; i++)
                {
                    CustomerBaseNewInput Input1 = new CustomerBaseNewInput();
                    #region 基本字段
                    Input1.F_CustomerId = model[i].F_CustomerId;//业务员
                    if (!string.IsNullOrWhiteSpace(model[i].F_CustomerCode))
                        Input1.F_CustomerCode = model[i].F_CustomerCode;

                    if (!string.IsNullOrWhiteSpace(model[i].F_CompanyName))
                        Input1.F_CompanyName = model[i].F_CompanyName;
                    Input1.F_AreaID = model[i].F_AreaID;//大区ID
                    Input1.F_BranchID = model[i].F_BranchID;//分公司ID

                    if (!string.IsNullOrEmpty(model[i].F_AreaID))
                    {
                        Model.T_Sys_Department pdModel = new T_Sys_Department();
                        try
                        {
                            pdModel = departmentBLL.GetModel(int.Parse(model[i].F_AreaID));
                        }
                        catch
                        {
                             pdModel = departmentBLL.GetModel(model[i].F_AreaID);
                        }
                           
                            if (pdModel != null)
                            {
                                Input1.F_AreaName = pdModel.F_DeptName.ToString();
                            }
                    }
                    if (!string.IsNullOrEmpty(model[i].F_BranchID))
                    {
                        Model.T_Sys_Department pdModel1 = new T_Sys_Department();
                        try
                        {
                            pdModel1 = departmentBLL.GetModel(int.Parse(model[i].F_BranchID));
                        }
                        catch
                        {
                            pdModel1 = departmentBLL.GetModel(model[i].F_BranchID);
                        }
                            if (pdModel1 != null)
                            {
                                Input1.F_BranchName = pdModel1.F_DeptName.ToString();
                            }
                    }
                    if (!string.IsNullOrEmpty(model[i].F_Gender))
                    {
                        if (model[i].F_Gender == "1")
                        {
                            Input1.F_Gender = "男";
                        }
                        else
                        {
                            Input1.F_Gender = "女";
                        }
                    }
                    Input1.F_Salesman = model[i].F_Salesman;//业务员
                    Input1.F_SalesPhone = model[i].F_SalesPhone;//业务员电话

                    Input1.F_Channel = model[i].F_Channel;// 渠道类型:总经销、二级商、种田大户、农户、化工客户、公司员工
                    Input1.F_Credit = model[i].F_Credit;//信用等级:一星、二星、三星、四星、五星、空
                    Input1.F_Legal = model[i].F_Legal;//法人 
                    Input1.F_LegalPhone = model[i].F_LegalPhone.Trim();//法人电话
                    Input1.F_AddressProvince = model[i].F_AddressProvince;//省
                    Input1.F_AddressCity = model[i].F_AddressCity;//市
                    Input1.F_AddressCountry = model[i].F_AddressCountry;//县
                    Input1.F_AddressTownship = model[i].F_AddressTownship;//乡
                    Input1.F_AddressFull = model[i].F_AddressFull;//详细地址
                    Input1.F_Brands = model[i].F_Brands;// 经营品牌:心连心、手拉手、沃利沃、双心、空
                    Input1.F_Product = model[i].F_Product;//产品:复合肥心连心、复合肥手拉手、复合肥沃利沃、复合肥双心、尿素心连心、尿素手拉手、尿素沃利沃、尿素双心
                    Input1.F_IsRunXLX = model[i].F_IsRunXLX;// 是否经营心连心:是、否
                    Input1.F_AnnualSales = model[i].F_AnnualSales;//年销量
                    Input1.F_Formula = model[i].F_Formula;//配方
                    Input1.F_RaiseCrops = model[i].F_RaiseCrops;//种植作物
                    Input1.F_PlantingArea = model[i].F_PlantingArea;//种植面积
                    Input1.F_FertilizerBrand = model[i].F_FertilizerBrand;//用肥品牌
                    Input1.F_Remark = model[i].F_Remark;//备注
                    Input1.F_FileId = 0;
                    Input.Add(Input1);
                    #endregion
                }

                return Input;
            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 根据传入的对象和input的内容返回对象
        /// </summary>
        private Model.T_Cus_CustomerBaseNew inputtoobj(Model.T_Cus_CustomerBaseNew model, CustomerBaseNewInput input)
        {
            var newmodel = model;
            if (!string.IsNullOrWhiteSpace(input.F_CustomerCode))
                model.F_CustomerCode = input.F_CustomerCode;
            else
                model.F_CustomerCode = model.F_CustomerCode;
            if (!string.IsNullOrWhiteSpace(input.F_CompanyName))
                model.F_CompanyName = input.F_CompanyName;
            #region 基本字段
            try
            {
                model.F_AreaID = int .Parse (input.F_AreaID).ToString ();//大区ID
            }
            catch
            {
                if (!string .IsNullOrEmpty (input.F_AreaID))
                {
                    Model.T_Sys_Department pdModel = departmentBLL.GetModel(input.F_AreaID);
                    if (pdModel != null)
                    {
                        model.F_AreaID = pdModel.F_DeptId .ToString();
                    }
                }
            }
            try
            {
                model.F_BranchID = int.Parse(input.F_BranchID).ToString();//分公司ID
            }
            catch
            {
                if (!string.IsNullOrEmpty(input.F_BranchID))
                {
                    Model.T_Sys_Department pdModel = departmentBLL.GetModel(input.F_BranchID);
                    if (pdModel != null)
                    {
                        model.F_BranchID = pdModel.F_DeptId.ToString();
                    }
                }
            }
         
            model.F_Gender = input.F_Gender;//分公司ID
            model.F_Salesman = input.F_Salesman;//业务员
            model.F_SalesPhone = input.F_SalesPhone;//业务员电话
            model.F_Channel = input.F_Channel;// 渠道类型:总经销、二级商、种田大户、农户、化工客户、公司员工
            model.F_Credit = input.F_Credit;//信用等级:一星、二星、三星、四星、五星、空
            model.F_Legal = input.F_Legal;//法人 
            model.F_LegalPhone = input.F_LegalPhone;//法人电话
            model.F_AddressProvince = input.F_AddressProvince;//省
            model.F_AddressCity = input.F_AddressCity;//市
            model.F_AddressCountry = input.F_AddressCountry;//县
            model.F_AddressTownship = input.F_AddressTownship;//乡
            model.F_AddressFull = input.F_AddressFull;//详细地址
            model.F_Brands = input.F_Brands;// 经营品牌:心连心、手拉手、沃利沃、双心、空
            model.F_Product = input.F_Product;//产品:复合肥心连心、复合肥手拉手、复合肥沃利沃、复合肥双心、尿素心连心、尿素手拉手、尿素沃利沃、尿素双心
            model.F_IsRunXLX = input.F_IsRunXLX;// 是否经营心连心:是、否
            model.F_AnnualSales = input.F_AnnualSales;//年销量
            model.F_Formula = input.F_Formula;//配方
            model.F_RaiseCrops = input.F_RaiseCrops;//种植作物
            model.F_PlantingArea = input.F_PlantingArea;//种植面积
            model.F_FertilizerBrand = input.F_FertilizerBrand;//用肥品牌
            model.F_Remark = input.F_Remark;//备注
            model.F_FileId = 0;
            #endregion
            return model;
        }

        /// <summary>
        /// 验证客户编号是否唯一
        /// </summary>
        public  bool getunique(int id, string code)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_CustomerCode='" + code + "')";
            if (id > 0)
                sql += " and F_CustomerId<>" + id;
            var count = cusbll.GetModelList(sql).Count();

            return count > 0;
        }
        /// <summary>
        /// 验证客户电话是否唯一
        /// </summary>
        public  bool getunphone(int id, string phone)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_LegalPhone='" + phone.Trim() + "')";
            if (id > 0)
                sql += " and F_CustomerId<>" + id;
            var count = cusbll.GetModelList(sql).Count();

            return count > 0;
        }
        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="ids"></param>getunique
        /// <returns></returns>
        public bool  DelCustomers(string id)
        {
              if (cusbll.DeleteList(id))
                {
                    // conbll.DeleteListByCusid(idd.TrimEnd(','));
                    return true;
                }
                else
                {
                    return false;
                }
           
        }
        /// <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 + ",";
                }
                if (!string.IsNullOrEmpty(idd.Trim()))
                {
                    if (cusbll.DeleteList(idd.TrimEnd(',')))
                    {
                       // conbll.DeleteListByCusid(idd.TrimEnd(','));
                        return Success("设置成功");
                    }
                    else
                    {
                        return Error("设置失败");
                    }
                }
                else
                {
                    return Error("请选择用户");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }
        public Model.T_Sys_Department IsModelDeptment(string deptname)
        {
            Model.T_Sys_Department pdModel = departmentBLL.GetModel(deptname);
            return pdModel;
        }
        #region 客户使用微信端才会使用
        ///// <summary>
        ///// 重置密码
        ///// </summary>
        ///// <param name="ids"></param>
        ///// <returns></returns>
        //public ActionResult UpdatePWD(string[] ids)
        //{
        //    if (ids != null && ids.Length > 0)
        //    {
        //        string idd = " ";
        //        foreach (string str in ids)
        //        {
        //            idd += str + ",";
        //        }
        //        if (!string.IsNullOrEmpty(idd.Trim()))
        //        {
        //            if (cusbll.UpdatePWD(idd.TrimEnd(','),"123456"))
        //            {
        //                return Success("设置成功");
        //            }
        //            else
        //            {
        //                return Error("设置失败");
        //            }
        //        }
        //        else
        //        {
        //            return Error("请选择用户");
        //        }
        //    }
        //    else
        //    {
        //        return Error("获取参数失败");
        //    }
        //}
        #endregion
        #endregion
        #region 导入客户资料
        /// <summary>
        /// 导入excel
        /// </summary>
        public ActionResult ImportExcel()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            string ip = DTRequest.GetIP();
            if (!string.IsNullOrWhiteSpace(usercode))
            {
                HttpPostedFile _upFile = RequestString.GetFile("upFile");
                if (_upFile != null)
                {
                    int headrow = 0;
                    #region 上传文件
                    string filepath = "";
                    string datepath = DateTime.Now.ToString("yyyyMMddHHMMss");
                    string aLastName = Path.GetExtension(_upFile.FileName);
                    string oriname = Path.GetFileNameWithoutExtension(_upFile.FileName);
                    if (aLastName != ".xls" && aLastName != ".xlsx")
                    {
                        return Error("文件类型错误，请选择Excel文件");
                    }
                    string newpath = datepath + "_" + _upFile.FileName;
                    if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData")))
                    {
                        Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData"));
                    }
                    filepath = this.Request.ApplicationPath + "/ExcelData/" + newpath;
                    string PhysicalPath = Server.MapPath(filepath);
                    _upFile.SaveAs(PhysicalPath);
                    #endregion
                    #region 添加附件日志
                    Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    model_T_Sys_Accessories.F_FileName = newpath;//附件名称
                    model_T_Sys_Accessories.F_FileType = aLastName;//附件类型
                    model_T_Sys_Accessories.F_FileUrl = filepath;//附件地址
                    model_T_Sys_Accessories.F_UserCode = usercode;//上传人  
                    model_T_Sys_Accessories.F_OriName = oriname;
                    int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    #endregion
                    NPOIHelper np = new NPOIHelper();
                    DataTable dt = np.ExcelToTable(_upFile, headrow);
                    string msg = string.Empty;
                    if (dt == null || dt.Rows.Count == 0)
                        return Error("文件没有数据");
                    else
                    {
                        Model.T_Cus_CustomerBaseNew dModel = new Model.T_Cus_CustomerBaseNew();
                        dModel.F_CreateBy = usercode;
                        dModel.F_IsDelete = 0;
                        dModel.F_FileId = fid;
                        foreach (DataRow dr in dt.Rows)
                        {
                            #region 数据入库
                            headrow = headrow + 1;
                            if (dr["客户编号"].ToString() != "" && valcode(dr["客户编号"].ToString()))
                            {
                                if (!getunique(0, dr["客户编号"].ToString()))
                                {
                                    dModel.F_CustomerCode = dr["客户编号"].ToString();
                                    dModel.F_CompanyName = dr["公司名称"].ToString();
                                    Model.T_Sys_Department pdModel = departmentBLL.GetModel(dr["大区名称"].ToString());
                                    if (pdModel != null)
                                    {
                                        dModel.F_AreaID = pdModel.F_DeptId.ToString();
                                    }
                                    else
                                        dModel.F_AreaID = "";
                                    Model.T_Sys_Department pdModel1 = departmentBLL.GetModel(dr["分公司名称"].ToString());
                                    if (pdModel1 != null)
                                    {
                                        dModel.F_BranchID = pdModel1.F_DeptId.ToString();
                                    }
                                    else
                                        dModel.F_BranchID = "";
                                    #region
                                    dModel.F_Salesman = dr["业务员"].ToString();
                                    dModel.F_SalesPhone = dr["业务员电话"].ToString();
                                    dModel.F_Channel = dr["渠道类型"].ToString();
                                    dModel.F_Credit = dr["信用等级"].ToString();
                                    dModel.F_Legal = dr["客户"].ToString();
                                    if (!string.IsNullOrEmpty(dr["性别"].ToString()))
                                    {
                                        if (dr["性别"].ToString() == "女")
                                        {
                                            dModel.F_Gender = "2";
                                        }
                                        else
                                        {
                                            dModel.F_Gender = "1";
                                        }
                                    }
                                    dModel.F_LegalPhone = dr["客户电话"].ToString().Trim();
                                    dModel.F_AddressProvince = dr["省"].ToString();
                                    dModel.F_AddressCity = dr["市"].ToString();
                                    dModel.F_AddressCountry = dr["县"].ToString();
                                    dModel.F_AddressTownship = dr["乡"].ToString();
                                    dModel.F_AddressFull = dr["详细地址"].ToString();
                                    dModel.F_Brands = dr["经营品牌"].ToString();
                                    dModel.F_Product = dr["产品"].ToString();
                                    dModel.F_IsRunXLX = dr["是否经营心连心"].ToString();
                                    dModel.F_AnnualSales = dr["年销量"].ToString();
                                    dModel.F_Formula = dr["配方"].ToString();
                                    dModel.F_RaiseCrops = dr["种植作物"].ToString();
                                    dModel.F_PlantingArea = dr["种植面积"].ToString();
                                    dModel.F_FertilizerBrand = dr["用肥品牌"].ToString();
                                    dModel.F_Remark = dr["备注"].ToString();
                                    #endregion
                                    dModel.F_CreateOn = DateTime.Now;
                                    var res = cusbll.Add(dModel);
                                    if (res > 0)
                                    {
                                        addoptlog(usercode, ip, EnumOpt.import.ToString(), res.ToString(), "导入成功,导入的文件为：" + newpath + ",当前为第" + headrow + "行");
                                    }
                                    else
                                    {
                                        msg = msg + "第" + headrow + "行，导入失败<br>";
                                    }
                                }
                                else
                                {
                                    var CustomerBase = new BLL.T_Cus_CustomerBaseNew().GetModelList("F_CustomerCode='" + dr["客户编号"].ToString() + "'").FirstOrDefault();

                                    if (CustomerBase != null)
                                    {
                                        CustomerBase.F_CompanyName = dr["公司名称"].ToString();
                                        Model.T_Sys_Department pdModel = departmentBLL.GetModel(dr["大区名称"].ToString());
                                        if (pdModel != null)
                                        {
                                            CustomerBase.F_AreaID = pdModel.F_DeptId.ToString();
                                        }
                                        else
                                            CustomerBase.F_AreaID = "";
                                        Model.T_Sys_Department pdModel1 = departmentBLL.GetModel(dr["分公司名称"].ToString());
                                        if (pdModel1 != null)
                                        {
                                            CustomerBase.F_BranchID = pdModel1.F_DeptId.ToString();
                                        }
                                        else
                                            CustomerBase.F_BranchID = "";
                                        #region
                                        CustomerBase.F_Salesman = dr["业务员"].ToString();
                                        CustomerBase.F_SalesPhone = dr["业务员电话"].ToString();
                                        CustomerBase.F_Channel = dr["渠道类型"].ToString();
                                        CustomerBase.F_Credit = dr["信用等级"].ToString();
                                        CustomerBase.F_Legal = dr["客户"].ToString();
                                        if (!string.IsNullOrEmpty(dr["性别"].ToString()))
                                        {
                                            if (dr["性别"].ToString() == "女")
                                            {
                                                CustomerBase.F_Gender = "2";
                                            }
                                            else
                                            {
                                                CustomerBase.F_Gender = "1";
                                            }
                                        }
                                        CustomerBase.F_LegalPhone = dr["客户电话"].ToString().Trim();
                                        CustomerBase.F_AddressProvince = dr["省"].ToString();
                                        CustomerBase.F_AddressCity = dr["市"].ToString();
                                        CustomerBase.F_AddressCountry = dr["县"].ToString();
                                        CustomerBase.F_AddressTownship = dr["乡"].ToString();
                                        CustomerBase.F_AddressFull = dr["详细地址"].ToString();
                                        CustomerBase.F_Brands = dr["经营品牌"].ToString();
                                        CustomerBase.F_Product = dr["产品"].ToString();
                                        CustomerBase.F_IsRunXLX = dr["是否经营心连心"].ToString();
                                        CustomerBase.F_AnnualSales = dr["年销量"].ToString();
                                        CustomerBase.F_Formula = dr["配方"].ToString();
                                        CustomerBase.F_RaiseCrops = dr["种植作物"].ToString();
                                        CustomerBase.F_PlantingArea = dr["种植面积"].ToString();
                                        CustomerBase.F_FertilizerBrand = dr["用肥品牌"].ToString();
                                        CustomerBase.F_Remark = dr["备注"].ToString();
                                        var res = cusbll.Update(CustomerBase);
                                        if (res)
                                        {
                                            addoptlog(usercode, ip, EnumOpt.import.ToString(), res.ToString(), "导入成功,导入的文件为：" + newpath + ",当前为第" + headrow + "行");
                                        }
                                        else
                                        {
                                            msg = msg + "第" + headrow + "行，导入失败<br>";
                                        }
                                    }


                                }



                            }
                            else
                                msg = msg + "第" + headrow + "行，客户编号为空或格式不正确，未导入<br>";
                            #endregion
                        }
                        if (string.IsNullOrEmpty(msg))
                            return Success("导入成功 ");
                        else
                            return Error(msg);
                    }
                }
                return Error("数据源上传失败");
            }
            return Error("用户登录失败，请重新登录");
        }

        //public ActionResult ImportExcel()
        //{
        //    string usercode = CurrentUser.UserData.F_UserCode;
        //    string ip = DTRequest.GetIP();
        //    if (!string.IsNullOrWhiteSpace(usercode))
        //    {
        //        HttpPostedFile _upFile = RequestString.GetFile("upFile");
        //        if (_upFile != null)
        //        {
        //            int a = 80528;
        //            int headrow = 0;
        //            #region 上传文件
        //            string filepath = "";
        //            string datepath = DateTime.Now.ToString("yyyyMMddHHMMss");
        //            string aLastName = Path.GetExtension(_upFile.FileName);
        //            string oriname = Path.GetFileNameWithoutExtension(_upFile.FileName);
        //            if (aLastName != ".xls" && aLastName != ".xlsx")
        //            {
        //                return Error("文件类型错误，请选择Excel文件");
        //            }
        //            string newpath = datepath + "_" + _upFile.FileName;
        //            if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData")))
        //            {
        //                Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData"));
        //            }
        //            filepath = this.Request.ApplicationPath + "/ExcelData/" + newpath;
        //            string PhysicalPath = Server.MapPath(filepath);
        //            _upFile.SaveAs(PhysicalPath);
        //            #endregion
        //            NPOIHelper np = new NPOIHelper();
        //            DataTable dt = np.ExcelToTable(_upFile, headrow);
        //            string msg = string.Empty;
        //            if (dt == null || dt.Rows.Count == 0)
        //                return Error("文件没有数据");
        //            else
        //            {
        //                Model.T_Sys_UserAccount dModel = new Model.T_Sys_UserAccount();

        //                foreach (DataRow dr in dt.Rows)
        //                {
        //                    headrow = headrow + 1;
        //                    string ucode = dr["职员编码"].ToString();
        //                    if (!string.IsNullOrEmpty(ucode))
        //                    {
        //                        dModel.F_UserCode = (a + headrow).ToString();
        //                        dModel.F_WorkNumber = ucode;
        //                    }
        //                    dModel.F_UserName = dr["姓名"].ToString();
        //                    dModel.F_Password = "123456";
        //                    dModel.F_DeptId = int.Parse(dr["大区"].ToString());
        //                    dModel.F_DeptCode = "|0|1|15|" + int.Parse(dr["大区"].ToString()) + "|";
        //                    if (dr["岗位"].ToString() == "大区经理")
        //                        dModel.F_RoleId = 62;
        //                    else if (dr["岗位"].ToString() == "业务员")
        //                        dModel.F_RoleId = 58;
        //                    else
        //                        return Error("失败");
        //                    dModel.F_SeatFlag = false;
        //                    dModel.F_SeatRight = "0";
        //                    dModel.F_SexFlag = "男";
        //                    dModel.F_Remark = dr["负责区域"].ToString();
        //                    dModel.F_Mobile = dr["联系方式"].ToString();
        //                    dModel.F_DeleteFlag = 0;
        //                    dModel.F_CreateOn = DateTime.Now;
        //                    BLL.T_Sys_UserAccount T_Sys_UserAccount = new BLL.T_Sys_UserAccount();
        //                    var res = T_Sys_UserAccount.Add(dModel);

        //                }
        //                if (string.IsNullOrEmpty(msg))
        //                    return Success("导入成功 ");
        //                else
        //                    return Error(msg);
        //            }
        //        }
        //        return Error("数据源上传失败");
        //    }
        //    return Error("用户登录失败，请重新登录");
        //}
        #endregion
        //   #endregion
     //   #region 私有方法
        /// <summary>
        /// 验证物料编码为10位纯数字
        /// </summary>
        public  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="usercode">操作人工号</param>
        /// <param name="ip">操作人IP</param>
        /// <param name="optcode">操作编号</param>
        /// <param name="optid">操作id</param>
        /// <param name="des">操作描述</param>
        private void addoptlog(string usercode, string ip, string optcode, string optid, string des)
        {
            new BLL.T_Sys_OperateLogs().AddOptLog("客户管理", usercode, ip, des, optcode, "T_Cus_CustomerBaseNew", optid);
        }
        #endregion
    }
}
