# -*- coding: utf-8 -*-
import json
import logging
from sqlalchemy import text

from website import db_mysql, errors
from website.handler import APIHandler, authenticated
from website.util import shortuuid
from website.db.enterprise_busi_model import enterprise_busi_model as DB_BusiModel
from website.db.file import file as DB_File


class ListHandler(APIHandler):
    """
    - 描述:企业部署的业务模型列表
    - 请求方式:post
    - 请求参数:
    > - pageNo
    > - pageSize
    > - entity_id, int, 企业id
    - 返回值:
    ```
        {
            "count": 123,
            "data": [
                {
                    "model_id": 123,  # 模型id
                    "model_name": "xxx", # 模型名称
                    "create_time": "xxxx", # 创建时间
                },
                ...
            ]
        }
    ```
    """
    @authenticated
    def post(self):
        pageNo = self.get_int_argument("pageNo", 1)
        pageSize = self.get_int_argument("pageSize", 10)
        entity_id = self.get_int_argument("entity_id")
        if not entity_id:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")

        db_busimodel = DB_BusiModel.EnterpriseBusiModelRepository()
        result = db_busimodel.list_enterprise_busi_model(entity_id=entity_id, page_no=pageNo, page_size=pageSize)
        self.finish({"count": result["count"], "data": result["data"]})


class AddHandler(APIHandler):
    """
    - 描述:添加企业部署的业务模型
    - 请求方式:post
    - 请求参数:
    > - entity_id, int, 企业id
    > - name, string, 业务模型名称
    > - comment, string, 简介
    > - basemodel_ids, string, 基础模型id, 多个使用逗号分割
    > - business_logic, string, 业务代码压缩包的md5
    > - business_conf_file, string, 业务配置压缩包的文件md5
    > - business_conf_param, string, 业务配置的参数,json字符串,eg: '{"a":1, "b":2}'
    > - link_node_ids, string, 关联节点id, 多个节点逗号分割
    - 返回值:无
    """
    @authenticated
    def post(self):
        entity_id = self.get_int_argument("entity_id")
        name = self.get_escaped_argument("name", "")
        comment = self.get_escaped_argument("comment", "")
        basemodel_ids = self.get_escaped_argument("basemodel_ids", "")
        business_logic = self.get_escaped_argument("business_logic", "")
        business_conf_file = self.get_escaped_argument("business_conf_file", "")
        business_conf_param = self.get_escaped_argument("business_conf_param", "")
        link_node_ids = self.get_escaped_argument("link_node_ids", "")
    
        if not entity_id or not name or not basemodel_ids:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
    
        if not business_logic:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "业务代码参数错误")
        
        if not business_conf_file and not business_conf_param:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "业务配置参数错误")
        
        if not link_node_ids:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "关联节点参数错误")

        model_data = {
            "entity_id": entity_id,
            "name": name,
            "comment": comment,
            "basemodel_ids": basemodel_ids,
            "business_logic": business_logic,
            "business_conf_file": business_conf_file,
            "business_conf_param": business_conf_param,
            "link_node_ids": link_node_ids,
        }

        db_busimodel = DB_BusiModel.EnterpriseBusiModelRepository()
        busimodel_id, busimodel_suid = db_busimodel.insert_busi_model(model_data)

        model_node_data = {
            "entity_id": entity_id,
            "busimodel_id": busimodel_id,
            "busimodel_suid": busimodel_suid,
            "node_ids": link_node_ids
        }
        db_model_node = DB_BusiModel.EnterpriseBusiModelNodeRepository()
        db_model_node.insert_busi_model_nodes(model_node_data)

        self.finish()


