<?php

namespace App\Servers;

use AlibabaAlihealthSynergyYzwDrugreportOptHistoryAllRequest;
use AlibabaAlihealthSynergyYzwQuerydrugreportRequest;
use AlibabaAlihealthSynergyYzwQuerysealdrugreportRequest;
use AlibabaAlihealthSynergyYzwQuerydrugreportassRequest;
use AlibabaAlihealthSynergyYzwBillSignedQueryRequest;
use AlibabaAlihealthSynergyYzwDrugreportGetRequest;
use AlibabaAlihealthSynergyYzwSignednotstampedbillQueryRequest;
use Page;
use TopClient;
use App\Facades\Servers\Logs\Log;

class QueryDrugReportService
{
    private $client;

    private $config;

    public function __construct()
    {
        $this->config = config('taobao');

        $this->client = new TopClient;
        $this->client->appkey = $this->config['app_key'];
        $this->client->secretKey = $this->config['secret_key'];
        $this->client->format = "json";
    }

    /**
     * 查询上游企业的待签收药检报告信息
     * @link https://open.taobao.com/api.htm?docId=70169&docType=2&scopeId=30361
     * @param string $beginTime
     * @param string $endTime
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \Exception
     */
    public function queryDrugReport(string $beginTime, string $endTime, int $page = 1, int $pageSize = 20): array
    {
        $req = new AlibabaAlihealthSynergyYzwQuerydrugreportRequest;
        $req->setRefEntId($this->config['enterprise_id']);
//        $req->setFromRefEntId(""); // 发货企业（可选）
//        $req->setBillCode(""); // 单据编号（可选）
        $req->setBeginTime($beginTime);
        $req->setEndTime($endTime);
//        $req->setDrugId(""); // 药品ID（可选）
//        $req->setBatchNo(""); // 批号（可选）

        $pageObj = new Page;
        $pageObj->page = $page;
        $pageObj->page_size = $pageSize;
        $req->setPage(json_encode($pageObj));
        $resp = $this->client->execute($req);
        if ('SUCCESS' <> $resp->res_result->msg_code) {
            throw new \Exception($resp->res_result->msg_info);
        }

        if (!isset($resp->res_result->model->result->onenet_drug_report_top_d_t_o)) {
            return [];
        }
        return json_decode(json_encode(
            $resp->res_result->model->result->onenet_drug_report_top_d_t_o
        ), true);
    }

    /**
     * 查询上传报告信息接口
     * @link https://open.taobao.com/api.htm?docId=70145&docType=2&scopeId=30361
     * @param string $beginTime
     * @param string $endTime
     * @param int $page
     * @param int $pageSize
     * @param int $isSeal
     * @return array
     * @throws \Exception
     */
    public function querySealDrugReport(string $beginTime, string $endTime, int $page = 1, int $pageSize = 20, int $isSeal = 0): array
    {
        $req = new AlibabaAlihealthSynergyYzwQuerysealdrugreportRequest;
        $req->setRefEntId($this->config['enterprise_id']);
        $req->setBeginTime($beginTime);
        $req->setEndTime($endTime);
        $req->setPage($page);
        $req->setPageSize($pageSize);

        if ($isSeal) {
            $req->setStatus($isSeal);
        }

        $resp = $this->client->execute($req);
        if ('SUCCESS' <> $resp->result->msg_code) {
            throw new \Exception($resp->result->msg_info);
        }

        if (!isset($resp->result->model->result_list->ocr_seal_drug_report_d_t_o)) {
            return [
                'data' => [],
                'total_num' => 0
            ];
        }
        $data = json_decode(json_encode(
            $resp->result->model->result_list->ocr_seal_drug_report_d_t_o
        ), true);
        $total_num  = $resp->result->model->total_num;
        return [
            'data' => $data,
            'total_num' => $total_num
        ];
    }

