import os.path as path
from datetime import datetime
from decimal import Decimal

import pytest

from src.batch.common.batch_context import BatchContext
from src.batch.ultmarc.utmp_tables.table_mapper.concrete import com_prefc_med_dis_treat_mapper
from src.db.database import Database
from tests.testing_utility import (assert_table_results,
                                   create_db_data_from_csv,
                                   create_delete_sql_with_parameter,
                                   create_insert_sql_with_parameter,
                                   create_ultmarc_table_mapper_sut,
                                   create_ultmarc_test_data_from_csv)


class TestComPrefcMedDisTreatMapper:
    """レイアウト区分134: COM_都道府県医療機能情報(疾患治療)"""

    db: Database
    batch_context: BatchContext
    test_file_path: str = path.dirname(__file__)

    @pytest.fixture(autouse=True, scope='function')
    def pre_test(self, database: Database):
        """テスト実行前後処理"""
        self.batch_context = BatchContext.get_instance()
        # setup
        self.db = database
        self.db.connect()
        self.db.begin()

        # testing
        yield

        # teardown
        self.db.rollback()
        self.db.disconnect()

    def test_insert_record(self):
        """
        Cases:
            COM_都道府県医療機能情報(疾患治療)テーブルにレコードを登録する
        Arranges:
            - CSVデータを用意し、読み込む
            - 追加対象となるレコードを削除する
        Expects:
            - 登録内容が期待値と一致すること
        """

        # Arrange
        # 処理日設定
        self.batch_context.syor_date = datetime.strftime(datetime.now(), '%Y/%m/%d')
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_prefc_med_dis_treat_insert.csv'))
        # 一旦全データをDBから削除
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_prefc_med_dis_treat', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)

        # Act
        for line_number, line in enumerate(test_dat_file, start=1):
            sut: com_prefc_med_dis_treat_mapper.ComPrefcMedDisTreatMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_prefc_med_dis_treat_mapper.ComPrefcMedDisTreatMapper, f'{line_number}行目:マッパークラスが期通りか'
            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_prefc_med_dis_treat_insert.csv'))
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_data_list]
        primary_keys_treatment_code = [{'treatment_code': columns['treatment_code']} for columns in expect_data_list]
        actual_data_list = []
        sp_field_select_sql = """\
        SELECT * FROM src05.com_prefc_med_dis_treat
        WHERE
            dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND
            treatment_code = :treatment_code
        """
        for param_dcf_dsf_inst_cd, param_treatment_code in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_treatment_code):
            sp_field_data = self.db.execute_select(
                sp_field_select_sql,
                {**param_dcf_dsf_inst_cd, **param_treatment_code})
            assert len(sp_field_data) == 1, '1件取得できていること'
            actual_data_list.append(sp_field_data[0])

        # 期待値検査
        ignore_columns = ['pre_num', 'regist_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_data_list, expect_data_list, ignore_col_name=ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_data_list, expect_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in ignore_columns:
                    if actual_col_name == 'pre_num':
                        if expect_row[expect_col_name] is not None and len(expect_row[expect_col_name]) > 0:
                            assert actual_row[actual_col_name] == Decimal(expect_row[expect_col_name]), f'{line_number}行目:{actual_col_name}が、期待値と一致すること'
                    else:
                        assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'

    def test_update_record(self):
        """
        Cases:
            COM_都道府県医療機能情報(疾患治療)テーブルのレコードを更新する
        Arranges:
            - CSVデータを用意し、読み込む
            - 更新対象となるレコードを登録する
        Expects:
            - 登録内容が期待値と一致すること
        """

        # Arrange
        # 処理日設定
        self.batch_context.syor_date = datetime.strftime(datetime.now(), '%Y/%m/%d')
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_prefc_med_dis_treat_update.csv'))
        # 一旦全データをDBから削除
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_prefc_med_dis_treat', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # テストデータをDBに登録
        # DBデータを読み込む
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_prefc_med_dis_treat_before_update.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_prefc_med_dis_treat',
                test_data.keys(),
                test_data.values()
            )
            self.db.execute(insert_sql, insert_parameter)

        # Act
        for line_number, line in enumerate(test_dat_file, start=1):
            sut: com_prefc_med_dis_treat_mapper.ComPrefcMedDisTreatMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_prefc_med_dis_treat_mapper.ComPrefcMedDisTreatMapper, f'{line_number}行目:マッパークラスが期通りか'
            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_prefc_med_dis_treat_update.csv'))
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_data_list]
        primary_keys_treatment_code = [{'treatment_code': columns['treatment_code']} for columns in expect_data_list]
        actual_data_list = []
        sp_field_select_sql = """\
        SELECT * FROM src05.com_prefc_med_dis_treat
        WHERE
            dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND
            treatment_code = :treatment_code
        """
        for param_dcf_dsf_inst_cd, param_treatment_code in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_treatment_code):
            sp_field_data = self.db.execute_select(
                sp_field_select_sql,
                {**param_dcf_dsf_inst_cd, **param_treatment_code})
            assert len(sp_field_data) == 1, '1件取得できていること'
            actual_data_list.append(sp_field_data[0])

        # 期待値検査
        ignore_columns = ['pre_num', 'regist_ymd', 'update_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_data_list, expect_data_list, ignore_col_name=ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_data_list, expect_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in ignore_columns:
                    if expect_row[expect_col_name] is None:
                        assert actual_row[actual_col_name] is None, f'{line_number}行目:{actual_col_name}が、登録されていないこと'
                    else:
                        if actual_col_name == 'pre_num':
                            if expect_row[expect_col_name] is not None and len(expect_row[expect_col_name]) > 0:
                                assert actual_row[actual_col_name] == Decimal(expect_row[expect_col_name]), f'{line_number}行目:{actual_col_name}が、期待値と一致すること'
                        else:
                            assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'

    def test_physical_delete(self):
        """
        Cases:
            COM_都道府県医療機能情報(疾患治療)テーブルのレコードを1件物理削除する
        Arranges:
            - CSVデータを用意し、読み込む
            - 削除対象となるレコードを登録する
        Expects:
            - 登録内容が期待値と一致すること
        """

        # Arrange
        # 処理日設定
        self.batch_context.syor_date = datetime.strftime(datetime.now(), '%Y/%m/%d')
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_prefc_med_dis_treat_delete.csv'))
        # 一旦全データをDBから削除
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_prefc_med_dis_treat', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # テストデータをDBに登録
        # DBデータを読み込む
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_prefc_med_dis_treat_before_delete.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_prefc_med_dis_treat',
                test_data.keys(),
                test_data.values()
            )
            self.db.execute(insert_sql, insert_parameter)

        # Act
        for line_number, line in enumerate(test_dat_file, start=1):
            sut: com_prefc_med_dis_treat_mapper.ComPrefcMedDisTreatMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_prefc_med_dis_treat_mapper.ComPrefcMedDisTreatMapper, f'{line_number}行目:マッパークラスが期通りか'
            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_prefc_med_dis_treat_delete.csv'))
        actual_record_count = self.db.execute_select('SELECT COUNT(*) AS count_num FROM src05.com_prefc_med_dis_treat')[0]['count_num']
        assert actual_record_count == len(expect_data_list), 'DBのレコード件数が期待値の件数と一致すること'
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_data_list]
        primary_keys_treatment_code = [{'treatment_code': columns['treatment_code']} for columns in expect_data_list]
        actual_data_list = []
        sp_field_select_sql = """\
        SELECT * FROM src05.com_prefc_med_dis_treat
        WHERE
            dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND
            treatment_code = :treatment_code
        """
        for param_dcf_dsf_inst_cd, param_treatment_code in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_treatment_code):
            sp_field_data = self.db.execute_select(
                sp_field_select_sql,
                {**param_dcf_dsf_inst_cd, **param_treatment_code})
            assert len(sp_field_data) == 1, '1件取得できていること'
            actual_data_list.append(sp_field_data[0])

        # 期待値検査
        ignore_columns = ['pre_num', 'regist_ymd', 'update_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_data_list, expect_data_list, ignore_col_name=ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_data_list, expect_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in ignore_columns:
                    if expect_row[expect_col_name] is None:
                        assert actual_row[actual_col_name] is None, f'{line_number}行目:{actual_col_name}が、登録されていないこと'
                    else:
                        if actual_col_name == 'pre_num':
                            if expect_row[expect_col_name] is not None and len(expect_row[expect_col_name]) > 0:
                                assert actual_row[actual_col_name] == Decimal(expect_row[expect_col_name]), f'{line_number}行目:{actual_col_name}が、期待値と一致すること'
                        else:
                            assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'
