import json

import pandas as pd
from django.db.models import Q

from payrollservice.data.response.graderesponse import GradeResponse
# from masterservice.models import Grade
from payrollservice.util.masterutil import Code_Gen_Type, Code_Gen_Value
from payrollservice.data.response.payrollmasterresponse import PayrollComponentResponse, CompanyContributionResponse, \
    EmployeePFResponse, ComponentTypeResponse, PayrollDeductionResponse, PaycomponentFlagmasterResponse, \
    SegmentMasterResponse
from payrollservice.models import PayrollComponent, PayrollDeduction, CompanyContribution, PaycomponentFlagmaster, \
    EmployeePFStructure, ComponentType, Segment, ReportColumns, ReportTemplate, ReportTemplateDetails
from payrollservice.util.payrollutil import Activestatus, FlagRef_Type, CompanyAllowanceType, category_val, \
    payrolldeduction_val
from utilityservice.data.response.nwisefinlist import NWisefinList
from utilityservice.data.response.nwisefinpaginator import NWisefinPaginator
from utilityservice.data.response.nwisefinsuccess import SuccessMessage, NWisefinSuccess, SuccessStatus
from utilityservice.data.response.nwisefinerror import NWisefinError
from utilityservice.data.response.nwisefinerrorconstants import ErrorDescription, ErrorMessage
from utilityservice.service.applicationconstants import ApplicationNamespace
from utilityservice.service.payroll_api_service import Payrollcommon_Apicall
from utilityservice.service.threadlocal import NWisefinThread
from django.utils import timezone
# from masterservice.service.Codegenerator import CommonCodeGenService, CodeGen
# from masterservice.util.codeutil import CodeUtil
from payrollservice.util.masterutil import CodeUtil
from hrmsmasterapiservice.hrmsmasterapi.masteranduserserviceapi import HrmsApiService

