Business.php 66.3 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 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
<?php

namespace app\admin\controller\antis\customer;

use addons\antis\model\BusinessStatus;
use addons\antis\model\Customer;
use addons\antis\model\Field;
use addons\antis\model\File;
use addons\antis\model\BusinessProduct;
use addons\antis\model\FormField;
use addons\antis\model\Product;
use addons\antis\library\StaffAuth;
use addons\antis\model\Staff;
use addons\qingdong\model\Amodela;
use app\admin\controller\antis\Base;
use addons\antis\model\BusinessOther;
use addons\antis\model\Form;
use addons\antis\model\Contract;
use addons\antis\model\Record;
use app\admin\model\fastflow\bill\Czgprz;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use think\Db;
use think\Exception;


/**
 * 项目管理
 */
class Business extends Base
{

    protected $noNeedLogin = ['*'];
    protected $relationSearch = true;
    /**
     * @var \addons\antis\model\Business
     */
    protected $model = null;


    public function _initialize()
    {
        // 如果是 save_quotation_link 方法,跳过父类初始化,避免可能的错误
        try {
            $action = strtolower($this->request->action());
            if ($action == 'save_quotation_link' || $action == 'test_save_quotation_link' || $action == 'test_amodela') {
                // 只执行必要的初始化,跳过可能导致错误的操作
                return;
            }
        } catch (\Exception $e) {
            // 如果获取 action 失败,继续执行
        }
        
        parent::_initialize();
        $this->model = new \addons\antis\model\Business;

        $this->view->assign("typeList", $this->model->getTypeList());
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {

                //halt(111);
                return $this->selectpage();
            }






            $filter = $this->request->get("filter", '');
            $op=$this->request->get("op", '', 'trim');
            $filter = (array)json_decode($filter, true);
            $op = (array)json_decode($op, true);
            $customer_name = null;
            if(isset($filter['customer.name'])){
                $customer_name = $filter['customer.name'];
                unset($filter['customer.name']);
                unset($op['customer.name']);
                \think\Request::instance()->get(['filter'=>json_encode($filter)]);
                \think\Request::instance()->get(['op'=>json_encode($op)]);

            }


            // halt($customer_name);

            //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
            $type = input('type', 0);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // halt($type);
            switch ($type) {
                case 1:
                    $staff = Staff::info();
                    $wheres['owner_staff_id'] = $staff->id;
                    break;
                case 2:
                    $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
                    break;
                case 3:
                    $start = date('Y-m-d 00:00:00');
                    $end = date('Y-m-d 23:59:59');
                    $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
                    $relationId = [];
                    foreach ($record as $k => $v) {
                        $whereRe['id'] = array('gt', $v['id']);
                        $whereRe['relation_id'] = $v['relation_id'];
                        $recordData = Record::where($whereRe)->count();
                        if ($recordData == 0) {
                            $relationId[] = $v['relation_id'];
                        }

                    }
                    $wheres['id'] = array('in', $relationId);
                    $staff = Staff::info();
                    $wheres['owner_staff_id'] = $staff->id;
                    break;
                case 4:
                    $start = date('Y-m-d 00:00:00');
                    $end = date('Y-m-d 23:59:59');
                    $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
                    $relationId = [];
                    foreach ($record as $k => $v) {
                        $whereRe['id'] = array('gt', $v['id']);
                        $whereRe['relation_id'] = $v['relation_id'];
                        $recordData = Record::where($whereRe)->count();
                        if ($recordData >= 1) {
                            $relationId[] = $v['relation_id'];
                        }

                    }
                    $wheres['id'] = array('in', $relationId);
                    $staff = Staff::info();
                    $wheres['owner_staff_id'] = $staff->id;
                    break;
                case 5:
                    $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
                    $wheres['id'] = array('not in', $record);
                    $staff = Staff::info();
                    $wheres['owner_staff_id'] = $staff->id;
                    break;
                default:
                    $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
                    break;

            }
            $ids = [];
            $group_id = input('group_id');
            $staff_id = input('staff_id');
            if ($group_id) {//角色组
                $ids = Staff::getGroupStaffIds($group_id);
            }
            if ($staff_id) {
                $ids = $staff_id;
            }
            if ($group_id || $staff_id) {
                $wheres['owner_staff_id'] = ['in', $ids];
            }
            // halt($where);

            



            $list = $this->model->where($where)
                ->where($wheres)
                ->with([
                    'customer'=>function($query)use($customer_name){
                        if(!empty($customer_name)){
                            // halt($customer_name);
                        }
                    },
                    'ownerStaff',
                    'product'
                ])->order($sort, $order)->paginate($limit);
            foreach($list as $k=>$v){
                $types = BusinessStatus::where(array('business_id'=>$v['id']))->order('id desc')->value('type');
                $list[$k]['type'] = $types ? (int)$types : 0;
            }
            //halt($list->items());
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $field = FormField::getFields(FormField::BUSINESS_TYPE);
        $this->assignconfig('fields', $field);
        return $this->view->fetch();
    }



