<?php


namespace JinDouYun\Controller\Cron;


use JinDouYun\Dao\Department\DStaff;
use JinDouYun\Dao\Enterprise\DEnterprise;
use JinDouYun\Dao\Order\DSupplierOrderDetails;
use JinDouYun\Dao\Order\DSupplierOrderIndex;
use JinDouYun\Model\Order\MSupplierOrderDetails;
use JinDouYun\Model\Order\TStdOrder;
use JinDouYun\Model\Purchase\MPurchase;
use JinDouYun\Model\System\MBasicSetup;
use Mall\Framework\Core\StatusCode;

class SupplierPurchaseCron
{
    use Cron;

    private $enterprises = [];

    use TStdOrder;


    public function __construct()
    {
        self::sendOutput('start-创建采购单');
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        self::sendOutput('end-创建采购单');
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/12/24
     * Time: 2:13 下午
     */
    public function getEnterprise()
    {
        //获取企业
        $time = time();
        $fault = 120;
        $fields = "e.id,e.enterpriseName,b.basicData";
        $sql = 'SELECT ' . $fields . ' FROM qianniao_enterprise_1 as e 
                LEFT JOIN qianniao_basic_setup as b ON e.id=b.enterpriseId 
                WHERE b.id IS NOT NULL';

        $objDEnterprise = new DEnterprise();
        $enterprises = $objDEnterprise->query($sql);
        if ($enterprises === false) {
            self::sendOutput('sql错误', $objDEnterprise->error(), true);
        }

        foreach ($enterprises as $val) {
            $json = json_decode($val['basicData'], true);
            $supplierSet = getArrayItem($json, 'supplierSet', []);

            $auto_ctime = getArrayItem($supplierSet, 'auto_ctime', 0);
            if (empty($auto_ctime)) {
                continue;
            }
            $auto_ctime = self::todayTime($auto_ctime);
            //测试的时候注释
            if (!($time - $auto_ctime > 0 && $time - $auto_ctime < $fault)) {
                continue;
            }

            $this->enterprises[] = [
                'enterpriseId'   => $val['id'],
                'enterpriseName' => $val['enterpriseName'],
                'auto_ctime'     => getArrayItem($supplierSet, 'auto_ctime', 0),
                'enable_istrue'  => getArrayItem($supplierSet, 'enable_istrue', StatusCode::$delete),
            ];
        }

        if (empty($this->enterprises)) {
            self::sendOutput('data null', '没有企业数据', true);
        }
    }

    /**
     * Doc: (des="将任意某天的时间戳转化为对应今日的时间戳，保留时分秒")
     * User: XMing
     * Date: 2020/12/24
     * Time: 10:49 上午
     * @param $ctime
     */
    function todayTime($ctime)
    {
        $arr = explode(':', $ctime);
        return mktime(
            getArrayItem($arr, 0, 1),
            getArrayItem($arr, 1, 0),
            getArrayItem($arr, 2, 0)
        );
    }


    /**
     * Doc: (des=)
     * User: XMing
     * Date: 2020/12/23
     * Time: 10:58 上午
     * @throws \Exception
     */
    public function create()
    {
        self::getEnterprise();
        $beginYesterday = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $endYesterday = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        $objDSupplierOrderIndex = new DSupplierOrderIndex();
        $objDSupplierOrderDetails = new DSupplierOrderDetails();
        foreach ($this->enterprises as $item) {
            $enterpriseId = getArrayItem($item, 'enterpriseId', 0);
            if (empty($enterpriseId)) {
                continue;
            }
            $objMPurchase = new MPurchase('', $enterpriseId);
            $objMSupplierOrderDetails = new MSupplierOrderDetails($enterpriseId, '');
            $objDSupplierOrderIndex->setTable('qianniao_supplier_order_index_' . $enterpriseId);


            $objDStaff = new DStaff();
            $objDStaff->setTable('qianniao_staff_'.$enterpriseId);
            $staff = $objDStaff->get(['departmentId' => 1],'userCenterId,staffName,departmentId');
            if ($staff === false){
                self::sendOutput('sql error', $objDStaff->error());
            }

            $fields = ' o.id as orderId,s.* ';
            /*$sql = 'SELECT ' . $fields . ' FROM qianniao_supplier_order_index_' . $enterpriseId . ' AS s
                    LEFT JOIN qianniao_order_index_' . $enterpriseId . ' AS o 
                    ON o.id = s.orderId WHERE s.purchaseStatus = ' . StatusCode::$delete . ' 
                    AND o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' 
                    AND s.createTime BETWEEN ' . $beginYesterday . ' AND ' . $endYesterday;*/

            $sql = 'SELECT ' . $fields . ' FROM qianniao_supplier_order_index_' . $enterpriseId . ' AS s 
                    LEFT JOIN qianniao_order_index_' . $enterpriseId . ' AS o 
                    ON o.id = s.orderId WHERE s.purchaseStatus = ' . StatusCode::$delete . ' 
                    AND o.auditStatus = ' . StatusCode::$auditStatus['auditPass'];//TODO(测试的时候用这个sql)
            $indexLists = $objDSupplierOrderIndex->query($sql);
            if ($indexLists === false) {
                self::sendOutput('sql error', $objDSupplierOrderIndex->error());
                continue;
            }
            if (empty($indexLists)) {
                continue;
            }
            $allGroupData = [];
            $detailsData = [];
            $ids = [];
            foreach ($indexLists as $list) {
                $tableNum = ceil($list['orderId'] / MSupplierOrderDetails::$cutTable);
                $allGroupData[$tableNum][] = $list['id'];
                $ids[] = $list['id'];
            }
            foreach ($allGroupData as $k => $ids) {
                $objDSupplierOrderDetails->setTable('qianniao_supplier_order_details_' . $enterpriseId . '_' . $k);
                $dbResult = $objDSupplierOrderDetails->select(['id' => $ids]);
                if ($dbResult === false) {
                    self::sendOutput('sql error', $objDSupplierOrderDetails->error());
                    continue;
                }
                $detailsData = array_merge($dbResult, $detailsData);
            }
            //将数据按照供应商分组
            $supplierDetailsGroupData = [];
            $supplierMap = [];
            foreach ($detailsData as $datum) {
                $supplierDetailsGroupData[$datum['supplierId']][] = $datum;
                $supplierMap[$datum['supplierId']] = [
                    'shopId'       => $datum['shopId'],
                    'shopName'     => $datum['shopName'],
                    'supplierId'   => $datum['supplierId'],
                    'supplierName' => $datum['supplierName']
                ];
            }

            foreach ($supplierMap as $supplierId => $common) {
                $lists = getArrayItem($supplierDetailsGroupData, $supplierId, []);
                if (empty($lists)) {
                    self::sendOutput('data is empty', '');
                    continue;
                }

                $common['operatorId'] = getArrayItem($staff,'userCenterId',0);
                $common['operatorName'] = getArrayItem($staff,'staffName','');
                $common['buyerId'] = getArrayItem($staff,'userCenterId',0);
                $common['buyerName'] = getArrayItem($staff,'staffName','');
                $common['departmentPath'] = getArrayItem($staff,'departmentId','');
                $buildInsert = self::buildPurchase($common, $lists);
                print_r($buildInsert);
                $result = $objMPurchase->addPurchase($buildInsert);
                if (!$result->isSuccess()) {
                    self::sendOutput('sql error', $result->getData());
                    continue;
                }
            }
            $updateResult = $objMSupplierOrderDetails->updatePurchaseStatus($ids);
            if (!$updateResult->isSuccess()) {
                self::sendOutput('sql error', $updateResult->getData());
                continue;
            }
            self::sendOutput('success', '创建采购单成功');
        }
    }

}