<?php

namespace app\command;

use app\common\model\store\order\StoreOrder;
use app\common\repositories\store\order\StoreOrderRepository;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class CommercialAreaOrderIndependentAccount extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('commercial-area-order-independent-account')
            ->setDescription('商贸区订单分账');
    }

    protected function execute(Input $input, Output $output)
    {
        // @todo 商贸区订单分账 496：会员专区，439：精品生活区
        $this->doCommercialAreaOrderIndependentAccount([439, 491, 496]);
    }

    /**
     * 商贸区订单分账
     *
     * @param $excludeMerId
     * @param $timeLimit
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function doCommercialAreaOrderIndependentAccount($excludeMerId = [], $timeLimit = 30)
    {
        $dst_mer_id = systemConfig('mer_365');

        // 商户信息
        $merchants = [];

        /** @var StoreOrderRepository $storeOrderRepository */
        $storeOrderRepository = app()->make(StoreOrderRepository::class);

        // 订单状态（0：待发货；1：待收货；2：待评价；3：已完成；4已申请退款；-1：已退款）5未支付 6已取消'
        $status = [2, 3];
        // 已支付、未结算
        $where = ['paid' => 1, 'is_independentaccount' => 0, 'is_del' => 0, 'is_system_del' => 0, 'is_settlement' => 1];
        // 普通订单 @todo 排除 特殊商户{$excludeMerId}：精彩生活区、会员区、复购区
        $cursor = Db::table('rrx_store_order')->where($where)->where('pay_type', 'in', '1,2,4')->whereIn('status', $status)
            ->whereNotIn('mer_id', $excludeMerId)->cursor();
        foreach ($cursor as $key => $value) {
            if (!isset($merchants[$value['mer_id']])) {
                $merchants[$value['mer_id']] = Db::name('merchant')->where('mer_id', $value['mer_id'])->find();
            }
            $group_order = Db::name('store_group_order')->alias('sgo')->where('sgo.group_order_id', $value['group_order_id'])->find();
            // @todo 分账账号 496：表示{会员专区}账户；商贸区分账如下：成本分账到商户，利润分账到{会员专区}账户
            $independentAccount = $storeOrderRepository->getIndependentAccount($value, $group_order, $dst_mer_id, $merchants[$value['mer_id']]['hf_member_id']);
            $mer_price = bcsub($value['total_price'] , $value['con_pri'],2);
            $platform_price = bcsub($value['fzone_pay_price'],$mer_price,2);
            // @todo 预分账处理
            $isSuccessed = $storeOrderRepository->prepareExecuteIndependentAccount(
                $value, $group_order, $independentAccount['api_key'], $independentAccount['hf_member_id'], $independentAccount['hf_platform_member_id'], $mer_price, $platform_price
            );
            if ($isSuccessed) {
                Db::name("log")->insert(array('data' => '商贸区-订单分账：' . json_encode($value, JSON_FORCE_OBJECT)));// 日志记录

                $order = StoreOrder::getInstance()->where('order_id', $value['order_id'])->find();
                $order->is_independentaccount = 1;
                $order->save();
            }
        }
    }

}