# -*- 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, IfaCustomerView, CustomerView


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(IfaCustomerView.customer_id).filter(and_(
            IfaCustomerView.ifa_id == ifa_id,
            IfaCustomerView.delete_tag == 0,
        )).all()
        customer_id_list = [r[0] for r in customer_id_list]
        conditions = [
            CustomerView.id.in_(customer_id_list),
            CustomerView.delete_tag == 0,
        ]
        if name:
            conditions.append(CustomerView.customer_name.like('%' + name + '%'))
        customer_list = tamp_diagnose_session.query(CustomerView).filter(and_(
            *conditions
        )).all()
        allow_field = ['id', 'customer_name', 'valueSex', 'phone']
        return [r.to_dict(allow_field) for r in customer_list]
