# -*- coding: utf-8 -*-
import http.client
import mimetypes
import math
from codecs import encode
from datetime import timedelta

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError


class InheritProductionTask(models.Model):
    _inherit = "roke.production.task"

    file_ids = fields.Many2many("ir.attachment", "roke_production_task_ir_attachment", "pro_id", "att_id")
    taskName = fields.Char(string="任务名称")
    UploadMsg = fields.Char(string="上传状态")
    TaskUUID = fields.Char(string="任务UUID")
    spare_parts_qty = fields.Float(string="切割零部件数", default=0)
    press_riveting_qty = fields.Float(string="压铆零部件数", default=0)
    bending_qty = fields.Float(string="折弯零部件数", default=0)

    work_order_hours = fields.Float(string="总报工时", compute="_compute_work_order_hours")

    @api.depends('work_order_ids')
    def _compute_work_order_hours(self):
        for record in self:
            record.work_order_hours = sum(record.work_order_ids.mapped("work_hours"))

    def upload_task(self):
        """
        上传任务 TODO 任务数量取计划数还是计划数-完成数？上传一次后还能再上传不？多个加工文件时，上传第一个还是最后一个？
        :return:
        """
        self.ensure_one()
        if not self.work_center_id:
            raise ValidationError("未指派工作中心，禁止上传")
        if not self.work_center_id.card_id:
            raise ValidationError("当前工作中心无控制卡信息，无法上传")
        if not self.file_ids:
            raise ValidationError("当前任务无加工文件，无法上传")
        if not self.taskName:
            raise ValidationError("必须填写任务名称")
        attachment = self.file_ids[:1]
        self.work_center_id.upload_task(self, attachment)

    def write(self, vals):
        res = super(InheritProductionTask, self).write(vals)
        if vals.get('file_ids'):
            files = []
            for i in self.file_ids:
                a = self.env['documents.document'].create({
                    'attachment_id': i.id,
                    'folder_id': 2})
                files.append(a.id)
                self.document_ids = [(4, a.id)]
        return res

    @api.onchange("routing_id", "product_id", "plan_qty", "type", "spare_parts_qty", "press_riveting_qty", "bending_qty")
    def _onchange_routing_id(self):
        return super(InheritProductionTask, self)._onchange_routing_id()

    def change_routing_id_work_order(self, routing):
        product = self.product_id
        plan_qty = self.plan_qty
        task_type = self.type
        routing_lines = self.get_create_wo_routing_lines(routing)
        work_orders = [(5, 0, 0)]
        date_num = (self.plan_date - self.plan_start_date).days
        work_order_num = len(routing_lines)
        if date_num == 0:
            for routing_line in routing_lines:
                date = self.plan_start_date
                work_order_data = self._get_new_work_order_data(routing_line, product, plan_qty, task_type)
                work_order_data['planned_start_time'] = date
                work_order_data['plan_date'] = date
                work_order_data['priority'] = self.priority
                work_orders.append(
                     (0, 0, work_order_data))
        else:
            num = work_order_num // date_num
            if num < 1:
                num = 1
            day = 0
            circulation_num = 1
            for routing_line in routing_lines:
                date = self.plan_start_date + timedelta(days=day)
                if circulation_num == num:
                    circulation_num = 1
                    if day + 1 <= date_num:
                        day += 1
                else:
                    circulation_num += 1
                work_order_data = self._get_new_work_order_data(routing_line, product, plan_qty, task_type)
                work_order_data['planned_start_time'] = date
                work_order_data['plan_date'] = date
                work_order_data['priority'] = self.priority
                work_orders.append(
                    (0, 0, work_order_data))
        return work_orders

    def _create_work_order_get_values(self, task, routing_line):
        """
        任务生成工单获取工单数据
        :return:
        """
        res = super(InheritProductionTask, self)._create_work_order_get_values(task, routing_line)
        rounding_type = self.env['ir.config_parameter'].sudo().get_param('e_bom.material.demand.rounding',
                                                                         default="精确计算")
        if "切割" in routing_line.process_id.name:
            plan_qty = task.spare_parts_qty
        elif "压铆" in routing_line.process_id.name:
            plan_qty = task.press_riveting_qty
        elif "折弯" in routing_line.process_id.name:
            plan_qty = task.bending_qty
        else:
            plan_qty = task.plan_qty * routing_line.multiple
        if rounding_type == "向上取整":
            plan_qty = math.ceil(plan_qty)
        elif rounding_type == "向下取整":
            plan_qty = int(plan_qty)
        res.update({"plan_qty": plan_qty})
        return res

    def _get_new_work_order_data(self, routing_line, product, plan_qty, task_type):
        """
        onchang获取工单数据
        :return:
        """
        res = super(InheritProductionTask, self)._get_new_work_order_data(routing_line, product, plan_qty, task_type)
        rounding_type = self.env['ir.config_parameter'].sudo().get_param('e_bom.material.demand.rounding', default="精确计算")
        if "切割" in routing_line.process_id.name:
            plan_qty = self.spare_parts_qty
        elif "压铆" in routing_line.process_id.name:
            plan_qty = self.press_riveting_qty
        elif "折弯" in routing_line.process_id.name:
            plan_qty = self.bending_qty
        else:
            plan_qty = self.plan_qty * routing_line.multiple
        if rounding_type == "向上取整":
            plan_qty = math.ceil(plan_qty)
        elif rounding_type == "向下取整":
            plan_qty = int(plan_qty)
        res.update({"plan_qty": plan_qty})
        return res

    def craft_design(self):
        if self.record_ids and not self.routing_id.routing_task_id:
            raise ValidationError("该任务已报工，无法生成新的工艺设计。")
        if not self.routing_id:
            routing_id = self.env["roke.routing"].create({
                "name": f"{self.product_id.name}({self.code})" or "",
                "routing_task_id": self.id
            })
            self.write({
                "routing_id": routing_id.id,
            })
            self.write({
                "work_order_ids": self.change_routing_id_work_order(routing_id)
            })
        elif not self.routing_id.routing_task_id or self.routing_id.routing_task_id.id != self.id:
            routing_id = self.routing_id.copy()
            routing_id.update({
                "name": f"{routing_id.name}({self.code})",
                "routing_task_id": self.id
            })
            self.write({"routing_id": routing_id.id})
            self.write({
                "work_order_ids": self.change_routing_id_work_order(routing_id)
            })
        else:
            routing_id = self.routing_id
        return {
            "name": f"工艺设计({self.code})",
            "type": "ir.actions.client",
            "tag": "jzjx_project.roke_craft_design",
            "target": "current",
            "params": {
                "controller": f"/roke/craft_design/index?product_id={self.product_id.id}&routing_id={routing_id.id}"
            }
        }
