import datetime

from odoo import http, tools
import os

from jinja2 import FileSystemLoader, Environment
import logging
_logger = logging.getLogger(__name__)

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
templateloader = FileSystemLoader(searchpath=BASE_DIR + "/static/src/js")
env = Environment(loader=templateloader)


class ProductIncomeExpenseIframe(http.Controller):

    @http.route("/roke/pub/product_income_expense_iframe", type="http", auth='user', cors='*', csrf=False)
    def product_income_expense_iframe(self, **kwargs):
        _self = http.request
        user_id = _self.env.user.id
        user_name = _self.env.user.name
        template = env.get_template('index.html')
        data = {"code": 1, "message": "请求通过", "user_id": user_id, "user_name": user_name}
        return template.render(data)

    @http.route("/roke/product/product_income_expense/create", type="json", auth='none', cors='*', csrf=False)
    def product_income_expense_create(self):
        _self = http.request
        data_list = _self.jsonrequest.get("data_list", [])
        for v in data_list:
            data = {
                "business_date": v.get("business_date", False),
                "abstract": v.get("abstract", False),
                "income": v.get("income", False),
                "expenditure": v.get("expenditure", False)
            }
            _self.env(user=v.get("user_id"))["roke.product.income.expense"].create(data)
        return {"code": 0, "message": "创建成功！"}

    @http.route("/roke/product/product_income_expense/get", type="json", auth='none', cors='*', csrf=False)
    def product_income_expense_get_list(self):
        _self = http.request
        limit = _self.jsonrequest.get("limit", 20)
        page = _self.jsonrequest.get("page", 1)
        start_date = _self.jsonrequest.get("start_date", "")
        end_date = _self.jsonrequest.get("end_date", "")
        domain = []
        if start_date and end_date:
            domain.append(("business_date", ">=", start_date))
            domain.append(("business_date", "<=", end_date))
        data_list = _self.env["roke.product.income.expense"].sudo().search(domain, limit=limit,
                                                                           offset=(page - 1) * limit,
                                                                           order="business_date desc, create_date desc")
        count = _self.env["roke.product.income.expense"].sudo().search_count(domain)
        data = []
        for v in data_list:
            data.append({
                "id": v.id,
                "business_date": v.business_date and v.business_date.strftime('%Y-%m-%d'),
                "abstract": v.abstract or "",
                "income": v.income or 0,
                "expenditure": v.expenditure or 0,
                "balance": v.balance or 0,
                "user_name": v.create_uid.name or "",
                "create_date": (v.create_date + datetime.timedelta(hours=8)).strftime('%Y-%m-%d %H:%M'),
            })
        return {"code": 0, "message": "获取成功！", "data": data, "count": count}

    @http.route("/roke/product/product_income_expense/delete", type="json", auth='none', cors='*', csrf=False)
    def product_income_expense_delete(self):
        _self = http.request
        del_id = _self.jsonrequest.get("del_id", False)
        if not del_id:
            return {"code": 1, "message": "删除失败，没找到对应数据。"}
        data = _self.env["roke.product.income.expense"].sudo().search([("id", "=", del_id)])
        if not data:
            return {"code": 1, "message": "删除失败，没找到对应数据。"}
        data.unlink()
        return {"code": 0, "message": "删除成功!"}
