# -*- coding: utf-8 -*-
import base64
import logging
import os
import json
import hashlib
import time
import requests
from datetime import datetime

from odoo import fields, models, api, _
from odoo.exceptions import ValidationError
from odoo.exceptions import UserError
from odoo.addons.sf_machine_connect.models import py2opcua, ftp_operate

_logger = logging.getLogger(__name__)


# ----------------------------------------------------------
# Models for client
# ----------------------------------------------------------

class FtpButton(models.Model):
    _inherit = 'sf.cnc.processing'

    button_state = fields.Boolean(string='是否已经下发')
    user_permissions = fields.Boolean(string='权限', related='workorder_id.user_permissions')
    state = fields.Selection(string='状态', related='workorder_id.state')

    @api.onchange('users_ids')
    def get_user_permissions(self):
        uid = self.env.uid
        for workorder in self:
            if workorder.users_ids:
                list_user_id = []
                for item in workorder.users_ids:
                    list_user_id.append(item.id)
                if uid in list_user_id:
                    workorder.user_permissions = True
                else:
                    workorder.user_permissions = False
            else:
                workorder.user_permissions = False

    def pri(self):
        """
        一个测试函数，用于检测能否从”获取cnc程序“处获得NC代码文件
        :return:
        """
        s = self.cnc_id
        s1 = self.cnc_id._filestore()
        print(s1)
        v = self.cnc_id.display_name
        a = self.cnc_id.datas
        print(v)
        print(a)
        ftp_operate.FtpController.prin(self)

    def up(self):
        """
        此函数用于将NC代码下发到机床
        :return:
        """
        # 点击下发按钮自动补偿三元检测偏差值

        try:
            try:
                if self.sequence_number == '1':
                    self.check_compensation_before_up()
            except Exception:
                raise UserError("补偿值写入执行超时，请检查机床状态或者写入状态")

            # host="192.168.2.158", port=8080, username="MITSUBISHI", password="CNC"
            host = self.workorder_id.workcenter_id.machine_tool_id.ftp_host
            port = self.workorder_id.workcenter_id.machine_tool_id.ftp_port
            username = self.workorder_id.workcenter_id.machine_tool_id.ftp_num
            pwd = self.workorder_id.workcenter_id.machine_tool_id.ftp_pwd
            remote_path = self.workorder_id.workcenter_id.machine_tool_id.ftp_remote_path
            print(host, port, username, pwd, remote_path)
            ftp = ftp_operate.FtpController(host, port, username, pwd)
            # ftp.delAllfile('C://Users//马广威//Desktop//ftp')
            a = self.cnc_id
            _logger.info(a.public)
            _logger.info(a.display_name)
            datas = base64.standard_b64decode(a.datas)

            # file_path = '{}\{}\{}'.format(a._filestore(), a.store_fname.split('/'[0]), a.display_name)
            file_path_local = '{}/{}'.format('/nc2machine', a.display_name)
            # file_path_remote = '{}\{}'.format('//M80(192,168,2,142)//DS', a.display_name)
            file_path_remote = '{}\{}'.format(remote_path, a.display_name)

            with open(file_path_local, mode='wb+') as file:
                file.write(datas)
            # 存在本地的文件下发到机床
            _logger.info("=====================11================")
            ftp.upload_file(remotepath=file_path_remote, localpath=file_path_local)
            _logger.info("=====================22================")
        except Exception as e:
            _logger.info("=====================================", e)
            raise UserError('NC下发执行超时, 请检查下发状态')

        # 补偿下发都执行完毕后，按钮标志位变为true
        self.button_state = True

    def check_compensation_before_up(self):
        """
        下发NC代码前自动补偿三元检测偏差值
        :return:
        """
        hongbianliang550 = self.workorder_id.workcenter_id.machine_tool_id.x_compensation_node
        hongbianliang551 = self.workorder_id.workcenter_id.machine_tool_id.y_compensation_node
        try:
            temp_dict = {}
            temp_dict[hongbianliang550] = self.workorder_id.compensation_value_x
            temp_dict[hongbianliang551] = self.workorder_id.compensation_value_y
            temp = py2opcua.Py2opcua()
            temp.write(temp_dict)
        except Exception as e:
            _logger.info("=====================================", e)
            raise UserError('补偿值获取失败，或机床未连接，请检查')


