using DocumentFormat.OpenXml.Spreadsheet;
using Flurl.Http.Content;
using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetTaste;
using NPOI.SS.Formula.Functions;
using OpenAuth.App.FormModule;
using OpenAuth.App.FormModule.Request;
using OpenAuth.App.FormScheme;
using OpenAuth.App.FormScheme.Request;
using OpenAuth.App.Request;
using OpenAuth.Repository.Domain;
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace OpenAuth.WebApi.Controllers
{
    /// <summary>
    /// 表单发布
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FormModuleController : ControllerBase
    {
        private readonly FormModuleApp _app;
        private readonly FormSchemeApp _schemeapp;
        public FormModuleController(FormModuleApp app, FormSchemeApp schemeapp)
        {
            _app = app;
            _schemeapp = schemeapp;
        }

        #region 查询数据
        /// <summary>
        /// 获取分页列表
        /// 2024 03.02
        /// </summary>
        /// <param name="keyword">筛选条件</param>
        /// <param name="pmoduleid">模板父级id</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Response<PageInfo<List<FormModuleEntity>>>> GetPageList(string keyword,string pmoduleid,int page=1,int limit=15)
        {
            return await _app.GetModulePageList(keyword, pmoduleid, page, limit);
        }

        /// <summary>
        /// 获取列表(单纯获取表单发布信息，不分页)
        /// 2024.03.06
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<FormModuleEntity>>> GetList()
        {
            return await _app.GetList();
        }

        /// <summary>
        /// 根据主键获取实体数据(编辑时使用)
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<FormModuleEntity>> GetForm(string id)
        {
            return await _app.GetForm(id);
        }

        /// <summary>
        /// 根据菜单主键获取实体数据
        /// </summary>
        /// <param name="id">菜单主键</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<FormModuleEntity>> GetFormByModuleId(string id)
        {
            return await _app.GetFormByModuleId(id);
        }

        /// <summary>
        /// 根据编号获取实体数据
        /// </summary>
        /// <param name="code">表单发布模板编号</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<FormModuleEntity>> GetFormByCode(string code)
        {
            return await _app.GetFormByCode(code);
        }

        /// <summary>
        /// 获取设计数据
        /// </summary>
        /// <param name="code">编码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<FormModuleSchemeReq>> GetEntityByCode(string code)
        {
            return await _app.GetEntityByCode(code);
        }
        #endregion

        #region 增删改
        /// <summary>
        /// 新增实体数据
        /// 2024 03.05
        /// </summary>
        /// <param name="entity">模板数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> AddForm(FormModuleReq entity)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.SaveEntity(string.Empty, entity.FormModuleEntity, entity.SysModule, entity.SysModuleElement, entity.SysModuleColumn, entity.SysModuleForm);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 更新实体数据
        /// 2024 03.05
        /// <param name="id">主键（表单发布模板id）</param>
        /// <param name="entity">模板数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateForm(string id, FormModuleReq entity)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.SaveEntity(id, entity.FormModuleEntity, entity.SysModule, entity.SysModuleElement, entity.SysModuleColumn, entity.SysModuleForm);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 更新状态
        /// 2024 03.05
        /// </summary>
        /// <param name="id">表单发布模板主键</param>
        /// <param name="state">状态（发布、未发布）</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateModuleState(string id, int state)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.UpdateState(id,state);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 根据菜单主键id删除实体数据
        /// </summary>
        /// <param name="moduleId">菜单id（Sysmodule的主键）</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteFormByModuleId(string moduleId)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.DeleteEntityByModuleId(moduleId);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }


        /// <summary>
        /// 删除实体数据（表单发布模板id）
        /// </summary>
        /// <param name="keyValue">表单发布主键（FormModule的主键）</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteForm(string keyValue)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.DeleteForm(keyValue);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 判断数据表字段重复
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="tableName">表名</param>
        /// <param name="keyName">主键名</param>
        /// <param name="filedsJson">数据字段</param>
        /// <param name="isNotSass">是否关闭开启</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<bool>> ExistFiled(string keyValue, string tableName, string keyName, string filedsJson)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.ExistFiled(keyValue, tableName, keyName, filedsJson);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }
        #endregion

        #region  获取数据库表
        /// <summary>
        /// 获取数据库表
        /// </summary>
        /// <param name="code">数据库编码</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public Response<List<DbTableInfo>> GetTableList(string code,string key)
        {
            return  _app.GetTableList(code,key);
        }
        #endregion

        #region 获取导出数据
        /// <summary>
        /// 获取导出数据
        /// </summary>
        /// <param name="mid">功能id</param>
        /// <param name="id">id数据</param>
        /// <param name="query">查询参数</param>
        /// <param name="code">编号</param>
        /// <returns></returns>
        [HttpPost]
        public  async Task<IActionResult>  Export(string mid, string id, string code, FormQueryReq query)
        {
            var res = new Response();
            //获取列表数据
            var result = await  _schemeapp.GetFormDataNewPage(mid, query.Ldparam, id, null, query.QueryJson);
            //获取模板数据
            var module = await _app.GetEntityByCode(code);
            //数据处理
            var data = result.Result.Items;
            var header = module.Result.Entity.Scheme;
            var obj = JsonConvert.DeserializeObject<JObject>(header);
            List<ModuleColumn> cl = new List<ModuleColumn>();
            foreach (var item in obj["table"]["columns"])
            {
                ModuleColumn c = new ModuleColumn();
                c.value = item["label"].ToString();
                c.key = item["key"].ToString();
                cl.Add(c);
            }

            var excelRes = _app.ListToExcel(data, cl);
            if (excelRes.Code == 200)
            {
                return File(excelRes.Result.ToArray(),
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "数据导出" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
            }
            else
            {
                res.Code = excelRes.Code;
                res.Message = "导出失败";
            }
            return Ok(res);
        }
        #endregion

    }

}