class PayrollComponentService(NWisefinThread):
    def __init__(self, scope):
        super().__init__(scope)
        self._set_namespace(ApplicationNamespace.PAYROLL_SERVICE)

    def create_payroll_component(self, data_obj, emp_id):
        try:
            resp = NWisefinSuccess()
            if data_obj.get_id() is not None:
                prm = PayrollComponent.objects.using(self._current_app_schema()).filter(id=data_obj.get_id()).update(name=data_obj.get_name(),
                                                 allowance_type=data_obj.get_allowance_type(),
                                                 percentage=data_obj.get_percentage(),
                                                 updated_by=emp_id,
                                                 pf_include=data_obj.get_pf_include(),
                                                 is_deduction=data_obj.get_is_deduction(),
                                                 updated_date=timezone.now(), grade=data_obj.get_gradelevel(), is_default=data_obj.get_is_default(),
                                                 cat_id=data_obj.get_cat_id(),
                                                 subcat_id=data_obj.get_subcat_id(),
                                                 glno=data_obj.get_glno(),
                                                 from_date=data_obj.get_from_date(),
                                                 to_date=data_obj.get_to_date())

                prm = PayrollComponent.objects.using(self._current_app_schema()).get(id=data_obj.get_id())

                message = SuccessMessage.UPDATE_MESSAGE
            else:
                prm = PayrollComponent.objects.using(self._current_app_schema()).create(name=data_obj.get_name(),
                                                       allowance_type=data_obj.get_allowance_type(),
                                                       percentage=data_obj.get_percentage(),
                                                       pf_include=data_obj.get_pf_include(),
                                                       is_deduction=data_obj.get_is_deduction(),
                                                       created_by=emp_id,
                                                       entity_id=self._entity_id(), grade=data_obj.get_gradelevel(),
                                                       is_default=data_obj.get_is_default(),
                                                       cat_id=data_obj.get_cat_id(),
                                                       subcat_id=data_obj.get_subcat_id(),
                                                       glno=data_obj.get_glno(),
                                                       from_date=data_obj.get_from_date(),
                                                       to_date=data_obj.get_to_date())
                # code_serv = CommonCodeGenService(self._scope())
                # code = code_serv.gen_code(CodeUtil.PAYROLL_COMPONENT, emp_id)
                code_serv = HrmsApiService(self._scope())
                code = code_serv.common_code_generate(CodeUtil.PAYROLL_COMPONENT, emp_id)
                prm.code = code
                prm.save()
                message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            resp.id = prm.id
            resp.is_deduction = prm.is_deduction
            return resp
        except:
            error = NWisefinError()
            error.set_code(ErrorMessage.UNEXPECTED_ERROR)
            error.set_description(ErrorDescription.UNEXPECTED_ERROR)
            return error

    def payroll_component_summary(self, name, vys_page,grade):
        condition = Q(status=Activestatus.active)
        if (name is not None) and (name != ''):
            condition &= Q(name__icontains=name)
        elif grade is not None and grade != '':
            condition &= Q(grade=grade)
        prm_list = PayrollComponent.objects.using(
            self._current_app_schema()).filter(
            condition)[vys_page.get_offset():vys_page.get_query_limit()]
        grade = [i.grade for i in prm_list]
        # grade_data = GradeService(self._scope()).get_grade_data_by_id(grade)
        grade_data = Payrollcommon_Apicall(self._scope()).get_grade_data_by_id(grade)
        list_data = NWisefinList()
        for prm in prm_list:
            resp = PayrollComponentResponse()
            resp.set_id(prm.id)
            resp.set_name(prm.name)
            resp.set_code(prm.code)
            resp.set_pf_include(prm.pf_include)
            resp.set_is_deduction(prm.is_deduction)
            allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(prm.allowance_type)
            resp.allowance_type = allowance_type_data
            resp.set_percentage(prm.percentage)
            resp.set_grade_val(prm.grade, grade_data)
            resp.set_cat_id(prm.cat_id)
            resp.set_subcat_id(prm.subcat_id)
            resp.set_glno(prm.glno)
            resp.set_from_date(prm.from_date)
            resp.set_to_date(prm.to_date)
            list_data.append(resp)
        v_page = NWisefinPaginator(prm_list, vys_page.get_index(), 10)
        list_data.set_pagination(v_page)
        return list_data




    def payroll_component_summary1(self, name,grade,action):
        condition = Q(status=Activestatus.active)
        if (name is not None) and (name != ''):
            condition &= Q(name__icontains=name)
        elif grade is not None and grade != '':
            condition &= Q(grade=grade)
        prm_list = PayrollComponent.objects.using(self._current_app_schema()).filter(condition)
        grade = [i.grade for i in prm_list]
        # grade_data = GradeService(self._scope()).get_grade_data_by_id(grade)
        grade_data = Payrollcommon_Apicall(self._scope()).get_grade_data_by_id(grade)
        list_data = NWisefinList()
        for prm in prm_list:
            resp = PayrollComponentResponse()
            allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(prm.allowance_type)
            if int(action) == allowance_type_data.category['id']:
                resp.set_id(prm.id)
                resp.set_name(prm.name)
                resp.set_code(prm.code)
                resp.set_pf_include(prm.pf_include)
                resp.set_is_deduction(prm.is_deduction)
                resp.set_percentage(prm.percentage)
                resp.set_grade_val(prm.grade, grade_data)
                resp.allowance_type = allowance_type_data
                resp.set_cat_id(prm.cat_id)
                resp.set_subcat_id(prm.subcat_id)
                resp.set_glno(prm.glno)
                resp.set_from_date(prm.from_date)
                resp.set_to_date(prm.to_date)
                list_data.append(resp)
        return list_data
    def get_payroll_component(self, comp_id):
        try:
            prm = PayrollComponent.objects.using(self._current_app_schema()).get(status=Activestatus.active, id=comp_id)
            grade_dict = {"status":Activestatus.active,'id':prm.grade}
            grade = HrmsApiService(self._scope()).get_grade_by_id(grade_dict)
            # grade = Grade.objects.using(self._current_app_schema()).get(status=Activestatus.active, id=prm.grade)
            resp = PayrollComponentResponse()
            resp.set_id(prm.id)
            resp.set_name(prm.name)
            resp.set_code(prm.code)
            resp.set_pf_include(prm.pf_include)
            resp.set_is_deduction(prm.is_deduction)
            allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(prm.allowance_type)
            resp.allowance_type = allowance_type_data
            resp.set_grade= grade.get('name') if grade else None
            resp.set_cat_id(prm.cat_id)
            resp.set_subcat_id(prm.subcat_id)
            resp.set_glno(prm.glno)
            resp.set_from_date(prm.from_date)
            resp.set_to_date(prm.to_date)
            return resp
        except PayrollComponent.DoesNotExist:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error
        except:
            error = NWisefinError()
            error.set_code(ErrorMessage.UNEXPECTED_ERROR)
            error.set_description(ErrorDescription.UNEXPECTED_ERROR)
            return error

    def delete_payroll_component(self, comp_id):
        prm = PayrollComponent.objects.using(self._current_app_schema()).filter(id=comp_id).update(status=Activestatus.inactive)
        if prm != 0:
            success = NWisefinSuccess()
            success.set_status(SuccessStatus.SUCCESS)
            success.set_message(SuccessMessage.DELETE_MESSAGE)
            return success
        else:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error

    def get_multiple_payroll_component(self, id_arr):
        prm_list = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_arr)
        grade = [i.grade for i in prm_list]
        # grade_data = GradeService(self._scope()).get_grade_data_by_id(grade)
        grade_data = Payrollcommon_Apicall(self._scope()).get_grade_data_by_id(grade)
        list_data = []
        for prm in prm_list:
            resp = PayrollComponentResponse()
            resp.set_id(prm.id)
            resp.set_name(prm.name)
            resp.set_code(prm.code)
            resp.set_pf_include(prm.pf_include)
            resp.set_is_deduction(prm.is_deduction)
            resp.set_percentage(prm.percentage)
            # allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(prm.allowance_type)
            # resp.allowance_type = allowance_type_data
            resp.set_grade_val(prm.grade, grade_data)
            resp.set_grade(prm.grade)
            resp.set_cat_id(prm.cat_id)
            resp.set_subcat_id(prm.subcat_id)
            resp.set_glno(prm.glno)
            list_data.append(resp)
        return list_data

    def get_multiple_payroll_component_val(self, id_arr):
        prm_list = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_arr)
        grade = [i.grade for i in prm_list]
        # grade_data = GradeService(self._scope()).get_grade_data_by_id(grade)
        grade_data = Payrollcommon_Apicall(self._scope()).get_grade_data_by_id(grade)
        list_data = []
        for prm in prm_list:
            resp = PayrollComponentResponse()
            resp.set_id(prm.id)
            resp.set_name(prm.name)
            resp.set_code(prm.code)
            resp.set_pf_include(prm.pf_include)
            resp.set_is_deduction(prm.is_deduction)
            allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(prm.allowance_type)
            resp.allowance_type = allowance_type_data
            resp.set_grade_val(prm.grade, grade_data)
            resp.set_grade(prm.grade)
            resp.set_cat_id(prm.cat_id)
            resp.set_subcat_id(prm.subcat_id)
            resp.set_glno(prm.glno)
            list_data.append(resp)
        return list_data

    def get_payrollcomponent_details(self, id_arr):
        prm_list = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active, id__in=id_arr)
        grade =[i.grade for i in prm_list]
        # grade_data = GradeService(self._scope()).get_grade_data_by_id(grade)
        grade_data = Payrollcommon_Apicall(self._scope()).get_grade_data_by_id(grade)
        list_data = []
        for prm in prm_list:
            resp = PayrollComponentResponse()
            resp.set_id(prm.id)
            resp.set_name(prm.name)
            resp.set_code(prm.code)
            allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(prm.allowance_type)
            resp.allowance_type = allowance_type_data
            resp.set_grade_val(prm.grade,grade_data)
            list_data.append(resp)
        return list_data

    def get_payrollcomponent_name(self, id_arr):
        prm_list = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_arr)[0]
        return prm_list.name


    def get_default_components(self):
        prm_list = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active, is_default=True)
        return prm_list

    def get_paycom_details(self, id_val):
        paycom = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_val)
        return paycom

    def update_default_component(self, component_id, type_val):
        if type_val == 1:
            val = True
            update = False
            comp = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id=component_id)
            if len(comp) != 0:
                alw_type = comp[0].allowance_type
                type_data = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active, allowance_type=alw_type,
                                                                                              is_default=True)
                if len(type_data) == 0:
                    update = True
            if update is False:
                error = NWisefinError()
                error.set_code(ErrorMessage.CANNOT_UPDATE)
                error.set_description(ErrorDescription.CANNOT_UPDATE)
                return error
        else:
            val = False
        PayrollComponent.objects.using(self._current_app_schema()).filter(id=component_id).update(is_default=val)
        success = NWisefinSuccess()
        success.set_status(SuccessStatus.SUCCESS)
        success.set_message(SuccessMessage.UPDATE_MESSAGE)
        return success

    # payrollcomponent and payrolldeduction summary
    def componentdeduction_summary(self, request, vys_page):
        condition = Q(status=Activestatus.active) & Q(entity_id=self._entity_id())
        name = request.GET.get('name')
        allowance_type = request.GET.get('allowance_type')
        type = request.GET.get('type')
        if name != None and name != "":
            condition &= Q(name__icontains=name)
        if allowance_type != None and allowance_type != "":
            condition &= Q(allowance_type=allowance_type)
        if type != None and type != "":
            condition &= Q(payrolldeduction__type=type)
        component_details= PayrollComponent.objects.using(self._current_app_schema()).select_related('payrolldeduction').filter(condition).values('id','name','code','allowance_type','is_deduction', 'pf_include', 'percentage','id', 'payrolldeduction__type', 'payrolldeduction__from_date', 'payrolldeduction__to_date', 'grade')[vys_page.get_offset():vys_page.get_query_limit()]
        list_data = NWisefinList()
        for compdeduction in component_details:
            resp = PayrollComponentResponse()
            resp.set_id(compdeduction['id'])
            resp.set_name(compdeduction['name'])
            resp.set_code(compdeduction['code'])
            resp.set_pf_include(compdeduction['pf_include'])
            resp.set_is_deduction(compdeduction['is_deduction'])
            resp.set_allowance_type(compdeduction['allowance_type'])
            resp.set_type(compdeduction['payrolldeduction__type'])
            resp.set_from_date(compdeduction['payrolldeduction__from_date'])
            resp.set_to_date(compdeduction['payrolldeduction__to_date'])
            list_data.append(resp)
            vpage = NWisefinPaginator(component_details, vys_page.get_index(), 10)
            list_data.set_pagination(vpage)
        return list_data

    def componentdeduction_summary_data(self, request, vys_page):
        condition = Q(status=Activestatus.active) & Q(entity_id=self._entity_id())
        name = request.GET.get('name')
        allowance_type = request.GET.get('allowance_type')
        type = request.GET.get('type')
        if name != None and name != "":
            condition &= Q(name__icontains=name)
        if allowance_type != None and allowance_type != "":
            condition &= Q(allowance_type=allowance_type)
        if type != None and type != "":
            condition &= Q(payrolldeduction__type=type)
        component_details = PayrollComponent.objects.using(self._current_app_schema()).filter(condition)[vys_page.get_offset():vys_page.get_query_limit()]
        id_arr=[i.id for i in component_details]
        empmonth_details = self.payroll_deductions(id_arr)
        grade = [i.grade for i in component_details]
        # grade_data = GradeService(self._scope()).get_grade_data_by_id(grade)
        grade_data = Payrollcommon_Apicall(self._scope()).get_grade_data_by_id(grade)
        list_data = NWisefinList()
        for compdeduction in component_details:
            resp = PayrollComponentResponse()
            resp.set_id(compdeduction.id)
            resp.set_name(compdeduction.name)
            resp.set_code(compdeduction.code)
            resp.set_pf_include(compdeduction.pf_include)
            resp.set_is_deduction(compdeduction.is_deduction)
            allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(compdeduction.allowance_type)
            resp.allowance_type = allowance_type_data
            resp.set_percentage(compdeduction.percentage)
            resp.set_payrolldeduct_val(compdeduction.id, empmonth_details)
            resp.set_grade_val(compdeduction.grade, grade_data)
            list_data.append(resp)
        v_page = NWisefinPaginator(component_details, vys_page.get_index(), 10)
        list_data.set_pagination(v_page)
        return list_data

    def emp_grade_paycomonent_get(self,request, grade, vys_page):
        list_data = NWisefinList()
        try:
            condition = Q(status=Activestatus.active) & Q(entity_id=self._entity_id()) & Q(grade=grade)
            name = request.GET.get('name')
            if name != None and name != "":
                condition &= Q(name__icontains=name)
            paycom_list = PayrollComponent.objects.using(self._current_app_schema()).filter(condition)[vys_page.get_offset():vys_page.get_query_limit()]
            if paycom_list.count() > 0:
                for i in paycom_list:
                    resp = PayrollComponentResponse()
                    resp.set_id(i.id)
                    resp.set_name(i.name)
                    resp.set_code(i.code)
                    resp.set_percentage(i.percentage)
                    allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(i.allowance_type)
                    resp.allowance_type = allowance_type_data
                    list_data.append(resp)
                    v_page = NWisefinPaginator(paycom_list, vys_page.get_index(), 10)
                    list_data.set_pagination(v_page)
                return list_data
            else:
                return list_data
        except:
            return list_data

    def deduction_payrollcomponent(self, is_deduction, vys_page):
        condition = Q(status=Activestatus.active)
        if is_deduction != None and is_deduction != "":
            condition &= Q(is_deduction=is_deduction)
        prm_list = PayrollComponent.objects.using(self._current_app_schema()).filter(condition)[vys_page.get_offset():vys_page.get_query_limit()]
        list_data = NWisefinList()
        for prm in prm_list:
            resp = PayrollComponentResponse()
            resp.set_id(prm.id)
            resp.set_name(prm.name)
            resp.set_code(prm.code)
            resp.set_pf_include(prm.pf_include)
            resp.set_is_deduction(prm.is_deduction)
            allowance_type_data = ComponentTypeService(self._scope()).fetch_componenttype(prm.allowance_type)
            resp.allowance_type = allowance_type_data
            resp.set_percentage(prm.percentage)
            resp.set_grade(prm.grade)
            list_data.append(resp)
        v_page = NWisefinPaginator(prm_list, vys_page.get_index(), 30)
        list_data.set_pagination(v_page)
        return list_data


    def payroll_deductions(self, id):
        condition = Q(entity_id=self._entity_id(), status=Activestatus.active) & Q(payrollcomp_id__in=id, payrollcomp__is_deduction=True)
        deduct_detail = PayrollDeduction.objects.using(self._current_app_schema()).filter(condition)
        resp_arr = []
        for paydeduct in deduct_detail:
            resp = PayrollDeductionResponse()
            resp.set_id(paydeduct.id)
            resp.set_payrollcomp_id(paydeduct.payrollcomp_id)
            resp.set_type(paydeduct.type)
            resp.set_from_date(paydeduct.from_date)
            resp.set_to_date(paydeduct.to_date)
            resp_arr.append(resp)
        return resp_arr

    def get_payrollcomponent_val(self,name):
        obj = PayrollComponent.objects.using(self._current_app_schema()).get(status=Activestatus.active,name__icontains=name)
        return obj.id

    def paystruct_details_data(self, id_data):
        obj = PayrollComponent.objects.using(self._current_app_schema()).filter(id__in=id_data, status=Activestatus.active)
        arr = []
        for i in obj:
            data_resp = PayrollComponentResponse()
            data_resp.paycomponent = i.id
            data_resp.paycomponent_name = i.name
            data_resp.paycomponent_percentage = str(i.percentage)
            arr.append(data_resp)
        return arr

    def paycomponent_details_data(self,paycomponent_id):
        obj = PayrollComponent.objects.using(self._current_app_schema()).get(id=paycomponent_id,status=Activestatus.active)
        data = {"paycomponent": obj.id, "paycomponent_name": obj.name, "paycomponent_percentage": str(obj.percentage)}
        return data

    def payrollcomtemplate_upload(self):
        obj = PayrollComponent.objects.using(self._current_app_schema()).filter(status=Activestatus.active)
        obj_df = pd.DataFrame(obj.values('name', 'percentage', 'id', 'allowance_type'))
        allowance_type_id = [i.allowance_type for i in obj]
        allowance_data = ComponentTypeService(self._scope()).struct_upload_data(allowance_type_id)
        print('data', allowance_data)
        df = obj_df.merge(allowance_data, left_on='allowance_type', right_on='id', how='inner')
        datadf = df.drop(['id_x', 'id_y', 'allowance_type'], axis=1)
        data_df1 = datadf.rename(columns={'name_x': 'Paycomponent', 'name_y': 'Paycomponent_type', 'percentage': 'Paycomponent_percenage'})
        return data_df1

    def payrollmaster_payrollcomponent_upload(self,payrollcomponent_data, user_id):
        try:
            resp = NWisefinSuccess()
            allowance_type =ComponentTypeService(self._scope()).get_componenttype_name(payrollcomponent_data['ALLOWANCE_TYPE'])
            # grade = payrollGradeService(self._scope()).get_grade_name(payrollcomponent_data['GRADE'])
            grade = Payrollcommon_Apicall(self._scope()).get_grade_name(payrollcomponent_data['GRADE'])
            prm = PayrollComponent.objects.using(self._current_app_schema()).create(name=payrollcomponent_data['NAME'],
                                                                                    allowance_type=allowance_type,
                                                                                    percentage=payrollcomponent_data['PERCENTAGE'],
                                                                                    pf_include=False,
                                                                                    is_deduction=False,
                                                                                    created_by=user_id,
                                                                                    entity_id=self._entity_id(),
                                                                                    grade=grade,
                                                                                    is_default=False,
                                                                                    cat_id=payrollcomponent_data['CAT_ID'],
                                                                                    subcat_id=payrollcomponent_data['SUBCAT_ID'],
                                                                                    glno=payrollcomponent_data['GL_NO'],
                                                                                    from_date=payrollcomponent_data['FROM_DATE'],
                                                                                    to_date=payrollcomponent_data['TO_DATE'])
            # code_serv = CommonCodeGenService(self._scope())
            # code = code_serv.gen_code(CodeUtil.PAYROLL_COMPONENT, user_id)
            code_serv = HrmsApiService(self._scope())
            code = code_serv.common_code_generate(CodeUtil.PAYROLL_COMPONENT, user_id)
            prm.code = code
            prm.save()
            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            return obj

