
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CallCenterApi.Interface.Controllers.Base;
using System.Data;
using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Models.Filter;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Interface.Models.Dto;
using System.Data.SqlClient;
using System.Text;

namespace CallCenterApi.Interface.Controllers.customer
{
    //[Authority]
    public class CustomerController : BaseController
    {
        private readonly BLL.T_Cus_CustomerBase customerBaseBLL = new BLL.T_Cus_CustomerBase();
        private readonly BLL.T_Cus_CustomerField customerFieldBLL = new BLL.T_Cus_CustomerField();
        private readonly BLL.T_Cus_CustomerExpand customerExpandBLL = new BLL.T_Cus_CustomerExpand();

        /// <summary>
        /// 获取客户列表搜索
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSearchFields()
        {
            DataTable dt = new DataTable();
            //系统列+自定义列 实体
            var columnList = customerFieldBLL.GetList().Where(x => x.F_IsShowOnList > 0).OrderBy(x => x.F_FieldType).ThenBy(x => x.F_Sort).ToList();
            //需要搜索的自定义列
            var searchFieldList = columnList.Where(x => x.F_Search > 0).ToList();
            return Success("获取成功", new
            {
                search = searchFieldList
            });

        }

        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSearch(FilterCustomer filter)
        {
            string sql = " cb.F_DeleteFlag=0 ";
            DataTable dt = new DataTable();

            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

            //系统列+自定义列 实体
            var columnList = customerFieldBLL.GetList().Where(x => x.F_IsShowOnList > 0).OrderBy(x => x.F_FieldType).ThenBy(x => x.F_Sort).ToList();
            var sysColumnList = columnList.Where(x => x.F_FieldType == 0);
            //系统列+自定义列 字符串
            var headList = columnList.Select(x => x.F_Name).ToList();
            //自定义列字段名
            var customerColumnArr = columnList.Where(x => x.F_FieldType == 1).Select(x => x.F_DBFieldName).ToList();
            //需要搜索的自定义列
            var searchFieldList = columnList.Where(x => x.F_Search > 0).ToList();

            //List<string> sqlList = new List<string>();
            //if (!string.IsNullOrWhiteSpace(filter.Fields) && !string.IsNullOrWhiteSpace(filter.FieldValues))
            //{
            //    var fieldArr = filter.Fields.Split(new char[] { ',' });
            //    var fieldValueArr = filter.FieldValues.Split(new char[] { ',' });
            //    if (fieldArr.Length > 0 && fieldValueArr.Length > 0 && fieldArr.Length == fieldValueArr.Length)
            //    {
            //        for (int i = 0; i < fieldValueArr.Length; i++)
            //        {
            //            if (string.IsNullOrWhiteSpace(fieldArr[i]))
            //                continue;
            //            sqlList.Add($" {fieldArr[i]}='{fieldValueArr[i]}'  ");
            //        }
            //    }
            //}

            //搜索
            List<string> customerIdList = new List<string>();
            DataTable dt1 = new DataTable();
            //if (sqlList.Count > 0)
            //{
            //    dt1 = DbHelperSQL.Query($"select F_CustomerId FROM T_Cus_CustomerExpand where {string.Join(" and ", sqlList)}").Tables[0];

            //}
            //else
            //{
            dt1 = DbHelperSQL.Query($"select F_CustomerId FROM T_Cus_CustomerExpand ").Tables[0];
            //}

            foreach (DataRow row in dt1.Rows)
            {
                customerIdList.Add(row["F_CustomerId"].ToString());
            }
            //获取主表数据
            var customerListAll = customerBaseBLL.DataTableToList(customerBaseBLL.GetList(sql).Tables[0]);
            var customerList = customerListAll.Where(x => customerIdList.Contains(x.F_Id))
                .Skip((filter.PageIndex - 1) * filter.PageSize).Take(filter.PageSize).ToList();


            //获取主表数据ID
            var customerIdArr = customerList.OrderByDescending(x => x.F_AddTime).Select(x => "'" + x.F_Id + "'").ToArray();
            DataTable customerExpandList = new DataTable();
            if (customerIdArr.Length > 0)
            {
                //根据主表数据ID获取自定义字段数据
                customerExpandList = DbHelperSQL.Query($"select F_CustomerId { (customerColumnArr.Count > 0 ? "," + string.Join(",", customerColumnArr) : "")} from T_Cus_CustomerExpand where   F_CustomerId IN ({string.Join(", ", customerIdArr)}) ").Tables[0];
            }
            else
            {
                customerExpandList = DbHelperSQL.Query("SET FMTONLY ON;SELECT * FROM T_Cus_CustomerExpand ;SET FMTONLY OFF; ").Tables[0];
            }
            //组织数据
            List<CustomerDto> dataList = new List<CustomerDto>();
            foreach (var c in customerList)
            {
                var model = new CustomerDto();
                model.id = c.F_Id;
                var e = customerExpandList.Select($"F_CustomerId='{c.F_Id}'");
                List<string> strList1 = new List<string>()
                {
                    c.F_Name, c.F_PhoneNum1, c.F_PhoneNum2, c.F_Address, c.F_AddAgentName, c.F_AddTime.ToString("yyyy-MM-dd HH:mm:ss"), c.F_Remark
                };
                List<string> strList2 = new List<string>();
                if (e.Count() > 0)
                {
                    foreach (var item in customerColumnArr)
                    {
                        strList2.Add(e[0][item].ToString());
                    }
                }
                else
                {
                    foreach (var item in customerColumnArr)
                    {
                        strList2.Add("");
                    }
                }

                strList1.AddRange(strList2);
                model.dataarr = strList1;
                dataList.Add(model);

            }


            return Success("获取成功", new
            {
                headlist = headList,
                datalist = dataList
            });

        }
        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCustomer(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
                return Error("参数错误");
            var userModel = customerBaseBLL.GetModel(id);
            if (userModel == null)
                return Error("获取失败，该客户信息不存在");
            //系统列+自定义列 实体
            var columnList = customerFieldBLL.GetList()
                .Where(x => (x.F_FieldType == 0 && x.F_IsNecessary > 0) || (x.F_FieldType == 1 && x.F_IsShowOnScrean > 0))
                .OrderBy(x => x.F_FieldType).ThenBy(x => x.F_Sort).ToList();
            //系统列+自定义列 字符串
            var headList = columnList.Select(x => x.F_Name).ToList();
            //系统列+自定义列 字段名
            var nameList = columnList.Select(x => x.F_DBFieldName).ToList();
            //自定义列字段名
            var customerColumnArr = columnList.Where(x => x.F_FieldType == 1).Select(x => x.F_DBFieldName).ToList();
            //自定义列值
            var expand = DbHelperSQL.Query("select  top 1 * from T_Cus_CustomerExpand where F_CustomerId=@F_CustomerId", new SqlParameter("@F_CustomerId", userModel.F_Id)).Tables[0].Rows[0];
            List<string> strList1 = new List<string>()
            {
                 userModel.F_Name, userModel.F_PhoneNum1, userModel.F_PhoneNum2, userModel.F_Address, userModel.F_Remark
            };
            List<string> strList2 = new List<string>();
            foreach (var item in customerColumnArr)
            {
                strList2.Add(expand[item].ToString());
            }
            strList1.AddRange(strList2);

            return Success("获取成功", new
            {
                namelist = nameList,
                headlist = headList,
                datalist = strList1
            });

        }

