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 Microsoft.AspNetCore.Http;
using System.Linq;
using System.Linq.Expressions;

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


        public RequisitionController(IMemoryCache memoryCache, IHttpClientFactory httpclientfactory)
        {

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

            IConfigurationRoot Configuration = builder.Build();


        }
        /// <summary>
        /// 向签证申请表插入数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("InsertRequisition")]
        public ActionResult InsertRequisition([FromBody] RequisitionPostForm postForm)
        {

            logger.Info($"【InsertRequisition】postForm:{JsonConvert.SerializeObject(postForm)}");

            var requisitions = postForm.Requisition;
            var list = postForm.List;

            requisitions.state = 0;
            var RequisitionType = 0;
            var RequisitionTypeName = ConvertRule.ToEnumString(RequisitionType, typeof(RequisitionType));
            var manager = new ConfigItemValueManager();
            string codeRule = manager.GetConfigItemValue(string.Format("项目管理(项目级)-基本参数-{0}申请单-编号规则", RequisitionTypeName), requisitions.ProjectCode);
            string codeStart = manager.GetConfigItemValue(string.Format("项目管理(项目级)-基本参数-{0}申请单-编号起始编码", RequisitionTypeName), requisitions.ProjectCode);
            string code = new UnitManager().GetNewSysCode(string.Format("{0}申请单编号", RequisitionTypeName), codeRule, ConvertRule.ToInt(codeStart), 0, requisitions.ProjectCode);
            requisitions.RequisitionNumber = code;
            var service = new RequisitionManager();
            var requisitionCode = service.InsertRequisition(requisitions, list);
            if (requisitionCode == null)
            {
                requisitionCode = "";
            }

            logger.Info($"【InsertRequisition】requisitionCode:{requisitionCode}");
            return Json(requisitionCode);
        }

        /// <summary>
        /// 更新签证申请单数据
        /// </summary>
        /// <param name="postForm"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateRequisition")]
        public ActionResult UpdateRequisition([FromBody] RequisitionPostForm postForm)
        {

            logger.Info($"【UpdateRequisition】postForm:{JsonConvert.SerializeObject(postForm)}");

            var requisitions = postForm.Requisition;
            var list = postForm.List;


            var service = new RequisitionManager();
            var requisitionCode = service.UpdateRequisition(requisitions, list);
            if (requisitionCode == null)
            {
                requisitionCode = "";
            }

            logger.Info($"【UpdateRequisition】requisitionCode:{requisitionCode}");
            return Json(requisitionCode);
        }

        /// <summary>
        /// 根据项目代码获取关联合同列表
        /// </summary>
        /// <param name="projectCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetRelationContract")]
        public ActionResult GetRelationContract(string projectCode, string search)
        {
            logger.Info($"【GetRelationContract】projectCode:{projectCode},search:{search}");
            var manager = new RequisitionManager();
            var list = manager.GetRelationContract(projectCode, search);

            return Json(list);
        }
        /// <summary>
        /// 获取签证类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetQianzhengDropDown")]
        public ActionResult GetQianzhengDropDown()
        {
            var manager = new DictionaryNameManager();
            var code = manager.GetDictionaryName("现场签证类型").dnCode;
            var list = manager.GetDictionaryItems(m => m.dnCode == code);
            var list1 = new List<string>();
            foreach (var item in list)
            {
                list1.Add(item.diName);
            }
            return Json(list1);
        }

        /// <summary>
        /// 获取签证申请单列表
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetRequisitionList")]
        public ActionResult GetRequisitionList(string where)
        {
            var manager = new RequisitionManager();
            var list = manager.GetRequisitionList(where);
            return Json(list);
        }



        /// <summary>
        /// 获取签证申请单详情
        /// </summary>
        /// <param name="reqisitionCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetRequistionDetail")]
        public ActionResult GetRequistionDetail(string reqisitionCode)
        {
            var bll = new RequisitionManager();
            var entity = bll.GetRequisition(reqisitionCode);
            var list = bll.GetRelationContracts(reqisitionCode);
            var attachments = bll.GetAttachMents(reqisitionCode, "RequisitionAttach");
            var data = new
            {
                entity = entity,
                list = list,
                attachments = attachments
            };
            return Json(data);
        }

        /// <summary>
        /// 根据项目代码，用户编号获取签证申请单列表
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("SelectRequisitionList")]
        public ActionResult SelectRequisitionList(string projectCode, string userCode, string searchValue)
        {
            var manager = new RequisitionManager();
            List<Requisition> list;
            if (searchValue.IsNullOrEmpty())
            {
                list = manager.GetList(m => m.ProjectCode == projectCode && m.Person == userCode && m.state == 2).OrderByDescending(m => m.RequisitionDate).ToList();
            }
            else
            {
                list = manager.GetList(m => m.ProjectCode == projectCode && m.Person == userCode && m.state == 2 && m.RequisitionName.Contains(searchValue)).OrderByDescending(m => m.RequisitionDate).ToList();
            }

            return Json(list);
        }
        /// <summary>
        /// 根据项目代码和签证申请单号获取相应的申请单关联合同
        /// </summary>
        /// <param name="projectCode"></param>
        /// <param name="requisitionCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetRelationRequistionContract")]
        public ActionResult GetRelationRequistionContract(string projectCode, string requisitionCode)
        {
            var manager = new RequisitionManager();
            var list = manager.GetRelationRequistionContract(projectCode, requisitionCode);
            return Json(list);
        }
    }
}
