using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using OpenAuth.App;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.FormModule;
using OpenAuth.App.FormScheme.Request;
using OpenAuth.App.ServiceApp.DataMaintenance;
using OpenAuth.App.ServiceApp.DataMaintenance.Request;
using OpenAuth.Repository.Domain.DataMaintenance;
using OpenAuth.WebApi.Model.CustomAttribute;
using System.Data;
using OpenAuth.App.CodeTable;
using System.Threading.Tasks;

namespace OpenAuth.WebApi.Controllers.ServiceControllers.DataMaintenance
{
    /// <summary>
    /// 应用管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ApplicationDataController : ControllerBase
    {
        readonly ApplicationManagementApp _app;

        public ApplicationDataController(ApplicationManagementApp app)
        {
            _app = app;
        }

        /// <summary>
        /// 查询应用列表
        /// </summary>
        /// <param name="name">目录或服务名称1</param>
        /// <param name="isCatalogue">是否只查询目录</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<ApplicationData>>> GetApplicationList(string name, int isCatalogue)
        {
            return await _app.GetApplicationList(name, isCatalogue);
        }
        /// <summary>
        /// 添加应用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> AddApplication(ApplicationData app)
        {
            return await _app.Add(app);
        }
        /// <summary>
        /// 编辑应用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateApplication(ApplicationData app)
        {
            return await _app.Update(app);
        }
        /// <summary>
        /// 删除应用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteApplication(long id)
        {
            return await _app.Delete(id);
        }
        /// <summary>
        /// 获取数据库表名及注释
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<DataTable>> GetGeomTableList(PageReq req)
        {
            return await _app.GetGeomTableList(req);
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="tableDataReq"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<PageInfo<List<object>>>> GetDataList(TableDataReq tableDataReq)
        {
            var result = new Response<PageInfo<List<object>>>();
            try
            {
                result = await _app.GetDataList(tableDataReq);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 获取数据库表及视图字段
        /// </summary>
        /// <param name="dbCode"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        [HttpGet]
        public Response<List<dynamic>> GetTableColumnList(string tableName)
        {
            var result = new Response<List<dynamic>>();
            try
            {
                result.Result = _app.GetTableAndViewColumnList(tableName);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        #region 获取导出数据
        /// <summary>
        /// 获取导出数据
        /// </summary>
        /// <param name="mid">功能id</param>
        /// <param name="id">id数据</param>
        /// <param name="query">查询参数</param>
        /// <param name="code">编号</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ExportExcel(TableDataReq tableDataReq)
        {
            //查询表头
            var tableHeader = _app.GetTableAndViewColumnList(tableDataReq.TableName);
            List<ModuleColumn> cl = new List<ModuleColumn>();
            foreach (var item in tableHeader)
            {
                ModuleColumn c = new ModuleColumn();
                c.key = item.column_name.ToString();
                c.value = item.description.ToString();
                cl.Add(c);
            }
            var excelRes = await _app.ListToExcel(tableDataReq, cl);
            if (excelRes.Code == 200)
            {
                return File(excelRes.Result.ToArray(),
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    $"{tableDataReq.TableCNName}.xls");
            }
            else
            {

            }
            return Ok();
        }
        /// <summary>
        /// 导出shp文件
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ExportShapefile(TableDataReq tableDataReq)
        {
            try
            {
                var tableHeader = _app.GetTableAndViewColumnList(tableDataReq.TableName);
                List<ModuleColumn> cl = new List<ModuleColumn>();
                foreach (var item in tableHeader)
                {
                    ModuleColumn c = new ModuleColumn();
                    c.key = item.column_name.ToString();
                    c.value = item.description.ToString();
                    cl.Add(c);
                }
                string shpFilePath = Path.Combine(Path.GetTempPath(), $"{tableDataReq.TableCNName}.shp");
                string shpFilePathzip = Path.Combine(Path.GetTempPath(), $"{tableDataReq.TableCNName}.zip");
                await _app.ExportShapefile(tableDataReq, shpFilePath, shpFilePathzip, cl);
                byte[] fileBytes = System.IO.File.ReadAllBytes(shpFilePathzip);
                return File(fileBytes, "application/octet-stream", $"{tableDataReq.TableCNName}.zip");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Internal server error: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateBatch(UpdateBatchDataReq req)
        {
            var result = new Response<bool>();
            try
            {
                return await _app.UpdateBatch(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        #endregion
    }
}
