//-----------------------------------------------------------------------
// <copyright file=" sys_allot.cs">
// * FileName: sys_allot.cs
// * history : Created by T4 2019-03-06 16:43:31 
// </copyright>
//-----------------------------------------------------------------------
using Dapper;
using Microsoft.EntityFrameworkCore;
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace Performance.Repository
{
    /// <summary>
    /// sys_allot Repository
    /// </summary>
    public partial class PerforPerallotRepository : PerforRepository<per_allot>
    {
        public bool UpdateAllotStates(int allotId, int states, string remark, int generate)
        {
            var allot = GetEntity(t => t.ID == allotId);
            allot.States = states;
            allot.Remark = remark;
            allot.Generate = generate;
            return Update(allot);
        }

        /// <summary>
        /// 只支持EXCEL抽取报表数据
        /// </summary>
        /// <param name="import"></param>
        /// <param name="pairs"></param>
        /// <returns></returns>
        public bool ImportData(rep_importconfig import, Dictionary<string, object> pairs)
        {
            using (var connection = context.Database.GetDbConnection())
            {
                var data = connection.Query(import.ImportScript, new DynamicParameters(pairs), commandTimeout: 60 * 60);
                ImportData(import, pairs, data);
            }
            return true;
        }

        /// <summary>
        /// 指定数据源插入MYSQL
        /// </summary>
        /// <param name="import"></param>
        /// <param name="pairs"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool ImportData(rep_importconfig import, Dictionary<string, object> pairs, IEnumerable<dynamic> data)
        {
            if (data != null && data.Any())
            {
                using (var connection = context.Database.GetDbConnection())
                {
                    if (connection.State != ConnectionState.Open) connection.Open();

                    using (var transaction = connection.BeginTransaction())
                    {
                        try
                        {
                            connection.Execute(import.DeleteScript, new DynamicParameters(pairs), commandTimeout: 60 * 60, transaction: transaction);

                            List<string> columns = new List<string>();
                            foreach (KeyValuePair<string, object> col in data.First())
                            {
                                columns.Add(col.Key);
                            }
                            var c1 = string.Join(",", columns.Select(w => $"`{w}`"));
                            var c2 = string.Join(",", columns.Select(w => $"@{w}"));
                            string insert = $"insert into {import.TableName}({c1}) values({c2})";
                            connection.Execute(insert, data, commandTimeout: 60 * 60, transaction: transaction);

                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw ex;
                        }
                    }
                }
            }
            return true;
        }

        public bool UpdateData(rep_importconfig import, Dictionary<string, object> pairs)
        {
            using (var connection = context.Database.GetDbConnection())
            {
                var flag = connection.Execute(import.ImportScript, new DynamicParameters(pairs), commandTimeout: 60 * 60);
                return flag > 0;
            }
        }

        /// <summary>
        /// 清除历史抽取数据
        /// </summary>
        /// <param name="allotid"></param>
        public void ClearResultData(int allotid)
        {
            using (var connection = context.Database.GetDbConnection())
            {
                if (connection.State != ConnectionState.Open) connection.Open();
                try
                {
                    string update = "update ex_result set isdelete = 1 where allotid =  @allotid ";
                    connection.Execute(update, new { allotid }, commandTimeout: 60 * 60);

                    string clear = "delete from ex_result where allotid = @allotid and isdelete = 1 and createtime < (select min(createtime) from (select distinct createtime from ex_result where allotid = @allotid and isdelete = 1 order by createtime desc limit 4) t);";
                    connection.Execute(clear, new { allotid }, commandTimeout: 60 * 60);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 保存工作量数据
        /// </summary>
        /// <param name="allot"></param>
        /// <param name="parameters"></param>
        public void ImportWorkloadData(per_allot allot, object parameters)
        {
            using (var connection = context.Database.GetDbConnection())
            {
                if (connection.State != ConnectionState.Open) connection.Open();

                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        string clear = "delete from report_original_workload where allotid = @allotid and hospitalid = @hospitalid;";
                        connection.Execute(clear, new { allotid = allot.ID, hospitalid = allot.HospitalId }, commandTimeout: 60 * 60, transaction: transaction);

                        string insert = "insert into report_original_workload(allotid,year,month,hospitalid,sourcetype,accountingunit,department,doctorname,personnelnumber,category,fee) values(@allotid,@year,@month,@hospitalid,@sourcetype,@accountingunit,@department,@doctorname,@personnelnumber,@category,@fee);";
                        connection.Execute(insert, parameters, commandTimeout: 60 * 60, transaction: transaction);

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 查询工作量数据
        /// </summary>
        /// <param name="allotid"></param>
        public IEnumerable<report_original_workload> QueryWorkloadData(int allotid, string accountingunit, string[] unittype)
        {
            using (var connection = context.Database.GetDbConnection())
            {
                if (connection.State != ConnectionState.Open) connection.Open();
                try
                {
                    string clear = "select t1.* from report_original_workload t1 join per_employee t2 on t1.doctorname = t2.doctorname and t1.personnelnumber = t2.personnelnumber where t1.allotid = @allotid and t1.accountingunit = @accountingunit and t1.accountingunit = @accountingunit and t2.unittype in @unittype order by fee desc,convert(t1.doctorname using gbk);";
                    return connection.Query<report_original_workload>(clear, new { allotid, accountingunit, unittype }, commandTimeout: 60 * 60);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}
