import os.path as path

import pytest

from src.batch.common.batch_context import BatchContext
from src.batch.ultmarc.utmp_tables.table_mapper.concrete import \
    com_dr_wrkplace_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 TestComDrWrkplaceMapper:
    """レイアウト区分502: COM_DCF医師勤務先"""

    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_DCF医師勤務先テーブルにレコードを登録する
        Arranges:
            - CSVデータを用意する
            - 追加対象となるレコードを削除する
        Expects:
            - COM_医師勤務先の登録内容が期待値と一致すること
            - COM_医師勤務先履歴にデータが登録されないこと
        """

        # Arrange
        # 処理日設定
        # 適用開始日と同値になる
        self.batch_context.syor_date = '2020/02/22'
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_dr_wrkplace_insert.csv'))
        # 一旦全データをDBから削除
        # COM_医師勤務先
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_dr_wrkplace', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # COM_医師勤務先履歴
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_dr_wrkplace_his', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # COM_所属部科
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_blng_sec', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)

        # COM_所属部科を登録
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_blng_sec_before_insert.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_blng_sec',
                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_dr_wrkplace_mapper.ComDrWrkplaceMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_dr_wrkplace_mapper.ComDrWrkplaceMapper, f'{line_number}行目:マッパークラスが期通りか'

            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_dr_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_dr_wrkplace_insert.csv'))
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_dr_data_list]
        primary_keys_dcf_pcf_dr_cd = [{'dcf_pcf_dr_cd': columns['dcf_pcf_dr_cd']} for columns in expect_dr_data_list]
        # 複合主キーのため、1件ずつ取得して期待値を作る
        actual_dr_data_list = []
        actual_dr_select_sql = """\
        SELECT * FROM src05.com_dr_wrkplace
        WHERE
                dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND dcf_pcf_dr_cd = :dcf_pcf_dr_cd\
        """
        actual_his_select_sql = """\
        SELECT * FROM src05.com_dr_wrkplace_his
        WHERE
                dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND dcf_pcf_dr_cd = :dcf_pcf_dr_cd
        """
        for param_dcf_dsf_inst_cd, param_dcf_pcf_dr_cd in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_dcf_pcf_dr_cd):
            # COM_医師勤務先の取得
            actual_dr_data = self.db.execute_select(
                actual_dr_select_sql,
                {**param_dcf_dsf_inst_cd, **param_dcf_pcf_dr_cd})
            assert len(actual_dr_data) == 1, '1件取得できていること'
            actual_dr_data_list.append(actual_dr_data[0])

            # COM_医師勤務先履歴の取得
            # 取得できないこと
            actual_his_data = self.db.execute_select(
                actual_his_select_sql,
                {**param_dcf_dsf_inst_cd, **param_dcf_pcf_dr_cd})
            assert len(actual_his_data) == 0, '履歴が作成されていないこと'

        assert len(actual_dr_data_list) == len(expect_dr_data_list), 'COM_医師勤務先が期待値通りの件数作成されていること'

        # 期待値検査
        ignore_columns = ['regist_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_dr_data_list, expect_dr_data_list, ignore_col_name=ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_dr_data_list, expect_dr_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:
                    assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'

    def test_update_record(self):
        """
        Cases:
            COM_DCF医師勤務先テーブルのレコードを更新する
        Arranges:
            - CSVデータを用意し、読み込む
            - 更新対象となるレコードを登録する
        Expects:
            - COM_医師勤務先の登録内容が期待値と一致すること
            - COM_医師勤務先履歴にデータが登録され、期待値と一致すること
        """

        # Arrange
        # 処理日設定
        # 適用開始日と同値、適用終了日の+1日になる
        self.batch_context.syor_date = '2020/02/23'
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_dr_wrkplace_update.csv'))
        # 一旦全データをDBから削除
        # COM_医師勤務先
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_dr_wrkplace', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # COM_医師勤務先履歴
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_dr_wrkplace_his', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # COM_所属部科
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_blng_sec', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)

        # COM_医師勤務先を登録
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_dr_wrkplace_before_update.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_dr_wrkplace',
                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_dr_wrkplace_mapper.ComDrWrkplaceMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_dr_wrkplace_mapper.ComDrWrkplaceMapper, f'{line_number}行目:マッパークラスが期通りか'

            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_dr_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_dr_wrkplace_update.csv'))
        expect_his_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_dr_wrkplace_his_update.csv'))
        # 複合主キーのため、1件ずつ取得して期待値を作る
        actual_dr_data_list = []
        actual_his_data_list = []
        actual_dr_select_sql = """\
        SELECT * FROM src05.com_dr_wrkplace
        WHERE
                dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND dcf_pcf_dr_cd = :dcf_pcf_dr_cd\
        """
        actual_his_select_sql = """\
        SELECT * FROM src05.com_dr_wrkplace_his
        WHERE
                dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND dcf_pcf_dr_cd = :dcf_pcf_dr_cd
        """
        # COM_医師勤務先の取得
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_dr_data_list]
        primary_keys_dcf_pcf_dr_cd = [{'dcf_pcf_dr_cd': columns['dcf_pcf_dr_cd']} for columns in expect_dr_data_list]
        for param_dcf_dsf_inst_cd, param_dcf_pcf_dr_cd in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_dcf_pcf_dr_cd):
            actual_dr_data = self.db.execute_select(
                actual_dr_select_sql,
                {**param_dcf_dsf_inst_cd, **param_dcf_pcf_dr_cd})
            assert len(actual_dr_data) == 1, '1件取得できていること'
            actual_dr_data_list.append(actual_dr_data[0])

        # COM_医師勤務先履歴の取得
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_his_data_list]
        primary_keys_dcf_pcf_dr_cd = [{'dcf_pcf_dr_cd': columns['dcf_pcf_dr_cd']} for columns in expect_his_data_list]
        for param_dcf_dsf_inst_cd, param_dcf_pcf_dr_cd in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_dcf_pcf_dr_cd):
            actual_his_data = self.db.execute_select(
                actual_his_select_sql,
                {**param_dcf_dsf_inst_cd, **param_dcf_pcf_dr_cd})
            assert len(actual_dr_data) == 1, '1件取得できていること'
            actual_his_data_list.append(actual_his_data[0])

        assert len(actual_his_data_list) == len(expect_his_data_list), 'COM_医師勤務先が期待値通りの件数作成されていること'
        assert len(actual_his_data_list) == len(expect_his_data_list), 'COM_医師勤務先履歴が期待値通りの件数作成されていること'

        # 期待値検査
        # COM_医師勤務先
        dr_ignore_columns = ['regist_ymd', 'update_ymd', 'sys_update_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_dr_data_list, expect_dr_data_list, ignore_col_name=dr_ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_dr_data_list, expect_dr_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in dr_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:
                        assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'

        # COM_医師勤務先履歴
        his_ignore_columns = ['dr_wrkplace_his_key', 'regist_ymd', 'update_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_his_data_list, expect_his_data_list, ignore_col_name=his_ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_dr_data_list, expect_dr_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in his_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:
                        assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'

    def test_delete_record(self):
        """
        Cases:
            COM_DCF医師勤務先テーブルのレコードを削除する
        Arranges:
            - CSVデータを用意し、読み込む
            - 削除対象となるレコードを登録する
        Expects:
            - COM_医師勤務先の登録内容が期待値と一致すること
            - COM_医師勤務先履歴にデータが登録されないこと
        """

        # Arrange
        # 処理日設定
        self.batch_context.syor_date = '2020/02/24'
        # テスト用のCSVを読み込む
        test_dat_file = create_ultmarc_test_data_from_csv(path.join(self.test_file_path, 'com_dr_wrkplace_delete.csv'))
        # 一旦全データをDBから削除
        # COM_医師勤務先
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_dr_wrkplace', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # COM_医師勤務先履歴
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_dr_wrkplace_his', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)
        # COM_所属部科
        delete_sql, delete_parameter = create_delete_sql_with_parameter('src05.com_blng_sec', {'1': '1'})
        self.db.execute(delete_sql, delete_parameter)

        # COM_医師勤務先を登録
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_dr_wrkplace_before_delete.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_dr_wrkplace',
                test_data.keys(),
                test_data.values()
            )
            self.db.execute(insert_sql, insert_parameter)

        # COM_医師勤務先履歴を登録
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_dr_wrkplace_his_before_delete.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_dr_wrkplace_his',
                test_data.keys(),
                test_data.values()
            )
            self.db.execute(insert_sql, insert_parameter)

        # COM_所属部科を登録
        test_sql_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'db_com_blng_sec_before_delete.csv'))
        for test_data in test_sql_data_list:
            insert_sql, insert_parameter = create_insert_sql_with_parameter(
                'src05.com_blng_sec',
                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_dr_wrkplace_mapper.ComDrWrkplaceMapper = create_ultmarc_table_mapper_sut(line, self.db)
            assert type(sut) is com_dr_wrkplace_mapper.ComDrWrkplaceMapper, f'{line_number}行目:マッパークラスが期通りか'

            sut.make_query()
            sut.execute_queries()

        # Assert
        # 期待値ファイルを読み込む
        expect_dr_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_dr_wrkplace_delete.csv'))
        expect_his_data_list = create_db_data_from_csv(path.join(self.test_file_path, 'expect_com_dr_wrkplace_his_delete.csv'))
        # 複合主キーのため、1件ずつ取得して期待値を作る
        actual_dr_data_list = []
        actual_his_data_list = []
        actual_dr_select_sql = """\
        SELECT * FROM src05.com_dr_wrkplace
        WHERE
                dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND dcf_pcf_dr_cd = :dcf_pcf_dr_cd\
        """
        actual_his_select_sql = """\
        SELECT * FROM src05.com_dr_wrkplace_his
        WHERE
                dcf_dsf_inst_cd = :dcf_dsf_inst_cd
            AND dcf_pcf_dr_cd = :dcf_pcf_dr_cd
        """

        # COM_医師勤務先の取得
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_dr_data_list]
        primary_keys_dcf_pcf_dr_cd = [{'dcf_pcf_dr_cd': columns['dcf_pcf_dr_cd']} for columns in expect_dr_data_list]
        for param_dcf_dsf_inst_cd, param_dcf_pcf_dr_cd in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_dcf_pcf_dr_cd):
            actual_dr_data = self.db.execute_select(
                actual_dr_select_sql,
                {**param_dcf_dsf_inst_cd, **param_dcf_pcf_dr_cd})
            assert len(actual_dr_data) == 1, '1件取得できていること'
            actual_dr_data_list.append(actual_dr_data[0])

        # COM_医師勤務先履歴の取得
        primary_keys_dcf_dsf_inst_cd = [{'dcf_dsf_inst_cd': columns['dcf_dsf_inst_cd']} for columns in expect_his_data_list]
        primary_keys_dcf_pcf_dr_cd = [{'dcf_pcf_dr_cd': columns['dcf_pcf_dr_cd']} for columns in expect_his_data_list]
        for param_dcf_dsf_inst_cd, param_dcf_pcf_dr_cd in zip(primary_keys_dcf_dsf_inst_cd, primary_keys_dcf_pcf_dr_cd):
            # COM_医師勤務先履歴の取得
            actual_his_data = self.db.execute_select(
                actual_his_select_sql,
                {**param_dcf_dsf_inst_cd, **param_dcf_pcf_dr_cd})
            assert len(actual_his_data) == 1, '1件取得できていること'
            actual_his_data_list.append(actual_his_data[0])

        assert len(actual_dr_data_list) == len(expect_dr_data_list), 'COM_医師勤務先が期待値通りの件数作成されていること'
        assert len(actual_his_data_list) == len(expect_his_data_list), 'COM_医師勤務先履歴が期待値通りの件数作成されていること'

        # 期待値検査
        # COM_医師勤務先
        dr_ignore_columns = ['regist_ymd', 'update_ymd', 'sys_update_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_dr_data_list, expect_dr_data_list, ignore_col_name=dr_ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_dr_data_list, expect_dr_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in dr_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:
                        assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'

        # COM_医師勤務先履歴
        his_ignore_columns = ['dr_wrkplace_his_key', 'regist_ymd', 'update_ymd', 'sys_update_date', 'sys_regist_date']
        assert_table_results(actual_his_data_list, expect_his_data_list, ignore_col_name=his_ignore_columns)
        # 動的日付項目の個別確認
        line_number = 0
        for actual_row, expect_row in zip(actual_dr_data_list, expect_dr_data_list):
            line_number += 1
            for actual_col_name, expect_col_name in zip(actual_row, expect_row):
                if actual_col_name in his_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:
                        assert actual_row[actual_col_name] >= expect_row[expect_col_name], f'{line_number}行目:{actual_col_name}が、期待値以降であること'
