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


class RokeUpdateStockOrderDateWizard(models.TransientModel):
    _name = "roke.update.stock.order.date.wizard"
    _description = "更新单据日期"

    stock_ids = fields.Many2many("roke.mes.stock.picking", string="调拨单")

    def action_confirm(self):
        pass


class RokeRandomStockOrderDateWizard(models.TransientModel):
    _name = "roke.random.stock.order.date.wizard"
    _description = "随机更新单据日期"

    stock_ids = fields.Many2many("roke.mes.stock.picking", string="调拨单")
    start_value = fields.Integer(string="开始天数", default=0, required=True)
    end_value = fields.Integer(string="结束天数", default=0, required=True)

    def action_confirm(self):
        if self.start_value > self.end_value:
            raise ValidationError("开始天数不能大于结束天数!")
        random_value = random.randint(self.start_value, self.end_value)
        # 只有 采购入库单  和 销售收货单 可以随机更新单据日期
        for stock_id in self.stock_ids:
            if stock_id.picking_type_id.picking_logotype == "XSCKD":
                # 销售收货单
                sale_order_date = stock_id.sale_id.order_date
                stock_id.write({"picking_date": sale_order_date + timedelta(days=random_value)})
            elif stock_id.picking_type_id.picking_logotype == "CGRKD":
                # 采购入库单
                purchase_order_date = stock_id.purchase_id.order_date
                stock_id.write({"picking_date": purchase_order_date + timedelta(days=random_value)})
            elif stock_id.picking_type_id.picking_logotype == "SCLLD":
                # 生产领料单
                task_code = stock_id.origin
                task_id = self.env["roke.production.task"].sudo().search([("code", "=", task_code)])
                if task_id:
                    task_id_create_date = task_id.create_date.date()
                    stock_id.write({"picking_date": task_id_create_date + timedelta(days=random_value)})
                else:
                    raise ValidationError("来源单据异常!")
            elif stock_id.picking_type_id.picking_logotype == "SCRKD":
                # 生产入库单  去拿 产出明细的创建时间
                move_line_ids = stock_id.move_line_ids
                for move_line_id in move_line_ids:
                    result_move_id = move_line_id.result_move_id
                    if result_move_id and result_move_id.result_id:
                        # 产出物 明细 的创建时间
                        production_result_create_date = result_move_id.result_id.create_date.date()
                        stock_id.write({"picking_date": production_result_create_date + timedelta(days=random_value)})
            else:
                raise ValidationError("单据异常!")