# -*- coding:utf-8 -*-
# 作者：齐振鋆
# 日期：2023/2/27
# 描述: 仓库验收
import logging
import os
import allure
import pytest
import pyautogui

from random import randint
from time import sleep, time

from component.GuKeYiTiHua import iframe, menu, list_page, button, order_detail_main, modal, dbq, table
from component.GuKeYiTiHua.StorageManage import first_menu
from page.GuKeYiTiHua.Public.orderDetailPage import OrderDetailTable, ScanTable
from unit.public.YamlUtil import UtilYaml

log = logging.getLogger(__name__)
pyautogui.FAILSAFE = False


class WarehouseVerify(object):
    third_menu = '仓库验收'

    def __init__(self):
        self.dbq = dbq
        self.iframe = iframe
        self.menu = menu
        self.list_page = list_page
        self.button = button
        self.table = table
        self.order_detail_main = order_detail_main
        self.order_detail_table = OrderDetailTable()
        self.scan_table = ScanTable()
        self.modal = modal

    @allure.step('打开菜单：{}'.format(third_menu))
    def open_verify_menu(self):
        self.iframe.out_frame()
        self.menu.open_menu(first_menu, self.third_menu)

    @allure.step('查询：{}'.format(third_menu))
    def verify_order_search(self, tap_name='待办', order_code=None, count=1):
        self.list_page.order_search(self.third_menu, tap_name, '订单号', order_code, count)

    @allure.step('扫码录入商品')
    def scan_input_goods(self, good_code, bar_code, order_type='OP', serial=None):
        if order_type == 'OP':
            bar = bar_code.split(' ')
            self.order_detail_main.text_input_item('第一条码 ', bar[0], enter=False)
            self.order_detail_main.text_input_item('第二条码 ', bar[1], enter=True)
            if self.menu.wait_element("//h4[text()='选择商品']", wait_time=3) is True:
                self.modal.search_and_choose_items(title='选择商品', text=good_code)
                while self.menu.wait_element("//h4[text()='选择商品']/ancestor::div[@class='el-overlay']",
                                             wait_time=3) is True:
                    sleep(1)
            serial_number = 'YC{}'.format(self.menu.tu.get_datetime('MS'))
        else:
            serial_number = serial
        self.order_detail_main.text_input_item('序列号 ', serial_number, enter=True)
        while self.menu.wait_element(self.order_detail_main.get_element_text('生产批号 ', get=True),
                                     3) is True:
            sleep(1)

    @allure.step('{}'.format(third_menu))
    def verify_edit_and_confirm(self, order_code, order_type='OP'):
        log.info("验收信息录入并提交.")
        self.verify_order_search(order_code=order_code)
        self.list_page.open_order(order_code=order_code)
        company = self.order_detail_main.get_element_text('公司编码 ')
        warehouse = self.order_detail_main.get_element_text('仓库编码 ')
        self.menu.zoom('-', 6)
        if order_type == 'OP':
            goods = self.order_detail_table.get_details(['商品编码', '到货数量'])
            for good in goods:
                good_code = good[0]
                good_serial_flag = self.dbq.get_serial_flag(warehouse, good_code)
                take_number = int(good[1])
                if good_serial_flag == 'Y':
                    good_sn_dic = UtilYaml('{}/data/goods_sn_data.yaml'.format(os.getcwd())).load_yaml()
                    try:
                        bar_code = good_sn_dic[good_code]
                        self.button.scan_bar()
                        self.iframe.to_bar_iframe(name='验收扫码')
                        for i in range(take_number):
                            self.scan_input_goods(good_code, bar_code)
                        self.button.click_button("//div[@class='form-item-view']", '提交')
                        self.iframe.to_parent_frame()
                        sleep(3)
                    except KeyError:
                        pytest.fail('有未维护的商品条码信息')
                else:
                    take_number = int(self.order_detail_table.get_cell_text('到货数量', good_code))
                    self.order_detail_table.input_text('验收数量', good_code, take_number)
                    stock_cargo_flag = self.dbq.get_stock_cargo(warehouse)
                    if stock_cargo_flag == 'Y':
                        sc_ph = self.dbq.get_pro_num(warehouse, good_code)
                        if sc_ph is None or sc_ph == '':
                            pytest.fail('启用货位管理的仓库：{}，未配置商品：{}的货位.'.format(warehouse, good_code))
                    else:
                        sc_ph = 'S{}'.format(int(time() * 100))
                    self.order_detail_table.input_text('生产批号', good_code, sc_ph)
                    self.order_detail_table.input_text('生产日期', good_code, self.menu.tu.get_date_str(-1))
                    self.order_detail_table.input_text('有效期/失效日期', good_code, self.menu.tu.get_date_str(5))
                sto_ste = self.dbq.get_storage_sterilization_flag(company, good_code)
                if sto_ste[0] == '001':
                    self.order_detail_table.input_text('启运温度 （摄氏度）', good_code, '{}'.format(randint(-5, 5)))
                    self.order_detail_table.input_text('到货温度（摄氏度）', good_code, '{}'.format(randint(-5, 5)))
                    self.order_detail_table.input_text('启运日期', good_code, self.menu.tu.get_date_str())
                    self.order_detail_table.input_text('启运时间', good_code, self.menu.tu.get_time_str(-1))
                    self.order_detail_table.input_text('到货时间', good_code, self.menu.tu.get_time_str(1))
                    self.order_detail_table.choose_item('运输工具说明', good_code, '冷藏车')
                if sto_ste[1] == 'Y':
                    self.order_detail_table.input_text('灭菌批号', good_code, 'M{}'.format(int(time() * 100)))
                    self.order_detail_table.input_text('灭菌日期', good_code, self.menu.tu.get_date_str())
                    self.order_detail_table.input_text('灭菌失效日期', good_code, self.menu.tu.get_date_str(5))
        else:
            back_info = self.menu.dd.get_value('back_info')
            for back_item in back_info:
                if back_item['sf'] == 'Y':
                    scan_sns = back_item['used_serial']
                    self.button.scan_bar()
                    self.iframe.to_bar_iframe(name='验收扫码')
                    for i in range(len(scan_sns)):
                        self.scan_input_goods(back_item['good'], bar_code=None, order_type=order_type,
                                              serial=scan_sns[i])
                    self.button.click_button("//div[@class='form-item-view']", '提交')
                    self.iframe.to_parent_frame()
                    sleep(3)
                else:
                    take_number = int(self.order_detail_table.get_cell_text('到货数量', back_item['good']))
                    self.order_detail_table.input_text('验收数量', back_item['good'], take_number)
        self.menu.zoom('+', 6)
        self.button.click_button("//div[@id='process-toolbar']", '提交')
        self.list_page.edit_iframe_is_show()
