using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bailun.DC.Services;
using Bailun.DC.Models;
using Bailun.DC.Common;
using Bailun.ServiceFabric.Authorize;
using Bailun.ServiceFabric.Core.Extension.HttpContext;
using Bailun.ServiceFabric.Core.Extension;

namespace Bailun.DC.Web.Areas.TaskCenter.Controllers
{
    [Area("TaskCenter")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        #region 任务模版

        public IActionResult Templates()
        {
            var datatypes = new Services.TaskCenterServices().ListDataType();

            ViewBag.datatypes = datatypes;
            return View();
        }

        /// <summary>
        /// 获取任务模版列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="status"></param>
        /// <param name="datatype"></param>
        /// <returns></returns>
        public string TemplatesJson(BtTableParameter parameter,int? status,int? datatype)
        {
            var total = 0;
            var _service = new Services.TaskCenterServices();
            var datatypes = _service.ListDataType();
            var obj = _service.List(parameter, status, datatype, ref total);

            var list = obj.Select(a => new {
                download_type = datatypes.Where(d=>d.data_type==a.download_type).FirstOrDefault()?.data_type_name??"",
                lastupdatetime = a.lastupdatetime.ToString("yyyy-MM-dd HH:mm:ss"),
                a.start_frequency_day,
                a.start_frequency_hour,
                a.start_frequency_month,
                status = a.status==1?"启用":"禁用",
                a.note,
                a.id,
            });


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

        }

        public ActionResult AddTaskTemplate(int? id)
        {
            var obj = new Services.TaskCenterServices().GetTaskTemplate(id ?? 0);

            if(obj==null)
            {
                obj = new taskcenter_template();
            }

            ViewBag.m = obj;

            var datatypes = new Services.TaskCenterServices().ListDataType();

            ViewBag.datatypes = datatypes;

            return View();
        }

        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult SaveTaskTemplate(taskcenter_template m)
        {
            var user = HttpContextHelper.Current?.User;

            m.lastupdateuserid = user != null ? user.GetUid() : 0;
            m.lastupdateusername = user != null ? user.GetUserName() : "";
            m.cron = "";

            var result = new Services.TaskCenterServices().SaveTaskTemplate(m);

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

        #endregion

        #region 任务列表

        public IActionResult ListTask()
        {
            var datatypes = new Services.TaskCenterServices().ListDataType();

            ViewBag.datatypes = datatypes;

            return View();
        }

        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="datatype"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public string ListTaskJson(BtTableParameter parameter, int? datatype, int? status)
        {
            var total = 0;
            var _service = new Services.TaskCenterServices();
            var datatypes = _service.ListDataType();
            var obj = _service.ListTask(parameter, status, datatype, ref total);

            var list = obj.Select(a => new { 
                a.account,
                createtime = a.createtime.ToString("yyyy-MM-dd HH:mm:ss"),
                datatype = datatypes.Where(d => d.data_type == a.datatype).FirstOrDefault()?.data_type_name ?? "",
                lastupdatetime = a.lastupdatetime.ToString("yyyy-MM-dd HH:mm:ss"),
                a.platform_type,
                status = Enum.GetName(typeof(Enum_TaskStatus),a.status),
                a.task_template_id,
                a.urlpath,
                a.website,
                a.id,
                a.fileurl
            });

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

        }

        #endregion

        #region 任务帐号管理

        public ActionResult ListAccount(int datatype)
        {

            ViewBag.datatype = datatype;  //数据类型
            return View();
        }

        /// <summary>
        /// 获取任务帐号列表
        /// </summary>
        /// <param name="templateid">模版id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListAccountJson(int datatype)
        {
            try
            {
                var _service = new Services.TaskCenterServices();
                var datatypes = _service.ListDataType();
                var obj = _service.ListAccount(datatype);

                var list = obj.Select(a => new { 
                    a.platform,
                    a.platform_index,
                    a.account,
                    a.apiurl,
                    data_type = datatypes.Where(d => d.data_type == a.data_type).FirstOrDefault()?.data_type_name ?? "",
                    a.frequency,
                    a.id,
                    note = a.note??"",
                    a.pwd,
                    status = a.status==1?"启用":"禁用",
                    a.token,
                    a.website,
                });


                return Json(new
                {
                    success = true,
                    msg = "",
                    data = list
                });
            }
            catch (Exception ex)
            {
                return Json(new { 
                    success = false,
                    msg = ex.Message
                });
            }
        }

        public ActionResult AccountDetail(int? id,int datatype)
        {
            var m = new Services.TaskCenterServices().GetAccountInfo(id ?? 0);

            if(m==null)
            {
                m = new taskcenter_accounts();

                m.data_type = datatype;
            }

            ViewBag.m = m;

            return View();
        }

        /// <summary>
        /// 保存帐号信息
        /// </summary>
        /// <param name="datatype">数据类型</param>
        /// <param name="platform">平台名称</param>
        /// <param name="platformindex">平台值</param>
        /// <param name="website">站点</param>
        /// <param name="account">帐号</param>
        /// <param name="pwd">密码</param>
        /// <param name="token">token</param>
        /// <param name="apiurl">访问地址</param>
        /// <param name="frequency">启动频率</param>
        /// <param name="status">帐号状态，1：启用，0：停用</param>
        /// <param name="note">备注</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult SaveAccount(int id,int datatype, string platform, int platformindex, string website, string account, string pwd, string token, string apiurl, string frequency, int status, string note)
        { 
            if(string.IsNullOrEmpty(platform))
            {
                return Json(new { 
                    success = false,
                    msg = "请填写平台名称",
                });
            }

            if(platformindex<=0)
            {
                return Json(new
                {
                    success = false,
                    msg = "平台索引值必须大于0",
                });
            }

            if (string.IsNullOrEmpty(account))
            {
                return Json(new
                {
                    success = false,
                    msg = "请填写帐号。",
                });
            }

            if(string.IsNullOrEmpty(pwd)&&string.IsNullOrEmpty(token))
            {
                return Json(new
                {
                    success = false,
                    msg = "密码和token必须填写一个，请确认是否已填写。",
                });
            }

            if (string.IsNullOrEmpty(apiurl))
            {
                return Json(new
                {
                    success = false,
                    msg = "请填写访问地址",
                });
            }

            var m = new taskcenter_accounts { 
                account = account,
                apiurl = apiurl,
                data_type = datatype,
                frequency = frequency,
                note = note,

                platform = platform,
                platform_index = platformindex,
                pwd = pwd,
                status = status,
                website = website,
                token = token,
                id = id,
            };

            var user = HttpContextHelper.Current?.User;

            var result = new Services.TaskCenterServices().SaveAccount(m, (user != null ? user.GetUid() : 0), (user != null ? user.GetUserName() : ""));

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

        #endregion

    }
}