class Machine_ftp(models.Model):
    """
    数据采集类
    """
    _inherit = 'sf.machine_tool'

    workorder_ids = fields.One2many('mrp.workorder', 'machine_tool_id', string='工单')

    # 机床配置项目
    # ftp相关
    ftp_num = fields.Char('ftp账号')
    ftp_pwd = fields.Char('ftp密码')
    ftp_host = fields.Char('ftp地址')
    ftp_port = fields.Integer('ftp端口')
    ftp_remote_path = fields.Char('机床ftp路径')
    # 补偿值写入相关
    x_compensation_node = fields.Char('x补偿值节点')
    y_compensation_node = fields.Char('y补偿值节点')
    # 数采配置相关
    machine_ip = fields.Char('机床IP')
    machine_signed = fields.Char('机床刷新间隔')
    machine_status = fields.Char('机床在线状态')
    machine_time_on = fields.Char('机床总在线时长')
    machine_tool_num = fields.Char('机床当前刀具')
    machine_program = fields.Char('机床当前程序')
    machine_run_status = fields.Char('机床运行状态')
    machine_run_time = fields.Char('机床总运行时长')
    machine_cut_time = fields.Char('机床总切削时长')
    machine_cut_status = fields.Char('机床切削状态')
    machine_emg_status = fields.Char('机床急停状态')
    machine_mode = fields.Char('机床操作模式')

    # 机床采集项目
    timestamp = fields.Datetime('时间戳', readonly=True)
    signed = fields.Integer('刷新间隔', readonly=True)
    status = fields.Boolean('在线状态', readonly=True)
    time_on = fields.Char('总在线时长', readonly=True)
    time_on_now = fields.Char('本次在线时长', readonly=True)
    tool_num = fields.Integer('当前刀具', readonly=True)
    program = fields.Char('当前程序', readonly=True)
    run_status = fields.Selection([('0', '空闲中'), ('1', '加工中'), ('2', '加工中'), ('3', '等待中')], string='运行状态',
                                  readonly=True, default='0')
    run_time = fields.Char('总运行时长', readonly=True)
    cut_time = fields.Char('总切削时长', readonly=True)
    cut_status = fields.Selection([('0', '未切削'), ('1', '切削中'), ('2', '切削中'), ('3', '切削中')], string='切削状态',
                                  readonly=True, default='0')

    tool_num_process_time1 = fields.Char('刀位1', readonly=True, default='0')
    tool_num_process_time2 = fields.Char('刀位2', readonly=True, default='0')
    tool_num_process_time3 = fields.Char('刀位3', readonly=True, default='0')
    tool_num_process_time4 = fields.Char('刀位4', readonly=True, default='0')
    tool_num_process_time5 = fields.Char('刀位5', readonly=True, default='0')
    tool_num_process_time6 = fields.Char('刀位6', readonly=True, default='0')
    tool_num_process_time7 = fields.Char('刀位7', readonly=True, default='0')
    tool_num_process_time8 = fields.Char('刀位8', readonly=True, default='0')
    tool_num_process_time9 = fields.Char('刀位9', readonly=True, default='0')
    tool_num_process_time10 = fields.Char('刀位10', readonly=True, default='0')
    tool_num_process_time11 = fields.Char('刀位11', readonly=True, default='0')
    tool_num_process_time12 = fields.Char('刀位12', readonly=True, default='0')
    tool_num_process_time13 = fields.Char('刀位13', readonly=True, default='0')
    tool_num_process_time14 = fields.Char('刀位14', readonly=True, default='0')
    tool_num_process_time15 = fields.Char('刀位15', readonly=True, default='0')
    tool_num_process_time16 = fields.Char('刀位16', readonly=True, default='0')
    tool_num_process_time17 = fields.Char('刀位17', readonly=True, default='0')
    tool_num_process_time18 = fields.Char('刀位18', readonly=True, default='0')
    tool_num_process_time19 = fields.Char('刀位19', readonly=True, default='0')
    tool_num_process_time20 = fields.Char('刀位20', readonly=True, default='0')
    tool_num_process_time21 = fields.Char('刀位21', readonly=True, default='0')
    tool_num_process_time22 = fields.Char('刀位22', readonly=True, default='0')
    tool_num_process_time23 = fields.Char('刀位23', readonly=True, default='0')
    tool_num_process_time24 = fields.Char('刀位24', readonly=True, default='0')