        /// <summary>
        /// 添加/修改客户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddCustomer(CustomerInput input)
        {
            Model.T_Cus_CustomerBase model = new Model.T_Cus_CustomerBase();
            Model.T_Cus_CustomerExpand expand = new Model.T_Cus_CustomerExpand();
            BLL.T_Cus_CustomerBase bll = new BLL.T_Cus_CustomerBase();
            if (string.IsNullOrWhiteSpace(input.Id))
            {
                model.F_Name = input.F_Name;
                model.F_Address = input.F_Address;
                model.F_CusType = input.F_CusType;
                model.F_YHFKId = input.F_YHFKId;
                model.F_YHFKName = input.F_YHFKName;
                model.F_Remark = input.F_Remark;
                model.F_PhoneNum1 = input.F_PhoneNum1;
                model.F_PhoneNum2 = input.F_PhoneNum2;
                model.F_AddAgentId = CurrentUser.UserData.F_UserId;
                model.F_DeptId = CurrentUser.UserData.F_DeptId;
                var id = bll.Add(model);
                if (!string.IsNullOrWhiteSpace(id))
                {
                    expand.F_CustomerId = id;
                    #region 自定义字段
                    expand.F_StrExpand1 = input.F_StrExpand1;
                    expand.F_StrExpand2 = input.F_StrExpand2;
                    expand.F_StrExpand3 = input.F_StrExpand3;
                    expand.F_StrExpand4 = input.F_StrExpand4;
                    expand.F_StrExpand5 = input.F_StrExpand5;
                    expand.F_StrExpand6 = input.F_StrExpand6;
                    expand.F_StrExpand7 = input.F_StrExpand7;
                    expand.F_StrExpand8 = input.F_StrExpand8;
                    expand.F_StrExpand9 = input.F_StrExpand9;
                    expand.F_StrExpand1 = input.F_StrExpand1;
                    expand.F_StrExpand11 = input.F_StrExpand11;
                    expand.F_StrExpand12 = input.F_StrExpand12;
                    expand.F_StrExpand13 = input.F_StrExpand13;
                    expand.F_StrExpand14 = input.F_StrExpand14;
                    expand.F_StrExpand15 = input.F_StrExpand15;
                    expand.F_StrExpand16 = input.F_StrExpand16;
                    expand.F_StrExpand17 = input.F_StrExpand17;
                    expand.F_StrExpand18 = input.F_StrExpand18;
                    expand.F_StrExpand19 = input.F_StrExpand19;
                    expand.F_StrExpand20 = input.F_StrExpand20;
                    expand.F_StrExpand21 = input.F_StrExpand21;
                    expand.F_StrExpand22 = input.F_StrExpand22;
                    expand.F_StrExpand23 = input.F_StrExpand23;
                    expand.F_StrExpand24 = input.F_StrExpand24;
                    expand.F_StrExpand25 = input.F_StrExpand25;
                    expand.F_StrExpand26 = input.F_StrExpand26;
                    expand.F_StrExpand27 = input.F_StrExpand27;
                    expand.F_StrExpand28 = input.F_StrExpand28;
                    expand.F_StrExpand29 = input.F_StrExpand29;
                    expand.F_StrExpand30 = input.F_StrExpand30;
                    expand.F_StrExpand31 = input.F_StrExpand31;
                    expand.F_StrExpand32 = input.F_StrExpand32;
                    expand.F_StrExpand33 = input.F_StrExpand33;
                    expand.F_StrExpand34 = input.F_StrExpand34;
                    expand.F_StrExpand35 = input.F_StrExpand35;
                    expand.F_StrExpand36 = input.F_StrExpand36;
                    expand.F_StrExpand37 = input.F_StrExpand37;
                    expand.F_StrExpand38 = input.F_StrExpand38;
                    expand.F_StrExpand39 = input.F_StrExpand39;
                    expand.F_StrExpand40 = input.F_StrExpand40;
                    #endregion
                    if (customerExpandBLL.Add(expand))
                        return Success("新增成功！");
                    return Error("自定义字段添加失败！");
                }

                return Error("新增失败！");

            }

            model = bll.GetModel(input.Id);
            if (model == null)
                return Error("修改失败，该客户信息不存在");
            model.F_Name = input.F_Name;
            model.F_Address = input.F_Address;
            model.F_CusType = input.F_CusType;
            model.F_YHFKId = input.F_YHFKId;
            model.F_YHFKName = input.F_YHFKName;
            model.F_Remark = input.F_Remark;
            model.F_PhoneNum1 = input.F_PhoneNum1;
            model.F_PhoneNum2 = input.F_PhoneNum2;
            if (bll.Update(model))
            {
                expand = customerExpandBLL.GetModelByCustomerId(model.F_Id);
                if (expand == null)
                    return Error("该数据有误，无法修改");
                #region 自定义字段
                expand.F_StrExpand1 = string.IsNullOrWhiteSpace(input.F_StrExpand1) ? expand.F_StrExpand1 : input.F_StrExpand1;
                expand.F_StrExpand2 = string.IsNullOrWhiteSpace(input.F_StrExpand2) ? expand.F_StrExpand2 : input.F_StrExpand2;
                expand.F_StrExpand3 = string.IsNullOrWhiteSpace(input.F_StrExpand3) ? expand.F_StrExpand3 : input.F_StrExpand3;
                expand.F_StrExpand4 = string.IsNullOrWhiteSpace(input.F_StrExpand4) ? expand.F_StrExpand4 : input.F_StrExpand4;
                expand.F_StrExpand5 = string.IsNullOrWhiteSpace(input.F_StrExpand5) ? expand.F_StrExpand5 : input.F_StrExpand5;
                expand.F_StrExpand6 = string.IsNullOrWhiteSpace(input.F_StrExpand6) ? expand.F_StrExpand6 : input.F_StrExpand6;
                expand.F_StrExpand7 = string.IsNullOrWhiteSpace(input.F_StrExpand7) ? expand.F_StrExpand7 : input.F_StrExpand7;
                expand.F_StrExpand8 = string.IsNullOrWhiteSpace(input.F_StrExpand8) ? expand.F_StrExpand8 : input.F_StrExpand8;
                expand.F_StrExpand9 = string.IsNullOrWhiteSpace(input.F_StrExpand9) ? expand.F_StrExpand9 : input.F_StrExpand9;
                expand.F_StrExpand1 = string.IsNullOrWhiteSpace(input.F_StrExpand1) ? expand.F_StrExpand1 : input.F_StrExpand1;
                expand.F_StrExpand11 = string.IsNullOrWhiteSpace(input.F_StrExpand11) ? expand.F_StrExpand11 : input.F_StrExpand11;
                expand.F_StrExpand12 = string.IsNullOrWhiteSpace(input.F_StrExpand12) ? expand.F_StrExpand12 : input.F_StrExpand12;
                expand.F_StrExpand13 = string.IsNullOrWhiteSpace(input.F_StrExpand13) ? expand.F_StrExpand13 : input.F_StrExpand13;
                expand.F_StrExpand14 = string.IsNullOrWhiteSpace(input.F_StrExpand14) ? expand.F_StrExpand14 : input.F_StrExpand14;
                expand.F_StrExpand15 = string.IsNullOrWhiteSpace(input.F_StrExpand15) ? expand.F_StrExpand15 : input.F_StrExpand15;
                expand.F_StrExpand16 = string.IsNullOrWhiteSpace(input.F_StrExpand16) ? expand.F_StrExpand16 : input.F_StrExpand16;
                expand.F_StrExpand17 = string.IsNullOrWhiteSpace(input.F_StrExpand17) ? expand.F_StrExpand17 : input.F_StrExpand17;
                expand.F_StrExpand18 = string.IsNullOrWhiteSpace(input.F_StrExpand18) ? expand.F_StrExpand18 : input.F_StrExpand18;
                expand.F_StrExpand19 = string.IsNullOrWhiteSpace(input.F_StrExpand19) ? expand.F_StrExpand19 : input.F_StrExpand19;
                expand.F_StrExpand20 = string.IsNullOrWhiteSpace(input.F_StrExpand20) ? expand.F_StrExpand20 : input.F_StrExpand20;
                expand.F_StrExpand21 = string.IsNullOrWhiteSpace(input.F_StrExpand21) ? expand.F_StrExpand21 : input.F_StrExpand21;
                expand.F_StrExpand22 = string.IsNullOrWhiteSpace(input.F_StrExpand22) ? expand.F_StrExpand22 : input.F_StrExpand22;
                expand.F_StrExpand23 = string.IsNullOrWhiteSpace(input.F_StrExpand23) ? expand.F_StrExpand23 : input.F_StrExpand23;
                expand.F_StrExpand24 = string.IsNullOrWhiteSpace(input.F_StrExpand24) ? expand.F_StrExpand24 : input.F_StrExpand24;
                expand.F_StrExpand25 = string.IsNullOrWhiteSpace(input.F_StrExpand25) ? expand.F_StrExpand25 : input.F_StrExpand25;
                expand.F_StrExpand26 = string.IsNullOrWhiteSpace(input.F_StrExpand26) ? expand.F_StrExpand26 : input.F_StrExpand26;
                expand.F_StrExpand27 = string.IsNullOrWhiteSpace(input.F_StrExpand27) ? expand.F_StrExpand27 : input.F_StrExpand27;
                expand.F_StrExpand28 = string.IsNullOrWhiteSpace(input.F_StrExpand28) ? expand.F_StrExpand28 : input.F_StrExpand28;
                expand.F_StrExpand29 = string.IsNullOrWhiteSpace(input.F_StrExpand29) ? expand.F_StrExpand29 : input.F_StrExpand29;
                expand.F_StrExpand30 = string.IsNullOrWhiteSpace(input.F_StrExpand30) ? expand.F_StrExpand30 : input.F_StrExpand30;
                expand.F_StrExpand31 = string.IsNullOrWhiteSpace(input.F_StrExpand31) ? expand.F_StrExpand31 : input.F_StrExpand31;
                expand.F_StrExpand32 = string.IsNullOrWhiteSpace(input.F_StrExpand32) ? expand.F_StrExpand32 : input.F_StrExpand32;
                expand.F_StrExpand33 = string.IsNullOrWhiteSpace(input.F_StrExpand33) ? expand.F_StrExpand33 : input.F_StrExpand33;
                expand.F_StrExpand34 = string.IsNullOrWhiteSpace(input.F_StrExpand34) ? expand.F_StrExpand34 : input.F_StrExpand34;
                expand.F_StrExpand35 = string.IsNullOrWhiteSpace(input.F_StrExpand35) ? expand.F_StrExpand35 : input.F_StrExpand35;
                expand.F_StrExpand36 = string.IsNullOrWhiteSpace(input.F_StrExpand36) ? expand.F_StrExpand36 : input.F_StrExpand36;
                expand.F_StrExpand37 = string.IsNullOrWhiteSpace(input.F_StrExpand37) ? expand.F_StrExpand37 : input.F_StrExpand37;
                expand.F_StrExpand38 = string.IsNullOrWhiteSpace(input.F_StrExpand38) ? expand.F_StrExpand38 : input.F_StrExpand38;
                expand.F_StrExpand39 = string.IsNullOrWhiteSpace(input.F_StrExpand39) ? expand.F_StrExpand39 : input.F_StrExpand39;
                expand.F_StrExpand40 = string.IsNullOrWhiteSpace(input.F_StrExpand40) ? expand.F_StrExpand40 : input.F_StrExpand40;
                #endregion
                if (customerExpandBLL.Update(expand))
                    return Success("修改成功！");
                return Error("自定义字段修改失败！");
            }

            return Error("修改失败！");
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns> 
        public ActionResult DelCustomer(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                var idStr = string.Join(",", ids.Select(x => $"'{x}'"));
                string sql = "update T_Cus_CustomerBase set F_DeleteFlag=1 where F_Id in(" + idStr + ")";
                if (string.IsNullOrEmpty(idStr))
                    return Error("请选择用户");

                if (DbHelperSQL.ExecuteSql(sql) > 0)
                    return Success("设置成功");
                return Error("设置失败");
            }

            return Error("获取参数失败");
        }

        public ActionResult GetCustomerField()
        {
            //系统列+自定义列 实体
            var columnList = customerFieldBLL.GetList()
                .Where(x => (x.F_FieldType == 0 && x.F_IsNecessary > 0) || (x.F_FieldType == 1 && x.F_IsShowOnScrean > 0))
                .OrderBy(x => x.F_FieldType).ThenBy(x => x.F_Sort).ToList();
            //系统列+自定义列 字符串
            var headList = columnList.Select(x => x.F_Name).ToList();
            //系统列+自定义列 字段名
            var nameList = columnList.Select(x => x.F_DBFieldName).ToList();
            return Success("", new
            {
                namelist = nameList,
                headlist = headList,
            });
        }
    }
}