    public function index2(){

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage2(2);
            }
        }
    }

    public function get_business_bill(){

        $param = $this->request->param();

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $AmodelaModel = new Amodela();

        // 查询该项目的所有报价单(包括用友集成和PHP项目的)
        // 简单查询:只要 business_id 匹配即可
        $business_id = $param['business_id'];
        
        // 调试:记录查询参数
        \think\Log::write('get_business_bill 查询参数: business_id=' . $business_id, 'info');
        
        // 查询所有记录(包括 bill_id 为 0 的用友集成报价单)
        $list = $AmodelaModel->where('business_id', $business_id)->order('id desc')->paginate($limit);
        
        // 调试:记录查询结果
        \think\Log::write('get_business_bill 查询结果数量: ' . $list->total(), 'info');
        if ($list->total() > 0) {
            foreach ($list->items() as $item) {
                \think\Log::write('get_business_bill 记录详情: id=' . $item['id'] . ', name=' . ($item['name'] ?? '') . ', bill_id=' . ($item['bill_id'] ?? 'null'), 'info');
            }
        } else {
            // 如果没有查询到结果,尝试查询所有 business_id 的记录(用于调试)
            $allRecords = $AmodelaModel->where('business_id', $business_id)->select();
            \think\Log::write('get_business_bill 未查询到分页结果,但直接查询找到 ' . count($allRecords) . ' 条记录', 'warning');
        }


        // items() 可能是 Model 对象,不能直接传入声明为 array 的 enrich(PHP8+ 会 TypeError 500)
        $rows = [];
        foreach ($list->items() as $row) {
            $item = is_array($row) ? $row : (is_object($row) && method_exists($row, 'toArray') ? $row->toArray() : (array)$row);
            self::enrichQuotationListRow($item, $AmodelaModel);
            $rows[] = $item;
        }

        $result = ['total' => $list->total(), 'rows' => $rows];

        return json($result);

    }

    /**
     * 测试接口 - 用于排查问题
     * @return \think\response\Json
     */
    public function test_save_quotation_link()
    {
        header('Content-Type: application/json; charset=utf-8');
        try {
            return json(['code' => 1, 'msg' => '测试接口正常', 'data' => ['time' => date('Y-m-d H:i:s')]]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '测试接口异常:' . $e->getMessage()]);
        }
    }

    /**
     * 测试接口2 - 测试 Amodela 模型
     * @return \think\response\Json
     */
    public function test_amodela()
    {
        header('Content-Type: application/json; charset=utf-8');
        try {
            $amodelaModel = new Amodela();
            $count = $amodelaModel->count();
            return json(['code' => 1, 'msg' => 'Amodela模型正常', 'data' => ['count' => $count]]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => 'Amodela模型异常:' . $e->getMessage()]);
        }
    }

    /**
     * 保存报价单关联(用于关联用友集成的报价单)
     * @return \think\response\Json
     */
    public function save_quotation_link()
    {
        // 立即设置响应头为 JSON,避免 ThinkPHP 输出 HTML 错误页面
        header('Content-Type: application/json; charset=utf-8');
        
        // 处理 CORS 跨域请求
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
            header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        }
        
        // 处理 OPTIONS 预检请求
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            http_response_code(200);
            exit;
        }
        
        // 使用 ob_start 捕获所有输出,确保只返回 JSON
        ob_start();
        
        try {
            \think\Log::write('save_quotation_link 开始执行', 'info');
            
            // 获取参数 - 使用 $_POST 或 $_REQUEST 直接获取,避免依赖 $this->request
            $business_id = isset($_POST['business_id']) ? $_POST['business_id'] : (isset($_REQUEST['business_id']) ? $_REQUEST['business_id'] : '');
            $quotation_id = isset($_POST['quotation_id']) ? $_POST['quotation_id'] : (isset($_REQUEST['quotation_id']) ? $_REQUEST['quotation_id'] : '');
            $quotation_number = isset($_POST['quotation_number']) ? $_POST['quotation_number'] : (isset($_REQUEST['quotation_number']) ? $_REQUEST['quotation_number'] : '');
            $quotation_name = isset($_POST['quotation_name']) ? $_POST['quotation_name'] : (isset($_REQUEST['quotation_name']) ? $_REQUEST['quotation_name'] : '');
            $total_amount = isset($_POST['total_amount']) ? floatval($_POST['total_amount']) : (isset($_REQUEST['total_amount']) ? floatval($_REQUEST['total_amount']) : 0);
            $lrl = isset($_POST['lrl']) ? floatval($_POST['lrl']) : (isset($_REQUEST['lrl']) ? floatval($_REQUEST['lrl']) : 0);
            $initiator_staff_id = isset($_POST['initiator_staff_id']) ? intval($_POST['initiator_staff_id']) : (isset($_REQUEST['initiator_staff_id']) ? intval($_REQUEST['initiator_staff_id']) : 0);
            
            // JSON 请求体:补全/覆盖参数(与用友前端 axios JSON 一致)
            $rawInput = file_get_contents('php://input');
            if (!empty($rawInput)) {
                $jsonInput = json_decode($rawInput, true);
                if ($jsonInput && is_array($jsonInput)) {
                    if (isset($jsonInput['business_id']) && $jsonInput['business_id'] !== '') {
                        $business_id = trim($jsonInput['business_id']);
                    }
                    if (isset($jsonInput['quotation_id']) && $jsonInput['quotation_id'] !== '') {
                        $quotation_id = trim($jsonInput['quotation_id']);
                    }
                    if (isset($jsonInput['quotation_number'])) {
                        $quotation_number = trim($jsonInput['quotation_number']);
                    }
                    if (isset($jsonInput['quotation_name'])) {
                        $quotation_name = trim($jsonInput['quotation_name']);
                    }
                    if (isset($jsonInput['total_amount'])) {
                        $total_amount = floatval($jsonInput['total_amount']);
                    }
                    if (isset($jsonInput['lrl'])) {
                        $lrl = floatval($jsonInput['lrl']);
                    }
                    if (isset($jsonInput['initiator_staff_id'])) {
                        $initiator_staff_id = intval($jsonInput['initiator_staff_id']);
                    }
                }
            }
            
            // 类型转换
            $business_id = intval($business_id);
            $quotation_id = intval($quotation_id);
            
            \think\Log::write('save_quotation_link 收到请求: business_id=' . $business_id . ', quotation_id=' . $quotation_id, 'info');
            
            if (empty($business_id) || empty($quotation_id)) {
                \think\Log::write('save_quotation_link 参数不完整', 'warning');
                ob_clean();
                echo json_encode(['code' => 0, 'msg' => '参数不完整:business_id 和 quotation_id 必填', 'data' => null], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            \think\Log::write('save_quotation_link 开始查询项目', 'info');
            
            // 直接创建 Business 模型实例,避免依赖 _initialize() 中的初始化
            $businessModel = new \addons\antis\model\Business();
            
            // 检查项目是否存在
            $business = $businessModel->where('id', $business_id)->find();
            if (!$business) {
                \think\Log::write('save_quotation_link 项目不存在: business_id=' . $business_id, 'warning');
                ob_clean();
                echo json_encode(['code' => 0, 'msg' => '项目不存在', 'data' => null], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            \think\Log::write('save_quotation_link 项目查询成功', 'info');
            
            // 获取客户信息
            $customer_id = null;
            $customer_name = '';
            try {
                // $business 可能是对象或数组,需要兼容处理
                if (is_object($business)) {
                    $customer_id = isset($business->customer_id) ? $business->customer_id : null;
                } else {
                    $customer_id = isset($business['customer_id']) ? $business['customer_id'] : null;
                }
                
                if ($customer_id) {
                    $customerModel = new \addons\antis\model\Customer();
                    $customer = $customerModel->where('id', $customer_id)->find();
                    $customer_name = $customer ? (is_object($customer) ? ($customer->name ?? '') : ($customer['name'] ?? '')) : '';
                }
            } catch (\Exception $e) {
                \think\Log::write('save_quotation_link 获取客户信息失败: ' . $e->getMessage(), 'warning');
                // 客户信息获取失败不影响主流程
            }
            
            \think\Log::write('save_quotation_link 开始创建 Amodela 记录', 'info');
            
            // 在 Amodela 表中创建关联记录
            // 由于 Amodela 表可能没有 quotation_id 字段,我们在 name 字段中包含 quotation_id 信息
            // name 格式:{客户名称}_{项目名称}_{yyyyMMdd}(quotation_{quotation_id})
            
            $amodelaModel = new Amodela();
            
            // 检查是否已存在关联记录(通过 business_id 和 name 中的 quotation_id)
            $existing = $amodelaModel->where('business_id', $business_id)
                ->where('name', 'like', '%(quotation_' . $quotation_id . ')%')
                ->find();
            
            // 确保 name 字段始终包含 quotation_id 标记,格式:{名称}(quotation_{quotation_id})
            // 如果 quotation_name 已经包含标记,直接使用;否则追加标记
            $quotationMarker = '(quotation_' . $quotation_id . ')';
            if ($quotation_name) {
                // 如果 quotation_name 中已经包含标记,直接使用;否则追加标记
                if (strpos($quotation_name, $quotationMarker) === false) {
                    $quotationName = $quotation_name . $quotationMarker;
                } else {
                    $quotationName = $quotation_name;
                }
            } else {
                // 未传 quotation_name:客户名称_项目名称_日期
                $businessName = '';
                if (is_object($business)) {
                    $businessName = isset($business->name) ? trim((string)$business->name) : '';
                } else {
                    $businessName = isset($business['name']) ? trim((string)$business['name']) : '';
                }
                $dateStr = date('Ymd');
                $segments = array_values(array_filter([trim($customer_name), $businessName, $dateStr], function ($v) {
                    return $v !== '';
                }));
                $baseName = implode('_', $segments);
                $quotationName = $baseName !== '' ? ($baseName . $quotationMarker) : ('用友报价单-' . $quotation_number . $quotationMarker);
            }
            
            if ($existing) {
                // 更新现有记录
                $existing->name = $quotationName;
                // 不更新 status,因为可能字段不存在
                $result = $existing->save();
                $amodelaModel = $existing;
            } else {
                // 创建新的关联记录
                
                // 构建保存数据
                // Amodela(amodel_a) 在现有系统里通常包含较多字段(Billczgprz 写入了 customer_id/business_name/type/json/amodel_id/status 等)
                // 为避免生产库字段存在 NOT NULL / 无默认值导致 500(System Error),这里补齐一套“安全默认值”
                $amodelaModel->business_id = $business_id;
                $amodelaModel->bill_id = 0; // 用友集成报价单:不对应 PHP 流程单据
                $amodelaModel->name = $quotationName;
                $amodelaModel->status = '1'; // 直接标记为已关联
                $amodelaModel->amodel_id = 0;
                $amodelaModel->type = 'goods';
                $amodelaModel->goods_id = '';
                $amodelaModel->json = json_encode([], JSON_UNESCAPED_UNICODE);
                $amodelaModel->lr = 1;
                $amodelaModel->file = '';

                // 补齐客户信息/项目名称(如果字段存在)
                // $business 可能是对象或数组,需要兼容处理
                $customerId = 0;
                $businessName = '';
                if (is_object($business)) {
                    $customerId = isset($business->customer_id) ? $business->customer_id : 0;
                    $businessName = isset($business->name) ? $business->name : '';
                } else {
                    $customerId = isset($business['customer_id']) ? $business['customer_id'] : 0;
                    $businessName = isset($business['name']) ? $business['name'] : '';
                }
                $amodelaModel->customer_id = $customerId;
                $amodelaModel->business_name = $businessName;
                if ($customerId) {
                    try {
                        $amodelaModel->customer_name = \addons\antis\model\Customer::where('id', $customerId)->value('name') ?: '';
                    } catch (\Exception $e) {
                        // customer_name 非关键字段,异常时置空即可
                        $amodelaModel->customer_name = '';
                    }
                } else {
                    $amodelaModel->customer_name = '';
                }
                
                // 调试:记录保存前的数据
                \think\Log::write('save_quotation_link 准备保存数据: business_id=' . $business_id . ', customer_id=' . $customerId . ', name=' . $quotationName . ', bill_id=0, type=goods, status=1, amodel_id=0', 'info');
                
                // 尝试保存
                try {
                    // 使用 allowField(true) 以数据库真实字段为准,避免“字段不存在”导致 SQL 报错
                    $result = $amodelaModel->allowField(true)->save();
                    
                    // 调试:记录保存结果
                    if ($result) {
                        $savedId = $amodelaModel->id;
                        \think\Log::write('save_quotation_link 保存成功: id=' . $savedId, 'info');
                        
                        // 立即验证保存是否成功
                        $verifyRecord = $amodelaModel->where('id', $savedId)->find();
                        if ($verifyRecord) {
                            \think\Log::write('save_quotation_link 验证成功: id=' . $savedId . ', name=' . $verifyRecord['name'], 'info');
                        } else {
                            \think\Log::write('save_quotation_link 警告: save()返回true但查询不到记录 id=' . $savedId, 'warning');
                        }
                    } else {
                        $errorMsg = $amodelaModel->getError() ?: '未知错误';
                        \think\Log::write('save_quotation_link 保存失败: ' . $errorMsg, 'error');
                        \think\Log::write('save_quotation_link 模型数据: ' . json_encode($amodelaModel->getData(), JSON_UNESCAPED_UNICODE), 'error');
                    }
                } catch (\Exception $e) {
                    \think\Log::write('save_quotation_link 保存异常: ' . $e->getMessage() . ' | 文件: ' . $e->getFile() . ' | 行号: ' . $e->getLine(), 'error');
                    \think\Log::write('save_quotation_link 异常堆栈: ' . $e->getTraceAsString(), 'error');
                    throw $e;
                }
            }
            
            if ($result && isset($amodelaModel->id) && $amodelaModel->id > 0) {
                $fastflowInfo = ['bill_id' => null, 'flow_started' => false, 'msg' => ''];
                try {
                    $fastflowInfo = self::syncYongyouBaojiadanAfterQuotationLink(
                        $amodelaModel,
                        $business,
                        (string)$quotation_number,
                        $quotation_id,
                        $total_amount,
                        $lrl,
                        $initiator_staff_id
                    );
                } catch (\Throwable $e) {
                    $fastflowInfo['msg'] = $e->getMessage();
                    \think\Log::write('save_quotation_link FastFlow 同步异常: ' . $e->getMessage(), 'error');
                }
                // 返回成功信息,包含保存的ID和name用于调试
                ob_clean();
                echo json_encode([
                    'code' => 1,
                    'msg' => '报价单关联成功',
                    'data' => [
                        'id' => $amodelaModel->id,
                        'name' => $amodelaModel->name,
                        'business_id' => $business_id,
                        'quotation_id' => $quotation_id,
                        'fastflow' => $fastflowInfo,
                    ]
                ], JSON_UNESCAPED_UNICODE);
                exit;
            } else {
                $errorMsg = '报价单关联失败:保存返回false或未获取到ID';
                if ($amodelaModel->getError()) {
                    $errorMsg .= ',错误:' . $amodelaModel->getError();
                }
                if (isset($amodelaModel->id)) {
                    $errorMsg .= ',ID:' . $amodelaModel->id;
                } else {
                    $errorMsg .= ',未获取到ID';
                }
                // 记录详细的错误信息
                \think\Log::write('save_quotation_link 保存失败详情: ' . $errorMsg, 'error');
                \think\Log::write('save_quotation_link 模型数据: ' . json_encode($amodelaModel->getData(), JSON_UNESCAPED_UNICODE), 'error');
                ob_clean();
                echo json_encode(['code' => 0, 'msg' => $errorMsg, 'data' => null], JSON_UNESCAPED_UNICODE);
                exit;
            }
        } catch (\Exception $e) {
            // 记录详细的错误信息
            $errorMsg = '保存关联关系失败:' . $e->getMessage();
            $errorMsg .= ' | 文件:' . $e->getFile();
            $errorMsg .= ' | 行号:' . $e->getLine();
            $errorMsg .= ' | 堆栈:' . $e->getTraceAsString();
            
            \think\Log::write('save_quotation_link 异常: ' . $errorMsg, 'error');
            
            // 确保返回 JSON 格式,而不是 HTML
            ob_clean();
            header('Content-Type: application/json; charset=utf-8');
            http_response_code(200);
            echo json_encode(['code' => 0, 'msg' => '保存关联关系失败:' . $e->getMessage(), 'data' => null], JSON_UNESCAPED_UNICODE);
            exit;
        } catch (\Throwable $e) {
            // 捕获所有可捕获的错误(包括致命错误)
            $errorMsg = '保存关联关系失败(致命错误):' . $e->getMessage();
            $errorMsg .= ' | 文件:' . $e->getFile();
            $errorMsg .= ' | 行号:' . $e->getLine();
            
            \think\Log::write('save_quotation_link 致命错误: ' . $errorMsg, 'error');
            
            ob_clean();
            header('Content-Type: application/json; charset=utf-8');
            http_response_code(200);
            echo json_encode(['code' => 0, 'msg' => '保存关联关系失败:' . $e->getMessage(), 'data' => null], JSON_UNESCAPED_UNICODE);
            exit;
        } finally {
            // 清理输出缓冲区
            if (ob_get_level() > 0) {
                ob_end_flush();
            }
        }
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params);
                if ($result !== true) {
                    $this->error($result);
                }
                $result = false;
                Db::startTrans();
                try {

                    $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params);

                    if ($params['product']) {
                        $params['product'] = json_decode($params['product'], true);
                    }
                    $result = $this->model::createBusiness($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $customer_id = input('customer_id');
        $this->assign('customer_id', $customer_id);
        //halt($customer_id);
        $this->assign('customer', Customer::get($customer_id));

        $this->assign('staffs', Staff::allList());
        $this->assign('form_data', Form::getDataValue('business'));
        return $this->view->fetch();
    }

    /**
     * 修改
     */
    public function edit($ids = null)
    {
        $map['id'] = $ids;
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params = $this->preExcludeFields($params);

            $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params,$ids);
            if ($result !== true) {
                $this->error($result);
            }
            Db::startTrans();
            try {
                $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params);
                $params['id'] = $ids;
                $result = $this->model::updateBusiness($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        $row = $this->model->where($map)->with(['customer'])->find();
        $product=BusinessProduct::where(['business_id'=>$ids])->with(['productinfo'])->select();
        foreach ($product as $k=>$v){
            if($v['productinfo']){
                $v['product_name']=$v['productinfo']['name'];
                $v['cost_price']=$v['productinfo']['cost_price'];
                $v['type']=$v['productinfo']['type'];
                if($v['productinfo']['goods']){
                    $v['goods_name']=$v['productinfo']['goods']['name'];
                }
            }
            $product[$k]=$v;
        }
        $row['product']=json_encode($product);
        $row = $row->toArray();
        $row = BusinessOther::getOther($row);

        $this->view->assign("row", $row);
        $this->assign('customers', Customer::getList());
        $this->assign('form_data', Form::getDataValue('business', $row));

        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->where(['id' => $ids])->with([
            'customer',
            'ownerStaff'
        ])->find();
        if (empty($row)) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $row = BusinessOther::getOther($row);

        //跟进记录
        $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
        $type = BusinessStatus::where(array('business_id'=>$ids))->order('id desc')->value('type');
        $row['type'] = $type ? (int)$type : 0;
        $this->assign('row', $row);
        $this->assign('ids', $ids);
        $this->assign('form_data', Form::getDataValue('business', $row));
        $customerName = '';
        if (!empty($row['customer']) && is_array($row['customer']) && !empty($row['customer']['name'])) {
            $customerName = $row['customer']['name'];
        }
        $this->assignconfig("idinfo", [
            'id' => $ids,
            'name' => $row['name'] ?? '',
            'customer_id' => $row['customer_id'] ?? '',
            'customer_name' => $customerName,
        ]);
        return $this->view->fetch();
    }

    /**
     * 添加跟进
     */
    public function record($ids = null) {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $params['relation_type'] = 5;
            $params['relation_id'] = $ids;

            if(!empty($params['files'])){
                $params['files']=File::getId($params['files']);
            }
            Db::startTrans();
            try {

                $result = Record::createRecord($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('创建跟进记录成功');
            }
            $this->error('创建失败');
        }

        $staff=Staff::where([])->column('name','id');
        $follow= Field::getField('项目状态');
        $this->assign('follow', $follow);
        $this->assign('ids', $ids);
        $this->assign('staff', $staff);
        return $this->view->fetch();
    }
    /**
     * 批量转移项目
     */
    public function batch_change($ids = null)
    {
        $ids = json_decode($ids, true);
        $ids = $this->model->where([
            'id' => ['in', $ids]
        ])->column('id');
        if (empty($ids)) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model::batchTransfer($ids, $params['owner_staff_id']);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $staffs = Staff::getList();
        $this->assign('staffs', $staffs);
        $this->assign('ids', json_encode($ids));

        return $this->view->fetch();
    }

    /**
     * 产品信息
     */
    public function product() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $business_id = input('business_id');
            $wheres['business_product.business_id'] =$business_id;
            $list   = BusinessProduct::where($where)->where($wheres)->with(['product'])->order($sort, $order)->paginate($limit);
            foreach($list as $k=>$v){
                if(!$v['product']['id']){
                    unset($list[$k]);
                }
            }
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 获取相关合同
     */
    public function get_contract()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $business_id = input('business_id');
        $wheres['business_id'] =$business_id;
        $list = Contract::where([
            'business_id' => $business_id,
        ])->with('customer')->order('id desc')->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }
    /**
     * 删除项目
     */
    public function delete($ids = null)
    {
        if(!$ids){
            $this->error('参数不正确');
        }
        $data = $this->model->where([
            'id' => $ids
        ])->column('id');
        if (empty($data)) {
            $this->error('项目不存在');
        }
        $result = $this->model->where(array('id'=>$ids))->update(array('updatetime'=>time(),'deletetime'=>time()));
        if(!$result){
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }
    /**
     * 推进项目
     */
    public function batch_status($ids = null)
    {
        $ids = $this->model->where([
            'id' => $ids
        ])->value('id');
        if (empty($ids)) {
            $this->error('项目不存在');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(!empty($params['file'])){
                    $params['file']=File::getId($params['file']);
                }
                $result = false;
                Db::startTrans();
                try {
                    $params['id'] = $ids;
                    $result = $this->model::batchStatus($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error('推进失败');
                }
            }
            $this->error('推进失败');
        }


        return $this->view->fetch();
    }
    /**
     * 获取推进项目
     */
    public function get_business_status()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $business_id = input('business_id');
        $wheres['business_id'] =$business_id;
        $list = BusinessStatus::where([
            'business_id' => $business_id,
        ])->order('id desc')->paginate($limit);
        foreach($list as $k=>$v){
            if($v['file']){
                $list[$k]['file'] = File::where(array('id'=>['in',$v['file']]))->select();
            }

        }
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }


    /**
     * 导入客户
     * @return string|void
     */
    public function import()
    {
        set_time_limit(0);
        if ($this->request->isPost()) {

            $file = $this->request->request('file');
            $staff_id = $this->request->request('staff_id', 0);
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . 'public' . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            //开始读取数据
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[$currentRow][] = $val;
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? '' : trim($val);
                }
            }
            if (!isset($fields[1])) {
                $this->error('导入文件第一行没有数据');
            }
            $lastid = $this->model->withTrashed()->order('id desc')->value('id');

            $lastid = $lastid + 5;//防止重复

            $customerRow = [];
            $errorInfo = [];

            $customerNames=Customer::where([])->column('id,owner_staff_id','name');

            $fieldnames = FormField::where(['types' => FormField::BUSINESS_TYPE])->column('field', 'name');
            if(!$fieldnames){
                $this->error('请在系统管理->字段管理中保存项目管理表单生成项目导入字段');
            }
            $fn = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                foreach ($values as $l) {
                    $fn[] = $fieldnames[$l] ?? '';
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
                $lastid++;
                $addBusiness = ['id' => $lastid];
                $customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0;
                if(empty($customer)){
                    $errorInfo[] = "第{$currentRow}行,客户名称不存在;";
                    continue;
                }
                $addBusiness['customer_id']=$customer['id'];
                $addBusiness['owner_staff_id']=$customer['owner_staff_id'];
                foreach ($values as $kv => $value) {
                    if (!isset($fn[$kv]) || empty($fn[$kv])) {
                        continue;
                    }
                    $addBusiness[$fn[$kv]] = $value;
                }

                if (empty($addBusiness['name'])) {
                    $errorInfo[] = "第{$currentRow}行,项目名称不能为空;";
                    continue;
                }
                $customerRow[] = $addBusiness;
            }
            if (!empty($errorInfo)) {
                $this->error(implode(',', $errorInfo));
            }
            Db::startTrans();
            try {
                $this->model::importBusiness($customerRow);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('导入成功');
        }
        $this->assign('staffs', Staff::getList());
        return $this->view->fetch();
    }

    /**
     * 模板
     */
    public function template()
    {
        $title = ['客户名称'];
        $dataValue = Form::getDataValue(Form::BUSINESS_TYPE);

        foreach ($dataValue as $val) {
            $title[] = $val['config']['label'];
        }

        $file = export_excel($title, [], '项目');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $file['fileName']);
        header('Cache-Control: max-age=0');

        $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('导出文件'); //设置标题
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('导出文件');
        /* 循环读取每个单元格的数据 */
        $a = 'A';
        $currentSheet = $obj->getActiveSheet();
        foreach ($title as $key => $value) {
            //读取工作表1
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
            //这里是设置单元格的内容
            $currentSheet->getCell($a . '1')->setValue($value);
            $a++;
        }

        $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);

        $PHPWriter->save('php://output');
    }

    /**
     * 导出信息
     */
    public function export()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $isall = input('isall',1);
        $wheres = array();
        //导出其中几条
        if (isset($ids) && $ids) {
            $wheres['id'] = array('in', $ids);
        }
        //导出全部
        if ($isall == 3) {
            unset($wheres['id']);
        }
        //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
        $type = input('type', 0);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $staff = Staff::info();
        $staff_id = $staff->id;
        switch ($type) {
            case 1:
                $wheres['owner_staff_id'] = $staff_id;
                break;
            case 2:
                $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
                break;
            case 3:
                $start = date('Y-m-d 00:00:00');
                $end = date('Y-m-d 23:59:59');
                $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
                $relationId = [];
                foreach ($record as $k => $v) {
                    $whereRe['id'] = array('gt', $v['id']);
                    $whereRe['relation_id'] = $v['relation_id'];
                    $recordData = Record::where($whereRe)->count();
                    if ($recordData == 0) {
                        $relationId[] = $v['relation_id'];
                    }

                }
                $wheres['id'] = array('in', $relationId);
                $staff = Staff::info();
                $wheres['owner_staff_id'] = $staff->id;
                break;
            case 4:
                $start = date('Y-m-d 00:00:00');
                $end = date('Y-m-d 23:59:59');
                $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
                $relationId = [];
                foreach ($record as $k => $v) {
                    $whereRe['id'] = array('gt', $v['id']);
                    $whereRe['relation_id'] = $v['relation_id'];
                    $recordData = Record::where($whereRe)->count();
                    if ($recordData >= 1) {
                        $relationId[] = $v['relation_id'];
                    }

                }
                $wheres['id'] = array('in', $relationId);
                $staff = Staff::info();
                $wheres['owner_staff_id'] = $staff->id;
                break;
            case 5:
                $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
                $wheres['id'] = array('not in', $record);
                $staff = Staff::info();
                $wheres['owner_staff_id'] = $staff->id;
                break;
            default:
                $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
                break;

        }

        $list = $this->model->with([
            'ownerStaff','businessOther','customer'
        ])->where($where)->where($wheres)->order($sort, $order)->select();
        $list = collection($list)->toArray();

        if (!$list) {
            $this->error('无导出数据');
        }
        $title = [
            '序号',
            '客户名称',
            '负责人',
            '创建时间',
            '下次联系时间',
        ];

        $dataValue = Form::getDataValue(Form::BUSINESS_TYPE);

        foreach ($dataValue as $val) {
            $title[] = $val['config']['label'];
        }
        foreach ($list as $k => $v) {
            if($v['business_other']){//其他客户
                $other=$v['business_other']['otherdata'];
                $other=json_decode($other,true);
                $v = array_merge($v, $other);
            }
            $field = array(
                $v['id'],
                $v['customer']['name'],

                $v['owner_staff']['name'],
                date('Y-m-d H:i:s',$v['createtime']),
                $v['next_time'],
            );
            foreach ($dataValue as $val) {
                if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
                    $field[] = $v[$val['id'] . '_str'] ?? '';
                } else {
                    $field[] = ($v[$val['id']] ?? '');
                }
            }
            $data[] = $field;
        }
        $file = export_excel($title, $data, '项目');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }


    /**
     * 导入产品明细
     * @return string|void
     */
    public function import_product()
    {
        set_time_limit(0);
        if ($this->request->isPost()) {

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . 'public' . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            //开始读取数据
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[$currentRow][] = $val;
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? '' : trim($val);
                }
            }
            if (!isset($fields[1])) {
                $this->error('导入文件第一行没有数据');
            }

            $lastid = BusinessProduct::order('id desc')->value('id');

            $lastid = $lastid + 5;//防止重复

            $businessProductRow = [];
            $errorInfo = [];

            $businessName=$this->model::where([])->column('id,name,money','name');
            $productName=Product::where([])->column('id,price','name');

            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
                $lastid++;
                $addContractProduct = ['id' => $lastid];
                $business = isset($businessName[$values[0]]) ? $businessName[$values[0]] : 0;
                if (empty($business)) {
                    $errorInfo[] = "第{$currentRow}行,项目名称不存在;";
                    continue;
                }
                $product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0;
                if (empty($product)) {
                    $errorInfo[] = "第{$currentRow}行,产品名称不存在;";
                    continue;
                }
                if (empty($values[2])) {
                    $errorInfo[] = "第{$currentRow}行,产品数量不能为空;";
                    continue;
                }
                if (empty($values[3])) {
                    $errorInfo[] = "第{$currentRow}行,产品售价不能为空;";
                    continue;
                }
                $addContractProduct['business_id'] = $business['id'];
                $addContractProduct['product_id'] = $product['id'];
                $addContractProduct['number'] = $values[2];
                $addContractProduct['price'] = $values[3];
                $businessProductRow[]=$addContractProduct;
            }
            if (!empty($errorInfo)) {
                $this->error(implode(',', $errorInfo));
            }
            Db::startTrans();
            try {
                BusinessProduct::importProduct($businessProductRow);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('导入成功');
        }
        $this->assign('staffs', Staff::getList());
        return $this->view->fetch();
    }

    /**
     * 模板
     */
    public function template_product()
    {
        $title = [
            '项目名称',
            '商品名称',
            '数量',
            '售价',
        ];

        $file = export_excel($title, [], '产品明细');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $file['fileName']);
        header('Cache-Control: max-age=0');

        $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('导出文件'); //设置标题
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('导出文件');
        /* 循环读取每个单元格的数据 */
        $a = 'A';
        $currentSheet = $obj->getActiveSheet();
        foreach ($title as $key => $value) {
            //读取工作表1
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
            //这里是设置单元格的内容
            $currentSheet->getCell($a . '1')->setValue($value);
            $a++;
        }

        $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);

        $PHPWriter->save('php://output');
    }

    /**
     * 导出信息
     */
    public function export_product()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $type = input('type');
        $wheres = array();
        //导出其中几条
        if (isset($ids)) {
            $wheres['business_id'] = array('in', $ids);
        }
        //导出全部
        if (isset($type)) {
            if ($type == 3) {
                unset($wheres['business_id']);
            }
        }

        $list=BusinessProduct::where($wheres)->with(['business','productinfo'])->select();
        $list = collection($list)->toArray();

        if (!$list) {
            $this->error('无导出数据');
        }
        $title = [
            '序号',
            '项目名称',
            '商品名称',
            '售价',
            '批发价',
            '产品',
            '规格',
            '数量',
        ];

        foreach ($list as $k => $v) {

            $field = array(
                $v['id'],
                $v['business']['name'],
                $v['productinfo']['name']??'',
                $v['price']??'',
                $v['productinfo']['cost_price']??'',
                $v['productinfo']['goods']['name']??'',
                $v['productinfo']['unit']??'',
                $v['number']??'',
            );
            $data[] = $field;
        }
        $file = export_excel($title, $data, '产品明细');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }

    /**
     * 项目详情报价单列表:统一补充 is_yongyou、external_url、流程状态文案(与 fastflow/bill/yongyouy_baojiadan 一致)。
     *
     * @param array $item amodel_a 一行(须为数组,调用方请先把 Model 转成 toArray)
     * @param Amodela|null $AmodelaModel 非空时保留原 PHP 报价单 status 回写逻辑
     */
    public static function enrichQuotationListRow(&$item, $AmodelaModel = null)
    {
        if (!is_array($item)) {
            $item = is_object($item) && method_exists($item, 'toArray') ? $item->toArray() : (array)$item;
        }
        $labels = ['0' => '待发起', '1' => '流程中', '2' => '通过', '3' => '终止'];
        $cModle = new Czgprz();

        if (isset($item['name']) && strpos($item['name'], '(quotation_') !== false) {
            $item['is_yongyou'] = true;
            if (preg_match('/\(quotation_(\d+)\)/', $item['name'], $matches)) {
                $item['quotation_id'] = $matches[1];
            } else {
                $item['quotation_id'] = null;
            }
            $item['external_url'] = get_yongyou_integration_full_url('quotation', [
                'id' => $item['quotation_id'],
                'mode' => 'view',
            ]);
            $bid = isset($item['bill_id']) ? (int)$item['bill_id'] : 0;
            if ($bid > 0) {
                $st = null;
                try {
                    $st = Db::name('yongyouy_baojiadan')->where('id', $bid)->value('status');
                } catch (\Throwable $e) {
                    \think\Log::write('enrichQuotationListRow 读取 yongyouy_baojiadan 失败: ' . $e->getMessage(), 'warning');
                }
                if ($st === null || $st === '') {
                    $item['status'] = '0';
                    $item['status_text'] = $labels['0'];
                } else {
                    $k = (string)$st;
                    $item['status'] = $k;
                    $item['status_text'] = isset($labels[$k]) ? $labels[$k] : $k;
                }
            } else {
                $item['status'] = '0';
                $item['status_text'] = '待发起流程';
            }
            return;
        }

        $item['is_yongyou'] = false;
        if (!empty($item['bill_id'])) {
            $status = $cModle->where('id', $item['bill_id'])->value('status');
            if ($status == '2' && $AmodelaModel) {
                $AmodelaModel->where('id', $item['id'])->update(['status' => '1']);
            }
            $item['status'] = $status;
            $k = (string)$status;
            $item['status_text'] = isset($labels[$k]) ? $labels[$k] : (string)$status;
        } else {
            $item['status_text'] = isset($item['status']) ? (string)$item['status'] : '';
        }
    }

    /**
     * 用友报价单写入项目后:创建/更新「报价单2026」表 (yongyouy_baojiadan),并尝试发起 FastFlow。
     * amodel_a.bill_id 存 yongyouy_baojiadan.id(与 PHP 报价单走 Czgprz 互斥:用友行靠 name 中 quotation_ 识别)。
     *
     * @return array{bill_id:int|null, flow_started:bool, msg:string}
     */
    protected static function syncYongyouBaojiadanAfterQuotationLink($amodelaModel, $business, $quotationNumber, $quotationId, $totalAmount, $lrl, $initiatorStaffId)
    {
        $ret = ['bill_id' => null, 'flow_started' => false, 'msg' => ''];
        $prefix = config('database.prefix');
        $billTable = $prefix . 'yongyouy_baojiadan';
        $flowId = Db::name('fastflow_flow')->where('bill', $billTable)->where('status', 1)->order('id', 'asc')->value('id');

        // 流程里「报价单编号」存集成报价单主键 id,便于跳转 /quotation?id=;业务单号在 amodel_a.name 中仍有体现
        $bjdbh = $quotationId > 0 ? (string)(int)$quotationId : ($quotationNumber !== '' ? (string)$quotationNumber : '');
        $bjdje = $totalAmount;
        $lrlVal = $lrl !== null ? floatval($lrl) : 0;

        $ownerStaffId = 0;
        if (is_object($business)) {
            $ownerStaffId = (int)($business->owner_staff_id ?? 0);
        } elseif (is_array($business)) {
            $ownerStaffId = (int)($business['owner_staff_id'] ?? 0);
        }
        $staffIdForFlow = $initiatorStaffId > 0 ? (int)$initiatorStaffId : $ownerStaffId;

        $adminId = 1;
        if ($staffIdForFlow > 0) {
            $aid = Staff::where('id', $staffIdForFlow)->value('admin_id');
            if ($aid) {
                $adminId = (int)$aid;
            }
        }

        $ffId = (int)($amodelaModel->bill_id ?? 0);
        $now = time();

        if ($ffId > 0) {
            Db::name('yongyouy_baojiadan')->where('id', $ffId)->update([
                'bjdbh' => $bjdbh,
                'bjdje' => $bjdje,
                'lrl' => $lrlVal,
                'updatetime' => $now,
            ]);
            $ret['bill_id'] = $ffId;
            $ret['flow_started'] = true;
            $ret['msg'] = '已更新流程单据字段';
            return $ret;
        }

        $ffId = (int)Db::name('yongyouy_baojiadan')->insertGetId([
            'bjdbh' => $bjdbh,
            'bjdje' => $bjdje,
            'lrl' => $lrlVal,
            'initiator_id' => $adminId,
            'status' => 0,
            'createtime' => $now,
            'updatetime' => $now,
        ]);

        if ($ffId <= 0) {
            $ret['msg'] = '创建报价单2026单据失败';
            return $ret;
        }

        Db::name('amodel_a')->where('id', $amodelaModel->id)->update(['bill_id' => $ffId]);
        $amodelaModel->bill_id = $ffId;
        $ret['bill_id'] = $ffId;

        if (!$flowId) {
            $ret['msg'] = '未配置 fastflow_flow(bill=' . $billTable . '),已建单未发起流程';
            return $ret;
        }

        $staffAuth = StaffAuth::instance(['type' => 'Mysqlstaff']);
        $didDirect = false;
        if ($staffIdForFlow > 0) {
            $didDirect = (bool)$staffAuth->direct($staffIdForFlow);
        }

        try {
            $api = new \addons\fastflow\model\api(new \app\admin\controller\fastflow\flow\CustomMessage(), null);
            $res = $api->startFlow([
                'flow_id' => $flowId,
                'bill' => $billTable,
                'bill_id' => $ffId,
                'ebill_id' => '',
            ]);
            if (is_array($res) && array_key_exists('code', $res)) {
                $ret['flow_started'] = ((int)$res['code'] === 1);
                $ret['msg'] = isset($res['msg']) ? (string)$res['msg'] : '';
            } else {
                $ret['msg'] = '流程返回异常';
            }
        } catch (\Throwable $e) {
            $ret['msg'] = $e->getMessage();
            \think\Log::write('syncYongyouBaojiadan startFlow: ' . $e->getMessage(), 'error');
        } finally {
            if ($didDirect) {
                try {
                    $staffAuth->logout();
                } catch (\Throwable $e) {
                }
            }
        }

        return $ret;
    }
}