from odoo import models, fields, api, _
from odoo.exceptions import UserError
import json
from datetime import datetime, timedelta, time


class RokeProductionResult(models.Model):
    _inherit = "roke.production.result"


    def update_create_uid(self):
        ids_list = []
        for rec in self:
            ids_list.append(rec.id)

        res = self.env["roke.update.create.user.wizard"].create({
            "res_ids_str": json.dumps(ids_list),
            "model_name": self._name
        })

        return {
            'name': '更改创建人',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'res_id': res.id,
            'res_model': 'roke.update.create.user.wizard'
        }

    def update_create_date(self):
        #
        orders = self.env[self._name].sudo().search([])
        for order in orders:
            # 更新 create_date 字段
            work_time = order.wr_id.work_time
            self.env.cr.execute(f"""UPDATE {order._name.replace(".", "_")}
                                    SET create_date = '{datetime.combine(work_time.date(), time.min).strftime('%Y-%m-%d %H:%M:%S')}'
                                    WHERE id = {order.id}""")
            for line in order.line_ids:
                self.env.cr.execute(f"""UPDATE {line._name.replace(".", "_")}
                                        SET create_date = '{datetime.combine(work_time.date(), time.min).strftime('%Y-%m-%d %H:%M:%S')}'
                                        WHERE id = {line.id}""")