class CompanyContributionService(NWisefinThread):
    def __init__(self, scope):
        super().__init__(scope)
        self._set_namespace(ApplicationNamespace.MASTER_SERVICE)

    def create_entry(self, data_obj, emp_id):
        try:
            resp = NWisefinSuccess()
            if data_obj.get_id() is not None:
                prm = CompanyContribution.objects.using(self._current_app_schema()).filter(id=data_obj.get_id()).update(name=data_obj.get_name(),
                                                 percentage=data_obj.get_percentage(),
                                                 effective_from=data_obj.get_effective_from(),
                                                 effective_to=data_obj.get_effective_to(),
                                                 amount=data_obj.get_amount(),
                                                 updated_by=emp_id,
                                                 updated_date=timezone.now(),
                                                 cat_id=data_obj.get_cat_id(),
                                                 subcat_id=data_obj.get_subcat_id(),
                                                 glno=data_obj.get_glno(),
                                                 sal_amount=data_obj.get_sal_amount())

                prm = CompanyContribution.objects.using(self._current_app_schema()).get(id=data_obj.get_id())
                message = SuccessMessage.UPDATE_MESSAGE
            else:
                prm = CompanyContribution.objects.using(self._current_app_schema()).create(name=data_obj.get_name(),
                                                       percentage=data_obj.get_percentage(),
                                                       effective_from=data_obj.get_effective_from(),
                                                       effective_to=data_obj.get_effective_to(),
                                                       amount=data_obj.get_amount(),
                                                       created_by=emp_id,
                                                       entity_id=self._entity_id(),
                                                       cat_id=data_obj.get_cat_id(),
                                                       subcat_id=data_obj.get_subcat_id(),
                                                       glno=data_obj.get_glno(),
                                                       sal_amount=data_obj.get_sal_amount())
                message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            resp.id = prm.id
            return resp
        except:
            error = NWisefinError()
            error.set_code(ErrorMessage.UNEXPECTED_ERROR)
            error.set_description(ErrorDescription.UNEXPECTED_ERROR)
            return error

    def company_contribution_summary(self, name, vys_page):
        condition = Q(status=Activestatus.active)
        if name != None and name != "":
            condition &= Q(name__icontains=name)
        # allowance_serv = CompanyAllowanceType()
        cc_list = CompanyContribution.objects.using(self._current_app_schema()).filter(condition)[vys_page.get_offset():vys_page.get_query_limit()]
        list_data = NWisefinList()
        for cc in cc_list:
            resp = CompanyContributionResponse()
            resp.set_id(cc.id)
            # type_val = allowance_serv.set_type(cc.type)
            resp.set_name(cc.name)
            resp.set_amount(cc.amount)
            resp.set_percentage(cc.percentage)
            resp.set_effective_from(cc.effective_from)
            resp.set_effective_to(cc.effective_to)
            resp.set_sal_amount(cc.sal_amount)
            flag_data = PaycomponentFlagmasterService(self._scope()).paycomponentflagmastersummary([cc.id],FlagRef_Type.COMPANYCONTRIBUTION)
            resp.paycomponentflagmaster = flag_data
            resp.set_cat_id(cc.cat_id)
            resp.set_subcat_id(cc.subcat_id)
            resp.set_glno(cc.glno)
            list_data.append(resp)
        v_page = NWisefinPaginator(cc_list, vys_page.get_index(), 10)
        list_data.set_pagination(v_page)
        return list_data

    def get_contribution_info(self, cont_id):
        try:
            cc = CompanyContribution.objects.using(self._current_app_schema()).get(status=Activestatus.active,id=cont_id)
            flag_data = PaycomponentFlagmasterService(self._scope()).paycomponentflagmastersummary([cc.id],FlagRef_Type.COMPANYCONTRIBUTION)
            allowance_serv = CompanyAllowanceType()
            resp = CompanyContributionResponse()
            resp.set_id(cc.id)
            # type_val = allowance_serv.set_type(cc.type)
            resp.set_name(cc.name)
            resp.set_amount(cc.amount)
            resp.set_percentage(cc.percentage)
            resp.set_effective_from(cc.effective_from)
            resp.set_effective_to(cc.effective_to)
            resp.paycomponentflagmaster = flag_data
            resp.set_cat_id(cc.cat_id)
            resp.set_sal_amount(cc.sal_amount)
            resp.set_subcat_id(cc.subcat_id)
            resp.set_glno(cc.glno)
            return resp
        except CompanyContribution.DoesNotExist:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error
        except:
            error = NWisefinError()
            error.set_code(ErrorMessage.UNEXPECTED_ERROR)
            error.set_description(ErrorDescription.UNEXPECTED_ERROR)
            return error

    def delete_contribution(self, cont_id):
        prm = CompanyContribution.objects.using(self._current_app_schema()).filter(id=cont_id).update(status=Activestatus.inactive)
        if prm != 0:
            com_con = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(status=Activestatus.active, map_id=cont_id, ref_type=FlagRef_Type.COMPANYCONTRIBUTION)
            if com_con.count() > 0:
                for i in com_con:
                    id_data = i.id
                    del_flagmaster = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(id=id_data).update(status=Activestatus.inactive)
            success = NWisefinSuccess()
            success.set_status(SuccessStatus.SUCCESS)
            success.set_message(SuccessMessage.DELETE_MESSAGE)
            return success
        else:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error

    def get_multiple_contribution(self, id_arr):
        cc_list = CompanyContribution.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_arr)
        amount = 0
        for each in cc_list:
            if each.name == "ESI" or each.name == "PF":
                amount = amount + each.amount
        list_data = []
        for cc in cc_list:
            allowance_serv = CompanyAllowanceType()
            resp = CompanyContributionResponse()
            resp.set_id(cc.id)
            # type_val = allowance_serv.set_type(cc.type)
            resp.set_name(cc.name)
            resp.set_amount(cc.amount)
            resp.set_yearly_amount(cc.amount)
            resp.set_percentage(cc.percentage)
            resp.set_effective_from(cc.effective_from)
            resp.set_effective_to(cc.effective_to)
            resp.set_cat_id(cc.cat_id)
            resp.set_subcat_id(cc.subcat_id)
            resp.set_glno(cc.glno)
            resp.set_total(amount)
            resp.set_yearly_total(amount)
            list_data.append(resp)
        return list_data

    def get_contribution(self, id_arr):
        cc_list = CompanyContribution.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_arr)[0]
        return cc_list.name
        # list_data = []
        # for cc in cc_list:
        #     allowance_serv = CompanyAllowanceType()
        #     resp = CompanyContributionResponse()
        #     resp.set_id(cc.id)
        #     # type_val = allowance_serv.set_type(cc.type)
        #     resp.set_name(cc.name)
        #     # resp.set_amount(cc.amount)
        #     # resp.set_percentage(cc.percentage)
        #     # resp.set_effective_from(cc.effective_from)
        #     # resp.set_effective_to(cc.effective_to)
        #     list_data.append(resp)
        # return list_data

    def get_emp_company_esi(self, ctc_amount):
        alw_type = CompanyAllowanceType()
        type_val = alw_type.esi['id']
        cc_list = CompanyContribution.objects.using(self._current_app_schema()).filter(status=Activestatus.active, type=type_val)
        if len(cc_list) != 0:
            contribution = ctc_amount * (cc_list[0].percentage/100)
            data = {"employee_contribution": str(contribution),
                    "employer_contribution": str(contribution)}
            return data
        else:
            return None

    def get_company_pf(self, ctc_amount):
        alw_type = CompanyAllowanceType()
        type_val = alw_type.pf['id']
        cc_list = CompanyContribution.objects.using(self._current_app_schema()).filter(status=Activestatus.active,type=type_val)
        if len(cc_list) != 0:
            basic_amount = cc_list[0].amount
            net_amt = ctc_amount * (cc_list[0].percentage * 100)
            if net_amt >= basic_amount:
                amount = basic_amount
            else:
                amount = net_amt
            return amount
        else:
            return None

    def company_contribution_val(self, name):
        obj = CompanyContribution.objects.using(self._current_app_schema()).get(status=Activestatus.active,name=name)
        return obj.id

    def company_contribution_data(self, id_val):
        pf = CompanyContribution.objects.using(self._current_app_schema()).filter(id=id_val,status=Activestatus.active).values('id', 'name','percentage','amount', 'sal_amount')
        return pf

    def get_cc_paycom_details(self):
        condition = Q(status=Activestatus.active)
        cc_obj = CompanyContribution.objects.using(self._current_app_schema()).filter(condition)
        list_data = []
        for cc_data in cc_obj:
            resp = CompanyContributionResponse()
            resp.set_id(cc_data.id)
            paycom = PaycomponentFlagmasterService(self._scope()).cc_epf_based_paycom(cc_data.id,FlagRef_Type.COMPANYCONTRIBUTION)
            resp.paycomponent = paycom
            resp.set_name(cc_data.name)
            resp.set_max_amount(cc_data.amount)
            resp.set_percentage1(cc_data.percentage)
            resp.set_cat_id(cc_data.cat_id)
            resp.set_subcat_id(cc_data.subcat_id)
            resp.set_glno(cc_data.glno)
            resp.set_sal_amount(cc_data.sal_amount)
            resp.set_effective_from(cc_data.effective_from)
            resp.set_effective_to(cc_data.effective_to)
            list_data.append(resp)
        return list_data
    def company_contribution_data_get(self,id_data):
        obj = CompanyContribution.objects.using(self._current_app_schema()).filter(id__in=id_data,
                                                                                   status=Activestatus.active)
        list_data = []
        for cc in obj:
            resp = CompanyContributionResponse()
            resp.set_id(cc.id)
            resp.set_name(cc.name)
            resp.set_amount(cc.amount)
            resp.set_percentage1(cc.percentage)
            resp.set_sal_amount(cc.sal_amount)
            # resp.set_effective_from(cc.effective_from)
            # resp.set_effective_to(cc.effective_to)
            # resp.set_cat_id(cc.cat_id)
            # resp.set_subcat_id(cc.subcat_id)
            # resp.set_glno(cc.glno)
            list_data.append(resp)
        return list_data

    def payrollmaster_companycontribution_upload(self,companycontribution_data, user_id):
        try:
            resp = NWisefinSuccess()
            cc = CompanyContribution.objects.using(self._current_app_schema()).create(name=companycontribution_data['NAME'],
                                                                                       percentage=companycontribution_data['PERCENTAGE'],
                                                                                       effective_from=companycontribution_data['EFFECTIVE_FROM'],
                                                                                       effective_to=companycontribution_data['EFFECTIVE_TO'],
                                                                                       amount=companycontribution_data['AMOUNT'],
                                                                                       created_by=user_id,
                                                                                       entity_id=self._entity_id(),
                                                                                       cat_id=companycontribution_data['CAT_ID'],
                                                                                       subcat_id=companycontribution_data['SUBCAT_ID'],
                                                                                       glno=companycontribution_data['GLNO'])
            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            resp.id = cc.id
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            obj.message = "INVALID_DATA"
            return obj





