using FrontendWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace FrontendWebApi.ApiControllers
{
    //[Route("api/[controller]")]
    //[ApiController]
    public class UtilityController : MyBaseApiController<DeviceManageController>
    {
        private readonly IBackendRepository backendRepository;
        private readonly IFrontendRepository frontendRepository;

        public UtilityController(IBackendRepository backendRepository, IFrontendRepository frontendRepository)
        {
            this.backendRepository = backendRepository;
            this.frontendRepository = frontendRepository;
        }

        public async Task<ActionResult<ApiResult<bool>>> isShowMaiSys()
        {
            ApiResult<bool> apiResult = new ApiResult<bool>(jwt_str);
            try
            {
                var isShow = await backendRepository.GetOneAsync<string>("select system_value from variable where system_type = 'show_main_system' and deleted = 0");
                var isBool = bool.Parse(isShow);
                apiResult.Data = isBool;
                apiResult.Code = "0000";
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
                return Ok(apiResult);
            }
            return Ok(apiResult);
        }

        /// <summary>
        /// 即時趨勢條件過濾條件面板
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/GetMainSub")]
        public async Task<ActionResult<ApiResult<History_MainSubBuildFloor>>> GetMainSub([FromBody] HistoryFind hf)
        {
            ApiResult<History_MainSubBuildFloor> apiResult = new ApiResult<History_MainSubBuildFloor>(jwt_str);
            if (!jwtlife)
            {
                apiResult.Code = "5000";
                return BadRequest(apiResult);
            }
            else if (string.IsNullOrEmpty(hf.building_tag))
            {
                apiResult.Code = "0002";
                apiResult.Msg = "必須選擇東別";
                return apiResult;
            }

            try
            {
                var dbsub = await frontendRepository.GetAllAsync<HistoryDBMainSub>(
                    @$"select distinct v1.system_key main_name, v1.system_value main_system_tag, v2.system_key sub_name, v2.system_value sub_system_tag, v1.system_priority, v2.system_priority,
                                       d.device_number, d.full_name as device_full_name, d.device_serial_tag
                        from role_auth a
                        join auth_page b on a.AuthCode = b.AuthCode
                        join userinfo c on c.role_guid = a.role_guid
                        join variable v2 on b.ShowView = v2.id and v2.system_type = @sub_system_type
                        join variable v1 on v1.id = v2.system_parent_id and v1.system_type = @main_system_type
                        join device d on v1.system_value = d.device_system_tag and v2.system_value = d.device_name_tag and d.deleted = 0
                        where c.account = @account
                        order by v1.system_priority, v2.system_priority", new { @account = myUser.account, @sub_system_type = sub_system_type, @main_system_type = main_system_type });
                var dbbuilding = await frontendRepository.GetAllAsync<History_Build>(
                    @$"select distinct d.building_guid,d.full_name,d.priority from role_auth a
                        join auth_page b on a.AuthCode = b.AuthCode
                        join userinfo c on c.role_guid = a.role_guid
                        join building d on d.building_tag = b.building_tag
                        where c.account = @account and d.building_tag = @building_tag
                        order by d.priority 
                        ", new { @account = myUser.account, @building_tag = hf.building_tag });
                var mains = dbsub.GroupBy(a => a.main_system_tag).ToList();
                apiResult.Data = new History_MainSubBuildFloor();
                apiResult.Data.history_Main_Systems = new List<History_Main_system>();
                foreach (var main in mains)
                {
                    History_Main_system history_Main_System = new History_Main_system();
                    history_Main_System.main_system_tag = main.Select(a => a.main_system_tag).FirstOrDefault();
                    history_Main_System.full_name = main.Select(a => a.main_name).FirstOrDefault();

                    var subs = dbsub.Where(x => x.main_system_tag == main.Select(m => m.main_system_tag).FirstOrDefault()).GroupBy(x => x.sub_system_tag).ToList();
                    history_Main_System.History_Sub_systems = subs.Count > 0 ? new List<History_Sub_system>() : null;
                    foreach (var sub in subs)
                    {
                        History_Sub_system history_Sub_System = new History_Sub_system();
                        history_Sub_System.full_name = sub.Select(x => x.sub_name).FirstOrDefault();
                        history_Sub_System.sub_system_tag = sub.Select(x => x.sub_system_tag).FirstOrDefault();
                        history_Main_System.History_Sub_systems.Add(history_Sub_System);
                    }
                    apiResult.Data.history_Main_Systems.Add(history_Main_System);
                }
                apiResult.Data.history_Builds = dbbuilding;
                apiResult.Code = "0000";
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
                return Ok(apiResult);
            }
            return Ok(apiResult);
        }

        [HttpPost]
        [Route("api/GetUsrFroList")]
        public async Task<ApiResult<List<AuthPage>>> UsrAuthPageList()
        {
            ApiResult<List<AuthPage>> apiResult = new ApiResult<List<AuthPage>>();
            List<AuthPage> authPage = new List<AuthPage>();

            try
            {
                var sqlString = $@"select ap.* from auth_page ap
                                    join role_auth ra on ap.AuthCode = ra.AuthCode
                                    join userinfo ui on ra.role_guid = ui.role_guid
                                    where ap.AuthCode like 'PF%' and ui.userinfo_guid = @userinfo_guid
                                    order by ap.AuthCode";
                authPage = await backendRepository.GetAllAsync<AuthPage>(sqlString, new { @userinfo_guid = myUser.userinfo_guid });
                apiResult.Code = "0000";
                apiResult.Data = authPage;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            return apiResult;
        }

        
    }
}