using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bailun.DC.Models;
using Newtonsoft.Json;
using Bailun.DC.Models.DataWareHouse;
using Bailun.ServiceFabric.Authorize;
using Bailun.ServiceFabric.Core.Extension.HttpContext;
using Bailun.ServiceFabric.Core.Extension;
using System.Data;

namespace Bailun.DC.Web.Areas.DataWareHouse.Controllers
{
    [Area("DataWareHouse")]
    public class ConfigController : Controller
    {
        public IActionResult TbConfigList()
        {
            return View();
        }

        /// <summary>
        /// 库表结构的分页信息
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public string TbConfigListJson(BtTableParameter parameter,string code)
        {
            var total = 0;

            var obj = new Services.DataWareHouse.TbConfigServices().ListTbConfig(parameter, code, ref total);

            var list = obj.Select(a => new { 
                a.code,
                a.name,
                a.fieldtype,
                a.length,
                a.decimals,
                a.note,
                type = a.type==1?"表":"字段"
            });

            return JsonConvert.SerializeObject(new { 
                rows = list,
                total = total
            });
        }

        public IActionResult AddTbConfig(int? id)
        {
            var m = new sys_table_info();
            if(id.HasValue&& id.Value>0)
            {
                m = new Services.DataWareHouse.TbConfigServices().GetTbConfig(id.Value);
                if(m==null)
                {
                    m = new sys_table_info();
                }
            }

            ViewBag.m = m;

            return View();
        }

        /// <summary>
        /// 保存表结构配置信息
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="code">编码</param>
        /// <param name="name">中文名称</param>
        /// <param name="fieldtype">字段类型</param>
        /// <param name="length">长度</param>
        /// <param name="decimals">小数位</param>
        /// <param name="note">备注说明</param>
        /// <param name="type">1：表格名称，2：字段名称</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult SaveTbConfig(int id,string code,string name,string fieldtype,int length,int decimals,string note,int type)
        {
            var user = HttpContextHelper.Current?.User;

            var result = new Services.DataWareHouse.TbConfigServices().SaveTbConfig(new sys_table_info { 
                id = id,
                code = code,
                name = name,
                
                decimals = decimals,
                length = length,
                fieldtype = fieldtype,
                note = note,
                type = type,
            
            }, (user != null ? user.GetUserName() : ""));

            return Json(new { 
                success = string.IsNullOrEmpty(result),
                msg = result
            });
        }

        /// <summary>
        /// 批量导入表结构配置数据
        /// </summary>
        /// <returns></returns>
        public JsonResult UploadTbConfig()
        {
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            var user = HttpContextHelper.Current?.User;

            var file = Request.Form.Files[0];
            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);
            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();

                var list = new List<sys_table_info>();
                var _service = new Services.DataWareHouse.TbConfigServices();

                for (var i = 0; i < tb.Value.Rows.Count; i++)
                {
                    var row = tb.Value.Rows[i];

                    var code = row["编码"].ToString();
                    var name = row["中文名称"].ToString();
                    var fieldtype = row["字段类型"].ToString();
                    var length = row["字段长度"].ToString();
                    var decimals = row["小数位"].ToString();
                    var note = row["备注"].ToString();
                    var type = row["编码类型"].ToString();

                    if (string.IsNullOrEmpty(code))
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(type))
                    {
                        return Json(new { 
                            success = false,
                            msg = $"第{(i+1)}行的编码类型为空，请填写表或者字段"
                        });
                    }

                    if (type.Trim() == "字段" && (fieldtype.Trim() == "" || length.Trim() == ""))
                    {
                        return Json(new
                        {
                            success = false,
                            msg = $"第{(i + 1)}行的字段类型或长度为空，请填写。"
                        });
                    }

                    var n_length = 0;
                    var n_decimal = 0;

                    int.TryParse(length, out n_length);
                    int.TryParse(decimals, out n_decimal);

                    if (type.Trim() == "字段" && n_length == 0)
                    {
                        return Json(new
                        {
                            success = false,
                            msg = $"第{(i + 1)}行的字段长度不能为0。"
                        });
                    }

                    var m = new sys_table_info {
                        code = code.Trim(),
                        name = name.Trim(),
                        fieldtype = fieldtype.Trim(),
                        length = n_length,
                        decimals = n_decimal,
                        note = note.Trim(),
                        type = type.Trim()=="表"?1:2,
                        id = 0,
                    };

                    list.Add(m);
                }

                //保存数据
                foreach (var item in list)
                {
                    var result = _service.SaveTbConfig(item, (user != null ? user.GetUserName() : ""));

                    if (!string.IsNullOrEmpty(result))
                    {
                        return Json(new { 
                            success= false,
                            msg = "上传失败，请重试！失败原因："+result,
                        });
                    }
                }

                return Json(new { 
                    success = true,
                    msg = "",
                });
            }

            return Json(new { 
                success = false,
                msg = "没有找到表格的内容数据",
            });
        }
    }
}