class WorkCenterBarcode(models.Model):
    """
    扫码托盘码可查到制造订单，由制造订单查工单
    """
    _inherit = "mrp.workorder"

    compensation_value_x = fields.Float(string='X轴补偿值')
    compensation_value_y = fields.Float(string='Y轴补偿值')
    button_compensation_state = fields.Boolean(string='是否已经补偿', readonly=True)
    button_up_all_state = fields.Boolean(string='是否已经全部下发', readonly=True)
    machine_tool_id = fields.Many2one('sf.machine_tool', string='机床')
    machine_tool_name = fields.Char(string='机床名称', default='未知机床', compute='_run_info', readonly=True)
    machine_tool_type_id = fields.Char(string='机床型号', default='未知型号', compute='_run_info', readonly=True)
    machine_tool_status = fields.Boolean(string='在线状态', compute='_run_info', readonly=True)
    machine_tool_run_status = fields.Selection([('0', '关机中'), ('1', '加工中'), ('2', '加工中'), ('3', '加工中')],
                                               string='运行状态', compute='_run_info', readonly=True, default='0')
    machine_tool_timestamp = fields.Datetime('时间戳', compute='_run_info', readonly=True)
    machine_tool_time_on = fields.Char('总在线时长', compute='_run_info', readonly=True)
    machine_tool_time_on_now = fields.Char('本次在线时长', compute='_run_info', readonly=True)
    machine_tool_tool_num = fields.Integer('当前刀具', compute='_run_info', readonly=True)
    machine_tool_program = fields.Char('当前程序', compute='_run_info', readonly=True)
    machine_tool_machine_ip = fields.Char('机床IP', compute='_run_info', readonly=True)
    machine_tool_cut_status = fields.Selection([('0', '未切削'), ('1', '切削中'), ('2', '切削中'), ('3', '切削中')],
                                               string='切削状态', compute='_run_info', readonly=True, default='0')
    machine_tool_compensation_value_x = fields.Char('x补偿值', compute='_run_info', readonly=True)
    machine_tool_compensation_value_y = fields.Char('y补偿值', compute='_run_info', readonly=True)

    @api.depends('workcenter_id.machine_tool_id.timestamp')
    def _run_info(self):
        # self.machine_tool_name = '1号机床'
        self.machine_tool_name = self.workcenter_id.machine_tool_id.name
        self.machine_tool_type_id = self.workcenter_id.machine_tool_id.type_id.name
        self.machine_tool_status = self.workcenter_id.machine_tool_id.status
        self.machine_tool_run_status = self.workcenter_id.machine_tool_id.run_status
        self.machine_tool_timestamp = self.workcenter_id.machine_tool_id.timestamp
        self.machine_tool_time_on = self.workcenter_id.machine_tool_id.time_on
        self.machine_tool_time_on_now = self.workcenter_id.machine_tool_id.time_on_now
        self.machine_tool_tool_num = self.workcenter_id.machine_tool_id.tool_num
        self.machine_tool_program = self.workcenter_id.machine_tool_id.program
        self.machine_tool_machine_ip = self.workcenter_id.machine_tool_id.machine_ip
        self.machine_tool_cut_status = self.workcenter_id.machine_tool_id.cut_status
        self.machine_tool_compensation_value_x = self.compensation_value_x
        self.machine_tool_compensation_value_y = self.compensation_value_y

    def compensation(self):

        hongbianliang550 = self.workcenter_id.machine_tool_id.x_compensation_node
        hongbianliang551 = self.workcenter_id.machine_tool_id.y_compensation_node
        try:
            temp_dict = {}
            temp_dict[hongbianliang550] = self.compensation_value_x
            temp_dict[hongbianliang551] = self.compensation_value_y
            print("=================================")
            print(temp_dict)
            temp = py2opcua.Py2opcua()
            temp.write(temp_dict)
            self.button_compensation_state = True
        except Exception as e:
            _logger.info("=====================================", e)
            raise UserError('补偿值获取失败，或机床未连接，请检查')
        # 补偿执行完毕后，按钮标志位变为true
        self.button_compensation_state = True

    def up_all(self):
        """
        此函数用于将NC代码全部下发到机床
        :return:
        """
        try:
            filepath = '/nc2machine'
            del_list = os.listdir(filepath)
            _logger.info("=====================================", del_list)
            for f in del_list:
                file_path = os.path.join(filepath, f)
                if os.path.isfile(file_path):
                    os.remove(file_path)
        except Exception as e:
            _logger.info("=====================================", e)
            raise UserError('程序删除失败，请重试')
        # host="192.168.2.158", port=8080, username="MITSUBISHI", password="CNC"
        host = self.workcenter_id.machine_tool_id.ftp_host
        port = self.workcenter_id.machine_tool_id.ftp_port
        username = self.workcenter_id.machine_tool_id.ftp_num
        pwd = self.workcenter_id.machine_tool_id.ftp_pwd
        remote_path = self.workcenter_id.machine_tool_id.ftp_remote_path
        print(host, port, username, pwd, remote_path)
        ftp = ftp_operate.FtpController(host, port, username, pwd)
        # ftp.delAllfile('C://Users//马广威//Desktop//ftp')
        try:
            for item in self.cnc_ids:
                a = item.cnc_id
                print(a.display_name)
                _logger.info(a.public)
                _logger.info(a.display_name)
                datas = base64.standard_b64decode(a.datas)

                # file_path = '{}\{}\{}'.format(a._filestore(), a.store_fname.split('/'[0]), a.display_name)
                file_path_local = '{}/{}'.format('/nc2machine', a.display_name)
                # 本地测试一键下发
                # file_path_local = '{}/{}'.format('D:\\jikimo', a.display_name)
                # file_path_remote = '{}\{}'.format('//M80(192,168,2,142)//DS', a.display_name)
                file_path_remote = '{}\{}'.format(remote_path, a.display_name)

                with open(file_path_local, mode='wb+') as file:
                    file.write(datas)
                # 存在本地的文件下发到机床
                _logger.info("=====================11================")
                ftp.upload_file(remotepath=file_path_remote, localpath=file_path_local)
            # _logger.info("=====================22================")
        except Exception as e:
            _logger.info("=====================================", e)
            raise UserError('NC下发执行超时, 请检查下发状态')
        # 下发都执行完毕后，按钮标志位变为true
        self.button_up_all_state = True

    def get__state(self):
        pay_time = str(datetime.now())
        json = {
            'params': {
                'model_name': 'jikimo.process.order',
                'field_name': 'name',
                'default_code': 'PO-2022-1207-0020',
                'state': '待付款',
                # 'pay_time': pay_time,
                # 'get_order_sf': 21,

            },
        }
        # res_str = json.dumps(vals)
        url = 'https://bfm.cs.jikimo.com/api/get/state'
        requests.post(url, json=json, data=None)

    def process_control(self):

        if self.routing_type == '获取CNC加工程序' and self.state == '进行中':
            json = {
                'params': {
                    'model_name': 'jikimo.process.order',
                    'field_name': 'name',
                    'default_code': 'PO-2022-1123-0014',
                    'state': '加工中',
                },
            }
            url = 'https://bfm.cs.jikimo.com/api/get/state'
            requests.post(url, json=json, data=None)
