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

class InheritRokeWorkOrder(models.Model):
    _inherit = "roke.work.order"

    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 multiple_assign_workers(self):
        # 批量作业人员报工
        work_order_id_list = [rec.id for rec in self]

        wizard_id = self.env["roke.multiple.assign.workers.wizard"].create({
            "word_order_ids": [(6, 0, work_order_id_list)]
        })

        return {
            'name': '批量作业人员报工',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'res_id': wizard_id.id,
            'res_model': 'roke.multiple.assign.workers.wizard',
        }

    def update_create_date(self):
        # 把 当前 model 的所有数据的 创建时间都更改 为 生产任务创建时间
        for order in self:
            # 更新 create_date 字段
            self.env.cr.execute(f"""UPDATE {order._name.replace(".", "_")}
                                    SET create_date = '{datetime.combine(order.task_id.create_date.date(), time.min).strftime('%Y-%m-%d %H:%M:%S')}',
                                        dispatch_time = '{datetime.combine(order.task_id.create_date.date(), time.min).strftime('%Y-%m-%d %H:%M:%S')}'
                                    WHERE id = {order.id}""")
            for assigned_record_id in order.assigned_record_ids:
                self.env.cr.execute(f"""UPDATE {assigned_record_id._name.replace(".", "_")}
                                        SET create_date = '{datetime.combine(order.task_id.create_date.date(), time.min).strftime('%Y-%m-%d %H:%M:%S')}'
                                        WHERE id = {assigned_record_id.id}""")

    def multiple_update_planned_start_time(self):
        """
        批量修改排产时间 为 计划开始时间
        """
        for rec in self:
            # 更新 create_date 字段
            self.env.cr.execute(f"""UPDATE {rec._name.replace(".", "_")}
                                    SET plan_start_time = '{rec.planned_start_time.date().strftime('%Y-%m-%d')}',
                                        plan_stop_time = '{rec.plan_date.date().strftime('%Y-%m-%d')}'
                                    WHERE id = {rec.id}""")