class EmployeePFService(NWisefinThread):
    def __init__(self, scope):
        super().__init__(scope)
        self._set_namespace(ApplicationNamespace.MASTER_SERVICE)

    def get_pf_details(self, pf_type, pf_percent, ctc_amount):
        pf_list = EmployeePFStructure.objects.using(self._current_app_schema()).filter(id=pf_type)
        if len(pf_list) != 0:
            if pf_list[0].is_standard is True:
                amount = ctc_amount * (pf_list[0].percentage / 100)
                percentage = pf_list[0].percentage
                type_val = pf_type
            else:
                if pf_list[0].amount is not None:
                    ctc_pf_amt = ctc_amount * (pf_list[0].percentage / 100)
                    if ctc_pf_amt > pf_list[0].amount:
                        amount = pf_list[0].amount
                    else:
                        amount = ctc_pf_amt
                    percentage = pf_list[0].percentage
                    type_val = pf_type
                else:
                    amount = ctc_amount * (pf_percent / 100)
                    percentage = pf_percent
                    type_val = pf_type
            data = {"amount": amount, "percentage": percentage, "type": type_val}
            return data
        else:
            return None

    def employee_pf_dd(self, vys_page, query):
        condition = Q(status=Activestatus.active)
        if (query is not None) and (query != ''):
            condition &= Q(name__icontains=query) | Q(code__icontains=query)
        pf_list = EmployeePFStructure.objects.using(self._current_app_schema()).filter(condition)[vys_page.get_offset():vys_page.get_query_limit()]
        # ref_data = [i.id for i in pf_list]
        list_data = NWisefinList()
        # flag_data = PaycomponentFlagmasterService(self._scope()).paycomponentflagmastersummary(ref_data, FlagRef_Type.PF)
        for pf in pf_list:
            resp = EmployeePFResponse()
            resp.set_id(pf.id)
            resp.set_name(pf.name)
            resp.set_code(pf.code)
            resp.set_glno(pf.glno)
            resp.set_sal_amount(pf.sal_amount)
            # percentage_flag = False
            # if pf.percentage is None:
            #     percentage_flag = True
            resp.set_percentage(pf.percentage)
            resp.set_is_standard(pf.is_standard)
            resp.set_amount(pf.amount)
            flag_data = PaycomponentFlagmasterService(self._scope()).paycomponentflagmastersummary([pf.id], FlagRef_Type.PF)
            resp.paycomponentflagmaster = flag_data
            # resp.set_ref_id_val(pf.id, flag_data)
            list_data.append(resp)
        v_page = NWisefinPaginator(pf_list, vys_page.get_index(), 10)
        list_data.set_pagination(v_page)
        return list_data

    def create_employee_pf(self, data_obj, emp_id):
        # try:
            resp = NWisefinSuccess()
            if data_obj.get_id() is not None:
                prm = EmployeePFStructure.objects.using(self._current_app_schema()).filter(id=data_obj.get_id()).update(name=data_obj.get_name(),
                                                 percentage=data_obj.get_percentage(),
                                                 updated_by=emp_id,
                                                 amount=data_obj.get_amount(),
                                                 # is_standard=data_obj.get_is_standard(),
                                                 updated_date=timezone.now(),
                                                 cat_id=data_obj.get_cat_id(),
                                                 subcat_id=data_obj.get_subcat_id(),
                                                 glno=data_obj.get_glno(),
                                                 sal_amount=data_obj.get_sal_amount())

                prm = EmployeePFStructure.objects.using(self._current_app_schema()).get(id=data_obj.get_id())
                message = SuccessMessage.UPDATE_MESSAGE
            else:
                prm = EmployeePFStructure.objects.using(self._current_app_schema()).create(name=data_obj.get_name(),
                                                       percentage=data_obj.get_percentage(),
                                                       amount=data_obj.get_amount(),
                                                       # is_standard=data_obj.get_is_standard(),
                                                       created_by=emp_id,
                                                       entity_id=self._entity_id(),
                                                       cat_id=data_obj.get_cat_id(),
                                                       subcat_id=data_obj.get_subcat_id(),
                                                       glno=data_obj.get_glno(),
                                                       sal_amount=data_obj.get_sal_amount())
                # code_serv = CommonCodeGenService(self._scope())
                # code = code_serv.gen_code(CodeUtil.EMP_PF_STRUCTURE, emp_id)
                code_serv = HrmsApiService(self._scope())
                code = code_serv.common_code_generate(CodeUtil.EMP_PF_STRUCTURE, emp_id)
                prm.code = code
                prm.save()
                message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            resp.id = prm.id
            return resp
        # except:
        #     error = NWisefinError()
        #     error.set_code(ErrorMessage.UNEXPECTED_ERROR)
        #     error.set_description(ErrorDescription.UNEXPECTED_ERROR)
        #     return error

    def get_pf_type(self, name):
        obj = EmployeePFStructure.objects.using(self._current_app_schema()).get(status=Activestatus.active,name=name)
        return obj.id

    def get_pf_name(self, id_arr):
        pf_list = EmployeePFStructure.objects.using(self._current_app_schema()).filter(status=Activestatus.active, id__in=id_arr)[0]
        return pf_list.name

    def get_emp_pf_info(self, cont_id):
        try:
            pf = EmployeePFStructure.objects.using(self._current_app_schema()).get(status=Activestatus.active,id=cont_id)
            flag_data = PaycomponentFlagmasterService(self._scope()).paycomponentflagmastersummary([pf.id], FlagRef_Type.PF)
            resp = EmployeePFResponse()
            resp.set_id(pf.id)
            resp.set_name(pf.name)
            resp.set_code(pf.code)
            resp.set_amount(pf.amount)
            resp.set_sal_amount(pf.sal_amount)
            # resp.set_yearly_PF_amount(pf.amount)
            resp.set_percentage(pf.percentage)
            resp.set_is_standard(pf.is_standard)
            resp.paycomponentflagmaster = flag_data
            resp.set_cat_id(pf.cat_id)
            resp.set_subcat_id(pf.subcat_id)
            resp.set_glno(pf.glno)
            # resp.set_ref_id_val(pf.id, flag_data)
            return resp
        except EmployeePFStructure.DoesNotExist:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error
        except:
            error = NWisefinError()
            error.set_code(ErrorMessage.UNEXPECTED_ERROR)
            error.set_description(ErrorDescription.UNEXPECTED_ERROR)
            return error

    def get_employeepf_type(self, id):
        pf = EmployeePFStructure.objects.using(self._current_app_schema()).get(id=id)
        resp = EmployeePFResponse()
        resp.set_id(pf.id)
        resp.set_name(pf.name)
        resp.set_code(pf.code)
        return resp

    def delete_emp_pf_structure(self, cont_id):
        prm = EmployeePFStructure.objects.using(self._current_app_schema()).filter(id=cont_id).update(status=Activestatus.inactive)
        if prm != 0:
            paycom = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(status=Activestatus.active,map_id=cont_id, ref_type=FlagRef_Type.PF)
            if paycom.count() > 0:
                for i in paycom:
                    id_data = i.id
                    del_flagmaster = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(id=id_data).update(status=Activestatus.inactive)
            success = NWisefinSuccess()
            success.set_status(SuccessStatus.SUCCESS)
            success.set_message(SuccessMessage.DELETE_MESSAGE)
            return success
        else:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error

    def get_multiple_emp_pf(self, id_arr):
        pf_list = EmployeePFStructure.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_arr)
        amount = 0
        for each in pf_list:
            if each.name == "ESI" or each.name == "PF":
                amount = amount + each.amount
        list_data = []
        for pf in pf_list:
            resp = EmployeePFResponse()
            resp.set_id(pf.id)
            resp.set_name(pf.name)
            resp.set_code(pf.code)
            resp.set_amount(pf.amount)
            resp.set_percentage(pf.percentage)
            resp.set_is_standard(pf.is_standard)
            list_data.append(resp)
        return list_data


    def get_employeepf_details(self, id_val):
        pf_list = EmployeePFStructure.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_val)
        return pf_list

    def get_employeepfstruct_details(self):
        condition = Q(status=Activestatus.active)
        epf_obj = EmployeePFStructure.objects.using(self._current_app_schema()).filter(condition)
        list_data = []
        for epf_data in epf_obj:
            resp = EmployeePFResponse()
            resp.set_id(epf_data.id)
            paycom = PaycomponentFlagmasterService(self._scope()).cc_epf_based_paycom(epf_data.id,FlagRef_Type.PF)
            resp.paycomponent = paycom
            resp.set_name(epf_data.name)
            resp.set_max_amount(epf_data.amount)
            resp.set_percentage(epf_data.percentage)
            resp.set_cat_id(epf_data.cat_id)
            resp.set_subcat_id(epf_data.subcat_id)
            resp.set_glno(epf_data.glno)
            resp.set_sal_amount(epf_data.sal_amount)
            list_data.append(resp)
        return list_data

    def segment_wise_employee_pf(self,id_data):
        epf_obj = EmployeePFStructure.objects.using(self._current_app_schema()).filter(id__in=id_data)
        list_data = []
        for epf_data in epf_obj:
            resp = EmployeePFResponse()
            resp.set_id(epf_data.id)
            # paycom = PaycomponentFlagmasterService(self._scope()).cc_epf_based_paycom(epf_data.id, FlagRef_Type.PF)
            # resp.paycomponent = paycom
            resp.set_name(epf_data.name)
            resp.set_max_amount(epf_data.amount)
            resp.set_percentage(epf_data.percentage)
            resp.set_cat_id(epf_data.cat_id)
            resp.set_subcat_id(epf_data.subcat_id)
            resp.set_glno(epf_data.glno)
            resp.set_sal_amount(epf_data.sal_amount)
            list_data.append(resp)
        return list_data

    def cal_employeepf_data(self, id_val):
        pf = EmployeePFStructure.objects.using(self._current_app_schema()).filter(id=id_val,status=Activestatus.active).values('id', 'name','percentage','amount','sal_amount')[0]
        return pf


    def payollmaster_employeepfstructure_upload(self,employeepfstructure_data, user_id):
        try:
            resp = NWisefinSuccess()
            prm = EmployeePFStructure.objects.using(self._current_app_schema()).create(name=employeepfstructure_data['NAME'],
                                                                                       percentage=employeepfstructure_data['PERCENTAGE'],
                                                                                       amount=employeepfstructure_data['AMOUNT'],
                                                                                       is_standard=False,
                                                                                       created_by=user_id,
                                                                                       entity_id=self._entity_id(),
                                                                                       cat_id=employeepfstructure_data['CAT_ID'],
                                                                                       subcat_id=employeepfstructure_data['SUBCAT_ID'],
                                                                                       glno=employeepfstructure_data['GLNO'])
            # code_serv = CommonCodeGenService(self._scope())
            # code = code_serv.gen_code(CodeUtil.EMP_PF_STRUCTURE, user_id)
            code_serv = HrmsApiService(self._scope())
            code = code_serv.common_code_generate(CodeUtil.EMP_PF_STRUCTURE, user_id)
            prm.code = code
            prm.save()
            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            resp.id = prm.id
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            obj.message = "INVALID_DATA"
            return obj


