# -*- coding:utf-8 -*-
# 作者：齐振鋆
# 日期：2023/3/6
# 描述: 骨科仓归还收货单
import logging
import allure

from random import randint
from time import sleep
from selenium.common.exceptions import TimeoutException
from component.GuKeYiTiHua import iframe, menu, list_page, order_detail_main, button, modal, order_detail_table, dbq
from component.GuKeYiTiHua.SurgeryFollow import first_menu
from unit.public.YamlUtil import UtilYaml

log = logging.getLogger(__name__)


class OrthopedicTake(object):
    third_menu = '骨科仓归还收货'

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

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

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

    @allure.step('新建：{}'.format(third_menu))
    def orthopedic_take_create(self, order_code=None, jc_code=None, follow='N'):
        """潜在问题，JC单中序列号数量过多时，会导致需要翻页，点不到的情况"""
        test_data_info = self.menu.dd.get_value('test_data_info')
        self.iframe.to_main_iframe()
        if order_code is None:
            self.button.new()
        else:
            self.orthopedic_take_search(order_code=order_code)
            self.list_page.open_order(order_code=order_code)
        self.order_detail_main.some_click_item('公司名称 ')
        self.modal.search_and_choose_items(text=test_data_info['company'])
        try:
            self.button.click_button("//*[text()='温馨提示']/ancestor::div[@class='el-message-box']", '确定')
        except TimeoutException:
            pass
        self.order_detail_main.some_click_item('还回仓库名称 ')
        self.modal.search_and_choose_items(title='选择还回仓库',
                                           text=test_data_info['warehouse_lend'])
        self.order_detail_main.some_click_item('客户名称 ')
        self.modal.search_and_choose_items(title='选择客户', text=test_data_info['customer'])

        lt = self.order_detail_main.some_click_item(name='连台标记 ', end_str='label', get=True)
        self.order_detail_main.some_click_item(name='连台标记 ', end_str='label') \
            if (follow == 'Y' and 'is-checked' not in self.menu.get_attribute(lt, 'class')) or \
               (follow == 'N' and 'is-checked' in self.menu.get_attribute(lt, 'class')) else 0
        self.button.save()
        while self.order_detail_main.get_element_text('收货单号 ').startswith('HHSH') is False:
            sleep(1)
        hhsh_code = self.order_detail_main.get_element_text('收货单号 ')
        UtilYaml(self.menu.dd.get_value('extract_path')).write_yaml({'hhsh_code': hhsh_code})
        log.info('还回收货单号：【{}】'.format(hhsh_code))
        self.menu.dd.set_value('hhsh_code', hhsh_code)
        self.button.click_button(button_name='添加')
        self.modal.search_and_choose_items(placeholder='模糊检索:还回单号,借出单号,商品编码,商品名称,序列号',
                                           text=jc_code, sing_choose=False)
        click_item = []
        # back_info = self.menu.dd.get_value('goods_batch_info') if back_info is None else back_info
        back_info = []
        for line in self.dbq.get_jr_info(jc_code):
            good = line[0]
            sf = line[1]
            batch = line[2]
            serial = []
            if sf == 'Y':
                for s in self.dbq.get_surgery_serial(jc_code, good, batch):
                    serial.append(s[0])
            back_info.append({
                'good': line[0],
                'sf': line[1],
                'batch': line[2],
                'check': line[3],
                'serial': serial
            })
        for index, item in enumerate(back_info):
            batch_num = item['batch']
            check_number = item['check']
            back_number = randint(1, check_number)
            if item['sf'] != 'Y':
                click_item.append(batch_num)
            else:
                sds = []
                for i in range(randint(1, len(item['serial']))):
                    s = back_info[index]['serial'].pop()
                    sds.append(s)
                    click_item.append(s)
                back_info[index].setdefault('used_serial', sds)
            back_info[index].setdefault('back', back_number)
        for item in click_item:
            self.modal.click_cell(text=item)
        self.button.click_button(
            "//div[@tabindex='-1']/ancestor::div[contains(@class, 'el-overlay') and not(ancestor-or-self::*[contains(@style,'display: none;')])]",
            '确定', "/parent::button[@style='']")
        self.menu.dd.set_value('back_info', back_info)
        log.info('还回信息：{}'.format(back_info))
        for item in back_info:
            self.order_detail_table.input_text('收货数量', item['good'],
                                               item['back']) if item['sf'] != 'Y' else 0
        self.button.submit()
        self.list_page.edit_iframe_is_show()
