# -*- 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__)


class UpSelectWizard(models.TransientModel):
    _name = 'up.select.wizard'

    workorder_id = fields.Many2one('mrp.workorder', string='工单', readonly=True)
    workcenter_id = fields.Many2one('mrp.workcenter', string='工作中心', related='workorder_id.workcenter_id',
                                    readonly=True)
    program_ids = fields.Many2many('sf.cnc.processing', string='程序列表')


    def confirm_up(self):
        # 合并下发前删除机床上的全部程序
        try:
            filepath = '/nc2machine'
            del_list = os.listdir(filepath)
            _logger.info("=====================================%s" % 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 = 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)
        sequence_collect = []
        file_path_local = ''
        file_path_remote = ''
        try:
            # 给文件名
            begin_name1 = self.program_ids[0].cnc_id.display_name.split('-')
            temp_name1 = begin_name1[-1].split('.')
            final_name = '%s-MERGE.%s' % (begin_name1[0], temp_name1[-1])
            print(final_name)

            for item in self.program_ids:
                # print(item.program_name)
                # print(item.cnc_id)
                sequence_collect.append(item.sequence_number)
                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_local = '{}/{}'.format('/nc2machine', final_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, final_name)
                # 合并文件
                with open(file_path_local, mode='ab+') as file:
                    file.write(datas)

                # 下发成功标识
                item.button_state = True

            # 存在本地的文件下发到机床
            _logger.info("==========存在服务器成功，准备下发===========")
            ftp.upload_file(remotepath=file_path_remote, localpath=file_path_local)
            ftp.close_ftp()

            up_time = str(datetime.now())
            sequence_str = ','.join(sequence_collect)
            self.workorder_id.delivery_records.create({
                'delivery_type': '合并下发',
                'delivery_time': up_time,
                'influence_record': sequence_str,
            })
            _logger.info("==============合并下发成功==============")
        except Exception as e:
            for item in self.program_ids:
                item.button_state = False
            _logger.info("=====================================", e)
            raise UserError('NC下发执行超时, 请检查下发状态')

