# -*- coding: utf-8 -*-
import json
import base64
import logging
import os
from datetime import date, timedelta
from odoo import http
from odoo.http import request


class Sf_Mrs_Connect(http.Controller):

    @http.route('/api/cnc_processing/create', type='json', auth='sf_token', methods=['GET', 'POST'], csrf=False,
                cors="*")
    def get_cnc_processing_create(self, **kw):
        """
        获取mrs下发的编程单
        :param kw:
        :return:
        """
        logging.info('get_cnc_processing_create:%s' % kw)
        try:
            res = {'status': 1, 'message': '成功'}
            datas = request.httprequest.data
            ret = json.loads(datas)
            ret = json.loads(ret['result'])
            # 查询状态为进行中且类型为获取CNC加工程序的工单
            cnc_workorder = request.env['mrp.workorder'].with_user(
                request.env.ref("base.user_admin")).search([('production_id.name', '=', ret['production_order_no']),
                                                            ('routing_type', '=', '获取CNC加工程序'),
                                                            ('state', '=', 'progress')])
            if cnc_workorder:
                # 拉取所有加工面的程序文件
                # i = 1
                for r in ret['processing_panel']:
                    download_state = request.env['sf.cnc.processing'].with_user(
                        request.env.ref("base.user_admin")).download_file_tmp(
                        ret['folder_name'], r)
                    if download_state == False:
                        res['status'] = -2
                        res['message'] = '制造订单号为%s的CNC程序文件从FTP拉取失败' % (cnc_workorder.production_id.name)
                        return json.JSONEncoder().encode(res)
                request.env['sf.cnc.processing'].with_user(
                    request.env.ref("base.user_admin")).cnc_processing_create(cnc_workorder, ret)
                return json.JSONEncoder().encode(res)
            else:
                res = {'status': 0, 'message': '该制造订单暂未开始'}
                return json.JSONEncoder().encode(res)
        except Exception as e:
            res = {'status': -1, 'message': '系统解析失败'}
            logging.info('get_cnc_processing_create error:%s' % e)
            return json.JSONEncoder().encode(res)