class InfoHandler(APIHandler):
    """
    - 描述:企业部署的业务模型详情
    - 请求方式:post
    - 请求参数:
    > - id, int, 业务模型id
    - 返回值:
    ```
        {
            "name": "xxx", 
            "comment": "xxx",
            "basemodel_list": "xxx,xx,xx",
            "business_logic": "xxx",
            "business_conf_file": "xxx",
            "business_conf_param": "xxx",
            "link_node_list": "xxx,xx,xx"
        }
    ```
    """
    @authenticated
    def post(self):
        busimodel_id = self.get_int_argument("id")
    
        if not busimodel_id:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
    
        db_busimodel = DB_BusiModel.EnterpriseBusiModelRepository() 
        busi_model_data = db_busimodel.get_busi_model_by_id(busimodel_id)

        if not busi_model_data:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "业务模型不存在")

        db_file = DB_File.FileRepository()
        files = db_file.get_file_by_md5([busi_model_data.business_conf_file, busi_model_data.business_logic])
        business_conf_name = files[0].filename
        business_logic_name = files[1].filename

        # business_conf_name = db_file.get_file_by_md5(busi_model_data.business_conf_file)
        # business_logic_name = db_file.get_file_by_md5(busi_model_data.business_logic)
        basemodel_list = json.loads(busi_model_data.basemodel)

        db_model_node = DB_BusiModel.EnterpriseBusiModelNodeRepository()
        link_nodes = db_model_node.get_nodes_by_busi_model(busimodel_id)
        link_node_list = []
        for node in link_nodes:
            link_node_list.append({"node_id": node.node_id, "node_name": node.node_name})

        self.finish({
            "name": busi_model_data.name, 
            "comment": busi_model_data.comment,
            "basemodel_list":basemodel_list,   # 关联模型
            "business_logic_name": business_logic_name,    # 业务代码压缩包文件名
            "business_logic_md5": busi_model_data.business_logic,     # 业务代码压缩包md5
            "business_conf_name": business_conf_name,     # 业务参数配置文件名
            "business_conf_md5": busi_model_data.business_conf_file,    # 业务参数配置md5
            "business_conf_param": busi_model_data.business_conf_param,    # 业务参数配置的字段
            "link_node_list": link_node_list    # 关联节点的id,多个id逗号分割
        })


class EditHandler(APIHandler):
    """
    - 描述:企业部署的业务模型编辑
    - 请求方式:post
    - 请求参数:
    > - id, int, 业务模型的id
    > - name, string, 业务模型名称
    > - comment, string, 简介
    > - basemodel_ids, string, 基础模型id, 多个使用逗号分割
    > - business_logic, string, 业务代码压缩包的md5
    > - business_conf_file, string, 业务配置压缩包的文件md5
    > - business_conf_param, string, 业务配置的参数,json字符串,eg: '{"a":1, "b":2}'
    > - link_node_ids, string, 关联节点id, 多个节点逗号分割
    - 返回值:无
    """
    @authenticated
    def post(self):
        busimodel_id = self.get_argument("id")
    
        if not busimodel_id:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
    
        db_busimodel = DB_BusiModel.EnterpriseBusiModelRepository()
        busi_model_data = db_busimodel.get_busi_model_by_id(busimodel_id)
        if not busi_model_data:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "业务模型不存在")
    
        name = self.get_escaped_argument("name", "")
        comment = self.get_escaped_argument("comment", "")
        basemodel_ids = self.get_escaped_argument("basemodel_ids", "")
        business_logic = self.get_escaped_argument("business_logic", "")
        business_conf_file = self.get_escaped_argument("business_conf_file", "")
        business_conf_param = self.get_escaped_argument("business_conf_param", "")
        link_node_ids = self.get_escaped_argument("link_node_ids", "")
    
        if not name or not basemodel_ids:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
    
        if not business_logic:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "业务代码参数错误")
        
        if not business_conf_file and not business_conf_param:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "业务配置参数错误")
        
        if not link_node_ids:
            raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "关联节点参数错误")

        # 更新业务模型
        model_data = {
            "id": busimodel_id,
            "name": name,
            "comment": comment,
            "basemodel_ids": basemodel_ids,
            "business_logic": business_logic,
            "business_conf_file": business_conf_file,
            "business_conf_param": business_conf_param,
            "link_node_ids": link_node_ids,
        }

        db_busimodel.edit_busi_model(model_data)

        # 获取业务模型的数据
        busi_model = db_busimodel.get_busi_model_by_id(busimodel_id)

        db_model_node = DB_BusiModel.EnterpriseBusiModelNodeRepository()

        # 删除关联节点
        db_model_node.delete_by_busi_model_id(busimodel_id)

        # 插入关联节点
        model_node_data = {
            "entity_id": busi_model.entity_id,
            "busimodel_id": busimodel_id,
            "busimodel_suid": busi_model.suid,
            "node_ids": link_node_ids
        }
        db_model_node.insert_busi_model_nodes(model_node_data)

        self.finish()