# -*- encoding: utf-8 -*-
# -----------------------------------------------------------------------------
# @File Name  : customer.py
# @Time       : 2021/1/11 下午5:53
# @Author     : X. Peng
# @Email      : acepengxiong@163.com
# @Software   : PyCharm
# -----------------------------------------------------------------------------
from sqlalchemy import and_

from app.api.engine import TAMP_SQL, tamp_diagnose_app_engine
from app.model.tamp_diagnose_app import Customer, IfaCustomer


def get_customer_list(args):
    """"""
    pageNumber = args['pageNumber']
    pageSize = args['pageSize']
    offset = (pageNumber - 1) * pageSize
    name = args.get('name')
    ifa_id = args.get('ifa_id')

    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        customer_id_list = tamp_diagnose_session.query(IfaCustomer.customer_id).filter(and_(
            IfaCustomer.ifa_id == ifa_id,
            IfaCustomer.delete_tag == 0,
        )).all()
        customer_id_list = [r[0] for r in customer_id_list]
        conditions = [
            Customer.id.in_(customer_id_list),
            Customer.delete_tag == 0,
        ]
        if name:
            conditions.append(Customer.customer_name.like('%' + name + '%'))
        customer_list = tamp_diagnose_session.query(Customer).filter(and_(
            *conditions
        )).all()
        allow_field = ['id', 'customer_name', 'valueSex', 'phone']
        return [r.to_dict(allow_field) for r in customer_list]