class PayrollDeductionService(NWisefinThread):
    def __init__(self, scope):
        super().__init__(scope)
        self._set_namespace(ApplicationNamespace.MASTER_SERVICE)

    def create_payrolldeduction(self,  request, data_obj, emp_id, data):
        resp = NWisefinSuccess()
        if data_obj.get_id() is not None:
            pay_dedu = PayrollDeduction.objects.using(self._current_app_schema()).filter(id=data_obj.get_id()).update(
                payrollcomp_id=data_obj.get_payrollcomp_id(),
                type=data_obj.get_type(),
                from_date=data_obj.get_from_date(),
                to_date=data_obj.get_to_date(),
                updated_by=emp_id,
                updated_date=timezone.now())

            pay_dedu = PayrollDeduction.objects.using(self._current_app_schema()).get(id=data_obj.get_id())
            message = SuccessMessage.UPDATE_MESSAGE
        else:
            pay_dedu = PayrollDeduction.objects.using(self._current_app_schema()).create(payrollcomp_id=data,
                                                                              type=data_obj.get_type(),
                                                                              from_date=data_obj.get_from_date(),
                                                                              to_date=data_obj.get_to_date(),
                                                                              created_by=emp_id,
                                                                              entity_id=self._entity_id())


            message = SuccessMessage.CREATE_MESSAGE
        resp.set_status(SuccessStatus.SUCCESS)
        resp.set_message(message)
        resp.id = pay_dedu.id
        return resp




