using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

using System.Security.Claims;
using System.IO;

using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using XHD.Core.IServices;
using XHD.Core.IRepository;
using XHD.Core.Common;
using XHD.Core.Models;

using System.Linq.Expressions;
using Newtonsoft.Json.Converters;
using System.Collections;
using XHD.Core.View.Configs;

using FreeSql;

using NPOI.HSSF.UserModel;
using UUIDNext;


namespace XHD.Core.View.Controllers
{
    [Authorize]
    public class CRM_ContactController : Controller
    {
        private readonly ILogger<CRM_ContactController> _logger;
        private readonly ICRM_ContactService _service;
        private readonly ICRM_followService _followservice;
        private readonly ISys_logService _LogService;
        private readonly IDBAuthService _dBAuthService;
        private readonly SysLogExt<CRM_Contact> logext = new SysLogExt<CRM_Contact>();
        private readonly Configs.NPOIExt _npoi;

        public CRM_ContactController(
            ILogger<CRM_ContactController> logger,
            ICRM_ContactService service, 
            ICRM_followService followservice, 
            ISys_logService LogService, 
            IDBAuthService dBAuthService,
            Configs.NPOIExt npoi
            )
        {
            _service = service;
            _logger = logger;
            _followservice = followservice;

            _LogService = LogService;
            _dBAuthService = dBAuthService;
            _npoi = npoi;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Add()
        {
            return View();
        }

        public async Task<string> Grid(PageView<CRM_Contact> model)
        {
            Expression<Func<CRM_Contact, bool>> exp = a => 1 == 1;

            if (!string.IsNullOrWhiteSpace(Request.Query["C_name"]))
            {
                exp = exp.And(a => a.C_name.Contains(Request.Query["C_name"]));
            }

            if (!string.IsNullOrWhiteSpace(Request.Query["keyword"]))
            {
                exp = exp.And(a => a.C_name.Contains(Request.Query["keyword"]));
            }

            if (!string.IsNullOrWhiteSpace(Request.Query["customer_id"]))
            {
                exp = exp.And(a => a.customer_id == Request.Query["customer_id"]);
            }

            if (!string.IsNullOrWhiteSpace(Request.Query["cus_name"]))
            {
                exp = exp.And(a => a.customer.cus_name.Contains(Request.Query["cus_name"]));
            }

            if (!string.IsNullOrWhiteSpace(Request.Query["C_tel"]))
            {
                exp = exp.And(a => a.C_tel.Contains(Request.Query["C_tel"]));
            }

            //exp = exp.And(a => _fsql.Select<hr_employee>().As("b").ToList(b => b.id).Contains(a.create_id));

            //权限
            //var roledata = await _dBAuthService.GetDataAuth(User.FindFirst(ClaimTypes.Sid).Value);
            var roledata = await _dBAuthService.GetDataAuth(User.FindFirst(ClaimTypes.Sid).Value);

            if (roledata.authtype != 4)
            {
                exp = exp.And(a => roledata.empList.Contains(a.customer.emp_id));
            }


            var result = await _service.GridAsync(exp, model.Page, model.Limit, "a.create_time desc");

            return result.ToString();
        }

        public async Task<string> Save(CRM_Contact model)
        {
            var result = 0;

            if (string.IsNullOrWhiteSpace(model.id))
            {
                model.id = UUIDNext.Uuid.NewSequential().ToString();
                model.create_id = User.FindFirst(ClaimTypes.Sid).Value;
                model.create_time = DateTime.Now;

                //权限
                var authbtn = await _dBAuthService.GetAuth(User.FindFirst(ClaimTypes.Sid).Value, "CRM_Contact|add");

                if (authbtn)
                {
                    result = await _service.AddAsync(model);
                }
                else
                {
                    return XHDResult.Error("无权限！").ToString();
                }
            }
            else
            {
                //权限
                var authbtn = await _dBAuthService.GetAuth(User.FindFirst(ClaimTypes.Sid).Value, "CRM_Contact|edit");

                if (authbtn)
                {
                    //日志
                    Expression<Func<CRM_Contact, bool>> exp = a => a.id == model.id;
                    var checknulldata = await _service.GridAsync(exp, 1, 1);

                    if (checknulldata.count == 0)
                    {
                        return XHDResult.Error("找不到数据！").ToString();
                    }

                    result = await _service.UpdateAsync(model);

                    //对比实体差别
                    
                    var content = logext.LogContent(checknulldata.data[0], model);

                    if (content.Length > 0)
                    {
                        //添加修改日志
                        Sys_log logmodels = new Sys_log();

                        logmodels.id = System.Guid.NewGuid().ToString();
                        logmodels.EventType = "[联系人]修改";
                        logmodels.EventID = model.id;
                        logmodels.EventTitle = model.C_name;
                        logmodels.UserID = User.FindFirst(ClaimTypes.Sid).Value;
                        logmodels.UserName = User.FindFirst(ClaimTypes.Name).Value;
                        logmodels.IPStreet = HttpContext.Connection.RemoteIpAddress.ToString();
                        logmodels.EventDate = DateTime.Now;
                        logmodels.Log_Content = content;

                        
                        await _LogService.UpdateLog(logmodels);
                    }

                    
                }
                else
                {
                    return XHDResult.Error("无权限！").ToString();
                }
            }

            if (result == 0)
            {
                return XHDResult.Error("操作失败，系统错误！").ToString();
            }

            return XHDResult.Success().ToString();
        }

        public async Task<string> Delete(string id)
        {
            //判断是否有跟进
            Expression<Func<CRM_follow, bool>> expfollow = a => a.contact_id == id;
            var followlist = await _followservice.GridAsync(expfollow, 1, 1);

            if (followlist.count > 0)
            {
                return XHDResult.Error("此联系人下含有跟进，不能删除！").ToString();
            }

            var result = 0;

            //权限
            var authbtn = await _dBAuthService.GetAuth(User.FindFirst(ClaimTypes.Sid).Value, "CRM_Contact|del");

            if (authbtn)
            {
                //判断是否有数据
                Expression<Func<CRM_Contact, bool>> exp = a => a.id == id;
                var checkdata = await _service.GridAsync(exp, 1, 1);

                if (checkdata.count == 0)
                {
                    return XHDResult.Error("找不到此数据！").ToString();
                }

                result = await _service.DeleteAsync(id);

                //日志

                //先存储删除的实体记录，用日志形式
                logext.getEntityText(checkdata.data[0]);

                //记录日志
                Sys_log logmodels = new Sys_log();

                logmodels.id = System.Guid.NewGuid().ToString();
                logmodels.EventType = "[联系人]删除";
                logmodels.EventID = id;
                logmodels.EventTitle = checkdata.data[0].C_name;
                logmodels.UserID = User.FindFirst(ClaimTypes.Sid).Value;
                logmodels.UserName = User.FindFirst(ClaimTypes.Name).Value;
                logmodels.IPStreet = HttpContext.Connection.RemoteIpAddress.ToString();
                logmodels.EventDate = DateTime.Now;
                //logmodels.Log_Content = content;

                
                await _LogService.DeleteLog(logmodels);
                //await _LogService.DeleteLog(logmodels);
            }
            else
            {
                return XHDResult.Error("无权限！").ToString();
            }

            //var result = await _service.Delete(id);

            if (result == 0)
            {
                return XHDResult.Error("删除失败！").ToString();
            }

            return XHDResult.Success().ToString();
        }


        public async Task<ActionResult> Export()
        {
            //先获取数据
            Expression<Func<CRM_Contact, bool>> exp = a => 1 == 1;

            if (!string.IsNullOrWhiteSpace(Request.Query["C_name"]))
            {
                exp = exp.And(a => a.C_name.Contains(Request.Query["C_name"]));
            }

            if (!string.IsNullOrWhiteSpace(Request.Query["keyword"]))
            {
                exp = exp.And(a => a.C_name.Contains(Request.Query["keyword"]));
            }

            if (!string.IsNullOrWhiteSpace(Request.Query["customer_id"]))
            {
                exp = exp.And(a => a.customer_id == Request.Query["customer_id"]);
            }

            if (!string.IsNullOrWhiteSpace(Request.Query["cus_name"]))
            {
                exp = exp.And(a => a.customer.cus_name.Contains(Request.Query["cus_name"]));
            }

            if (!string.IsNullOrWhiteSpace(Request.Query["C_tel"]))
            {
                exp = exp.And(a => a.C_tel.Contains(Request.Query["C_tel"]));
            }

            //exp = exp.And(a => _fsql.Select<hr_employee>().As("b").ToList(b => b.id).Contains(a.create_id));

            //权限
            //var roledata = await _dBAuthService.GetDataAuth(User.FindFirst(ClaimTypes.Sid).Value);
            var roledata = await _dBAuthService.GetDataAuth(User.FindFirst(ClaimTypes.Sid).Value);

            if (roledata.authtype != 4)
            {
                exp = exp.And(a => roledata.empList.Contains(a.customer.emp_id));
            }


            var result = await _service.GridAsync(exp,  "a.create_time desc");

            string sheet_name = "联系人列表";
            string title_name = "联系人列表";

            var sheet_title = new string[] {
                "姓名","客户名字","性别","部门","职务",
                "生日","电话","微信","邮箱","手机",
                "QQ","地址","爱好","备注"
            };

            JArray arr = new JArray();

            foreach (var contact in result.data)
            {
                var cus_name = "";
                if (contact.customer != null)
                {
                    cus_name = contact.customer.cus_name;
                }

                JObject obj = new JObject();

                obj.Add("C_name", contact.C_name);
                obj.Add("cus_name", cus_name);
                obj.Add("C_sex", contact.C_sex);
                obj.Add("C_department", contact.C_department);
                obj.Add("C_position", contact.C_position);
                obj.Add("C_birthday", contact.C_birthday);
                obj.Add("C_tel", contact.C_tel);
                obj.Add("C_weichat", contact.C_weichat);
                obj.Add("C_email", contact.C_email);
                obj.Add("C_mob", contact.C_mob);
                obj.Add("C_QQ", contact.C_QQ);
                obj.Add("C_add", contact.C_add);
                obj.Add("C_hobby", contact.C_hobby);
                obj.Add("C_remarks", contact.C_remarks);

                arr.Add(obj);
            }

            HSSFWorkbook book = new HSSFWorkbook();

            _npoi.create_sheet(book, sheet_name, title_name, sheet_title, arr);

            MemoryStream memoryStream = new MemoryStream();
            book.Write(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);
            //byte[] buf = memoryStream.GetBuffer();
            //return buf;

            return File(memoryStream, "application/vnd.ms-excel", $"联系人列表{DateTime.Now.ToString("yyyyMMddHH:mm:ss")}.xls");

        }


    }
}
