using System.Data;
using Infrastructure;
using Infrastructure.Helpers.Excel;
using Infrastructure.Helpers.Excel.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using OpenAuth.App.FormScheme;
using OpenAuth.App.FormScheme.Request;
using OpenAuth.App.FormScheme.Response;
using OpenAuth.App.Request;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.WebApi.Controllers
{
    /// <summary>
    /// 日 期： 2024-03-02
    /// 描 述： 表单设计
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FormSchemeController : ControllerBase
    {
        private readonly FormSchemeApp _app;
        public FormSchemeController(FormSchemeApp app)
        {
            _app = app;
        }
        /// <summary>
        /// 查询表单分页信息 custmerform/scheme/page
        /// </summary>
        /// <param name="keyWord">关键字</param>
        /// <param name="category">分类</param>
        /// <param name="isEnabled">状态1启用0未启用2草稿3全部</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<FormSchemeInfo>>>> LoadFormPage(string keyWord, string category, int page, int limit, int isEnabled = 3)
        {
            return await _app.LoadFormPage(keyWord, category, page, limit, isEnabled);
        }
        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="schemeId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<FormScheme>> LoadFormScheme(string schemeId)
        {
            try
            {

                return new Response<FormScheme>()
                {
                    Result = await _app.GetScheme(schemeId),
                    Code = 200,
                    Message = "获取数据成功"
                };
            }
            catch (Exception e)
            {

                return new Response<FormScheme>()
                {
                    Result = null,
                    Code = 500,
                    Message = "获取数据失败"
                };
            }

        }
        /// <summary>
        /// 新增自定义表单custmerform/scheme
        /// </summary>
        /// <param name="entity">模板数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<string>> AddForm(FormSchemeReq entity)
        {
            var result = new Response<string>();
            try
            {
                result = await _app.SaveEntity(string.Empty, entity.Info, entity.Scheme);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 获取自定义表单设计数据custmerform/scheme/{id}
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns> 
        [HttpGet]
        public async Task<Response<FormSchemeReq>> GetForm(string id)
        {
            try
            {
                FormSchemeReq data = new FormSchemeReq();
                data.Info = await _app.GetSchemeInfo(id);
                if (data.Info != null)
                {
                    data.Scheme = await _app.GetScheme(data.Info.SchemeId);
                }
                return new Response<FormSchemeReq>
                {
                    Result = data
                };
            }
            catch (Exception ex)
            {
                return new Response<FormSchemeReq>
                {
                    Code = 500,
                    Message = "获取数据失败",
                };
            }

        }
        /// <summary>
        /// 获取自定义表单基础信息custmerform/scheme/info/{id}
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<FormSchemeInfo>> GetSchemeInfoEntity(string id)
        {
            try
            {

                var data = await _app.GetSchemeInfo(id);
                return new Response<FormSchemeInfo>
                {
                    Result = data
                };
            }
            catch (Exception ex)
            {
                return new Response<FormSchemeInfo>
                {
                    Code = 500,
                    Message = "获取数据失败",
                };
            }

        }
        /// <summary>
        /// 更新自定义表单custmerform/scheme/{id}
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="entity">模板数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateForm(string id, FormSchemeReq entity)
        {
            var result = new Response<bool>();
            try
            {
                await _app.SaveSchEntity(id, entity.Info, entity.Scheme);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 更新表单模板版本 custmerform/scheme/history/{id}
        /// </summary>
        /// <param name="id">信息主键</param>
        /// <param name="schemeId">模板主键</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateScheme(string id, string schemeId)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.UpdateScheme(id, schemeId);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 启用/停用表单custmerform/scheme/state/{id}
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="state">状态1启用0禁用</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateState(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.Message;
            }
            return result;
        }
        /// <summary>
        /// 删除自定义表单custmerform/scheme/{id}
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteForm(string id)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.Delete(id);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 获取数据源列名custmerform/sql/colnames/{dbCode}
        /// </summary>
        /// <param name="code">数据源编码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<List<string>>> GetDataColName(string dbCode, string sql)
        {
            var result = new Response<List<string>>();
            try
            {
                result.Result = await _app.GetDataColName(dbCode, sql);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 获取自定义表单预览
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<FormScheme>> GetPreviewForm(string keyValue)
        {
            try
            {
                var scheme = await _app.GetScheme(keyValue);
                return new Response<FormScheme>
                {
                    Result = scheme
                };
            }
            catch (Exception ex)
            {
                return new Response<FormScheme>
                {
                    Code = 500,
                    Message = "获取数据失败"
                };
            }
        }
        /// <summary>
        /// 获取自定义表单模板历史数据custmerform/scheme/history/page/{id}
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="schemeInfoId">自定义表单信息主键</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<FormScheme>>>> GetSchemePageList([FromQuery] PageReq pagination, string schemeInfoId)
        {
            try
            {
                return await _app.GetSchemePageList(pagination, schemeInfoId);
            }
            catch (Exception ex)
            {
                return new Response<PageInfo<List<FormScheme>>>
                {
                    Code = 500,
                    Message = "获取数据失败"
                };
            }
        }

        /// <summary>
        /// 获取表单分页数据custmerform/data/page/{mid}/{id}
        /// </summary>
        /// <param name="paginationInputDto">分页参数</param>
        /// <param name="mid">功能id</param>
        /// <param name="id">id数据</param>
        /// <param name="queryJson">查询参数</param>
        /// <param name="ldparam">桌面跳转参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<PageInfo<DataTable>>> GetFormDataPage(string mid, string id, FormQueryReq query)
        {
            try
            {
                //return await _app.GetFormDataPage(mid, query.Ldparam, id, query.PaginationInputDto, query.QueryJson);
                return await _app.GetFormDataNewPage(mid, query.Ldparam, id, query.PaginationInputDto, query.QueryJson);

            }
            catch (Exception ex)
            {
                return new Response<PageInfo<DataTable>>
                {
                    Code = 500,
                    Message = ex.Message.ToString()
                };
            }
        }
        /// <summary>
        /// 获取表单列表数据custmerform/datas/{mid}/{id}
        /// </summary>
        /// <param name="mid">功能id</param>
        /// <param name="id">id数据</param>
        /// <param name="queryJson">查询参数</param>
        /// <param name="sidx">排序字段</param>
        /// <param name="ldparam">桌面跳转参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<DataTable>> GetFormDataList(string mid, string id, FormQueryReq query)
        {
            try
            {
                return new Response<DataTable>
                {
                    Result = await _app.GetFormDataList(mid, id, query.QueryJson, query.Sidx)
                };

            }
            catch (Exception ex)
            {
                return new Response<DataTable>
                {
                    Code = 500,
                    Message = "获取数据失败"
                };
            }
        }
        /// <summary>
        /// 获取表单数据 "custmerform/data/{id}"
        /// </summary>
        /// <param name="id">模板id</param>
        /// <param name="key">条件字段</param>
        /// <param name="keyValue">条件值</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<Dictionary<string, DataTable>>> GetFormData(string id, string key, string keyValue)
        {
            var response = new Response<Dictionary<string, DataTable>>();
            try
            {
                response.Result = await _app.GetFormDataNew(id, key, keyValue);
                return response;
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message.ToString();
                return response;
            }
        }
        /// <summary>
        /// 保存自定义表单数据 custmerform/data
        /// </summary>
        /// <param name="dto">提交参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<JObject>> SaveForm(FormDataReq dto)
        {
            var result = new Response<JObject>();
            try
            {
                result = await _app.SaveFormDataNew(dto);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message.ToString();
            }
            return result;
        }

        /// <summary>
        /// 删除表单数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="key"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<string>> DeleteFormData(string id, string key, string keyValue)
        {
            var result = new Response<string>();
            try
            {
                result = await _app.DeleteFormData(id, key, keyValue);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = "提交失败";
            }
            return result;
        }

        #region 导入
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pkey"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<dynamic>> ImportExcel(string id, string pkey, string path)
        {
            var result = new Response<dynamic>();
            try
            {
                // 获取excel文件数据（暂时只支持单sheet导入，后续升级）
                DataTable dt = ExcelHelper.ExcelImport(path);
                var res2 = await _app.ImportTable(id, dt, pkey);
                var data = new
                {
                    Success = res2.snum,
                    Fail = res2.fnum,
                    data = res2.elist
                };
                result.Result = data;
                return result;
            }
            catch (Exception ex) 
            {
                result.Result = false;
                result.Message = ex.Message.ToString();
                return result;
            }
        }
        /// <summary>
        /// 下载模板
        /// </summary>
        /// <param name="keyValue">文件id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FileStreamResult> DownTemplateFile(string id)
        {
            //解析表单
            List<ExcelImportFileds> list = new List<ExcelImportFileds>();
            Repository.Domain.FormScheme schemeEntity = await _app.GetScheme(id);
            FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();
            FormDbTableInfo mainTable = formSchemeModel.Db.Find(t => t.Type == "main");
            foreach (var tab in formSchemeModel.FormInfo.TabList)
            {
                foreach (var component in tab.Schemas)
                {
                    if (component == null || component.ComponentProps == null || string.IsNullOrEmpty(component.ComponentProps.DataTable))
                    {
                        continue;
                    }
                    ExcelImportFileds excelImportFileds = new ExcelImportFileds();
                    excelImportFileds.ColName = component.Label;
                    excelImportFileds.Name = component.ComponentProps.FieldName;
                    excelImportFileds.CsType = component.CsType;
                    excelImportFileds.RelationType = 0;
                    list.Add(excelImportFileds);
                }
            }
            //设置导出格式
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "数据模板.xls";
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnEntity = new List<ColumnModel>();
            //表头
            DataTable dt = new DataTable();
            foreach (var col in list)
            {
                if (col.RelationType != 1 && col.RelationType != 4 && col.RelationType != 5 && col.RelationType != 6 && col.RelationType != 7)
                {
                    excelconfig.ColumnEntity.Add(new ColumnModel()
                    {
                        Column = col.Name,
                        ExcelColumn = col.ColName,
                        Alignment = "center",
                    });
                    dt.Columns.Add(col.Name, typeof(string));
                }
            }

            return File(ExcelHelper.ExportMemoryStream(dt, excelconfig), "application/ms-excel", excelconfig.FileName);
        }
        #endregion
    }
}
