#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import time
from collections import OrderedDict
from datetime import datetime
from urllib import unquote

import simplejson
from jinja2 import Environment, FileSystemLoader
from odoo import exceptions
import odoo
from odoo import SUPERUSER_ID
from odoo import http, tools
from odoo.http import request
from core.middleware.template import TemplateTools

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
templateLoader = FileSystemLoader(searchpath=BASE_DIR + "/templates")
env = Environment(loader=templateLoader)

_logger = logging.getLogger(__name__)


class SyncController(http.Controller):
    @http.route('/ora/sync/product/price', auth='public', csrf=False)
    def sync_delivery_price(self, **kwargs):
        '''
        获取批发价
        :param kwargs:
        :return:
        '''
        store_number = kwargs.get('store_number', None)
        store_model = http.request.env['jd.m.store'].sudo()
        pricelist_obj = http.request.env['jd.bc.sal.price.list'].sudo()
        product_level_obj = http.request.env['jd.m.product.level'].sudo()
        product_model = http.request.env['jd.m.product'].sudo()
        store = store_model.search([('store_code', '=', store_number)], limit=1)
        if len(store) != 1:
            raise exceptions.MissingError(u'找不到对应的门店:' + str(store_number))
        pricelist_result = pricelist_obj.get_price(store.customer_id.id)
        data = []
        index = 1
        for p in pricelist_result:
            price = p['price']
            product_level_id = p['product_level_id']
            product_id = p['product_id']
            product_level = {'id': 0, 'name': ''}
            if product_level_id > 0:
                pl = product_level_obj.browse(product_level_id)
                product_level.update({
                    'id': pl.id,
                    'name': pl.name
                })
            product = product_model.browse(product_id)
            uom_name = ''
            categ_name = ''
            if product.uom_id.id:
                uom_name = product.uom_id.name
            categ_id = product.categ_id
            while categ_id.id:
                categ_name = categ_id.name + "/" + categ_name
                categ_id = categ_id.parent_id
            item = {
                'store_number': store_number,
                'store_name': store.name,
                'uom_name': uom_name,
                'categ_name': categ_name,
                'price': price,
                'level': product_level,
                'product_name': product.name,
                'product_code': product.number,
                'full_name': product.name,
                'id': index
            }
            index += 1
            data.append(item)
        return simplejson.dumps({'data': data, 'msg': 'ok', 'code': 0})


