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


class RokeMultipleAssignWorkersWizard(models.TransientModel):
    _name = "roke.multiple.assign.workers.wizard"
    _description = "批量作业人员报工"

    word_order_ids = fields.Many2many("roke.work.order", string="生产工单")
    employee_id = fields.Many2one("roke.employee", string="作业人员")

    def action_confirm(self):
        for word_order_id in self.word_order_ids:
            allow_qty, default_qty = word_order_id._get_wo_allow_qty()
            if allow_qty <= 0:
                raise ValidationError(
                    f"当前工单{word_order_id.code}可报数量为0，请先完成前道工序。（或联系管理员设置系统【允许自由报工（生产设置）】并【允许超库存报工（物料设置）】")
            res = self.env["roke.create.work.record.wizard"].create(
                word_order_id._create_work_record_get_values(allow_qty, default_qty, False))
            res.employee_id = self.employee_id
            res.confirm()

            # 修改报工时间
            word_order_id.write({"finish_time": datetime.combine(word_order_id.plan_date, time.min)})

            # 修改报工记录的数据
            record_ids = word_order_id.record_ids
            for record_id in record_ids:
                # 更新 create_date 等字段  TODO 创建人 要看下怎么改
                self.env.cr.execute(f"""UPDATE {record_id._name.replace(".", "_")}
                                        SET create_date = '{datetime.combine(word_order_id.create_date.date(), time.min).strftime("%Y-%m-%d %H:%M:%S")}',
                                            work_time='{datetime.combine(word_order_id.plan_date, time.min).strftime("%Y-%m-%d %H:%M:%S")}'
                                        WHERE id = {record_id.id}""")