    /**
     * 药检报告操作日志
     * @link https://open.taobao.com/api.htm?docId=71189&docType=2&scopeId=30361
     * @param string $beginDate
     * @param string $endDate
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \Exception
     */
    public function drugReportOptHistory(string $beginDate, string $endDate, int $page = 1, int $pageSize = 20): array
    {
        $req = new AlibabaAlihealthSynergyYzwDrugreportOptHistoryAllRequest;
        $req->setRefEntId($this->config['enterprise_id']);
        $req->setBeginTime($beginDate);
        $req->setEndTime($endDate);
//        $req->setBatchNo(""); // 批次号（可选）
//        $req->setDrugId(""); // 药品ID（可选）
        $req->setPage($page);
        $req->setPageSize($pageSize);

        $resp = $this->client->execute($req);
        if ('SUCCESS' <> $resp->result->msg_code) {
            throw new \Exception($resp->result->msg_info);
        }

        if (!isset($resp->result->model->result_list->top_drug_report_opt_log)) {
            return [
                'data' => [],
                'total_num' => 0
            ];
        }
        $data = json_decode(json_encode(
            $resp->result->model->result_list->top_drug_report_opt_log
        ), true);
        $total_num  = $resp->result->model->total_num;
        return [
            'data' => $data,
            'total_num' => $total_num
        ];
    }
    /**
     * 查询上游出库单，支持以自己身份查询或者货主身份查询
     * @link https://open.taobao.com/api.htm?docId=71591&docType=2&scopeId=30361
     * @param string $beginTime
     * @param string $endTime
     * @param string $pageValue
     * @param int $pageSize
     * @param int $isSeal
     * @return array
     * @throws \Exception
     */
    public function querydrugreportass(string $beginTime, string $endTime,  string $pageValue = '1', int $pageSize = 20, int $isSeal = 0,$setTimeType="0",$billCode='',$batchNo = '',$drugId = ''): array
    {
        $req = new AlibabaAlihealthSynergyYzwQuerydrugreportassRequest;
        $req->setRefEntId($this->config['enterprise_id']);
        //$req->setFromRefEntId('320000000000015243');
        $req->setBeginTime($beginTime);
        $req->setEndTime($endTime);
        $page = new Page;
        $page->page=$pageValue;
        $page->page_size="20";
        $req->setPage(json_encode($page));
        if ($setTimeType){
            $req->setTimeType($setTimeType);
        }else{
            $req->setTimeType("0");
        }
        if ($isSeal) {
            $req->setSealStatus($isSeal);
        }
        if ($billCode)      $req->setBillCode($billCode);
        if ($batchNo)       $req->setBatchNo($batchNo);
        if ($drugId)        $req->setDrugId($drugId);
        //$req->setSealStatus("0");
        //$req->setStatusType("3");
        $resp = $this->client->execute($req);
        if ('SUCCESS' <> $resp->res_result->msg_code) {
            log::info('querydrugreportass', '请求异常', ['err'=>$resp->res_result->msg_info]);
        }
        if (!isset($resp->res_result->model->result->onenet_drug_report_top_d_t_o)) {
            return [
                'data' => [],
                'total_num' => 0
            ];
        }
        $data = json_decode(json_encode(
            $resp->res_result->model->result->onenet_drug_report_top_d_t_o
        ), true);
        $total_num  = $resp->res_result->model->total_num;
        return [
            'data' => $data,
            'total_num' => $total_num
        ];
    }
    /**
     * 查询一段时间内已经签收的单据
     * @link https://open.taobao.com/api.htm?docId=71591&docType=2&scopeId=30361
     */
    public function queryDrugReportSignedAss(string $beginTime, string $endTime,  string $pageValue = '1', int $pageSize = 20)
    {
        $req = new AlibabaAlihealthSynergyYzwBillSignedQueryRequest;
        $req->setRefEntId($this->config['enterprise_id']);
        $req->setBeginTime($beginTime);
        $req->setEndTime($endTime);
        $page = new Page;
        $page->page=$pageValue;
        $page->page_size="20";
        $req->setPage(json_encode($page));
        $resp = $this->client->execute($req);
        if ('SUCCESS' <> $resp->res_result->msg_code) {
            log::info('querydrugreportass', '请求异常', ['err'=>$resp->res_result->msg_info]);
        }
        if (!isset($resp->res_result->model->result->onenet_drug_report_top_d_t_o)) {
            return [
                'data' => [],
            ];
        }
        $data = json_decode(json_encode(
            $resp->res_result->model->result->onenet_drug_report_top_d_t_o
        ), true);
        return [
            'data' => $data,
        ];
    }
    /**
     * 查询一段时间内已经签收的单据
     * @link https://open.taobao.com/api.htm?docId=71591&docType=2&scopeId=30361
     */
    public function synergyDrugReport(string $reportId)
    {
        $req = new AlibabaAlihealthSynergyYzwDrugreportGetRequest;
        $req->setRefEntId($this->config['enterprise_id']);
        $req->setReportId($reportId);
        $resp = $this->client->execute($req);
        if ('SUCCESS' <> $resp->res_result->msg_code) {
            log::info('querydrugreportass', '请求异常', ['err'=>$resp->res_result->msg_info]);
        }
        if (!isset($resp->res_result->model->result->onenet_drug_report_top_d_t_o)) {
            return [
                'data' => [],
            ];
        }
        $data = json_decode(json_encode(
            $resp->res_result->model->result->onenet_drug_report_top_d_t_o
        ), true);
        return [
            'data' => $data,
        ];
    }
    /**
     * 查询已经签收但是还未盖章的单据
     * @link https://open.taobao.com/api.htm?docId=71591&docType=2&scopeId=30361
     */
    public function signednotstampedbill(string $beginTime, string $endTime,  string $pageValue = '1', int $pageSize = 20)
    {
        $req = new AlibabaAlihealthSynergyYzwSignednotstampedbillQueryRequest;
        $req->setRefEntId($this->config['enterprise_id']);
        $req->setBeginTime($beginTime);
        $req->setEndTime($endTime);
        $page = new Page;
        $page->page=$pageValue;
        $page->page_size="20";
        $req->setPage(json_encode($page));
        $resp = $this->client->execute($req);
        if ('SUCCESS' <> $resp->res_result->msg_code) {
            log::info('querydrugreportass', '请求异常', ['err'=>$resp->res_result->msg_info]);
        }
        if (!isset($resp->res_result->model->result->holo_bill_search_common_show_d_t_o)) {
            return [
                'data' => [],
            ];
        }
        $data = json_decode(json_encode(
            $resp->res_result->model->result->holo_bill_search_common_show_d_t_o
        ), true);
        $total_num  = $resp->res_result->model->total_num;
        return [
            'data' => $data,
            'total_num' => $total_num
        ];
    }
}
