using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using MadRunFabric.Common;
using WorkOrderApi.IRepositories;
using Microsoft.Extensions.Logging;
using System.Security.Claims;
using MadRunFabric.Model.WorkOrderApi;
using WorkOrderApi.Areas.Hy_Order.Input;
using MongoDB.Bson;
using Microsoft.Extensions.Configuration;
using System.Reflection;
using ConfigurationApi.IRepositories;
using System.Data;
using WorkOrderApi.Model.Dto;
using MongoDB.Driver;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WorkOrderApi.Areas.Hy_Order.Controllers
{
    /// <summary>
    /// 客户档案 - 售后管理系统
    /// </summary>
    [Area("hy")]
    //[Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class CusCustomerController : BaseController
    {
        private readonly ILogger<CusCustomerController> _logger;
        private readonly ICus_Customer_BaseRepository _cus_customer_baseRepository;
        private readonly ICus_Customer_ProjectRepository _cus_customer_projectepository;
        private readonly IConfiguration _configuration;
        private readonly ISys_DictionaryValueRepository _sys_dictionaryValuerepository;
        private readonly ICus_FollowRecordRepository _cus_followrecordrepository;
        private readonly ISys_ProvincesRepository _sys_provincesrepository;
        private readonly ISys_CityRepository _sys_cityrepository;
        public CusCustomerController(
           ILogger<CusCustomerController> logger,
           ICus_Customer_BaseRepository cus_customer_baseRepository,
           IConfiguration configuration,
           ICus_Customer_ProjectRepository cus_customer_projectepository,
            ISys_DictionaryValueRepository sys_dictionaryValuerepository,
            ICus_FollowRecordRepository cus_followrecordrepository,
            ISys_ProvincesRepository sys_provincesrepository,
            ISys_CityRepository sys_cityrepository
           )
        {
            _logger = logger;
            _cus_customer_baseRepository = cus_customer_baseRepository;
            _configuration = configuration;
            _cus_customer_projectepository = cus_customer_projectepository;
            _sys_dictionaryValuerepository = sys_dictionaryValuerepository;
            _cus_followrecordrepository = cus_followrecordrepository;
            _sys_provincesrepository = sys_provincesrepository;
            _sys_cityrepository = sys_cityrepository;
        }


        #region 客户档案
        /// <summary>
        /// 获取客户分页
        /// </summary>
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(string keyword, string province, string city, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            int recordCount = 0;
            var result = _cus_customer_baseRepository.GetListsByPage(keyword, province, city, stime, etime, rolecode, usercode, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取客户详情 by 手机，单位名称
        /// </summary>
        /// <param name="tel"></param>
        /// <param name="companyame"></param>
        /// <returns></returns>
        [HttpGet("getsinglebytelcompanyame")]
        public async Task<IActionResult> GetSingleByTelCompanyameAsync(string tel, string companyame)
        {
            if (string.IsNullOrEmpty(tel))
                return Success("参数错误", null);
            var model = (await _cus_customer_baseRepository.GetSingle(x => x.mobilephone == tel && x.companyame == companyame && x.isdelete == 0));
            return Success("获取成功", model);
        }

        /// <summary>
        /// 获取客户详情
        /// </summary>
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            var model = await _cus_customer_baseRepository.GetSingle(x => x.id == id && x.isdelete == 0);
            return Success("获取成功", model);
        }

        /// <summary>
        /// 添加客户
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(CusCustomerInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            try
            {
                #region 判断验证
                if (string.IsNullOrWhiteSpace(input.name))
                    return Error("请输入联系人");
                if (string.IsNullOrEmpty(input.mobilephone))
                    return Error("请输入手机号码");
                var listCus = await _cus_customer_baseRepository.Get(x => x.mobilephone == input.mobilephone && x.isdelete == 0);
                var model = listCus.FirstOrDefault();
                if (model != null)
                    return Error("手机号码已存在");
                #endregion

                model = new Cus_Customer_Base();
                #region model 添加客户对象
                //model.id = cusid;
                model.name = input.name;
                model.mobilephone = input.mobilephone;
                model.telephone = input.telephone;
                model.manager = input.manager;

                model.customername = input.customername;
                model.companyame = input.companyame;
                model.province = input.province;    //省
                model.city = input.city;            //市
                model.address = input.address;
                model.iscustomer = input.iscustomer;
                model.customfields = input.customfields;

                model.rolecode = input.rolecodes;
                model.usercode = input.usercodes;
                model.createuser = usercode;
                model.createusername = username;
                #endregion
                string customerid = await _cus_customer_baseRepository.AddRetID(model);
                if (!string.IsNullOrEmpty(customerid))
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");

            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        /// <summary>
        /// 修改客户
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(CusCustomerInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var model = (await _cus_customer_baseRepository.Get(p => p.id == input.id)).FirstOrDefault();
            if (model != null)
            {
                #region 判断验证
                if (model.isdelete == 1)
                    return Error("用户已删除");
                if (string.IsNullOrWhiteSpace(input.name))
                    return Error("请输入联系人");
                if (string.IsNullOrEmpty(input.mobilephone))
                    return Error("请输入联系电话");
                #endregion

                #region model 客户对象
                model.name = input.name;
                model.mobilephone = input.mobilephone;
                model.telephone = input.telephone;
                model.manager = input.manager;

                model.customername = input.customername;
                model.companyame = input.companyame;
                model.province = input.province;    //省
                model.city = input.city;            //市
                model.address = input.address;
                model.iscustomer = input.iscustomer;
                model.customfields = input.customfields;
                model.rolecode = input.rolecodes;
                model.usercode = input.usercodes;
                #endregion

                bool b = await _cus_customer_baseRepository.UpdateOne(model);
                if (b)
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
            return Error("参数错误");
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //使用逻辑删除
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    var model = await _cus_customer_baseRepository.GetSingle(id);
                    model.isdelete = 1;
                    model.deleteuser = usercode;
                    model.deletetime = DateTime.Now;
                    if (await _cus_customer_baseRepository.UpdateOne(model))
                    {
                        #region 删除相关表数据
                        var listCus_Pro = await _cus_customer_projectepository.Get(p => p.customerid == model.id && p.isdelete == 0);
                        foreach (var modelPro in listCus_Pro)
                        {
                            modelPro.isdelete = 1;
                            modelPro.deleteuser = usercode;
                            modelPro.deletetime = DateTime.Now;
                            await _cus_customer_projectepository.UpdateOne(modelPro);
                        }
                        #endregion

                        res += 1;
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败");
                else
                    return Error("删除失败");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 上传文件并导入数据库 - 客户档案
        /// </summary>
        /// <param name="headrow">默认为-1：1、为-1时，获取excel标题；2、为0时，不获取excel标题</param>
        /// <returns></returns>
        [HttpPost("importexcelcus")]
        public async Task<IActionResult> ImportExcelCus(int headrow = -1)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;            

            Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
            if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={_upfile.ContentType}");

            NPOIHelper npoi = new NPOIHelper();
            var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            int num = dtExcel.Rows.Count;
            var cols = dtExcel.Columns;
            int colnum = cols.Count;

            string dbkeys = _configuration["upload:acotdbkeys"].ToString();
            string[] dbcols = dbkeys.Split(",");
            string errmsg = string.Empty;

            if (num > 0)
            {
                var list_pro = (await _sys_provincesrepository.Get()).ToList();
                var list_city = (await _sys_cityrepository.GetAll()).ToList();

                int index = 1;
                // 初始化新增列（字段名称）
                string fields_names = string.Empty;
                foreach (System.Data.DataRow dr in dtExcel.Rows)
                {
                    var dbcolslist = dbcols.ToList();
                    if (index == 1)
                    {
                        // 获取第一行标题 dbcolslist.Count
                        for (int i = 0; i < colnum; i++)
                        {
                            fields_names = dr[i].ToString() + ",";
                        }
                        fields_names = fields_names.TrimEnd(',');
                    }
                    else
                    {
                        // 获取数据
                        var model = new Cus_Customer_Base();

                        model.createuser = usercode;
                        model.createusername = username;
                        //model.cusname = dr.cusname;
                        //model.phone = dr.phone;
                        //model.cusaddr = dr.cusaddr;
                        model.createtime = DateTime.Now.ToLocalTime();

                        Type t = model.GetType();
                        PropertyInfo[] PropertyList = t.GetProperties();

                        var province_code = "";
                        foreach (PropertyInfo item in PropertyList)
                        {
                            if (dbcolslist.Contains(item.Name))
                            {
                                object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);

                                #region 省市获取code by name
                                if (item.Name == "province")
                                {
                                    var model_pro = list_pro.FirstOrDefault(x => x.provincename.Equals(v.ToString()));
                                    province_code = model_pro != null ? model_pro.provincecode : "";
                                    item.SetValue(model, province_code, null);
                                }
                                if (item.Name == "city")
                                {
                                    var model_city = list_city.FirstOrDefault(x => x.provincecode.Equals(province_code) && x.cityname.Equals(v.ToString()));
                                    var city_code = model_city != null ? model_city.citycode : "";
                                    item.SetValue(model, city_code, null);
                                }
                                #endregion

                                item.SetValue(model, v, null);
                            }
                        }

                        #region 自定义新增列 - 处理
                        var fields_names_list = fields_names.Split(",").ToList();
                        var customfields = new List<CustomfieldsList>();
                        for (int i = dbcolslist.Count; i < colnum; i++)
                        {
                            var model_fields = new CustomfieldsList();
                            string name = fields_names_list[i];
                            string fields = ChineseToPinYin.Convert(name);
                            string value = dr[i].ToString();

                            model_fields.name = name;
                            model_fields.fields = fields;
                            model_fields.value = value;
                            customfields.Add(model_fields);
                        }
                        #endregion

                        model.customfields = customfields;

                        bool b = await _cus_customer_baseRepository.Add(model);
                        if (!b)
                        {
                            if (!string.IsNullOrEmpty(errmsg))
                            {
                                errmsg = errmsg + "\r\n第" + index + "行导入失败！";
                            }
                            else
                            {
                                errmsg = "第" + index + "行导入失败！";
                            }
                        }
                    }
                    index++;
                }
            }
            else
            {
                return Error("文件中无数据");
            }

            if (!string.IsNullOrEmpty(errmsg))
            {
                //删除已导入的部分
                return Error(errmsg);
            }

            return Success("导入成功");
        }

        /// <summary>
        /// 导出excel - 客户档案
        /// </summary>
        /// <param name="taskid"></param>
        /// <param name="calloutok"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("exportexcelcus")]
        [AllowAnonymous]
        public IActionResult ExportExcelCusAsync(string keyword, string province, string city, string stime, string etime)
        {
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            try
            {
                var result = _cus_customer_baseRepository.GetListsExport(keyword, province, city, stime, etime, rolecode, usercode);

                //导出
                NPOIHelper npoi = new NPOIHelper();
                var tlist = result.ToList();
                var tb = ModelConvertHelper<Cus_Customer_BaseDto>.ConvertListToDataTable(tlist);

                string[] cols = { "姓名", "手机号码", "固定号码", "所在省", "所在市", "具体地址" };
                string[] colname = { "name", "mobilephone", "telephone", "provincename", "cityname", "address" };
                byte[] sm = npoi.ExportToExcel1(tb, cols, colname);
                if (sm != null)
                {
                    return File(sm, "application/vnd.ms-excel", "客户档案信息.xlsx");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出异常");
                return Error("导出失败");
            }
        }

        /// <summary>
        /// 转移客户
        /// </summary>
        [HttpPost("move")]
        public async Task<IActionResult> MoveAsync(string id,string rolecode, string usercode)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var model = (await _cus_customer_baseRepository.Get(p => p.id == id)).FirstOrDefault();
            if (model != null)
            {
                #region 判断验证
                if (model.isdelete == 1)
                    return Error("用户已删除");
                //if (string.IsNullOrWhiteSpace(model.rolecode))
                //    return Error("无需转移客户信息");
                if (string.IsNullOrEmpty(model.usercode))
                    return Error("此用户不是个人用户，无转移权限");
                #endregion

                #region model 客户对象
                model.rolecode = rolecode;
                model.usercode = usercode;
                #endregion

                bool b = await _cus_customer_baseRepository.UpdateOne(model);
                if (b)
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
            return Error("参数错误");
        }
        #endregion

        #region 来电弹屏
        /// <summary>
        /// 获取客户详情 by tel - 来电弹屏
        /// </summary>
        [HttpGet("getsinglebytelold")]
        public async Task<IActionResult> GetSingleByTelAsyncOLD(string tel)
        {
            if (string.IsNullOrEmpty(tel))
                return Success("参数错误", null);
            var list = (await _cus_customer_baseRepository.Get(x => x.mobilephone == tel && x.isdelete == 0)).ToList();
            var model = list.FirstOrDefault();
            return Success("获取成功", model);
        }

        //2019-2-20去掉客户信息部分做修改
        /// <summary>
        /// 获取客户项目详情 by tel - 来电弹屏
        /// </summary>
        [HttpGet("getsinglebytel")]
        public async Task<IActionResult> GetSingleByTelAsync(string tel)
        {
            if (string.IsNullOrEmpty(tel))
                return Success("参数错误", null);
            var list = (await _cus_customer_projectepository.Get(x => (x.project_mobilephone == tel || x.mobilephone == tel) && x.isdelete == 0)).ToList();
            var model = list.FirstOrDefault();
            return Success("获取成功", model);
        }

        /// <summary>
        /// 获取客户项目列表 by tel - 来电弹屏
        /// </summary>
        [HttpGet("getinfobytel")]
        public async Task<IActionResult> GetInfoByTelAsync(string tel)
        {
            if (string.IsNullOrEmpty(tel))
                return Success("参数错误", null);
            var list = (await _cus_customer_projectepository.Get(x => (x.project_mobilephone == tel || x.mobilephone == tel) && x.isdelete == 0)).ToList();
            //var model = list.FirstOrDefault();
            return Success("获取成功", list);
        }

        /// <summary>
        /// 添加修改客户档案 - 来电弹屏
        /// </summary>
        [HttpPost("save")]
        public async Task<IActionResult> SaveAsync(CusCustomerInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            #region 判断验证
            if (string.IsNullOrWhiteSpace(input.name))
                return Error("请输入联系人   asdfasdf");
            if (string.IsNullOrEmpty(input.mobilephone))
                return Error("请输入联系电话");
            #endregion

            var list = await _cus_customer_baseRepository.Get(x => x.mobilephone == input.mobilephone && x.isdelete == 0);
            var model = list.FirstOrDefault();
            if (model == null)
            {
                model = new Cus_Customer_Base();
                //添加客户信息
                #region model 添加客户对象
                model.name = input.name;
                model.mobilephone = input.mobilephone;
                model.telephone = input.telephone;
                model.manager = input.manager;

                model.customername = input.customername;
                model.companyame = input.companyame;
                model.province = input.province;    //省
                model.city = input.city;            //市
                model.address = input.address;

                model.createuser = usercode;
                model.createusername = username;
                #endregion
                string customerid = await _cus_customer_baseRepository.AddRetID(model);

                if (!string.IsNullOrEmpty(customerid))
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
            else
            {
                //model = (await _cus_customer_baseRepository.Get(p => p.id == input.id)).FirstOrDefault();
                #region model 客户对象
                model.name = input.name;
                model.mobilephone = input.mobilephone;
                model.telephone = input.telephone;
                model.manager = input.manager;

                model.customername = input.customername;
                model.companyame = input.companyame;
                model.province = input.province;    //省
                model.city = input.city;            //市
                model.address = input.address;
                #endregion

                bool b = await _cus_customer_baseRepository.UpdateOne(model);
                if (b)
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
        }

        /// <summary>
        /// 添加修改客户项目 - 来电弹屏
        /// </summary>
        [HttpPost("savepro")]
        public async Task<IActionResult> SaveProAsync(CusCustomerProInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            #region 判断验证
            //if (string.IsNullOrWhiteSpace(input.pro_customerid))
            //    return Error("用户id不能为空");
            if (string.IsNullOrEmpty(input.pro_mobilephone))
                return Error("请输入联系电话");
            //if (string.IsNullOrEmpty(input.pro_project_name))
            //    return Error("请输入项目名称");
            #endregion

            //var list = (await _cus_customer_projectepository.Get(x => x.id == input.pro_id && x.customerid == input.pro_customerid && x.isdelete == 0)).ToList();
            var list = (await _cus_customer_projectepository.Get(x => x.name == input.pro_name && x.project_name == input.pro_project_name && x.isdelete == 0)).ToList();
            var model = list.FirstOrDefault();
            if (model == null)
            {
                model = new Cus_Customer_Project();
                //添加客户信息
                #region model 添加客户对象
                model.customerid = input.pro_customerid;
                model.name = input.pro_name;
                model.mobilephone = input.pro_mobilephone;
                model.telephone = input.pro_telephone;

                model.customername = input.pro_customername;
                model.companyame = input.pro_companyame;
                model.address = input.pro_address;

                model.project_name = input.pro_project_name;
                model.ordertime = input.pro_ordertime;
                model.acceptancetime = input.pro_acceptancetime;
                model.orderendtime = input.pro_orderendtime;
                model.guarantee_period = input.pro_guarantee_period;
                model.isend = input.pro_isend;
                model.project_amount = input.pro_project_amount;
                model.project_typeid = input.pro_project_typeid;
                model.oem_name = input.pro_oem_name;
                model.content = input.pro_content;
                model.servicecontent = input.pro_servicecontent;

                model.createuser = usercode;
                model.createusername = username;

                //2019-2-20 添加项目负责人信息
                model.project_cusname = input.project_cusname;
                model.project_mobilephone = input.project_mobilephone;
                model.project_telephone = input.project_telephone;
                model.project_address = input.project_address;

                //2019-4-12添加客户类型
                model.customerdept = input.customerdept;
                model.customeremail = input.customeremail;
                model.customertype = input.customertype;
                #endregion
                bool bl = await _cus_customer_projectepository.Add(model);
                if (bl)
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
            else
            {
                #region model 客户对象
                model.name = input.pro_name;
                model.mobilephone = input.pro_mobilephone;
                model.telephone = input.pro_telephone;

                model.customername = input.pro_customername;
                model.companyame = input.pro_companyame;
                model.address = input.pro_address;

                model.project_name = input.pro_project_name;
                model.ordertime = input.pro_ordertime;
                model.acceptancetime = input.pro_acceptancetime;
                model.orderendtime = input.pro_orderendtime;
                model.guarantee_period = input.pro_guarantee_period;
                model.isend = input.pro_isend;
                model.project_amount = input.pro_project_amount;
                model.project_typeid = input.pro_project_typeid;
                model.oem_name = input.pro_oem_name;
                model.content = input.pro_content;
                model.servicecontent = input.pro_servicecontent;

                //2019-2-20 添加项目负责人信息
                model.project_cusname = input.project_cusname;
                model.project_mobilephone = input.project_mobilephone;
                model.project_telephone = input.project_telephone;
                model.project_address = input.project_address;

                //2019-4-12添加客户类型
                model.customerdept = input.customerdept;
                model.customeremail = input.customeremail;
                model.customertype = input.customertype;
                #endregion

                bool b = await _cus_customer_projectepository.UpdateOne(model);
                if (b)
                {
                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
        }

        #endregion

        #region 客户项目
        /// <summary>
        /// 获取客户分页
        /// </summary>
        [HttpGet("getprolistbypage")]
        public IActionResult GetProListsByPageAsync(string keyword, string customerid, string stime, string etime, string projecttypeid, string qdstime, string qdetime, string dqstime, string dqetime, string customertype, string gjstime, string gjetime, int? isend, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _cus_customer_projectepository.GetProListsByPage(keyword, customerid, stime, etime, projecttypeid, qdstime, qdetime, dqstime, dqetime, customertype, gjstime, gjetime, isend, pageindex, pagesize, out recordCount);

            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取客户项目下拉
        /// </summary>
        [HttpGet("getprolist")]
        public IActionResult GetProListsAsync()
        {
            int recordCount = 0;
            var result = _cus_customer_projectepository.GetProLists();

            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取客户项目下拉
        /// </summary>
        [HttpGet("getpro")]
        public IActionResult GetProAsync()
        {
            int recordCount = 0;
            var result = _cus_customer_projectepository.GetPro();
            var resu = result.Distinct().ToList();//去重
            var obj = new
            {
                rows = resu,
                total = resu.Count 
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取客户详情
        /// </summary>
        [HttpGet("getprosingle")]
        public IActionResult GetProSingleAsync(string id)
        {
            var model = _cus_customer_projectepository.GetProDetails(id);
            return Success("获取成功", model);
        }

        /// <summary>
        /// 添加客户
        /// </summary>
        [HttpPost("addpro")]
        public async Task<IActionResult> AddProAsync(CusCustomerProInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            #region 判断验证
            //if (string.IsNullOrWhiteSpace(input.pro_customerid))
            //    return Error("用户id不能为空");
            if (string.IsNullOrWhiteSpace(input.pro_name))
                return Error("请输入联系人");
            if (string.IsNullOrEmpty(input.pro_mobilephone))
                return Error("请输入联系电话");
            //if (string.IsNullOrEmpty(input.pro_project_name))
            //    return Error("请输入项目名称");
            if (!string.IsNullOrEmpty(input.pro_companyame))
            {
                var listCus = (await _cus_customer_projectepository.Get(x => x.companyame == input.pro_companyame && x.isdelete == 0)).ToList();
                var models = listCus.FirstOrDefault();
                if (models != null)
                    return Error("单位名称已存在");
            }
            #endregion

            var model = new Cus_Customer_Project();
            #region model 添加客户对象
            model.customerid = input.pro_customerid;
            model.name = input.pro_name;
            model.mobilephone = input.pro_mobilephone;
            model.telephone = input.pro_telephone;

            model.customername = input.pro_customername;
            model.companyame = input.pro_companyame;
            //model.province = input.province;    //省
            //model.city = input.city;            //市
            model.address = input.pro_address;

            model.project_name = input.pro_project_name;
            model.ordertime = input.pro_ordertime;
            model.acceptancetime = input.pro_acceptancetime;
            model.orderendtime = input.pro_orderendtime;
            model.guarantee_period = input.pro_guarantee_period;
            model.isend = input.pro_isend;
            model.project_amount = input.pro_project_amount;
            model.project_typeid = input.pro_project_typeid;
            model.oem_name = input.pro_oem_name;
            model.content = input.pro_content;
            model.servicecontent = input.pro_servicecontent;

            model.createuser = usercode;
            model.createusername = username;

            //2019-2-20 添加项目负责人信息
            model.project_cusname = input.project_cusname;
            model.project_mobilephone = input.project_mobilephone;
            model.project_telephone = input.project_telephone;
            model.project_address = input.project_address;

            //2019-4-12添加客户类型
            model.customerdept = input.customerdept;
            model.customeremail = input.customeremail;
            model.customertype = input.customertype;
            //2019-5-6添加附件
            if (input.attachment != null)
            {
                model.attachment = input.attachment;
            }
            else
            {
                model.attachment = new List<FileBaseModel>();
            }
            #endregion
            bool bl = await _cus_customer_projectepository.Add(model);
            if (bl)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        /// <summary>
        /// 上传文件并导入数据库
        /// </summary>
        /// <returns></returns>
        [HttpPost("importexcelpro")]
        public async Task<IActionResult> ImportExcelPro(string customerid, int headrow = 0)//string customerid,
        {

            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;



            if (Request.Form.Files.Count <= 0)
            {
                return Error("获取不到要导入的文件");
            }
            Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
            if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={_upfile.ContentType}");

            NPOIHelper npoi = new NPOIHelper();
            var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            int num = dtExcel.Rows.Count;
            var cols = dtExcel.Columns;
            int colnum = cols.Count;

            string dbkeys = _configuration["upload:prodbkeys"].ToString();

            string[] dbcols = dbkeys.Split(",");
            string errmsg = string.Empty;

            if (num > 0)
            {

                int index = 1;
                foreach (System.Data.DataRow dr in dtExcel.Rows)
                {
                    var model = new Cus_Customer_Project();

                    model.createuser = usercode;
                    model.createusername = username;
                    //model.cusname = dr.cusname;
                    //model.phone = dr.phone;
                    //model.cusaddr = dr.cusaddr;
                    model.createtime = DateTime.Now.ToLocalTime();
                    //model.customerid = customerid;
                    model.customertype = "签约客户";
                    var dbcolslist = dbcols.ToList();

                    Type t = model.GetType();
                    PropertyInfo[] PropertyList = t.GetProperties();

                    foreach (PropertyInfo item in PropertyList)
                    {
                        if (dbcolslist.Contains(item.Name))
                        {
                            if (item.Name == "project_typeid")
                            {
                                var models = await _sys_dictionaryValuerepository.GetSingle(x => x.name == dr[dbcolslist.IndexOf(item.Name)].ToString());

                                if (models != null)
                                {
                                    model.project_typeid = models.id;
                                }

                            }
                            else
                            {
                                if (dr[dbcolslist.IndexOf(item.Name)].ToString() != null)
                                {
                                    if (item.PropertyType == typeof(DateTime))
                                    {
                                        if (dr[dbcolslist.IndexOf(item.Name)].ToString() != "")
                                        {
                                            object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                                            item.SetValue(model, v, null);

                                        }
                                    }
                                    else
                                    {
                                        if (dr[dbcolslist.IndexOf(item.Name)].ToString() != "")
                                        {
                                            object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                                            item.SetValue(model, v, null);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    bool b = await _cus_customer_projectepository.Add(model);
                    if (!b)
                    {
                        if (!string.IsNullOrEmpty(errmsg))
                        {
                            errmsg = errmsg + "\r\n第" + index + "行导入失败！";
                        }
                        else
                        {
                            errmsg = "第" + index + "行导入失败！";
                        }
                    }
                    index++;
                }
            }
            else
            {
                return Error("文件中无数据");
            }

            if (!string.IsNullOrEmpty(errmsg))
            {
                //删除已导入的部分
                return Error(errmsg);
            }

            return Success("导入成功");
        }

        /// <summary>
        /// 修改客户
        /// </summary>
        [HttpPost("updatepro")]
        public async Task<IActionResult> UpdateProAsync(CusCustomerProInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var model = (await _cus_customer_projectepository.Get(p => p.id == input.pro_id)).FirstOrDefault();
            if (model != null)
            {
                #region 判断验证
                if (model.isdelete == 1)
                    return Error("用户已删除");
                //if (string.IsNullOrWhiteSpace(input.pro_customerid))
                //    return Error("用户id不能为空");
                if (string.IsNullOrWhiteSpace(input.pro_name))
                    return Error("请输入联系人");
                if (string.IsNullOrEmpty(input.pro_mobilephone))
                    return Error("请输入联系电话");
                //if (string.IsNullOrEmpty(input.pro_project_name))
                //    return Error("请输入项目名称");
                #endregion

                #region model 客户对象
                model.name = input.pro_name;
                model.mobilephone = input.pro_mobilephone;
                model.telephone = input.pro_telephone;

                model.customername = input.pro_customername;
                model.companyame = input.pro_companyame;
                //model.province = input.province;    //省
                //model.city = input.city;            //市
                model.address = input.pro_address;

                model.project_name = input.pro_project_name;
                model.ordertime = input.pro_ordertime;
                model.acceptancetime = input.pro_acceptancetime;
                model.orderendtime = input.pro_orderendtime;
                model.guarantee_period = input.pro_guarantee_period;
                model.isend = input.pro_isend;
                model.project_amount = input.pro_project_amount;
                model.project_typeid = input.pro_project_typeid;
                model.oem_name = input.pro_oem_name;
                model.content = input.pro_content;
                model.servicecontent = input.pro_servicecontent;

                //2019-2-20 添加项目负责人信息
                model.project_cusname = input.project_cusname;
                model.project_mobilephone = input.project_mobilephone;
                model.project_telephone = input.project_telephone;
                model.project_address = input.project_address;

                //2019-4-12添加客户类型
                model.customerdept = input.customerdept;
                model.customeremail = input.customeremail;
                model.customertype = input.customertype;
                model.followcontent = input.followcontent;
                model.followtime = input.followtime;

                //2019-5-6添加附件
                if (input.attachment != null)
                {
                    model.attachment = input.attachment;
                }
                else
                {
                    model.attachment = new List<FileBaseModel>();
                }
                #endregion

                bool b = await _cus_customer_projectepository.UpdateOne(model);
                if (b)
                {
                    #region 修改最新一条跟进记录
                    if (string.IsNullOrEmpty(input.followcontent))
                    {
                        var sort = Builders<Cus_FollowRecord>.Sort.Descending("createTime");
                        var dModel = await _cus_followrecordrepository.GetSingle(s => s.proid.Equals(input.pro_id), sort);
                        if (dModel != null)
                        {
                            dModel.content = input.followcontent;
                            dModel.createTime = (DateTime)input.followtime;
                            await _cus_followrecordrepository.UpdateOne(dModel);
                        }
                    }
                    #endregion

                    return Success("保存成功");
                }
                else
                    return Error("保存失败");
            }
            return Error("参数错误");
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deletepro")]
        public async Task<IActionResult> DeleteProAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //使用逻辑删除
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    var model = await _cus_customer_projectepository.GetSingle(id);
                    model.isdelete = 1;
                    model.deleteuser = usercode;
                    model.deletetime = DateTime.Now;
                    if (await _cus_customer_projectepository.UpdateOne(model))
                    {
                        res += 1;
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败");
                else
                    return Error("删除失败");
            }
            else
                return Error("请选择要删除的记录");
        }

        #endregion

        #region 潜在客户信息
        /// <summary>
        /// 添加跟进信息
        /// </summary>
        [HttpPost("addfollowinfo")]
        public async Task<IActionResult> AddFollowAsync(string id, string content)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;


            var model = new Cus_FollowRecord();
            #region model 添加跟进信息
            model.content = content;
            model.createName = usercode;
            model.createTime = DateTime.Now.ToLocalTime();
            model.proid = id;
            #endregion
            bool bl = await _cus_followrecordrepository.Add(model);
            if (bl)
            {
                //更新客户项目表跟进时间 
                var modelc = await _cus_customer_projectepository.GetSingle(id);
                modelc.followtime = DateTime.Now;
                modelc.followcontent = content;
                if (await _cus_customer_projectepository.UpdateOne(modelc))
                {
                    return Success("跟进信息保存成功");
                }
                else
                    return Error("信息更新失败");
            }
            else
                return Error("信息保存失败");
        }

        /// <summary>
        /// 获取跟进信息
        /// </summary>
        [HttpGet("getfollowlist")]
        public async Task<IActionResult> GetFollowListsAsync(string id)
        {

            var lists = (await _cus_followrecordrepository.Get(p => p.proid == id)).ToList();
            return Success("获取成功", lists);
        }

        /// <summary>
        /// 用于项目负责人、客户类型相互转移
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("changeinfo")]
        public async Task<IActionResult> ChangeInfoAsync(string id, string cusname, string customertype, string cusphone)
        {

            var model = await _cus_customer_projectepository.GetSingle(id);
            if (!string.IsNullOrEmpty(cusname))
            {
                model.project_cusname = cusname;
            }
            if (!string.IsNullOrEmpty(customertype))
            {
                model.customertype = customertype;
            }
            if (!string.IsNullOrEmpty(cusphone))
            {
                model.project_mobilephone = cusphone;
            }
            if (await _cus_customer_projectepository.UpdateOne(model))
            {
                return Success("转移成功"); ;
            }

            else
                return Error("转移失败");

        }

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <param name="taskid"></param>
        /// <param name="calloutok"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("exportexcel")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportExcelAsync(string keyword, string customerid, string stime, string etime, string projecttypeid, string qdstime, string qdetime, string dqstime, string dqetime, string customertype, string gjstime, string gjetime, int? isend)
        {
            try
            {

                int recordCount = 0;
                var result = _cus_customer_projectepository.GetProLists(keyword, customerid, stime, etime, projecttypeid, qdstime, qdetime, dqstime, dqetime, customertype, gjstime, gjetime, isend, out recordCount);

                //导出
                NPOIHelper npoi = new NPOIHelper();
                var tlist = result.ToList();
                var tb = ModelConvertHelper<Cus_Customer_ProjectDto>.ConvertListToDataTable(tlist);

                if (customertype == "签约客户")
                {
                    string[] cols = { "姓名", "手机号码", "固定号码", "客户名称", "单位名称", "地址", "项目名称", "项目负责人", "负责人手机号", "负责人固话", "负责人地址", "项目类型", "项目金额", "合同签订时间", "验收日期", "到期日期", "质保期", "是否到期", "设备厂家 / 中间件", "授权内容", "售后服务内容" };
                    string[] colname = { "name", "mobilephone", "telephone", "customername", "companyame", "address", "project_name", "project_cusname", "project_mobilephone", "project_telephone", "project_address", "project_typeid", "project_amount", "ordertime", "acceptancetime", "orderendtime", "guarantee_period", "isend", "oem_name", "content", "servicecontent" };
                    byte[] sm = npoi.ExportToExcel1(tb, cols, colname);
                    if (sm != null)
                    {
                        return File(sm, "application/vnd.ms-excel", "客户信息.xlsx");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                else if (customertype == "潜在客户")
                {
                    //获取历史跟进信息
                    DataTable dtnew = tb;
                    dtnew.Columns.Add("followRecord");
                    for (int i = 0; i < tb.Rows.Count; i++)
                    {
                        string id = tb.Rows[i]["id"].ToString();
                        var lists = (await _cus_followrecordrepository.Get(p => p.proid == id)).ToList();
                        string fr = "";
                        int n = 1;
                        foreach (var l in lists)
                        {
                            fr += n.ToString() + "、" + l.createTime.ToString("yyyy-MM-dd") + "  " + l.content + "\n";
                            n++;
                        }
                        dtnew.Rows[i]["followRecord"] = fr;
                    }

                    string[] cols = { "单位名称", "客户部门", "手机号码", "联系人", "邮箱", "项目负责人", "跟进日期", "跟进内容", "跟进记录" };
                    string[] colname = { "companyame", "customerdept", "mobilephone", "name", "customeremail", "project_cusname", "followtime", "followcontent", "followRecord" };
                    byte[] sm = npoi.ExportToExcel1(dtnew, cols, colname);
                    if (sm != null)
                    {
                        return File(sm, "application/vnd.ms-excel", "潜在客户信息.xlsx");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Error("导出失败");

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出异常");
                return Error("导出失败");
            }
            //return Success("导出成功");
        }

        /// <summary>
        /// 上传文件并导入数据库--导入潜在客户
        /// </summary>
        /// <returns></returns>
        [HttpPost("importexcelqz")]
        public async Task<IActionResult> ImportQExcel(int headrow = 0)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //if (string.IsNullOrEmpty(taskid))
            //    return Error("任务id不能为空");

            //string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
            if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={_upfile.ContentType}");

            NPOIHelper npoi = new NPOIHelper();
            var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            int num = dtExcel.Rows.Count;
            var cols = dtExcel.Columns;
            int colnum = cols.Count;

            string dbkeys = _configuration["upload:qrodbkeys"].ToString();
            string[] dbcols = dbkeys.Split(",");
            string errmsg = string.Empty;

            if (num > 0)
            {
                int index = 1;
                foreach (System.Data.DataRow dr in dtExcel.Rows)
                {
                    DateTime ftime = DateTime.Now;//跟进时间
                    string fcontent = "";//跟进内容
                    var model = new Cus_Customer_Project();

                    model.createuser = usercode;
                    model.createusername = username;
                    //model.cusname = dr.cusname;
                    //model.phone = dr.phone;
                    //model.cusaddr = dr.cusaddr;
                    model.createtime = DateTime.Now.ToLocalTime();
                    model.customertype = "潜在客户";

                    var dbcolslist = dbcols.ToList();

                    Type t = model.GetType();
                    PropertyInfo[] PropertyList = t.GetProperties();

                    foreach (PropertyInfo item in PropertyList)
                    {
                        _logger.LogError(item.Name.ToString(), "导出异常");
                        _logger.LogError(dbcolslist.ToString(), "导出异常");
                        if (dbcolslist != null && item != null && item.Name != null && dbcolslist.Contains(item.Name))
                        {
                            //object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                            //item.SetValue(model, v, null);

                            if (dr[dbcolslist.IndexOf(item.Name)].ToString() != null)
                            {
                                if (item.PropertyType == typeof(DateTime?) || item.PropertyType == typeof(DateTime))
                                {
                                    if (dr[dbcolslist.IndexOf(item.Name)] != null && dr[dbcolslist.IndexOf(item.Name)].ToString() != "")
                                    {
                                        #region 可空类型
                                        /*Type ty = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
                                        DateTime? date = DateTime.Now;
                                        string s = dr[dbcolslist.IndexOf(item.Name)].ToString();
                                        if (ty.IsGenericType && ty.GetGenericTypeDefinition() == typeof(Nullable<>))
                                        {
                                            if (String.IsNullOrEmpty(s))
                                                item.SetValue(model, null, null);
                                            else
                                            {
                                                //date = Convert.ChangeType(s, t.GetGenericArguments()[0]);
                                                //object y = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                                                item.SetValue(model, Convert.ChangeType(s, t.GetGenericArguments()[0]), null);
                                            }
                                        }
                                        else
                                        {
                                            item.SetValue(model, null, null);
                                        }*/
                                        #endregion
                                        object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                                        item.SetValue(model, v, null);
                                        if (item.Name == "followtime")
                                        {
                                            ftime = DateTime.Parse(dr[dbcolslist.IndexOf(item.Name)].ToString());
                                        }
                                        else if (item.Name == "followcontent")
                                        {
                                            fcontent = dr[dbcolslist.IndexOf(item.Name)].ToString();
                                        }
                                    }
                                }
                                else
                                {
                                    if (dr[dbcolslist.IndexOf(item.Name)].ToString() != "")
                                    {
                                        object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                                        item.SetValue(model, v, null);
                                        if (item.Name == "followcontent")
                                        {
                                            fcontent = dr[dbcolslist.IndexOf(item.Name)].ToString();
                                        }
                                    }
                                }
                            }
                        }
                    }

                    string addid = await _cus_customer_projectepository.AddRetID(model);//bool b = await _cus_customer_projectepository.Add(model)
                    //保存跟进记录
                    if (fcontent != "")
                    {
                        var modelr = new Cus_FollowRecord();
                        modelr.content = fcontent;
                        modelr.createName = usercode;
                        modelr.createTime = ftime;
                        modelr.proid = addid;
                        bool bl = await _cus_followrecordrepository.Add(modelr);
                    }

                    if (string.IsNullOrEmpty(addid))
                    {
                        if (!string.IsNullOrEmpty(errmsg))
                        {
                            errmsg = errmsg + "\r\n第" + index + "行导入失败！";
                        }
                        else
                        {
                            errmsg = "第" + index + "行导入失败！";
                        }
                    }
                    index++;
                }
            }
            else
            {
                return Error("文件中无数据");
            }

            if (!string.IsNullOrEmpty(errmsg))
            {
                //删除已导入的部分
                return Error(errmsg);
            }

            return Success("导入成功");
        }
        #endregion

        //2019-5-6 获取合同到期提醒
        [Authorize]
        [HttpGet("gettxlist")]
        public async Task<IActionResult> GetListAsync(int daykind = 0)//到期前一月或前几天提醒
        {
            #region 条件信息

            var listfilter = new List<FilterDefinition<Cus_Customer_Project>>();
            listfilter.Add(Builders<Cus_Customer_Project>.Filter.Eq("isdelete", 0));
            var filter = Builders<Cus_Customer_Project>.Filter.And(listfilter);
            DateTime dtstart = DateTime.Now;
            var sort = Builders<Cus_Customer_Project>.Sort.Descending("orderendtime");
            var list = await _cus_customer_projectepository.Get(filter, null, sort); ;
            switch (daykind)
            {
                case 0://到期前一月orderendtime到期时间减去现在时间大于0小于等于30
                    DateTime dtend = dtstart.AddDays(30);
                    DateTime dt = DateTime.Now.ToLocalTime();
                    if (DateTime.TryParse(dtstart.ToString("yyyy-MM-dd") + " 00:00:00", out dt))
                        listfilter.Add(Builders<Cus_Customer_Project>.Filter.Gt("orderendtime", dt));
                    if (DateTime.TryParse(dtend.ToString("yyyy-MM-dd") + " 23:59:59", out dt))
                        listfilter.Add(Builders<Cus_Customer_Project>.Filter.Lt("orderendtime", dt));
                    var filter0 = Builders<Cus_Customer_Project>.Filter.And(listfilter);
                    list = await _cus_customer_projectepository.Get(filter0, null, sort);
                    break;
                case 1://到期当天
                    DateTime dtend1 = dtstart;//.AddDays(30);
                    DateTime dt1 = DateTime.Now.ToLocalTime();
                    if (DateTime.TryParse(dtstart.ToString("yyyy-MM-dd") + " 00:00:00", out dt1))
                        listfilter.Add(Builders<Cus_Customer_Project>.Filter.Gt("orderendtime", dt1));
                    if (DateTime.TryParse(dtend1.ToString("yyyy-MM-dd") + " 23:59:59", out dt1))
                        listfilter.Add(Builders<Cus_Customer_Project>.Filter.Lt("orderendtime", dt1));
                    var filter1 = Builders<Cus_Customer_Project>.Filter.And(listfilter);
                    list = await _cus_customer_projectepository.Get(filter1, null, sort);
                    break;
                default:
                    break;
            }

            #endregion


            var obj = new
            {
                data = list
            };
            return Success("成功", obj);
        }


    }
}
