using NLog;
using Org.BouncyCastle.Bcpg;
using System;
using WebAPIBase.API.Requests;
using WebAPIBase.Service.Interface;
using Newtonsoft.Json;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using Sugar.Enties;
using System.Text;
using WebAPIBase.Utils;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Collections.Specialized;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.AspNetCore.Authorization;
using System.Drawing;
using Microsoft.AspNetCore.Http;
using System.Linq.Expressions;


namespace WebAPIBase.API.Controllers
{
    [Produces("application/json;charset=UTF-8")]
    [Route("api/Common")]
    public class CommonController : Controller
    {
        private static Logger Logger = NLog.LogManager.GetCurrentClassLogger();


        public CommonController(IMemoryCache memoryCache, IHttpClientFactory httpclientfactory)
        {

            IConfigurationBuilder builder = new ConfigurationBuilder()
              .SetBasePath(Directory.GetCurrentDirectory())
              .AddJsonFile("appsettings.json");

            IConfigurationRoot Configuration = builder.Build();

        }

        /// <summary>
        /// 获取部门用户
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("GetUnitUser")]
        public ActionResult GetUnitUser(string projectid)
        {
            var unitManager = new UnitManager();
            var tree = unitManager.GetUnitUser(projectid);
            var list = new List<TreeDTO>();
            list.Add(tree);
            Logger.Info($"【getunituser】{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("GetUnit")]
        public ActionResult GetUnit(string projectid)
        {
            var unitManager = new UnitManager();
            var tree = unitManager.GetUnit(projectid);
            var list = new List<TreeDTO>();
            list.Add(tree);
            Logger.Info($"【GetUnit】{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }
        /// <summary>
        /// 根据用户代码获取用户所属部门
        /// </summary>
        /// <param name="usercode"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("GetUserDepartment")]
        public ActionResult GetUserDepartment(string usercode)
        {
            var unitManager = new UnitManager();
            var department = unitManager.GetUserDepartment(usercode);

            Logger.Info($"【GetUserDepartment】{department}");
            return Json(department);
        }

        /// <summary>
        /// 获取项目列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("GetProjectList")]
        public ActionResult GetProjectList()
        {
            var unitManager = new UnitManager();
            var list = unitManager.GetProjectList();

            Logger.Info($"【GetProjectList】{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// /图片上传
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadImage")]
        public ActionResult UploadImage([FromForm] IFormCollection formCollection)
        {
            var list = new List<AttachMent>();
            //logger.Info(Request.Body);
            var createPerson = Request.Form["createPerson"].ToString();
            var masterCode = Request.Form["masterCode"].ToString();
            var attachMentType = Request.Form["attachMentType"].ToString();
            //logger.Info(Request.Form["masterCode"]);
            FormFileCollection filelist = (FormFileCollection)formCollection.Files;
            //logger.Info(JsonConvert.SerializeObject(filelist));
            var manager = new AttachMentManager();
            foreach (IFormFile file in filelist)
            {
                var attachMent = new AttachMent();
                attachMent.FileName = file.FileName;
                attachMent.Content_Type = file.ContentType;
                attachMent.Length = (int?)file.Length;
                var stream = file.OpenReadStream();
                attachMent.Content = Utils.UploadFileHelper.StreamToBytes(stream);
                attachMent.AttachMentType = attachMentType;
                attachMent.CreatePerson = createPerson;
                attachMent.MasterCode = masterCode;
                manager.AddOrUpdate(attachMent);
            }


            return Json("success");
        }

        /// <summary>
        /// 附件显示
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("ShowImg")]
        public FileResult ShowImg(string code)
        {
            var bll = new AttachMentManager();
            var entity = bll.GetAttachMent(code);

            return File(entity.Content, entity.Content_Type);
        }

        /// <summary>
        /// 获取父子权限的数据列表
        /// </summary>
        /// <param name="classCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetMaterialTree")]
        public ActionResult GetMaterialTree(string classCode)
        {
            var manager = new UnitManager();
            var list = manager.GetMaterial(classCode);
            return Json(list);
        }
        /// <summary>
        /// 根据功能模块代码返回有权限的岗位代码和用户代码列表
        /// </summary>
        /// <param name="functionStructureCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserFunctions")]
        public ActionResult GetUserFunctions(string functionStructureCode)
        {
            var manager = new RoleManager();
            var list = manager.GetUserFunctions(functionStructureCode);
            return Json(list);
        }
        /// <summary>
        /// 根据功能模块代码和用户代码返回用户权限实例
        /// </summary>
        /// <param name="functionStructureCode"></param>
        /// <param name="usercode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserFunction")]
        public ActionResult GetUserFunction(string functionStructureCode, string usercode)
        {
            var manager = new RoleManager();
            var entity = manager.GetUserFunction(functionStructureCode, usercode);
            return Json(entity);
        }

        /// <summary>
        /// 根据项目代码获取材料合同
        /// </summary>
        /// <param name="projectcode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetContracts")]
        public ActionResult GetContracts(string projectcode, string searchValue)
        {
            var manager = new UnitManager();
            var list = manager.GetContracts(projectcode, searchValue);
            return Json(list);
        }
        /// <summary>
        /// 根据合同单号获取合同实体
        /// </summary>
        /// <param name="contractCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetContract")]
        public ActionResult GetContract(string contractCode)
        {
            var manager = new UnitManager();
            var model = manager.GetContract(contractCode);
            return Json(model);
        }
        /// <summary>
        /// 根据项目代码获取工程合同
        /// </summary>
        /// <param name="projectcode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetEngineeringContracts")]
        public ActionResult GetEngineeringContracts(string projectcode, string searchValue)
        {
            var manager = new UnitManager();
            Expression<Func<Contract, bool>> lambda = m => m.ProjectCode == projectcode && m.contracttype == "工程合同" && (m.Status == 0 || m.Status == 2);
            if (!string.IsNullOrEmpty(searchValue))
            {
                lambda = lambda.And(m => m.ContractID.Contains(searchValue) || m.ContractName.Contains(searchValue));

            }
            var list = manager.GetContracts(lambda);
            return Json(list);
        }
        /// <summary>
        /// 获取供应商名称和类型
        /// </summary>
        /// <param name="supplierCode"></param>
        /// <param name="SupplierTypeCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetSupplierNameAndType")]
        public ActionResult GetSupplierNameAndType(string supplierCode, string SupplierTypeCode)
        {
            var manager = new MaterialInManager();
            var str = manager.GetSupplierNameAndType(supplierCode, SupplierTypeCode);
            return Json(str);
        }

        /// <summary>
        ///  获取质量安全检查项
        /// </summary>
        /// <param name="type">0:质量检查 1：安全检查</param>
        /// <param name="searchvalue"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetQualityAndSafeItems")]
        public ActionResult GetQualityAndSafeItems(int type = -1, string searchvalue = "")
        {
            Logger.Info($"【GetQualityAndSafeItems】type:{type},searchvalue:{searchvalue}");
            //10034:质量检查项目 10035：安全检查项目
            var manager = new DictionaryNameManager();
            List<DictionaryItem> list;
            Expression<Func<DictionaryItem, bool>> lambda = m => true;
            if (type == 0)
            {
                lambda = lambda.And(m => m.dnCode == "10034");
            }
            else if (type == 1)
            {
                lambda = lambda.And(m => m.dnCode == "10035");
            }
            else
            {
                lambda = lambda.And(m => m.dnCode == "10034" || m.dnCode == "10035");
            }
            if (!searchvalue.IsNullOrEmpty())
            {
                lambda = lambda.And(m => m.diName.Contains(searchvalue));
            }


            list = manager.GetDictionaryItems(lambda);

            return Json(list);
        }
    }
}
