using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.Middlelayer.Dapper
{
    public class LabelCounterRepository : DapperRepositoryBase
    {
        private readonly int _companyId;
        private readonly int _projectId;
        public LabelCounterRepository(int companyId, int projectId) : base(companyId, projectId)
        {
            _companyId = companyId;
            _projectId = projectId;
        }

        public int GetLabelCount(int machineId, int spindleId, string programNum, int toolNum, string startTime, string endTime)
        {
            var search = $@" AND companyID = {_companyId} AND projectID = {_projectId} AND machineID = {machineId} AND spindleID = {spindleId} 
                    AND programNum = '{programNum}' AND toolNum = {toolNum} AND endtime >= {startTime} AND endtime <= {endTime}";

            using (var conn = GetDbConnection())
            {
                var sql = $@"SELECT COUNT(DISTINCT(toolNum)) AS cccount FROM KM_LabelCounter
                            WHERE 1=1 {search} GROUP BY cycleCounter ";
                var result = conn.Query<int>(sql);
                if (result == null || !result.Any())
                {
                    return 0;
                }
                return result.Sum();
            }
        }

        public int GetProcessCount(int machineId, int toolNum, string startTime, string endTime)
        {
            var query = $@" WHERE toolNum={toolNum} AND machineID={machineId} AND projectID={_projectId} AND startTime>'{startTime}' AND endTime<'{endTime}'";
            using (var conn = GetDbConnection())
            {
                var sql = $@"SELECT cycleCounter FROM `KM_LabelCounter` {query}  ORDER BY endTime DESC";
                var result = conn.Query<int>(sql);
                if (result == null || !result.Any())
                {
                    return 0;
                }
                return result.First() - result.Last();
            }
        }

        public int GetProcessCount(string installTime, int mid, int toolnum)
        {
            var unixStart = UnixTimeHelper.GetUnixByShortDate(installTime).ToStr() + "000";
            var unixEnd = UnixTimeHelper.GetUnixByShortDate(DateTime.Now.ToStr()) + "000";
            return GetProcessCount(mid, toolnum, unixStart, unixEnd);
        }

        public override void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