class ComponentTypeService(NWisefinThread):
    def __init__(self, scope):
        super().__init__(scope)
        self._set_namespace(ApplicationNamespace.MASTER_SERVICE)


    def create_componenttype(self, resp_obj, emp_id):
        resp = NWisefinSuccess()
        if resp_obj.get_id() is not None:
            com_type = ComponentType.objects.using(self._current_app_schema()).filter(id=resp_obj.get_id()).update(
                                                                                name=resp_obj.get_name(),
                                                                                percentage=resp_obj.get_percentage(),
                                                                                category=resp_obj.get_category(),
                                                                                updated_by=emp_id,
                                                                                updated_date=timezone.now())

            com_type = ComponentType.objects.using(self._current_app_schema()).get(id=resp_obj.get_id())
            message = SuccessMessage.UPDATE_MESSAGE

        else:
            com_type = ComponentType.objects.using(self._current_app_schema()).create(name=resp_obj.get_name(),
                                                                                      percentage=resp_obj.get_percentage(),
                                                                                      category=resp_obj.get_category(),
                                                                                      created_by=emp_id,
                                                                                      entity_id=self._entity_id())

            message = SuccessMessage.CREATE_MESSAGE
        resp.set_status(SuccessStatus.SUCCESS)
        resp.set_message(message)
        return resp


    def summary_componenttype(self,request, vys_page):
        condition = Q(status=Activestatus.active) & Q(entity_id=self._entity_id())
        name= request.GET.get('name')
        if name != None and name != "":
            condition &= Q(name__icontains=name)
        comtype_info = ComponentType.objects.using(self._current_app_schema()).filter(condition)[vys_page.get_offset():vys_page.get_query_limit()]
        component_list_data = NWisefinList()
        for compdata in comtype_info:
            data_obj = ComponentTypeResponse()
            data_obj.set_id(compdata.id)
            data_obj.set_name(compdata.name)
            data_obj.set_percentage(compdata.percentage)
            data_obj.set_category(compdata.category)
            component_list_data.append(data_obj)
            v_page = NWisefinPaginator(comtype_info, vys_page.get_index(), 10)
            component_list_data.set_pagination(v_page)
        return component_list_data

    def fetch_componenttype(self, id):
        try:
            com_type = ComponentType.objects.using(self._current_app_schema()).get(status=Activestatus.active,id=id)
            data_obj = ComponentTypeResponse()
            data_obj.set_id(com_type.id)
            data_obj.set_name(com_type.name)
            data_obj.set_percentage(com_type.percentage)
            data_obj.set_category(com_type.category)
            return data_obj
        except:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error

    def fetch_componenttype1(self, id,category):
        com_type = ComponentType.objects.using(self._current_app_schema()).get(status=Activestatus.active,category=category)
        data_obj = ComponentTypeResponse()
        data_obj.set_id(com_type.id)
        data_obj.set_name(com_type.name)
        data_obj.set_percentage(com_type.percentage)
        data_obj.set_category(com_type.category)
        return data_obj

    def componenttype_delete(self, id):
        com_type = ComponentType.objects.using(self._current_app_schema()).filter(id=id).update(status=Activestatus.inactive)
        if com_type != 0:
            success = NWisefinSuccess()
            success.set_status(SuccessStatus.SUCCESS)
            success.set_message(SuccessMessage.DELETE_MESSAGE)
            return success
        else:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error

    def get_multiple_component_type(self, id_arr):
        component_list = ComponentType.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_arr)
        list_data = []
        for comp in component_list:
            data_obj = ComponentTypeResponse()
            data_obj.set_id(comp.id)
            data_obj.set_name(comp.name)
            data_obj.set_percentage(comp.percentage)
            data_obj.set_category(comp.category)
            list_data.append(data_obj)
        return list_data


    def get_componenttype_name(self, name):
        obj = ComponentType.objects.using(self._current_app_schema()).get(status=Activestatus.active,name=name)
        return obj.id

    def struct_upload_data(self, id_arr):
        obj = ComponentType.objects.using(self._current_app_schema()).filter(status=Activestatus.active, id__in=id_arr)
        df = pd.DataFrame(obj.values('id', 'name'))
        return df

    def get_componenttype_name1(self, name):
        obj = ComponentType.objects.using(self._current_app_schema()).get(status=Activestatus.active,name=name,category=6)
        return obj.id

    def fetch_category(self):
        com_type = ComponentType.objects.using(self._current_app_schema()).filter(status=Activestatus.active,category=6)
        if com_type.count() > 0:
            obj_df = pd.DataFrame(com_type.values('id', 'name', 'percentage','category'))
            data_df1 = obj_df.rename(columns={'id': 'ID', 'name': 'NAME','percentage': 'PERCENTAGE','category':'CATEGORY'})
        else:
            finaldf = ['ID','NAME','PERCENTAGE','CATEGORY']
            data_df1 = pd.DataFrame(columns=finaldf)
        return data_df1

    def payollmaster_componenttype_upload(self,component_type_data, user_id):
        try:
            resp = NWisefinSuccess()
            category_type = category_val(component_type_data['CATEGORY'])['id']
            com_type = ComponentType.objects.using(self._current_app_schema()).create(name=component_type_data['NAME'],
                                                                                      percentage=component_type_data['PERCENTAGE'],
                                                                                      category=category_type,
                                                                                      created_by=user_id,
                                                                                      entity_id=self._entity_id())

            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            return obj

    def component_arr_function(self,query):
        condition = Q(status=1)
        if query !=None and query !="":
            condition&= Q(category=query)
        Componentlist=ComponentType.objects.using(self._current_app_schema()).filter(condition).values("id").values_list("id",flat=True)
        return Componentlist

class PaycomponentFlagmasterService(NWisefinThread):
    def __init__(self, scope):
        super().__init__(scope)
        self._set_namespace(ApplicationNamespace.MASTER_SERVICE)


    def create_paycomponentflag(self,resp_obj, emp_id, ref_type, map_id):
        resp = NWisefinSuccess()
        obj = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(status=Activestatus.active,  map_id=map_id, ref_id=resp_obj.get_ref_id(), ref_type=ref_type)
        if len(obj)!=0:
            for i in obj:
                id_data = i.id
                if id_data is not None:
                    flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(id=id_data).update(
                        map_id=map_id,
                        ref_id=resp_obj.get_ref_id(),
                        ref_type=ref_type,
                        updated_by=emp_id,
                        updated_date=timezone.now())

                    flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).get(id=id_data)
                    resp = SuccessMessage.UPDATE_MESSAGE

        else:
            flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).create(map_id=map_id,
                                                                                    ref_id=resp_obj.get_ref_id(),
                                                                                    ref_type=ref_type,
                                                                                    created_by=emp_id,
                                                                                    entity_id=self._entity_id())

            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            resp.map_id = flag_data.map_id
        return resp

    def create_paycomponentflagmaster(self,resp_obj, emp_id):
        resp = NWisefinSuccess()
        if resp_obj.get_id() is not None:
            flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(id=resp_obj.get_id()).update(status=Activestatus.inactive)
            if flag_data != 0:
                success = NWisefinSuccess()
                success.set_status(SuccessStatus.SUCCESS)
                success.set_message(SuccessMessage.DELETE_MESSAGE)
                return success

        else:
            flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).create(map_id=resp_obj.get_map_id(),
                                                                                                ref_id=resp_obj.get_ref_id(),
                                                                                                ref_type=resp_obj.get_ref_type(),
                                                                                                created_by=emp_id,
                                                                                                entity_id=self._entity_id())

            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            return resp

    def paycomponentflagmastersummary(self, id, ref_type):
        flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(map_id__in=id, ref_type=ref_type,status=Activestatus.active)
        resp=[]
        ref_data = [i.ref_id for i in flag_data]
        ref_id_details = PayrollComponentService(self._scope()).get_multiple_payroll_component(ref_data)
        for i in flag_data:
            resp_obj = PaycomponentFlagmasterResponse()
            resp_obj.set_id(i.id)
            resp_obj.set_map_id(i.map_id)
            resp_obj.set_ref_id_val(i.ref_id, ref_id_details)
            # resp_obj.set_ref_type(i.ref_type)
            resp.append(resp_obj)
        return resp

    def get_payrolltemplate_data(self,map_id):
        flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(map_id=map_id, status=Activestatus.active)
        resp = []
        ref_data = [i.ref_id for i in flag_data]
        ref_id_details = SegmentMasterService(self._scope()).get_multiple_segment_data(ref_data)
        for i in flag_data:
            resp_obj = PaycomponentFlagmasterResponse()
            resp_obj.set_id(i.id)
            resp_obj.set_map_id(i.map_id)
            resp_obj.set_ref_id_data(i.ref_id, ref_id_details)
            # resp_obj.set_ref_type(i.ref_type)
            resp.append(resp_obj)
        return resp



    def inactive_paycomponentflagmaster(self,id,map_id):
        flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(ref_id=id, map_id=map_id).update(status=Activestatus.inactive)
        if flag_data != 0:
            success = NWisefinSuccess()
            success.set_status(SuccessStatus.SUCCESS)
            success.set_message(SuccessMessage.DELETE_MESSAGE)
            return success
        else:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error

    def get_component_values(self, ref_id):
        obj = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(status=Activestatus.active,ref_id__in=ref_id)
        arr = []
        ref_data = [i.ref_id for i in obj]
        map_data = [i.map_id for i in obj]
        pf_structure_data = EmployeePFService(self._scope()).get_multiple_emp_pf(map_data)
        ref_id_details = PayrollComponentService(self._scope()).get_multiple_payroll_component(ref_data)
        for i in obj:
            data_resp = PaycomponentFlagmasterResponse()
            data_resp.set_map_id_val(i.map_id, pf_structure_data)
            data_resp.set_ref_id_val(i.ref_id, ref_id_details)
            arr.append(data_resp)
        return arr

    def get_paycomponent_data(self, map_id):
        obj = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(map_id__in=[map_id], status=Activestatus.active)
        ref_id = [i.ref_id for i in obj]
        pf_structure_name = EmployeePFStructure.objects.using(self._current_app_schema()).get(id=map_id, status=Activestatus.active)
        # company_contribution = CompanyContribution.objects.using(self._current_app_schema()).get(id=map_id[0])
        ref_id_details = PayrollComponentService(self._scope()).get_multiple_payroll_component(ref_id)
        paycomponet_id = [i.id for i in ref_id_details]
        data = {'pfstructure_percentage': pf_structure_name.percentage, 'paycomponent': paycomponet_id,
                'amount': pf_structure_name.amount, 'structure_name': pf_structure_name.name,'sal_amount': pf_structure_name.sal_amount}
                # 'contribution_structure_name': company_contribution.name,
                # 'company_contribution_percentage': company_contribution.percentage,
                #'company_contribution_amount': company_contribution.amount}
        return data

    def get_companycontri_data(self, map_id):
        obj = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(status=Activestatus.active,map_id__in=[map_id], ref_type=3)
        if len(obj) > 0:
            ref_id = [i.ref_id for i in obj]
            company_contribution = CompanyContribution.objects.using(self._current_app_schema()).get(status=Activestatus.active,id=map_id[0])
            pf_values = EmployeePFStructure.objects.using(self._current_app_schema()).get(status=Activestatus.active,name=company_contribution.name)
            ref_id_details = PayrollComponentService(self._scope()).get_multiple_payroll_component(ref_id)
            paycomponet_id = [i.id for i in ref_id_details]
            data = {'contribution_structure_name': company_contribution.name,
                    'paycomponent': paycomponet_id,
                    'company_contribution_percentage': company_contribution.percentage,
                    'company_contribution_amount': company_contribution.amount,'sal_amount':pf_values.sal_amount}
        else:
            data = {'contribution_structure_name': None,
                    'paycomponent':None,
                    'company_contribution_percentage':None,
                    'company_contribution_amount':None}
        return data

    def get_employee_pf_data(self,id_arr):
        pf_info=EmployeePFStructure.objects.using(self._current_app_schema()).filter(id__in=id_arr,status=Activestatus.active).values('name', 'code', 'percentage', 'amount', 'id','sal_amount')
        return pf_info

    def get_paycomponent_flag_val(self, id_data):
        component_info = PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(status=Activestatus.active, map_id__in=id_data['id']).values('map_id', 'ref_id')
        return component_info

    def list_of_map_id_val(self,map_id):
        flag_master = list(PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(map_id=map_id,status=Activestatus.active).values_list('ref_id', flat=True))
        return flag_master

    def cc_epf_based_paycom(self, map_id, ref_type):
        flag_data = list(PaycomponentFlagmaster.objects.using(self._current_app_schema()).filter(map_id=map_id, ref_type=ref_type, status=Activestatus.active).values_list('ref_id', flat=True))
        return flag_data

    def payrollmaster_paycomflag_upload(self,flagmaster_data, user_id,ref_type,map_id):
        try:
            resp = NWisefinSuccess()
            if ref_type is FlagRef_Type.PAYROLLTEMPLATE:
                ref_id=SegmentMasterService(self._scope()).get_segment_name(flagmaster_data['SEGMENT'])
            else:
                ref_id = PayrollComponentService(self._scope()).get_payrollcomponent_val(flagmaster_data['PAYCOMPONENT'])
            flag_data = PaycomponentFlagmaster.objects.using(self._current_app_schema()).create(map_id=map_id,
                                                                                                ref_id=ref_id,
                                                                                                ref_type=ref_type,
                                                                                                created_by=user_id,
                                                                                                entity_id=self._entity_id())

            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            resp.ref_id = ref_id
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            return obj

