import random
import datetime
from odoo import api, models, fields
from odoo.exceptions import UserError, ValidationError
import logging
_logger = logging.getLogger(__name__)

class LogSyncHandleModel(models.Model):

    _name = "log.sync.handle.model"
    _description = "日志生成"


    model_name = fields.Char(string="模块名称")
    model_type = fields.Char(string="模块类型")


    def add_log(self):
        if self.model_name == "roke.mes.stock.picking" and self.model_type:
            try:
                values = self.env[self.model_name].sudo().search([("picking_logotype", "=", self.model_type)])
            except:
                raise ValidationError("输入模型名字或者类型错误,请重新输入!")
        else:
            try:
                values = self.env[self.model_name].sudo().search([])
            except:
                raise ValidationError("输入模型错误,请重新输入!")

        for value in values:
            # if value.state == "确认":
            #     continue

            # 将 状态变为 确认  只有 销售订单 和 采购订单 才需要处理
            if self.model_name == "roke.sale.order":
                if value.state != "确认":
                    value.status_confirm()
            elif self.model_name == "roke.purchase.order":
                if value.state != "确认":
                    value.make_confirm()
            # 更改日志的创建时间  创建人修改 author_id 字段   时间修改 data
            mail_messages = self.env["mail.message"].sudo().search(
                [("res_id", "=", value.id), ("model", "=", self.model_name)])
            for mail_message in mail_messages:
                if mail_messages[-1] == mail_message:
                    mail_message.write({"date": value.create_date})
                    continue
                mail_message.unlink()
            # self.env["mail.message"].sudo().create({
            #     "model": self.model_name,
            #     "res_id": value.id,
            #     "author_id": value.create_uid.id,
            #     "date": value.create_date,
            #     "body": value._description + " 生成" if value._description else "创建成功",
            # })