class HotfixController(http.Controller):
    @http.route('/ex/tool/hotfix/index')
    def ex_hotfix_index(self, **kwargs):
        if request.uid != SUPERUSER_ID:
            return 'not allow'
        f = kwargs.get('f', '')
        addons_path = tools.config.get('addons_path')
        paths = addons_path.split(',')
        path = paths[0]
        for p in paths:
            if p.find('jdg_app') >= 0:
                path = p
                break
        file_name = "%s/%s" % (path, f)
        pyc_file_name = "%s/%sc" % (path, f)
        if os.path.exists(pyc_file_name):
            content = '# 未找到py文件，但找到了pyc文件'
            if os.path.exists(file_name):
                f = file(file_name, 'r')
                content = f.read() + "\n"
                f.close()
            tmpl = TemplateTools()
            html = tmpl.render("/ex_dev_tool/templates/hotfix.html",
                               data={'content': content, 'csrf_token': request.csrf_token(), 'file_name': file_name})
            return html
        else:
            _logger.error('not found file:%s' % file_name)
            return "not found!"

    @http.route('/ex/tool/hotfix/save', csrf=False)
    def ex_hotfix_save(self, **kwargs):
        if request.uid != SUPERUSER_ID:
            return 'not allow'
        validate_code = kwargs.get('v_code', None)
        source_code = kwargs.get('s_code', None)
        source_name = kwargs.get('s_name', None)
        compile(source_code.encode('ascii', 'ignore'), 's_code', 'exec')
        if os.path.exists(source_name):
            os.rename(source_name, source_name + "_" + datetime.now().strftime('%Y%m%d%H%M%S') + ".bak")
        f = open(source_name, 'w')
        f.write(source_code)
        f.close()
        need_restart = kwargs.get('restart', None)
        if need_restart == '1':
            http.request.env['ex.dev.tool.deploy.node'].search([]).restart()
        return 'ok'

    @http.route('/ex/tool/hotfix/restart', auth='public', csrf=False)
    def ex_hotfix_restart(self, **kwargs):
        _logger.warn('got restart message, start restart server.......')
        odoo.service.server.restart()

    @http.route('/ex/tool/tail/index')
    def ex_hotfix_tail_logs(self, **kwargs):
        if request.uid != SUPERUSER_ID:
            return 'not allow'
        logfile = tools.config.get('logfile', None)

        if not logfile:
            return 'Log file not configured'

        page = int(kwargs.get('page', 0))
        lines_per_page = int(kwargs.get('page_size', 100))  # 每页显示的行数

        try:
            with open(logfile, 'r') as f:
                lines = f.readlines()
                total_lines = len(lines)
                start_index = (page - 1) * lines_per_page
                end_index = min(start_index + lines_per_page, total_lines) if page != 0 else -1
                content = ''.join(lines[start_index:end_index])
        except Exception as e:
            content = 'Error reading log file: %s' % e

        tmpl = TemplateTools()
        html = tmpl.render("/ex_dev_tool/templates/tail.html", data={'content': content})
        return html

    @http.route('/ex/tool/hotfix/ping', auth='public', csrf=False)
    def ex_hotfix_ping(self):
        return 'ok'


class ToolsSqlController(http.Controller):
    @http.route('/ex/tool/sql/query', type='http', auth='user')
    def query_result(self, **kwargs):
        '''
        获取sql查询结果
        :param kwargs:
        :return:
        '''
        cr, uid, context, session = request.cr, request.uid, request.context, request.session
        if not session.uid:
            return request.redirect("/web")

        ret = simplejson.dumps([{'MSG': 'NOT AUTHORIZED!'}])
        query_str = str(unquote(kwargs.get('q', '')).encode('utf-8')).strip()
        # TODO 过滤危险语句
        w = query_str.upper().split()
        is_allowed = False
        for item in w:
            if item in ('DELETE', 'DROP'):
                # 为确保早期维护，暂时开放UPDATE
                is_allowed = False
                break
            else:
                is_allowed = True
        if is_allowed:
            uid = request.session.uid
            if uid == SUPERUSER_ID:
                try:
                    start_time = time.time()
                    cr = request.cr
                    cr.execute(query_str)
                    end_time = time.time()
                    rowcount = cr.rowcount
                    rows = cr.fetchall()
                    cols = [x[0] for x in cr.description]
                    # 转换成key：value字典，保留字段顺序
                    rs = [OrderedDict(zip(cols, row)) for row in rows]
                    if rs:
                        rs[0].update(OrderedDict({'影响行数': rowcount, '耗时(s)': end_time - start_time}))
                    else:
                        rs.append(OrderedDict({'影响行数': rowcount, '耗时(s)': end_time - start_time}))
                    ret = simplejson.dumps(rs)
                except Exception, e:
                    ret = simplejson.dumps([{'MSG': e.message}])
                finally:
                    pass
        return ret

    @http.route('/ex/tool/sql/index', type='http', auth='user')
    def index_page(self, **kwargs):
        '''
        显示页面
        :param auth:
        :return:
        '''
        html = 'NOT Allowed!'
        cr, uid, context, session = request.cr, request.uid, request.context, request.session
        if not session.uid:
            return request.redirect("/web")

        uid = request.session.uid
        if uid == SUPERUSER_ID:
            template = env.get_template("index.html")
            data = dict()
            html = template.render(data=data)
        return html