class SegmentMasterService(NWisefinThread):
    def __init__(self, scope):
        super().__init__(scope)
        self._set_namespace(ApplicationNamespace.MASTER_SERVICE)

    def create_segmentmaster(self, smr_obj, emp_id):
        resp = NWisefinSuccess()
        # if smr_obj.get_id() is not None:
        #     condition= Q(status=Activestatus.active) & ~Q(id=smr_obj.get_id())
        # else:
        #     condition = Q(status=Activestatus.active)
        # categatory_percentage_limit = list(Segment.objects.using(self._current_app_schema()).filter(condition, component_type_id=smr_obj.get_component_type()).values_list('percentage',flat=True))
        # sum_percentage= sum(categatory_percentage_limit)
        # percentage_limit = abs(100-sum_percentage)
        # valid_percentage = float(sum_percentage)+float(smr_obj.get_percentage())
        # if valid_percentage <= 100:
        if smr_obj.get_id() is not None:
            smr_create = Segment.objects.using(self._current_app_schema()).filter(id=smr_obj.get_id()).update(name=smr_obj.get_name(),
                                             component_type_id=smr_obj.get_component_type(),
                                             type=smr_obj.get_type(),
                                             percentage=smr_obj.get_percentage(),
                                             updated_by=emp_id,
                                             updated_date=timezone.now(),
                                             glno=smr_obj.get_glno())

            smr_create = Segment.objects.using(self._current_app_schema()).get(id=smr_obj.get_id())
            message = SuccessMessage.UPDATE_MESSAGE
        else:
            smr_create = Segment.objects.using(self._current_app_schema()).create(name=smr_obj.get_name(),
                                                 component_type_id=smr_obj.get_component_type(),
                                                 type=smr_obj.get_type(),
                                                 percentage=smr_obj.get_percentage(),
                                                 created_by=emp_id,
                                                 entity_id=self._entity_id(),
                                                 glno=smr_obj.get_glno())
            message = SuccessMessage.CREATE_MESSAGE
        resp.set_status(SuccessStatus.SUCCESS)
        resp.set_message(message)
        return resp
        # else:
        #     error = NWisefinError()
        #     error.set_message(ErrorMessage.ERROR)
        #     error.set_description('Category Type Percentage Must be 100')
        #     return error



    def segmentmaster_summary(self, request, vys_page):
        condition = Q(status=Activestatus.active) & Q(entity_id=self._entity_id())
        name = request.GET.get('name')
        if name != None and name != "":
            condition &= Q(name__icontains=name)
        sm_list = Segment.objects.using(self._current_app_schema()).filter(condition)[vys_page.get_offset():vys_page.get_query_limit()]
        component = [i.component_type_id for i in sm_list]
        component_data = ComponentTypeService(self._scope()).get_multiple_component_type(component)
        list_data = NWisefinList()
        if sm_list.count() > 0:
            for segment in sm_list:
                resp = SegmentMasterResponse()
                resp.set_id(segment.id)
                resp.set_name(segment.name)
                resp.set_component_type_val(segment.component_type_id, component_data)
                resp.set_type(segment.type)
                resp.set_percentage(segment.percentage)
                resp.set_glno(segment.glno)
                list_data.append(resp)
                v_page = NWisefinPaginator(sm_list, vys_page.get_index(), 10)
                list_data.set_pagination(v_page)
            return list_data
        else:
            return list_data

    def get_segmentmaster(self, id):
        try:
            sm_list = Segment.objects.using(self._current_app_schema()).filter(status=Activestatus.active, id=id).first()
            if not sm_list:
                error = NWisefinError()
                error.set_code(ErrorMessage.INVALID_DATA)
                error.set_description(ErrorDescription.INVALID_DATA)
                return error
            resp = SegmentMasterResponse()
            resp.set_id(sm_list.id)
            resp.set_name(sm_list.name)
            component_data = ComponentTypeService(self._scope()).get_multiple_component_type([sm_list.component_type_id])
            resp.component_type = component_data
            resp.set_type(sm_list.type)
            resp.set_glno(sm_list.glno)
            resp.set_percentage(sm_list.percentage)
            return resp
        except:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error


    def inactive_segmentmaster(self, id):
        seg = Segment.objects.using(self._current_app_schema()).filter(id=id).update(status=Activestatus.inactive)
        if seg != 0:
            success = NWisefinSuccess()
            success.set_status(SuccessStatus.SUCCESS)
            success.set_message(SuccessMessage.DELETE_MESSAGE)
            return success
        else:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error

    def get_multiple_segment_data(self, id_data):
        obj = Segment.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_data)
        component = [i.component_type_id for i in obj]
        component_data = ComponentTypeService(self._scope()).get_multiple_component_type(component)
        list_data = []
        for i in obj:
            data_resp = SegmentMasterResponse()
            data_resp.set_id(i.id)
            data_resp.set_name(i.name)
            data_resp.set_component_type_val(i.component_type_id, component_data)
            data_resp.set_type(i.type)
            data_resp.set_percentage(i.percentage)
            list_data.append(data_resp)
        return list_data

    def segment_details_data(self, id_data):
        obj = Segment.objects.using(self._current_app_schema()).filter(status=Activestatus.active,id__in=id_data)
        component = [i.component_type_id for i in obj]
        component_data = ComponentTypeService(self._scope()).get_multiple_component_type(component)
        list_data = []
        for i in obj:
            data_resp = SegmentMasterResponse()
            data_resp.set_id(i.id)
            data_resp.set_name(i.name)
            data_resp.set_component_type_data(i.component_type_id, component_data)
            data_resp.set_type_val(i.type)
            data_resp.set_percentage(i.percentage)
            list_data.append(data_resp)
        return list_data

    def get_segment_name(self, name):
        prm_list = Segment.objects.using(self._current_app_schema()).filter(status=Activestatus.active,name=name)[0]
        return prm_list.id


    def segment_for_structure_get(self, id_data, paycomponent_dta,unique_segment_info):
        try:
            obj = Segment.objects.using(self._current_app_schema()).get(id=id_data)
            segment_percentage = unique_segment_info[obj.id] if unique_segment_info else None
            data = {"paycomponent_type": obj.component_type.name, "segment_id": obj.id,
                    "segment_name": obj.name, "segment_percentage": segment_percentage, "component_category_type" : category_val(obj.component_type.category)['category'],
                    "paycomponent_data": paycomponent_dta}
        except:
            data = {"paycomponent_type": None, "segment_id": None,"segment_name": None, "segment_percentage": None, "component_category_type" : None,
                    "paycomponent_data": None}
        return data

    def get_segment_name_ids(self, query):
        condition = Q(status=Activestatus.active)
        if query != None and query != "":
            condition &= (Q(name__icontains=query))
        obj = list(Segment.objects.using(self._current_app_schema()).filter(condition).values_list('id', flat=True))
        return obj



    def payrollmaster_segment_upload(self,segment_data, user_id):
        try:
            resp = NWisefinSuccess()
            type = payrolldeduction_val(segment_data['TYPE'])['id']
            component_type_id = ComponentTypeService(self._scope()).get_componenttype_name(segment_data['COMPONENT_TYPE'])
            smr_create = Segment.objects.using(self._current_app_schema()).create(name=segment_data['NAME'],
                                                                                  component_type_id=component_type_id,
                                                                                  type=type,
                                                                                  percentage=segment_data['PERCENTAGE'],
                                                                                  created_by=user_id,
                                                                                  entity_id=self._entity_id())
            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            return obj

