
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 GetList(FilterCustomer filter)
        {
            string sql = " 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_Sort).ToList();
            //系统列+自定义列 字符串
            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();

            StringBuilder sb = new StringBuilder();
            if (filter.Fields.Length > 0 && filter.FieldValues.Length > 0 && filter.Fields.Length == filter.FieldValues.Length)
            {
                for (int i = 0; i < filter.Fields.Length; i++)
                {
                    if (i == filter.Fields.Length - 1)
                    {
                        sb.Append($" {filter.Fields[i]}='{filter.FieldValues[i]}' ");
                        continue;
                    }
                    sb.Append($" {filter.Fields[i]}='{filter.FieldValues[i]}', ");
                }
            }

            //搜索
            List<string> customerIdList = new List<string>();
            DataTable dt1 = new DataTable();
            if (!string.IsNullOrWhiteSpace(sb.ToString()))
            {
                dt1 = DbHelperSQL.Query($"select F_CustomerId FROM T_Cus_CustomerExpand where {sb.ToString()}").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, {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_CusType.ToString(), c.F_AddAgentId.ToString(), 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,
                search = searchFieldList
            });

        }

        /// <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_IsShowOnList > 0).OrderBy(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_CusType.ToString(), userModel.F_AddAgentId.ToString(), userModel.F_AddTime.ToString("yyyy-MM-dd HH:mm:ss"), 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();
            BLL.T_Cus_CustomerBase bll = new BLL.T_Cus_CustomerBase();
            if (!string.IsNullOrWhiteSpace(input.Id))
            {
                model.F_Name = input.Name;
                model.F_Address = input.Address;
                model.F_CusType = input.CusType;
                model.F_YHFKId = input.YHFKId;
                model.F_YHFKName = input.YHFKName;
                model.F_Remark = input.Remark;
                model.F_PhoneNum1 = input.PhoneNum1;
                model.F_PhoneNum2 = input.PhoneNum2;
                model.F_AddAgentId = CurrentUser.UserData.F_UserId;
                model.F_DeptId = CurrentUser.UserData.F_DeptId;



                if (bll.Add(model) > 0)
                    return Success("新增成功！");
                return Error("新增失败！");

            }

            model = bll.GetModel(input.Id);
            if (model == null)
                return Error("修改失败，该客户信息不存在");
            model.F_Name = input.Name;
            model.F_Address = input.Address;
            model.F_CusType = input.CusType;
            model.F_YHFKId = input.YHFKId;
            model.F_YHFKName = input.YHFKName;
            model.F_Remark = input.Remark;
            model.F_PhoneNum1 = input.PhoneNum1;
            model.F_PhoneNum2 = input.PhoneNum2;
            if (bll.Update(model))
                return Success("修改成功！");
            return Error("修改失败！");
        }

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

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

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

        public ActionResult GetCustomerField()
        {
            //系统列+自定义列 实体
            var columnList = customerFieldBLL.GetList().Where(x => x.F_IsShowOnList > 0).OrderBy(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();

            return Success("", new
            {
                namelist = nameList,
                headlist = headList,
            });
        }
    }
}