# -*- coding: utf-8 -*-

from application.app import db, ma
from .base import PrimaryModel
{%- if extend %} {# 判断是否有扩展字段，也就是model对象不包含的字段，因为查询里面还有page和pageSize等这两种字段 #}
from marshmallow import Schema, fields, INCLUDE, EXCLUDE
{%- endif %}

class {{ config['name'] | letterUpper }}Model(PrimaryModel):
    __tablename__ = '{{ application["tablePrefix"] }}{{ config['name'] }}'
{% for value in config['model']['fields'] %}
{%- if value.get('primaryKey', None) %}
<<<<<<< HEAD
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}, primary_key = True, {% if value.get('autoIncrement') %}autoincrement = True{% endif %})
{%- elif value.get('dataType') == "Int" or value.get('dataType') == "Integer" %}
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}{% if value.get("length", None) %}{% endif %}{% if value.get("index", False) %}, index = True{% endif %}{% if value.get("default", None) %}, default = {{value.get("default")}}{% endif %})
{%- else %}
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}{% if value.get("length", None) %}({{value.get("length")}}){% endif %}{% if value.get("index", False) %}, index = True{% endif %}{% if value.get("default", None) %}, default = {{value.get("default")}}{% endif %})
=======
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}, primary_key = True)
{%- elif value.get('dataType') == "Int" or value.get('dataType') == "Integer" %}
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}{% if value.get("length", None) %}{% endif %}{% if value.get("index", False) %}, index = True{% endif %}{% if value.get("required", False) %}, nullable = False{% else %}, nullable = True{% endif %}{% if value.get("default", None) %}, default = {{value.get("default")}}{% endif %})
{%- else %}
    {{ value.get('name') }} = db.Column(db.{{ value.get('dataType') }}{% if value.get("length", None) %}({{value.get("length")}}){% endif %}{% if value.get("index", False) %}, index = True{% endif %}{% if value.get("required", False) %}, nullable = False{% else %}, nullable = True{% endif %}{% if value.get("default", None) %}, default = {{value.get("default")}}{% endif %})
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
{%- endif %}
{%- endfor %}

    # __table_args__ = (
    #     db.Index('idx_xxx', 'xxx', mysql_using='btree'),
    # )

    def __init__(self{% for value in config['model']['fields'] %}, {{ value.get("name") }}{% endfor %}):
{%- for value in config['model']['fields'] %}
        self.{{ value.get("name") }} = {{ value.get("name") }}
{%- endfor %}

    def __repr__(self):
        return '<{{ config['name'] | letterUpper }}Model %r>' % (self.{{ config['model']['fields'][0]["name"] }})

    def to_json(self):
        return {
        {%- for item in config['model']['fields'] %}
        {%- if item.get("toJson") %}
            '{{ item.get("name") }}': self.{{ item.get("name") }},
        {%- endif %}
        {%- endfor %}
        }

{% for key, value in config["view"].items() %}
class {{ key | letterUpper }}{{ config['name'] | letterUpper }}Schema(ma.SQLAlchemySchema):
    class Meta:
        # unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
        # unknown = EXCLUDE # 未知字段默认排除
=======
        unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
        model = {{ config['name'] | letterUpper }}Model
{%- if config['model']['foreignKey'] %}
        include_fk = {{ config['model']['foreignKey'] }}
{% endif %}
{# 
    这里需要判断下，如果是数据库表的字段，则使用auto_field()，否则应该使用json配置中的字段信息 

    class BandMembersSchema(Schema):
        # missing用来指定反序列化时默认缺省值，default用来指定序列化时默认缺省值
        # 在通常的web api中，dump_only和load_only参数就类似于“read-only”和“write-only”字段
        id = fields.UUID(missing=uuid.uuid1)
        name = fields.String(required=True, validate=validate.Length(min=1)) # 更多校验类型，移步：https://marshmallow.readthedocs.io/en/stable/api_reference.html#api-validators
        email = fields.Email(data_key="emailAddress") # 解决序列化与反序列化字段不一致问题
        birthdate = fields.DateTime(default=dt.datetime(2017, 9, 29))
        city = fields.String(
            required=True,
            error_messages={"required": {"message": "City required", "code": 400}},
        )
        age = fields.Int(validate=validate.Range(min=18, max=40))
        permission = fields.Str(validate=validate.OneOf(["read", "write", "admin"]))
        password = fields.Str(load_only=True) # password is "write-only"
        created_at = fields.DateTime(dump_only=True) # created_at is "read-only"

#}
{%- for p in value['params'] %}
<<<<<<< HEAD
{%- if p.get("name") in fields %}
=======
{%- if p.get("priority") %}
    {{ p.get("name") }} = fields.{{ p.get("dataType") }}(required={{ p.get("required") }}{%- if p.get("dataType") == "String" %}, length={{ p.get("length") }}{%- endif %})
{%- elif p.get("name") in fields %}
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
    {{ p.get("name") }} = ma.auto_field()
{%- else %}
    {{ p.get("name") }} = fields.{{ p.get("dataType") }}(required={{ p.get("required") }}{%- if p.get("dataType") == "String" %}, length={{ p.get("length") }}{%- endif %})
{%- endif %}
{%- endfor %}

{{ key }}{{ config['name'] | letterUpper }}Schema = {{ key | letterUpper }}{{ config['name'] | letterUpper }}Schema()
<<<<<<< HEAD
{%- if key == "post" %}
=======
{%- if key == "getList" %}
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
{{ key }}{{ config['name'] | letterUpper }}sSchema = {{ key | letterUpper }}{{ config['name'] | letterUpper }}Schema(many=True)
{%- endif %}
{% endfor %}