using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class AccSqlRepository: ApiConfigRepositoryBase<SigerTrDict>, IAccSqlRepository
    {
        private readonly ApiConfigDbContext _context;
        public AccSqlRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }
   
        private IEnumerable<dynamic> FillOptionFromSql(string sql)
        {
            using (var cmd = _context.Database.GetDbConnection().CreateCommand())
            {
                cmd.CommandText = sql;
                if (cmd.Connection.State != System.Data.ConnectionState.Open)
                    cmd.Connection.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var row = new System.Dynamic.ExpandoObject() as IDictionary<string, object>;

                        for (var field = 0; field < reader.FieldCount; field++)
                        {
                            row.Add(reader.GetName(field), reader[field]);
                        }
                        yield return row;
                    }
                }
            }
        }

        public IEnumerable<dynamic> FillOption(RquestFillOption fillOption, int projectId)
        {
            try
            {
                var table = fillOption.tb;
                var icol = fillOption.icol;
                var vcol = fillOption.vcol;
                var condition = fillOption.condition;
                var strSql = string.Empty;
                if (icol != vcol)
                {
                    strSql = string.Format("select {0},{1} from {2} where Projectid={3} and status={4}", icol, vcol,
                        table, projectId, RowState.Valid.GetHashCode());
                }
                else
                {
                    strSql = string.Format("select {0} from {1} where Projectid={2} and status={3}", icol, table,
                        projectId, RowState.Valid.GetHashCode());
                }

                if (!string.IsNullOrEmpty(condition))
                {
                    strSql = strSql + string.Format(" and {0}", condition);
                }

                return FillOptionFromSql(strSql);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public void InitQmsData(int projectId)
        {
            try
            {
                var time = DateTime.Now.ToString(ParameterConstant.DateTimeFormat);
                var sql = $@"INSERT INTO `siger_qms_type_count_setting` (type_code,type_name,check_count,status,projectid,create_time) VALUES (1, '首检', 5, 1, {projectId}, '{time}');
INSERT INTO `siger_qms_type_count_setting` (type_code,type_name,check_count,status,projectid,create_time) VALUES (2, '抽检', 1, 1, {projectId}, '{time}');
INSERT INTO `siger_qms_type_count_setting` (type_code,type_name,check_count,status,projectid,create_time) VALUES (3, '末检', 1, 1, {projectId}, '{time}');
INSERT INTO `siger_qms_type_count_setting` (type_code,type_name,check_count,status,projectid,create_time) VALUES (4, '二级件校对', 1, 1, {projectId}, '{time}');
INSERT INTO `siger_qms_type_count_setting` (type_code,type_name,check_count,status,projectid,create_time) VALUES (5, '首件', 1, 1, {projectId}, '{time}');
INSERT INTO `siger_qms_type_count_setting` (type_code,type_name,check_count,status,projectid,create_time) VALUES (6, 'SPC检查', 5, 1, {projectId}, '{time}');
INSERT INTO `siger_qms_type_count_setting` (type_code,type_name,check_count,status,projectid,create_time) VALUES (7, '其他', 1, 1, {projectId}, '{time}');
INSERT INTO `siger_qms_abnormal_rule` (`key`,rule,k_value,continuous,discrete,trigger_andon,status,projectid) VALUES (1, 'K点落在控制限之外', 1, 1, 1, 0, 1, {projectId});
INSERT INTO `siger_qms_abnormal_rule` (`key`,rule,k_value,continuous,discrete,trigger_andon,status,projectid) VALUES (2, '连续K点在中心线同侧', 7, 1, 1, 0, 1, {projectId});
INSERT INTO `siger_qms_abnormal_rule` (`key`,rule,k_value,continuous,discrete,trigger_andon,status,projectid) VALUES (3, '连续K点上升或下降', 7, 1, 1, 0, 1, {projectId});
INSERT INTO `siger_qms_abnormal_rule` (`key`,rule,k_value,continuous,discrete,trigger_andon,status,projectid) VALUES (4, '连续3点中有K点，距离中心线（同侧）大于二倍标准差', 2, 1, 1, 0, 1, {projectId});
INSERT INTO `siger_qms_abnormal_rule` (`key`,rule,k_value,continuous,discrete,trigger_andon,status,projectid) VALUES (5, '连续K点落在距离中心线一倍标准差线区间之内', 15, 1, 1, 0, 1, {projectId});
INSERT INTO `siger_qms_abnormal_rule` (`key`,rule,k_value,continuous,discrete,trigger_andon,status,projectid) VALUES (6, '连续K点落在距离中心线一倍标准差线区间之外', 8, 1, 1, 0, 1, {projectId});
INSERT INTO `siger_qms_abnormal_rule` (`key`,rule,k_value,continuous,discrete,trigger_andon,status,projectid) VALUES (7, '连续5点中有K点，距离中心线（同侧）大于一倍标准差', 4, 1, 1, 0, 1, {projectId});
INSERT INTO `siger_qms_abnormal_rule` (`key`,rule,k_value,continuous,discrete,trigger_andon,status,projectid) VALUES (8, '连续K点上下交错', 14, 1, 1, 0, 1, {projectId});";

                using (var cmd = _context.Database.GetDbConnection().CreateCommand())
                {
                    cmd.CommandText = sql;
                    if (cmd.Connection.State != System.Data.ConnectionState.Open)
                        cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception e)
            {
                Logger.WriteLineError("InitQmsData Error:" + e.Message);
            }
        }

        public void InitTpmData(int projectId)
        {
            try
            {
                var sql = $@"INSERT INTO `siger_project_repair_cooperate_reason`(`reason`, `status`, `projectid`, `sort`, `language`) VALUES ('寻找技术支持', 1, {projectId}, 1, 0);
INSERT INTO `siger_project_repair_cooperate_reason`(`reason`, `status`, `projectid`, `sort`, `language`) VALUES ('维修内容不属于工作范畴', 1, {projectId}, 2, 0);
INSERT INTO `siger_project_repair_cooperate_reason`(`reason`, `status`, `projectid`, `sort`, `language`) VALUES ('换班', 1, {projectId}, 3, 0);
INSERT INTO `siger_project_repair_cooperate_reason`(`reason`, `status`, `projectid`, `sort`, `language`) VALUES ('其他', 1, {projectId}, 4, 0);
INSERT INTO `siger_project_repair_cooperate_reason`(`reason`, `status`, `projectid`, `sort`, `language`) VALUES ('Ask for tech assistant', 1, {projectId}, 1, 1);
INSERT INTO `siger_project_repair_cooperate_reason`(`reason`, `status`, `projectid`, `sort`, `language`) VALUES ('Out of working scope', 1, {projectId}, 2, 1);
INSERT INTO `siger_project_repair_cooperate_reason`(`reason`, `status`, `projectid`, `sort`, `language`) VALUES ('Shift changing', 1, {projectId}, 3, 1);
INSERT INTO `siger_project_repair_cooperate_reason`(`reason`, `status`, `projectid`, `sort`, `language`) VALUES ('Other', 1, {projectId}, 4, 1);";

                using (var cmd = _context.Database.GetDbConnection().CreateCommand())
                {
                    cmd.CommandText = sql;
                    if (cmd.Connection.State != System.Data.ConnectionState.Open)
                        cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception e)
            {
                Logger.WriteLineError("InitTpmData Error:" + e.Message);
            }
        }

    }
}
