YonyouBip.php 32.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
<?php

namespace app\admin\controller\antis;

use app\admin\controller\antis\Base;
use app\admin\library\YonyouBipClient;
use app\admin\model\kuerp\GoodsSalesOrder;
use app\admin\model\kuerp\GoodsSalesOrderInfo;
use app\admin\model\kuerp\Customers;
use app\admin\model\kuerp\Goods;
use app\admin\model\YonyouBipBaseData;
use addons\antis\model\Staff;
use addons\antis\model\StaffDepartment;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 用友BIP集成控制器
 * 处理销售订单和发货单的同步
 */
class YonyouBip extends Base
{
    /**
     * 用友BIP客户端实例
     * @var YonyouBipClient
     */
    private $bipClient;

    public function _initialize()
    {
        parent::_initialize();
        
        // 初始化用友BIP客户端(延迟初始化,避免在test页面时出错)
        // 可以从数据库配置表读取配置
        try {
            $config = $this->getBipConfig();
            if (!empty($config['app_key']) && !empty($config['app_secret'])) {
                $this->bipClient = new YonyouBipClient($config);
            }
        } catch (\Exception $e) {
            Log::error('用友BIP客户端初始化失败: ' . $e->getMessage());
            // 不抛出异常,允许页面加载
        }
    }

    /**
     * 获取用友BIP配置
     * @return array
     */
    private function getBipConfig()
    {
        // 从配置文件读取,如果配置文件没有加载,使用默认值
        $config = config('yonyou_bip');
        
        return [
            'base_url' => $config['base_url'] ?? 'https://c4.yonyoucloud.com',
            'app_key' => $config['app_key'] ?? '',
            'app_secret' => $config['app_secret'] ?? '',
            'tenant_id' => $config['tenant_id'] ?? '',
        ];
    }

    /**
     * 确保BIP客户端已初始化
     * @return YonyouBipClient
     * @throws Exception
     */
    private function ensureBipClient()
    {
        if (!$this->bipClient) {
            $config = $this->getBipConfig();
            if (empty($config['app_key']) || empty($config['app_secret'])) {
                throw new Exception('用友BIP配置不完整,请检查AppKey和AppSecret是否已配置');
            }
            $this->bipClient = new YonyouBipClient($config);
        }
        return $this->bipClient;
    }

    /**
     * 同步销售订单到用友BIP
     * @return \think\response\Json
     */
    public function syncSalesOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $orderId = $this->request->post('order_id');
        if (empty($orderId)) {
            $this->error('订单ID不能为空');
        }

