<?php

namespace crmeb\jobs;

use app\models\store\StoreOrderCartInfo;
use app\models\wechat\StoreService;
use app\models\user\BindUser;
use crmeb\services\WechatService;
use crmeb\services\MiniProgramService;
use crmeb\basic\BaseJob;
use think\facade\Log;

/**
 * 订单消息队列
 */
class PaySuccessJob extends BaseJob
{
	//新订单提醒
    const REMIND = 'Pr-Lg7zgHJKnXEsicuLCwihJLA2BpfkyUp1FU1FMtEs';

	public static function sendTemplate($order)
	{
		$info = StoreOrderCartInfo::where('oid', $order['id'])->field('cart_info')->select();
        $info = count($info) ? $info->toArray() : [];
        $goodsName = [];
        foreach ($info as $k => $v) {
            $cart_info = is_string($v['cart_info']) ? json_decode($v['cart_info'], true) : $v['cart_info'];
            $suk = '';
            if (isset($cart_info['productInfo']['attrInfo'])) {
                if (isset($cart_info['productInfo']['attrInfo']['suk'])) {
                    $suk = '(' . $cart_info['productInfo']['attrInfo']['suk'] . ')';
                }
            }
            $goodsName[] = implode(
                [$cart_info['productInfo']['store_name'],
                    $suk,
                    "[{$cart_info['cart_num']} * {$cart_info['truePrice']}]"
                ], ' ');
        }
		$user = StoreService::alias('s')->where(['mer_id' => $order['mer_id'], 'status' => 1])->join('wechat_user u', 'u.uid=s.uid')->column('routine_openid');
        $bindUser = BindUser::where(['mer_id' => $order['mer_id'], 'status' => 1, 'is_del' => 0])->column('openid');
        foreach($bindUser as $value){
            $firstWeChat = '你有一个新的订单';
            $keyword1WeChat = $order['order_id'];
            $keyword2WeChat = date("Y-m-d H:i:s", $order['add_time']);
            $keyword3WeChat = $goodsName ? implode("\n", $goodsName) : '';
            $keyword4WeChat = $order['user_address'];
            $remarkWeChat = '请登录后台管理系统进行查看';
            WechatService::sendTemplate($value, self::REMIND, [
               'first' => $firstWeChat,
               'keyword1' => $keyword1WeChat,
               'keyword2' => $keyword2WeChat,
               'keyword3' => $keyword3WeChat,
               'keyword4' => $keyword4WeChat,
               'remark' => $remarkWeChat
            ]);
        }
	}

    public static function profitSharingFinish($order)
    {
        @file_put_contents('paySuccess.txt', 11111111 . PHP_EOL, FILE_APPEND);
        @file_put_contents('paySuccess.txt', $order->toArray() . PHP_EOL, FILE_APPEND);
        $res = MiniProgramService::profit_sharing_finish($order['transaction_id'], $order['order_id'], $order['mer_id']);
        dump($res);
        @file_put_contents('paySuccess.txt', 22222222 . PHP_EOL, FILE_APPEND);
        @file_put_contents('paySuccess.txt', $res->toArray() . PHP_EOL, FILE_APPEND);
    }
}