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

namespace WorkOrderApi.Areas.Hy_Order.Controllers
{
    /// <summary>
    /// 客户授权管理
    /// </summary>
    [Area("hy")]
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class CusAuthManageController : BaseController
    {
        private readonly ILogger<CusAuthManageController> _logger;
        private readonly ICus_AuthManageRepository _cus_authmanageRepository;
        private readonly IConfiguration _configuration;
        private readonly ICus_AuthOrderRepository _cus_authorderRepository;
        private readonly IBus_Msg_ListRepository _bus_msg_listRepository;

        public CusAuthManageController(
           ILogger<CusAuthManageController> logger,
           ICus_AuthManageRepository cus_authmanageRepository,
           IConfiguration configuration,
            IBus_Msg_ListRepository bus_msg_listRepository,
           ICus_AuthOrderRepository cus_authorderRepository
           )
        {
            _logger = logger;
            _cus_authmanageRepository = cus_authmanageRepository;
            _configuration = configuration;
            _bus_msg_listRepository = bus_msg_listRepository;
            _cus_authorderRepository = cus_authorderRepository;
        }

        /// <summary>
        /// 获取基础数据列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string pro_name,string auth_type,string oem_name,string stime,string etime,string progress,string smanager,string pexecutor,string pmanager,string fmanager, string value, string code,int isend=-1, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                //排序字段
                var sort = Builders<Cus_AuthManage>.Sort.Descending("createtime");

                //根据条件查询集合
                var flist = new List<FilterDefinition<Cus_AuthManage>>();
                flist.Add(Builders<Cus_AuthManage>.Filter.Eq("isdelete", 0));
                if (!string.IsNullOrWhiteSpace(pro_name))
                    flist.Add(Builders<Cus_AuthManage>.Filter.Where(s => s.pro_name.Equals (pro_name)));
                if (!string.IsNullOrWhiteSpace(auth_type))
                    flist.Add(Builders<Cus_AuthManage>.Filter.Where(s => s.auth_type.Equals(auth_type)));
                if (!string.IsNullOrWhiteSpace(oem_name))
                    flist.Add(Builders<Cus_AuthManage>.Filter.Where(s => s.oem_name.Equals(oem_name)));
                                
                if (!string.IsNullOrEmpty(stime))
                {
                    DateTime dt = DateTime.Parse(stime);
                    if (DateTime.TryParse(dt.ToString("yyyy-MM-dd") + " 00:00:00", out dt))
                        flist.Add(Builders<Cus_AuthManage>.Filter.Gt("authendtime", dt));
                }
                if (!string.IsNullOrEmpty(stime))
                {
                    DateTime dt = DateTime.Parse(stime);
                    if (DateTime.TryParse(dt.ToString("yyyy-MM-dd") + " 23:59:59", out dt))
                        flist.Add(Builders<Cus_AuthManage>.Filter.Lt("authendtime", dt));
                }
                if (!string.IsNullOrWhiteSpace(progress ))
                    flist.Add(Builders<Cus_AuthManage>.Filter.Where(s => s.pro_progress .Equals(progress)));
                if (!string.IsNullOrWhiteSpace(smanager))
                    flist.Add(Builders<Cus_AuthManage>.Filter.Where(s => s.sale_manager .Equals(smanager)));
                if (!string.IsNullOrWhiteSpace(pexecutor))
                    flist.Add(Builders<Cus_AuthManage>.Filter.Where(s => s.pro_executor .Equals(pexecutor)));
                if (!string.IsNullOrWhiteSpace(pmanager))
                    flist.Add(Builders<Cus_AuthManage>.Filter.Where(s => s.product_manager .Equals(pmanager)));
                if (isend >-1)
                    flist.Add(Builders<Cus_AuthManage>.Filter.Eq("isend", isend ));

                
                var filter = Builders<Cus_AuthManage>.Filter.And(flist);
                var list = await _cus_authmanageRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _cus_authmanageRepository.CountAsync(filter);
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = list,
                    total = count,
                };
                return Content(obj.ToJson());
                //return Success("根据条件获取分页数据成功", list);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取基础数据分页数据异常");
                return Error("获取基础数据分页数据失败");
            }
        }


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

            try
            {
                var model = new Cus_AuthManage();
                #region model 添加客户对象
                //model.id = cusid;
                model.pro_name = input.pro_name;
                model.auth_type = input.auth_type;
                model.oem_name = input.oem_name;
                model.authendtime = input.authendtime;

                model.auth_code = input.auth_code;
                model.auth_num = input.auth_num;
                model.pro_progress = input.pro_progress;    
                model.sale_manager = input.sale_manager;            
                model.pro_executor = input.pro_executor;

                model.product_manager = input.product_manager;
                model.finance_manager = input.finance_manager;
                model.general_manager = input.general_manager;
                model.isend = input.isend;
                model.content = input.content;
                model.createtime = DateTime.Now;
                model.createuser = usercode;
                model.createusername = username;
                #endregion
                string customerid = await _cus_authmanageRepository.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(CusAuthManageInput 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_authmanageRepository.Get(p => p.id == input.id)).FirstOrDefault();
            if (model != null)
            {
                #region model 客户对象
                model.pro_name = input.pro_name;
                model.auth_type = input.auth_type;
                model.oem_name = input.oem_name;
                model.authendtime = input.authendtime;

                model.auth_code = input.auth_code;
                model.auth_num = input.auth_num;
                model.pro_progress = input.pro_progress;    
                model.sale_manager = input.sale_manager;            
                model.pro_executor = input.pro_executor;

                model.product_manager = input.product_manager;
                model.finance_manager = input.finance_manager;
                model.general_manager = input.general_manager;
                model.isend = input.isend;
                model.content = input.content;
                model.createtime = DateTime.Now;
                model.createuser = usercode;
                model.createusername = username;
                #endregion

                bool b = await _cus_authmanageRepository.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_authmanageRepository.GetSingle(id);
                    model.isdelete = 1;
                    model.deleteuser = usercode;
                    model.deletetime = DateTime.Now;
                    if (await _cus_authmanageRepository.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("请选择要删除的记录");
        }


        /// <summary>
        /// 获取授权到期提醒
        /// </summary>
        /// <param name="daykind"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("gettxlist")]
        public async Task<IActionResult> GetListAsync(int daykind = 0)//到期前一月或前几天提醒
        {
            #region 条件信息
            var listfilter = new List<FilterDefinition<Cus_AuthManage>>();
            DateTime dtstart = DateTime.Now;
            var sort = Builders<Cus_AuthManage>.Sort.Descending("authendtime");
            var list = await _cus_authmanageRepository.Get(null, null, sort); 
            switch (daykind)
            {
                case 0://到期前15天到期时间减去现在时间大于0小于等于30
                    DateTime dtend = dtstart.AddDays(15);
                    DateTime dt = DateTime.Now.ToLocalTime();
                    if (DateTime.TryParse(dtstart.ToString("yyyy-MM-dd") + " 00:00:00", out dt))
                        listfilter.Add(Builders<Cus_AuthManage>.Filter.Gt("authendtime", dt));
                    if (DateTime.TryParse(dtend.ToString("yyyy-MM-dd") + " 23:59:59", out dt))
                        listfilter.Add(Builders<Cus_AuthManage>.Filter.Lt("authendtime", dt));
                    var filter = Builders<Cus_AuthManage>.Filter.And(listfilter);
                    list = await _cus_authmanageRepository.Get(filter, null, sort);
                    break;
                case 1://到期当天
                    DateTime dtend1 = dtstart;
                    DateTime dt1 = DateTime.Now.ToLocalTime();
                    if (DateTime.TryParse(dtstart.ToString("yyyy-MM-dd") + " 00:00:00", out dt1))
                        listfilter.Add(Builders<Cus_AuthManage>.Filter.Gt("authendtime", dt1));
                    if (DateTime.TryParse(dtend1.ToString("yyyy-MM-dd") + " 23:59:59", out dt1))
                        listfilter.Add(Builders<Cus_AuthManage>.Filter.Lt("authendtime", dt1));
                    var filter1 = Builders<Cus_AuthManage>.Filter.And(listfilter);
                    list = await _cus_authmanageRepository.Get(filter1, null, sort);
                    break;
                default:
                    break;
            }

            #endregion


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

        //导入授权信息
        /// <summary>
        /// 上传文件并导入数据库
        /// </summary>
        /// <returns></returns>
        [HttpPost("importexcel")]
        public async Task<IActionResult> ImportExcel(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:sqdbkeys"].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_AuthManage();

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


                    var dbcolslist = dbcols.ToList();

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

                    foreach (PropertyInfo item in PropertyList)
                    {
                        if (dbcolslist.Contains(item.Name))
                        {
                            object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                            item.SetValue(model, v, null);
                        }
                    }

                    bool b = await _cus_authmanageRepository.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>
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            var cls = await _cus_authmanageRepository.Get(p => p.id  == id && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();
            if (clmodel != null)
            {
                

                return Success("获取成功", clmodel);
            }
            else
                return Error("获取失败");
        }

        //申请续期
        /// <summary>
        /// 添加授权续期申请
        /// </summary>
        [HttpPost("addsq")]
        public async Task<IActionResult> AddSQAsync(string proid, string proname,string content,string authtype,string authendtime,int infotype=0)
        {
            
            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_AuthOrder();
            
            #region model 添加工单对象
            model.pro_id = proid;
            model.pro_name = proname;
            model.content  = content;   
            model.auth_type = authtype;
            model.authendtime = DateTime.Parse (authendtime);
            model.infotype = infotype;
            model.createuser = usercode;           
            model.createtime = DateTime.Now;
            model.isdelete = 0;
            #endregion
            bool bl = await _cus_authorderRepository.Add(model);
            if (bl)
            {
                string mes = "";
                if (infotype == 1)
                {
                     mes = usercode + "(" + username + "） 发起授权续期申请";
                }
                else if (infotype == 2)
                {
                     mes = usercode + "(" + username + "） 创建授权续期任务";
                }
                else if (infotype == 3)
                {
                     mes = usercode + "(" + username + "） 创建项目开启任务";
                }
                else if (infotype == 4)
                {
                     mes = usercode + "(" + username + "） 创建项目暂停任务";
                }
               
                AddItems(proid,  mes, usercode, username);
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        /// <summary>
        /// 获取基础数据列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getsqlistbypage")]
        public async Task<IActionResult> GetSQListsByPage(string pro_name, string auth_type, string stime, string etime, string createuser,int infotype=-1, int state = -1, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                //排序字段
                var sort = Builders<Cus_AuthOrder>.Sort.Descending("createtime");

                //根据条件查询集合
                var flist = new List<FilterDefinition<Cus_AuthOrder>>();
                flist.Add(Builders<Cus_AuthOrder>.Filter.Eq("isdelete", 0));
                if (!string.IsNullOrWhiteSpace(pro_name))
                    flist.Add(Builders<Cus_AuthOrder>.Filter.Where(s => s.pro_name.Equals(pro_name)));
                if (!string.IsNullOrWhiteSpace(auth_type))
                    flist.Add(Builders<Cus_AuthOrder>.Filter.Where(s => s.auth_type.Equals(auth_type)));
                if (!string.IsNullOrWhiteSpace(createuser))
                    flist.Add(Builders<Cus_AuthOrder>.Filter.Where(s => s.createuser.Equals(createuser)));
                if (infotype > -1)
                {
                    flist.Add(Builders<Cus_AuthOrder>.Filter.Eq("infotype", infotype));
                }
                if (state > -1)
                {
                    flist.Add(Builders<Cus_AuthOrder>.Filter.Eq("state", state));
                }

                if (!string.IsNullOrEmpty(stime))
                {
                    DateTime dt = DateTime.Parse(stime);
                    if (DateTime.TryParse(dt.ToString("yyyy-MM-dd") + " 00:00:00", out dt))
                        flist.Add(Builders<Cus_AuthOrder>.Filter.Gt("createtime", dt));
                }
                if (!string.IsNullOrEmpty(stime))
                {
                    DateTime dt = DateTime.Parse(stime);
                    if (DateTime.TryParse(dt.ToString("yyyy-MM-dd") + " 23:59:59", out dt))
                        flist.Add(Builders<Cus_AuthOrder>.Filter.Lt("createtime", dt));
                }
               
                var filter = Builders<Cus_AuthOrder>.Filter.And(flist);
                var list = await _cus_authorderRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _cus_authorderRepository.CountAsync(filter);
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = list,
                    total = count,
                };
                return Content(obj.ToJson());
                //return Success("根据条件获取分页数据成功", list);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取基础数据分页数据异常");
                return Error("获取基础数据分页数据失败");
            }
        }

        //添加操作记录
        private async void AddItems(string pro_id, string detail, string usercode, string username)
        {
            var model = new Bus_Msg_List();
            model.ordercode = pro_id;
            model.createuser = usercode;
            model.createusername = username;
            model.createtime = DateTime.Now;
            model.detail = detail;
            await _bus_msg_listRepository.Add(model);
        }

        /// <summary>
        /// 获取授权申请动态
        /// </summary>
        [HttpGet("getdt")]
        public async Task<IActionResult> GetDTAsync(string proid)
        {
            var cls = await _bus_msg_listRepository.Get(p => p.ordercode == proid && p.isdelete == 0);

            if (cls != null)
            {


                return Success("获取成功", cls);
            }
            else
                return Error("获取失败");
        }

        /// <summary>
        /// 修改授权信息
        /// </summary>
        [HttpPost("updatesq")]
        public async Task<IActionResult> UpdateSQAsync(string id,string proid, string proname, string content, string authtype, string authendtime)
        {
            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_authorderRepository.Get(p => p.id ==id)).FirstOrDefault();
            if (model != null)
            {
                #region model 添加对象
                model.pro_id = proid;
                model.pro_name = proname;
                model.content = content;   
                model.auth_type = authtype;
                model.authendtime = DateTime.Parse(authendtime);

                model.createuser = usercode;
                model.createtime = DateTime.Now;
                model.isdelete = 0;
                #endregion

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

        /// <summary>
        /// 删除授权信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deletesq")]
        public async Task<IActionResult> DeleteSQAsync(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_authorderRepository.GetSingle(id);
                    model.isdelete = 1;
                    model.deleteuser = usercode;
                    model.deletetime = DateTime.Now;
                    if (await _cus_authorderRepository.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("请选择要删除的记录");
        }

        //操作，通过、撤回、确认续期
        /// <summary>
        /// 操作授权信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deal")]
        public async Task<IActionResult> DealAsync(string id, int state = 0)
        {
            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_authorderRepository.GetSingle(id);
            model.state  = state;
            model.deleteuser = usercode;
            model.deletetime = DateTime.Now;
            if (await _cus_authorderRepository.UpdateOne(model))
            {
                string mes = "";
                if (state == 5)
                {
                    mes = usercode + "(" + username + "） 撤回授权续期申请";
                }
                else if (state == 6)
                {
                    mes = usercode + "(" + username + "） 审批通过授权续期申请";
                }
                else if (state == 7)
                {
                    mes = usercode + "(" + username + "） 确认已续期";
                }
                else if (state == 8)
                {
                    mes = usercode + "(" + username + "） 确认已暂停";
                }
                else if (state == 7)
                {
                    mes = usercode + "(" + username + "） 确认已开启";
                }

                AddItems(id, mes, usercode, username);

                return Success("操作成功");
            }
            else
                return Error("操作失败");
            
        }
    }
}