using Foresight.Data;
using Foresight.Fleet.Services.Asset;
using Foresight.ServiceModel;
using IronIntel.Contractor.Users;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IronIntel.Contractor.Maintenance
{
    public class AlertManager : BusinessBase
    {
        public AlertManager(string dbstr) : base(dbstr)
        {
        }

        /// <summary>
        /// 获取AlertType
        /// </summary>
        /// <returns></returns>
        public StringKeyValue[] GetAlertTypes()
        {
            const string SQL = "select distinct ltrim(rtrim(ALERTTYPE)) as ALERTTYPE from ALERTS with(nolock) where ISNULL(ALERTTYPE,'')<>''";
            DataTable tb = GetDataTableBySQL(SQL);
            if (tb.Rows.Count == 0)
            {
                return new StringKeyValue[0];
            }
            List<StringKeyValue> list = new List<StringKeyValue>();
            foreach (DataRow dr in tb.Rows)
            {
                string type = FIDbAccess.GetFieldString(dr["ALERTTYPE"], string.Empty);
                StringKeyValue kv = new StringKeyValue();
                kv.Key = type;
                kv.Value = type;
                list.Add(kv);
            }
            return list.OrderBy(t => t.Key).ToArray();
        }
        /// <summary>
        /// 根据WorkorderId获取Alert列表
        /// </summary>
        /// <returns></returns>
        public AlertInfo[] GetAlertsByWorkOrder(long workorderid, Foresight.Fleet.Services.User.UserInfo user)
        {
            const string SQL = @"select a.ALERTID,ALERTTYPE,a.ALERTTIME_UTC,COMPLETED,a.MACHINEID,a.VIN,a.MACHINENAME,a.ENGINGHOURS,a.ALERTDESC,pit.SERVICEDESCRIPTION,a.PMTYPE from ALERTS a
		  left join PM_ALERTS pa on a.ALERTID=pa.ALERTID left join PM_INTERAVLS pit on pa.PMINTERVALID=pit.PMINTERVALID
		  where a.ALERTID in (select ALERTID from WORKORDER_ALERTS where WORKORDERID={0}) order by ALERTID";
            DataTable tb = GetDataTableBySQL(SQL, workorderid);
            if (tb.Rows.Count == 0)
            {
                return new AlertInfo[0];
            }
            List<AlertInfo> ls = new List<AlertInfo>(tb.Rows.Count);
            foreach (DataRow dr in tb.Rows)
            {
                AlertInfo ai = ConvertToAlertInfo(dr, user);
                ai.ServiceDescription = FIDbAccess.GetFieldString(dr["SERVICEDESCRIPTION"], string.Empty);
                ls.Add(ai);
            }
            return ls.ToArray();
        }

        public void AcknowledgeAlert(string useriid, long[] alertids, string acknowledgmentcomment)
        {
            const string SQL = "update ALERTS set ACKNOWLEDGED=1,ACKNOWLEDGEDBY={1},ACKNOWLEDGMENTCOMMENT={2},ACKNOWLEDGEDDATE_UTC=GETUTCDATE() where ALERTID={0}";
            const string SQL_S = "select ALERTID from ALERTS where ISNULL(ACKNOWLEDGED,0)<>1 and ISNULL(COMPLETED,0)<>1 and MACHINEID=(select MACHINEID from ALERTS where ALERTID={0}) and ALERTDESC=(select ALERTDESC from ALERTS where ALERTID={0}) ";

            if (alertids != null && alertids.Length > 0)
            {
                FISqlConnection db = new FISqlConnection(DbConnectionString);
                foreach (long aid in alertids)
                {
                    DataTable dt = db.GetDataTableBySQL(SQL_S, aid);
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            long alertid = FIDbAccess.GetFieldInt64(dr["ALERTID"], 0);
                            ExecSQL(SQL, alertid, useriid, acknowledgmentcomment);
                        }
                    }
                }
            }
        }

        public void AssignedAlertsToWorkOrder(long workorderid, long[] alertid)
        {
            const string SQL_Del = "delete from WORKORDER_ALERTS where WORKORDERID={0}";
            const string SQL_ALERT = "insert into WORKORDER_ALERTS(WORKORDERID,ALERTID,ADDEDON_UTC) values({0},{1},GETUTCDATE())";
            ExecSQL(SQL_Del, workorderid);
            if ((alertid != null) && (alertid.Length > 0))
            {
                foreach (long aid in alertid)
                {
                    ExecSQL(SQL_ALERT, workorderid, aid);
                }
            }
        }

        private static AlertInfo ConvertToAlertInfo(DataRow dr, Foresight.Fleet.Services.User.UserInfo user)
        {
            AlertInfo ai = new AlertInfo();
            ai.AlertID = FIDbAccess.GetFieldInt(dr["ALERTID"], 0);
            ai.AlertType = FIDbAccess.GetFieldString(dr["ALERTTYPE"], string.Empty);
            ai.AlertTime_UTC = FIDbAccess.GetFieldDateTime(dr["ALERTTIME_UTC"], DateTime.MinValue);
            if (ai.AlertTime_UTC != DateTime.MinValue)
                ai.AlertLocalTime = SystemParams.ConvertToUserTimeFromUtc(user, ai.AlertTime_UTC);
            ai.Completed = FIDbAccess.GetFieldInt(dr["COMPLETED"], 0) == 1;
            ai.MachineID = FIDbAccess.GetFieldInt(dr["MACHINEID"], 0);
            ai.VIN = FIDbAccess.GetFieldString(dr["VIN"], string.Empty);
            ai.MachineName = FIDbAccess.GetFieldString(dr["MACHINENAME"], string.Empty);
            ai.EngineHours = FIDbAccess.GetFieldDouble(dr["ENGINGHOURS"], 0);
            ai.Description = FIDbAccess.GetFieldString(dr["ALERTDESC"], string.Empty);
            ai.Description = ai.FormatDescription(ai.Description);
            ai.PMType = FIDbAccess.GetFieldString(dr["PMTYPE"], string.Empty);
            return ai;
        }

    }
}