        try {
            // 确保客户端已初始化
            $this->ensureBipClient();
            
            // 获取订单信息
            $order = GoodsSalesOrder::with(['customers'])->find($orderId);
            if (!$order) {
                $this->error('订单不存在');
            }

            // 获取订单明细
            $orderItems = GoodsSalesOrderInfo::where('purchase_code', $order['purchase_code'])->select();

            // 转换订单数据格式
            $bipOrderData = $this->convertOrderToBipFormat($order, $orderItems);

            // 调用用友BIP API创建订单
            $result = $this->bipClient->createSalesOrder($bipOrderData);

            // 保存同步结果
            $this->saveSyncResult($orderId, 'sales_order', $result);

            $this->success('销售订单同步成功', null, $result);
        } catch (Exception $e) {
            Log::error('同步销售订单失败: ' . $e->getMessage());
            $this->error('同步失败: ' . $e->getMessage());
        }
    }

    /**
     * 同步销售订单发货单到用友BIP
     * @return \think\response\Json
     */
    public function syncSalesDelivery()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $orderId = $this->request->post('order_id');
        if (empty($orderId)) {
            $this->error('订单ID不能为空');
        }

        try {
            // 确保客户端已初始化
            $this->ensureBipClient();
            
            // 获取订单信息
            $order = GoodsSalesOrder::find($orderId);
            if (!$order) {
                $this->error('订单不存在');
            }

            // 检查订单是否已发货
            if ($order['status'] != 2) { // 假设2表示已发货状态
                $this->error('订单尚未发货,无法同步发货单');
            }

            // 获取订单明细
            $orderItems = GoodsSalesOrderInfo::where('purchase_code', $order['purchase_code'])->select();

            // 转换发货数据格式
            $deliveryData = $this->convertDeliveryToBipFormat($order, $orderItems);

            // 调用用友BIP API创建发货单
            $result = $this->bipClient->createSalesDelivery($deliveryData);

            // 保存同步结果
            $this->saveSyncResult($orderId, 'sales_delivery', $result);

            $this->success('销售订单发货单同步成功', null, $result);
        } catch (Exception $e) {
            Log::error('同步销售订单发货单失败: ' . $e->getMessage());
            $this->error('同步失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量同步销售订单
     * @return \think\response\Json
     */
    public function batchSyncSalesOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $orderIds = $this->request->post('order_ids/a', []);
        if (empty($orderIds)) {
            $this->error('请选择要同步的订单');
        }

        $successCount = 0;
        $failCount = 0;
        $errors = [];

        // 确保客户端已初始化
        try {
            $this->ensureBipClient();
        } catch (\Exception $e) {
            $this->error('用友BIP配置错误: ' . $e->getMessage());
        }

        foreach ($orderIds as $orderId) {
            try {
                $order = GoodsSalesOrder::with(['customers'])->find($orderId);
                if (!$order) {
                    $errors[] = "订单ID {$orderId}: 订单不存在";
                    $failCount++;
                    continue;
                }

                $orderItems = GoodsSalesOrderInfo::where('purchase_code', $order['purchase_code'])->select();
                $bipOrderData = $this->convertOrderToBipFormat($order, $orderItems);
                $result = $this->bipClient->createSalesOrder($bipOrderData);
                $this->saveSyncResult($orderId, 'sales_order', $result);
                $successCount++;
            } catch (Exception $e) {
                $errors[] = "订单ID {$orderId}: " . $e->getMessage();
                $failCount++;
                Log::error("批量同步订单失败 [{$orderId}]: " . $e->getMessage());
            }
        }

        $message = "同步完成:成功 {$successCount} 条,失败 {$failCount} 条";
        if ($failCount > 0) {
            $message .= "\n错误信息:" . implode("\n", $errors);
        }

        $this->success($message, null, [
            'success' => $successCount,
            'fail' => $failCount,
            'errors' => $errors,
        ]);
    }

    /**
     * 将订单数据转换为用友BIP格式
     * @param GoodsSalesOrder $order 订单对象
     * @param array $orderItems 订单明细
     * @return array
     */
    private function convertOrderToBipFormat($order, $orderItems)
    {
        // 获取客户信息
        $customer = Customers::find($order['customers_id']);
        
        // 获取用友BIP基础数据映射
        $salesOrg = $this->getBipSalesOrganization($order);
        $transactionType = $this->getBipTransactionType($order);
        $salesDept = $this->getBipSalesDepartment($order);
        $salesPerson = $this->getBipSalesPerson($order);
        $bipCustomer = $this->getBipCustomer($order['customers_id']);
        
        // 构建订单数据
        $bipData = [
            // 订单基本信息
            'orderCode' => $order['purchase_code'], // 订单编号
            'orderDate' => date('Y-m-d', $order['purchase_time']), // 订单日期
            
            // 基础数据(必填)
            'salesOrgCode' => $salesOrg ? $salesOrg['bip_code'] : '', // 销售组织编码
            'salesOrgName' => $salesOrg ? $salesOrg['bip_name'] : '', // 销售组织名称
            'transactionTypeCode' => $transactionType ? $transactionType['bip_code'] : '', // 交易类型编码
            'transactionTypeName' => $transactionType ? $transactionType['bip_name'] : '', // 交易类型名称
            
            // 客户信息
            'customerCode' => $bipCustomer ? $bipCustomer['bip_code'] : ($customer ? $customer['customer_code'] : ''), // 客户编码(优先使用用友BIP的客户编码)
            'customerName' => $customer ? $customer['customer_name'] : '', // 客户名称
            
            // 销售部门和业务员
            'salesDeptCode' => $salesDept ? $salesDept['bip_code'] : '', // 销售部门编码
            'salesDeptName' => $salesDept ? $salesDept['bip_name'] : '', // 销售部门名称
            'salesPersonCode' => $salesPerson ? $salesPerson['bip_code'] : '', // 销售业务员编码
            'salesPersonName' => $salesPerson ? $salesPerson['bip_name'] : '', // 销售业务员名称
            
            // 金额信息
            'totalAmount' => $order['all_money'] ?? 0, // 订单总金额
            'taxAmount' => $order['tax_money'] ?? 0, // 税额
            'totalAmountWithTax' => $order['money_tax_price'] ?? 0, // 含税总金额
            'remark' => $order['remark'] ?? '', // 备注
            
            // 订单明细
            'orderItems' => [],
        ];

        // 转换订单明细
        foreach ($orderItems as $item) {
            $goods = Goods::find($item['goods_code']);
            
            $bipData['orderItems'][] = [
                'goodsCode' => $item['goods_code'], // 商品编码
                'goodsName' => $goods ? $goods['goods_name'] : '', // 商品名称
                'specification' => $item['goods_attr'] ?? '', // 规格
                'quantity' => $item['number'] ?? 0, // 数量
                'unitPrice' => $item['price'] ?? 0, // 单价
                'amount' => $item['all_money'] ?? 0, // 金额
                'taxRate' => $item['tax_rate'] ?? 0, // 税率
                'taxAmount' => $item['tax_money'] ?? 0, // 税额
                'amountWithTax' => $item['money_tax_price'] ?? 0, // 含税金额
                'warehouseCode' => $item['stores_id'] ?? '', // 仓库编码
                'remark' => $item['remark'] ?? '', // 备注
            ];
        }

        return $bipData;
    }

    /**
     * 将发货数据转换为用友BIP格式
     * @param GoodsSalesOrder $order 订单对象
     * @param array $orderItems 订单明细
     * @return array
     */
    private function convertDeliveryToBipFormat($order, $orderItems)
    {
        $customer = Customers::find($order['customers_id']);
        
        $deliveryData = [
            // 发货单基本信息
            'deliveryCode' => $order['purchase_code'] . '_DELIVERY', // 发货单编号
            'orderCode' => $order['purchase_code'], // 关联订单编号
            'deliveryDate' => $order['delivery_time'] ? date('Y-m-d', $order['delivery_time']) : date('Y-m-d'), // 发货日期
            'customerCode' => $customer ? $customer['customer_code'] : '',
            'customerName' => $customer ? $customer['customer_name'] : '',
            'remark' => $order['remark'] ?? '',
            
            // 发货明细
            'deliveryItems' => [],
        ];

        // 转换发货明细
        foreach ($orderItems as $item) {
            $goods = Goods::find($item['goods_code']);
            
            // 已发货数量(根据实际业务逻辑调整)
            $deliveredQty = $item['store_number'] ?? $item['number'] ?? 0;
            
            $deliveryData['deliveryItems'][] = [
                'goodsCode' => $item['goods_code'],
                'goodsName' => $goods ? $goods['goods_name'] : '',
                'specification' => $item['goods_attr'] ?? '',
                'quantity' => $deliveredQty, // 发货数量
                'warehouseCode' => $item['stores_id'] ?? '',
                'remark' => $item['remark'] ?? '',
            ];
        }

        return $deliveryData;
    }

    /**
     * 获取用友BIP销售组织
     * @param GoodsSalesOrder $order 订单对象
     * @return array|null
     */
    private function getBipSalesOrganization($order)
    {
        // 优先从订单配置中获取,如果没有则使用默认配置
        // 可以从订单表扩展字段或配置表中读取
        $defaultOrgCode = config('yonyou_bip.default_sales_org_code', '');
        if ($defaultOrgCode) {
            return YonyouBipBaseData::getByTypeAndCode(YonyouBipBaseData::TYPE_ORGANIZATION, $defaultOrgCode);
        }
        return null;
    }

    /**
     * 获取用友BIP交易类型
     * @param GoodsSalesOrder $order 订单对象
     * @return array|null
     */
    private function getBipTransactionType($order)
    {
        // 优先从订单配置中获取,如果没有则使用默认配置
        $defaultTypeCode = config('yonyou_bip.default_transaction_type_code', '');
        if ($defaultTypeCode) {
            return YonyouBipBaseData::getByTypeAndCode(YonyouBipBaseData::TYPE_TRANSACTION_TYPE, $defaultTypeCode);
        }
        return null;
    }

    /**
     * 获取用友BIP销售部门
     * @param GoodsSalesOrder $order 订单对象
     * @return array|null
     */
    private function getBipSalesDepartment($order)
    {
        // 从订单的销售部门或负责人部门获取
        if (isset($order['sale_user']) && $order['sale_user']) {
            // 获取销售人员的部门
            $staff = Staff::where(['id' => $order['sale_user']])->find();
            if ($staff && isset($staff['department_id'])) {
                $dept = StaffDepartment::find($staff['department_id']);
                if ($dept) {
                    // 查找本地部门对应的用友BIP部门
                    return YonyouBipBaseData::getByTypeAndLocalId(YonyouBipBaseData::TYPE_DEPARTMENT, $dept['id']);
                }
            }
        }
        
        // 如果没有,使用默认部门
        $defaultDeptCode = config('yonyou_bip.default_sales_dept_code', '');
        if ($defaultDeptCode) {
            return YonyouBipBaseData::getByTypeAndCode(YonyouBipBaseData::TYPE_DEPARTMENT, $defaultDeptCode);
        }
        return null;
    }

    /**
     * 获取用友BIP销售业务员
     * @param GoodsSalesOrder $order 订单对象
     * @return array|null
     */
    private function getBipSalesPerson($order)
    {
        // 从订单的销售业务员获取
        if (isset($order['sale_user']) && $order['sale_user']) {
            // 查找本地业务员对应的用友BIP业务员
            return YonyouBipBaseData::getByTypeAndLocalId(YonyouBipBaseData::TYPE_PERSON, $order['sale_user']);
        }
        return null;
    }

    /**
     * 获取用友BIP客户
     * @param int $customerId 客户ID
     * @return array|null
     */
    private function getBipCustomer($customerId)
    {
        if ($customerId) {
            // 查找本地客户对应的用友BIP客户
            return YonyouBipBaseData::getByTypeAndLocalId(YonyouBipBaseData::TYPE_CUSTOMER, $customerId);
        }
        return null;
    }

    /**
     * 保存同步结果
     * @param int $orderId 订单ID
     * @param string $type 同步类型
     * @param array $result 同步结果
     */
    private function saveSyncResult($orderId, $type, $result)
    {
        try {
            // 获取订单信息
            $order = GoodsSalesOrder::find($orderId);
            if (!$order) {
                return;
            }

            // 判断同步是否成功
            $syncStatus = 0;
            $bipOrderId = null;
            $errorMessage = null;

            // 根据用友BIP返回结果判断(根据实际API返回格式调整)
            if (isset($result['code']) && $result['code'] == 200) {
                $syncStatus = 1;
                $bipOrderId = $result['data']['id'] ?? $result['data']['orderId'] ?? null;
            } else {
                $errorMessage = $result['message'] ?? $result['msg'] ?? '同步失败';
            }

            // 获取表前缀
            $prefix = config('database.prefix', 'ats_');
            
            // 保存同步记录到数据库
            $syncData = [
                'order_id' => $orderId,
                'order_code' => $order['purchase_code'],
                'sync_type' => $type,
                'sync_status' => $syncStatus,
                'sync_result' => json_encode($result, JSON_UNESCAPED_UNICODE),
                'bip_order_id' => $bipOrderId,
                'error_message' => $errorMessage,
                'sync_time' => time(),
                'createtime' => time(),
                'updatetime' => time(),
            ];

            // 检查表是否存在,如果存在则保存
            $tableExists = Db::query("SHOW TABLES LIKE '{$prefix}yonyou_bip_sync_log'");
            if (!empty($tableExists)) {
                Db::name('yonyou_bip_sync_log')->insert($syncData);
            }
            
            // 更新订单表的同步状态字段(如果字段存在)
            if ($syncStatus == 1) {
                $tableName = $prefix . 'kuerp_goods_sales_order';
                $columns = Db::query("SHOW COLUMNS FROM `{$tableName}` LIKE 'bip_sync_status'");
                if (!empty($columns)) {
                    Db::name('kuerp_goods_sales_order')->where('id', $orderId)->update([
                        'bip_sync_status' => 1,
                        'bip_order_id' => $bipOrderId,
                        'bip_sync_time' => time(),
                    ]);
                }
            }
        } catch (\Exception $e) {
            Log::error('保存同步结果失败: ' . $e->getMessage());
        }
    }

    /**
     * 查询同步状态
     * @return \think\response\Json
     */
    public function getSyncStatus()
    {
        $orderId = $this->request->get('order_id');
        if (empty($orderId)) {
            $this->error('订单ID不能为空');
        }

        try {
            // 查询订单信息
            $order = GoodsSalesOrder::find($orderId);
            if (!$order) {
                $this->error('订单不存在');
            }

            // 获取表前缀
            $prefix = config('database.prefix', 'ats_');
            
            // 查询同步记录
            $syncLog = null;
            $tableExists = Db::query("SHOW TABLES LIKE '{$prefix}yonyou_bip_sync_log'");
            if (!empty($tableExists)) {
                $syncLog = Db::name('yonyou_bip_sync_log')
                    ->where('order_id', $orderId)
                    ->order('sync_time desc')
                    ->find();
            }

            // 从订单表获取同步状态
            $tableName = $prefix . 'kuerp_goods_sales_order';
            $columns = Db::query("SHOW COLUMNS FROM `{$tableName}` LIKE 'bip_sync_status'");
            $bipSyncStatus = 0;
            $bipOrderId = null;
            $bipSyncTime = null;
            
            if (!empty($columns)) {
                $bipSyncStatus = $order['bip_sync_status'] ?? 0;
                $bipOrderId = $order['bip_order_id'] ?? null;
                $bipSyncTime = $order['bip_sync_time'] ?? null;
            }

            $result = [
                'order_id' => $orderId,
                'order_code' => $order['purchase_code'],
                'sync_status' => $bipSyncStatus,
                'bip_order_id' => $bipOrderId,
                'sync_time' => $bipSyncTime ? date('Y-m-d H:i:s', $bipSyncTime) : null,
                'sync_log' => $syncLog,
            ];

            $this->success('查询成功', null, $result);
        } catch (\Exception $e) {
            Log::error('查询同步状态失败: ' . $e->getMessage());
            $this->error('查询失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取销售组织列表
     * @return \think\response\Json
     */
    public function getSalesOrganizations()
    {
        try {
            $list = YonyouBipBaseData::getListByType(YonyouBipBaseData::TYPE_ORGANIZATION);
            $this->success('获取成功', null, $list);
        } catch (\Exception $e) {
            Log::error('获取销售组织列表失败: ' . $e->getMessage());
            $this->error('获取失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取交易类型列表
     * @return \think\response\Json
     */
    public function getTransactionTypes()
    {
        try {
            $list = YonyouBipBaseData::getListByType(YonyouBipBaseData::TYPE_TRANSACTION_TYPE);
            $this->success('获取成功', null, $list);
        } catch (\Exception $e) {
            Log::error('获取交易类型列表失败: ' . $e->getMessage());
            $this->error('获取失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取销售部门列表
     * @return \think\response\Json
     */
    public function getSalesDepartments()
    {
        try {
            $list = YonyouBipBaseData::getListByType(YonyouBipBaseData::TYPE_DEPARTMENT);
            $this->success('获取成功', null, $list);
        } catch (\Exception $e) {
            Log::error('获取销售部门列表失败: ' . $e->getMessage());
            $this->error('获取失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取销售业务员列表
     * @return \think\response\Json
     */
    public function getSalesPersons()
    {
        try {
            $list = YonyouBipBaseData::getListByType(YonyouBipBaseData::TYPE_PERSON);
            $this->success('获取成功', null, $list);
        } catch (\Exception $e) {
            Log::error('获取销售业务员列表失败: ' . $e->getMessage());
            $this->error('获取失败: ' . $e->getMessage());
        }
    }

    /**
     * 从用友BIP同步基础数据
     * @return \think\response\Json
     */
    public function syncBaseData()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $type = $this->request->post('type', '');
        $types = [
            'organization' => '销售组织',
            'transaction_type' => '交易类型',
            'department' => '销售部门',
            'person' => '销售业务员',
            'customer' => '客户',
        ];

        if (!isset($types[$type])) {
            $this->error('不支持的数据类型');
        }

        try {
            // 确保客户端已初始化
            $this->ensureBipClient();
            
            // 从用友BIP获取数据
            $result = $this->bipClient->syncBaseData($type);
            
            // 解析返回结果(根据实际API返回格式调整)
            $dataList = $result['data'] ?? $result['list'] ?? [];
            
            if (empty($dataList)) {
                $this->error('未获取到数据');
            }

            $successCount = 0;
            $failCount = 0;

            // 保存到本地数据库
            foreach ($dataList as $item) {
                try {
                    // 根据实际API返回格式调整字段名
                    $bipCode = $item['code'] ?? $item['orgCode'] ?? $item['deptCode'] ?? $item['personCode'] ?? $item['customerCode'] ?? '';
                    $bipName = $item['name'] ?? $item['orgName'] ?? $item['deptName'] ?? $item['personName'] ?? $item['customerName'] ?? '';
                    $localId = $item['localId'] ?? null; // 如果有本地ID映射
                    
                    if ($bipCode && $bipName) {
                        YonyouBipBaseData::saveOrUpdate($type, $bipCode, $bipName, $localId, $item);
                        $successCount++;
                    } else {
                        $failCount++;
                    }
                } catch (\Exception $e) {
                    $failCount++;
                    Log::error("保存基础数据失败 [{$type}]: " . $e->getMessage());
                }
            }

            $message = "同步完成:成功 {$successCount} 条,失败 {$failCount} 条";
            $this->success($message, null, [
                'type' => $type,
                'type_name' => $types[$type],
                'success' => $successCount,
                'fail' => $failCount,
            ]);
        } catch (\Exception $e) {
            Log::error('同步基础数据失败: ' . $e->getMessage());
            $this->error('同步失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量同步所有基础数据
     * @return \think\response\Json
     */
    public function syncAllBaseData()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $types = [
            'organization' => '销售组织',
            'transaction_type' => '交易类型',
            'department' => '销售部门',
            'person' => '销售业务员',
            'customer' => '客户',
        ];

        $results = [];
        $totalSuccess = 0;
        $totalFail = 0;

        foreach ($types as $type => $typeName) {
            try {
                $result = $this->bipClient->syncBaseData($type);
                $dataList = $result['data'] ?? $result['list'] ?? [];
                
                $successCount = 0;
                $failCount = 0;

                foreach ($dataList as $item) {
                    try {
                        $bipCode = $item['code'] ?? $item['orgCode'] ?? $item['deptCode'] ?? $item['personCode'] ?? $item['customerCode'] ?? '';
                        $bipName = $item['name'] ?? $item['orgName'] ?? $item['deptName'] ?? $item['personName'] ?? $item['customerName'] ?? '';
                        $localId = $item['localId'] ?? null;
                        
                        if ($bipCode && $bipName) {
                            YonyouBipBaseData::saveOrUpdate($type, $bipCode, $bipName, $localId, $item);
                            $successCount++;
                        } else {
                            $failCount++;
                        }
                    } catch (\Exception $e) {
                        $failCount++;
                    }
                }

                $totalSuccess += $successCount;
                $totalFail += $failCount;

                $results[$type] = [
                    'type_name' => $typeName,
                    'success' => $successCount,
                    'fail' => $failCount,
                ];
            } catch (\Exception $e) {
                $results[$type] = [
                    'type_name' => $typeName,
                    'success' => 0,
                    'fail' => 0,
                    'error' => $e->getMessage(),
                ];
                Log::error("同步基础数据失败 [{$type}]: " . $e->getMessage());
            }
        }

        $message = "批量同步完成:总计成功 {$totalSuccess} 条,失败 {$totalFail} 条";
        $this->success($message, null, [
            'total_success' => $totalSuccess,
            'total_fail' => $totalFail,
            'results' => $results,
        ]);
    }

    /**
     * 设置本地数据与用友BIP数据的映射关系
     * @return \think\response\Json
     */
    public function setDataMapping()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $type = $this->request->post('type', '');
        $localId = $this->request->post('local_id', 0);
        $bipCode = $this->request->post('bip_code', '');

        if (empty($type) || empty($localId) || empty($bipCode)) {
            $this->error('参数不完整');
        }

        try {
            // 获取用友BIP数据
            $bipData = YonyouBipBaseData::getByTypeAndCode($type, $bipCode);
            if (!$bipData) {
                $this->error('用友BIP数据不存在,请先同步基础数据');
            }

            // 更新本地ID映射
            $bipData->local_id = $localId;
            $bipData->save();

            $this->success('映射关系设置成功');
        } catch (\Exception $e) {
            Log::error('设置数据映射失败: ' . $e->getMessage());
            $this->error('设置失败: ' . $e->getMessage());
        }
    }

    /**
     * 测试连接(用于验证配置是否正确)
     * @return \think\response\Json
     */
    public function testConnection()
    {
        try {
            $config = $this->getBipConfig();
            
            // 检查配置是否完整
            if (empty($config['app_key']) || empty($config['app_secret'])) {
                $this->error('配置不完整:请检查 AppKey 和 AppSecret 是否已配置');
            }
            
            if (empty($config['base_url'])) {
                $this->error('配置不完整:请检查服务地址是否已配置');
            }
            
            // 确保客户端已初始化
            $this->ensureBipClient();
            
            // 测试获取Token
            $token = $this->bipClient->getAccessToken();
            
            $this->success('连接成功!', null, [
                'base_url' => $config['base_url'],
                'app_key' => substr($config['app_key'], 0, 8) . '...', // 只显示前8位
                'token_length' => strlen($token),
                'token_preview' => substr($token, 0, 20) . '...',
                'message' => 'Token获取成功,可以开始使用API',
            ]);
        } catch (\Exception $e) {
            Log::error('用友BIP连接测试失败: ' . $e->getMessage());
            $this->error('连接失败: ' . $e->getMessage());
        }
    }

    /**
     * 测试页面
     * @return string
     */
    public function test()
    {
        // 获取配置信息
        $config = $this->getBipConfig();
        
        // 获取订单列表(最近10条)
        $orderList = [];
        
        // 使用Db直接查询,避免模型关联问题
        try {
            $orders = Db::name('kuerp_goods_sales_order')
                ->order('purchase_time', 'desc')
                ->limit(10)
                ->select();
            
            // 处理订单数据
            foreach ($orders as $order) {
                $orderData = $order;
                
                // 获取客户信息
                if (!empty($orderData['customers_id'])) {
                    $customer = Db::name('kuerp_customers')
                        ->where('id', $orderData['customers_id'])
                        ->find();
                    if ($customer) {
                        $orderData['customers'] = $customer;
                    }
                }
                
                $orderList[] = $orderData;
            }
        } catch (\Exception $e) {
            // 如果查询失败,使用空数组,不影响页面加载
            Log::error('获取订单列表失败: ' . $e->getMessage());
            $orderList = [];
        }
        
        // 获取配置状态
        $configStatus = [
            'base_url' => isset($config['base_url']) ? $config['base_url'] : '未配置',
            'app_key' => !empty($config['app_key']) ? substr($config['app_key'], 0, 8) . '...' : '未配置',
            'app_secret' => !empty($config['app_secret']) ? '已配置' : '未配置',
            'tenant_id' => !empty($config['tenant_id']) ? $config['tenant_id'] : '未配置',
        ];
        
        $this->assign('config', $configStatus);
        $this->assign('orderList', $orderList);
        
        return $this->view->fetch();
    }

    /**
     * 获取订单列表(用于测试页面)
     * @return \think\response\Json
     */
    public function getOrderList()
    {
        if (!$this->request->isAjax()) {
            $this->error('请求方式错误');
        }

        try {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $list = GoodsSalesOrder::with(['customers'])
                ->where($where)
                ->order('purchase_time', 'desc')
                ->paginate($limit);
            
            foreach ($list as $row) {
                $row->getRelation('customers')->visible(['customer_name']);
            }
            
            $result = [
                "total" => $list->total(),
                "rows" => $list->items()
            ];
            
            return json($result);
        } catch (\Exception $e) {
            $this->error('获取订单列表失败: ' . $e->getMessage());
        }
    }
}