<?php
namespace model;

use \model;

/**
 * 菲尔IBP系统接口模型
 * 对应配置项: \mvc::$cfg['FREYIBP']
 */
class freyIbp extends \model
{
    public $confifg = [];
    public function __construct()
    {
        parent::__construct();
       
        $this->config = \mvc::$cfg['FREYIBP'];
    }
    /**
     * @method 发送请求到IBP接口
     * @param string $path 接口路径, 例如: FreyApi/Product/PdmPro/receive
     * @param array $data 请求数据 (Body)
     * @param string $method 请求方式 POST/GET
     * @return array|mixed
     * @author zhengweihua
     */
    public function request($path, $data = [], $method = 'POST')
    {
        if(empty($this->config)||empty($this->config['url'])){
            return [];
        }
        try {
            // 获取基础配置
            
            $baseUrl = rtrim($this->config['url'], '/');
            $url = $baseUrl . '/' . ltrim($path, '/');
            
            // 构建默认Header
            $defaultHeaders = isset($this->config['header']) ? $this->config['header'] : [];
            
            $headers = [];
            foreach ($defaultHeaders as $key => $value) {
                $headers[] = "$key: $value";
            }
            // 如果默认header里没有Content-Type
            $hasContentType = false;
            foreach($headers as $h){
                if(stripos($h, 'Content-Type') !== false){
                    $hasContentType = true;
                    break;
                }
            }
            if(!$hasContentType){
                $headers[] = "Content-Type: application/json";
            }

            $ch = curl_init();

            // 设置URL
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            // 处理请求方法和数据
            if (strtoupper($method) === 'POST') {
                curl_setopt($ch, CURLOPT_POST, true);

                if (!empty($data)) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                }
            } else {
                // GET 请求处理
                if (!empty($data)) {
                    $url .= '?' . http_build_query($data);
                    curl_setopt($ch, CURLOPT_URL, $url);
                }
            }

            $output = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);

            if ($error) {
                throw new \Exception("Curl Error: " . $error);
            }

            // 尝试解析JSON
            $result = json_decode($output, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                // 如果不是JSON，返回原始内容或错误
                return [
                    'code' => $httpCode,
                    'data' => $output
                ];
            }

            return $result;

        } catch (\Exception $e) {

            return [
                'code' => 500,
                'msg' => $e->getMessage(),
                'success' => false
            ];
        }
    }

    /**
     * @method PDM物料基础/所有数据新增/变更
     * @param string|array $pIds PDM产品ID，可英文逗号分隔字符串或数组
     * @param string $type 数据更新类型 all-所有 base-基础资料变更
     * @return array
     */
    public function receivePdmProBase($pIds, $type = 'base')
    {   
        if(empty($pIds)){
            return [];
        }
        if (is_array($pIds)) {
            $pIds = implode(',', $pIds);
        }
        
        $data = [
            'p_ids' => $pIds,
            'type' => $type
        ];

        return $this->request('FreyApi/Product/PdmPro/receive', $data, 'POST');
    }

    /**
     * @method PDM物料关联数据新增/变更
     * @param string|array $plcIds 事业部产品关联ID，可英文逗号分隔字符串或数组
     * @param string $type 数据更新类型 com_link-事业部关联
     * @return array
     */
    public function receivePdmProLink($plcIds, $type = 'com_link')
    {   
        if(empty($plcIds)){
            return [];
        }
        if (is_array($plcIds)) {
            $plcIds = implode(',', $plcIds);
        }

        $data = [
            'plc_ids' => $plcIds,
            'type' => $type
        ];

        return $this->request('FreyApi/Product/PdmPro/receive', $data, 'POST');
    }

    /**
     * @method PDM物料包装数据新增/变更
     * @param string|array $freyNos 菲尔物料编码，英文逗号或数组格式
     * @param string|array $companyNos 公司编码，英文逗号或数组格式
     * @param string $type 数据更新类型 pack-包装数据
     * @return array
     */
    public function receivePdmProPack($freyNos, $companyNos, $type = 'pack')
    {   
        if(empty($freyNos) || empty($companyNos)){
            return [];
        }
        if (is_array($freyNos)) {
            $freyNos = implode(',', $freyNos);
        }
        if (is_array($companyNos)) {
            $companyNos = implode(',', $companyNos);
        }

        $data = [
            'frey_nos' => $freyNos,
            'company_nos' => $companyNos,
            'type' => $type
        ];

        return $this->request('FreyApi/Product/PdmPro/receive', $data, 'POST');
    }
}