class payrollGradeService(NWisefinThread):
    def __init__(self, scope):
        super().__init__(scope)
        self._set_namespace(ApplicationNamespace.MASTER_SERVICE)


    def create_grade(self, grade_request, emp_id):
        grade_create = {"id":grade_request.get_id(),"name":grade_request.get_name(),"points":grade_request.get_points(),"min_amount":grade_request.get_min_amount(),
                        "max_amount":grade_request.get_max_amount(),"emp_id":emp_id}
        data_dict = {'grade_request':grade_create}
        grade_create = HrmsApiService(self._scope()).create_grade(data_dict)
        if grade_create is not None:
            return grade_create
        else:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(ErrorDescription.INVALID_DATA)
            return obj

        # resp = NWisefinSuccess()
        # if grade_request.get_id() is not None:
        #     grade_create = Grade.objects.using(self._current_app_schema()).filter(id=grade_request.get_id()).update(name=grade_request.get_name(),
        #                                      points=grade_request.get_points(),
        #                                      min_amount=grade_request.get_min_amount(),
        #                                      max_amount=grade_request.get_max_amount(),
        #                                      updated_by=emp_id,
        #                                      updated_date=timezone.now())
        #
        #     grade_create = Grade.objects.using(self._current_app_schema()).get(id=grade_request.get_id())
        #     message = SuccessMessage.UPDATE_MESSAGE
        # else:
        #     grade_create = Grade.objects.using(self._current_app_schema()).create(name=grade_request.get_name(),
        #                                                                   points=grade_request.get_points(),
        #                                                                   min_amount=grade_request.get_min_amount(),
        #                                                                   max_amount=grade_request.get_max_amount(),
        #                                                                   created_by=emp_id,
        #                                                                   entity_id=self._entity_id())
        #
        #     code_ger = CodeGen(self._scope())
        #     code = code_ger.codegenerator(Code_Gen_Type.GRADE, self._entity_id(), emp_id,Code_Gen_Value.GRADE)
        #     grade_create.code = code
        #     grade_create.save()
        #     message = SuccessMessage.CREATE_MESSAGE
        #
        # resp.set_status(SuccessStatus.SUCCESS)
        # resp.set_message(message)
        # return resp


    def summary_grade(self,request, vys_page,page=None):
        # condition = Q(status=Activestatus.active) & Q(entity_id=self._entity_id())
        # name = request.GET.get('name')
        # if name != None and name != "":
        #     condition &= Q(name__icontains=name)
        # grade_get = Grade.objects.using(self._current_app_schema()).filter(condition)[vys_page.get_offset():vys_page.get_query_limit()]
        data_dict = {"name":request.GET.get('name'),'page':page}
        grade_get = HrmsApiService(self._scope()).grade_summary_get(data_dict)
        if isinstance(grade_get, dict):
            grade_get = json.dumps(grade_get)
        else:
            grade_get = dict()
        return grade_get
        # grade_list = NWisefinList()
        # # if grade_get.get('grade') is not None and grade_get > 0:
        # if grade_get is not None and len(grade_get) > 0:
        #     for grade_data in grade_get.get('grade'):
        #         get_resp = GradeResponse()
        #         get_resp.set_id(grade_data.get('id'))
        #         get_resp.set_name(grade_data.get('name'))
        #         get_resp.set_code(grade_data.get('code'))
        #         get_resp.set_is_active(grade_data.get('is_active'))
        #         get_resp.set_points(grade_data.get('points'))
        #         get_resp.set_min_amount(grade_data.get('min_amount'))
        #         get_resp.set_max_amount(grade_data.get('max_amount'))
        #         grade_list.append(get_resp)
        #     vpage = NWisefinPaginator(grade_get, vys_page.get_index(), 10)
        #     grade_list.set_pagination(vpage)
        #     return grade_list
        # else:
        #     return grade_list


    def get_grade_details(self, id):
        try:
            grade_list = HrmsApiService(self._scope()).get_grade_by_id({"id":id,"status":Activestatus.active})
            # grade_list = Grade.objects.using(self._current_app_schema()).filter(status=Activestatus.active, id=id)[0]
            resp = GradeResponse()
            resp.set_id(grade_list.get('id'))
            resp.set_name(grade_list.get('name'))
            resp.set_code(grade_list.get('code'))
            resp.set_is_active(grade_list.get('is_active'))
            resp.set_points(grade_list.get('points'))
            resp.set_min_amount(grade_list.get('min_amount'))
            resp.set_max_amount(grade_list.get('max_amount'))
            return resp
        except:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error


    def grade_inactive(self, id):
        data_dict = {'id':id,'status':Activestatus.inactive}
        grade_val = HrmsApiService(self._scope()).grade_inactive(data_dict)
        # grade_val = Grade.objects.using(self._current_app_schema()).filter(id=id).update(status=Activestatus.inactive)
        if grade_val != 0:
            success = NWisefinSuccess()
            success.set_status(SuccessStatus.SUCCESS)
            success.set_message(SuccessMessage.DELETE_MESSAGE)
            return success
        else:
            error = NWisefinError()
            error.set_code(ErrorMessage.INVALID_DATA)
            error.set_description(ErrorDescription.INVALID_DATA)
            return error


    def payrollmaster_grade_upload(self, grade_data, user_id):
        try:
            resp = NWisefinSuccess()
            if grade_data['MIN_AMOUNT'] is None:
                min_amount = 0.00
            else:
                min_amount = grade_data['MIN_AMOUNT']
            if grade_data['MAX_AMOUNT'] is None:
                max_amount = 0.00
            else:
                max_amount = grade_data['MAX_AMOUNT']

            data_dict ={"grade_request" :{"name":grade_data.get('name'),"points":grade_data.get('points'),"min_amount":min_amount,
                        "max_amount":max_amount,"emp_id":user_id}}

            grade_res = HrmsApiService(self._scope()).create_grade(data_dict)
            if grade_res is not None:
                return grade_res
            else:
                obj = NWisefinError()
                obj.set_code(ErrorMessage.INVALID_DATA)
                obj.set_description(ErrorDescription.INVALID_DATA)
                return obj
            # grade_create = Grade.objects.using(self._current_app_schema()).create(name=grade_data['NAME'],
            #                                                                       points=grade_data['POINTS'],
            #                                                                       min_amount=min_amount,
            #                                                                       max_amount=max_amount,
            #                                                                       created_by=user_id,
            #                                                                       entity_id=self._entity_id())
            #
            # code_ger = CodeGen(self._scope())
            # code = code_ger.codegenerator(Code_Gen_Type.GRADE, self._entity_id(), user_id, Code_Gen_Value.GRADE)
            # grade_create.code = code
            # grade_create.save()
            # message = SuccessMessage.CREATE_MESSAGE
            # resp.set_status(SuccessStatus.SUCCESS)
            # resp.set_message(message)
            # return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            return obj

    def payrollmaster_reportcolumns_upload(self,reportcolumns_data, user_id):
        try:
            resp = NWisefinSuccess()
            prm = ReportColumns.objects.using(self._current_app_schema()).create(name=reportcolumns_data['NAME'],
                                                                                  type=reportcolumns_data['TYPE'],
                                                                                  created_by=user_id,
                                                                                  entity_id=self._entity_id())
            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            return obj

    def get_reportcolumns_name(self, name):
        reportcolumns_list = ReportColumns.objects.using(self._current_app_schema()).filter(status=Activestatus.active,name=name)[0]
        return reportcolumns_list.id


    def payollmaster_reporttemplate_upload(self,reporttemplate_data, user_id):
        try:
            resp = NWisefinSuccess()
            bank_id = Payrollcommon_Apicall(self._scope()).get_bank_namepay(reporttemplate_data['BANK'])
            prm = ReportTemplate.objects.using(self._current_app_schema()).create(name=reporttemplate_data['NAME'],
                                                                                 bank_id=bank_id,
                                                                                 created_by=user_id,
                                                                                 entity_id=self._entity_id())
            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            resp.id = prm.id
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            obj.message = "INVALID_DATA"
            return obj

    def reporttemplate_details_upload(self,flagmaster_data, user_id,temp_id):
        try:
            resp = NWisefinSuccess()
            reportscolumns = self.get_reportcolumns_name(flagmaster_data['REPORTCOLUMNS'])
            prm = ReportTemplateDetails.objects.using(self._current_app_schema()).create(report_template_id=temp_id,
                                                                                  reportcolumns_id=reportscolumns,
                                                                                  order=flagmaster_data['ORDER'],
                                                                                  created_by=user_id,
                                                                                  entity_id=self._entity_id())
            message = SuccessMessage.CREATE_MESSAGE
            resp.set_status(SuccessStatus.SUCCESS)
            resp.set_message(message)
            return resp
        except Exception as excep:
            obj = NWisefinError()
            obj.set_code(ErrorMessage.INVALID_DATA)
            obj.set_description(str(excep))
            return obj
