<?php

namespace app\api\controller\activity;

use app\models\store\StoreDescription;
use app\models\store\StoreProductAttr;
use app\models\store\StoreProductAttrValue;
use app\models\store\StoreProductRelation;
use app\models\system\SystemAttachment;
use app\models\routine\RoutineCode;
use app\models\store\StoreAssistance;
use app\models\store\StoreAssistanceActive;
use app\models\store\StoreProductReply;
use app\models\store\StoreOrder;
use app\models\store\{PopScreen as PopScreenModel};
use app\Request;
use crmeb\services\QrcodeService;
use crmeb\services\SystemConfigService;
use crmeb\services\UploadService;
use crmeb\services\UtilService;
use crmeb\services\CacheService;

/**
 * 助力类
 * Class StoreAssistanceController
 * @package app\api\controller\activity
 */
class StoreAssistanceController
{
    /**
     * 助力列表
     * @param Request $request
     * @return mixed
     */
    public function lst(Request $request)
    {
        list($page, $limit) = UtilService::getMore([
            ['page', 1],
            ['limit', 10],
        ], $request, true);
        $assistanceList = StoreAssistance::getAll($page, $limit, $request->mer_id());
        if (!count($assistanceList)) return app('json')->successful([]);
        return app('json')->successful($assistanceList->hidden(['info', 'product_id', 'images', 'mer_id', 'attr', 'sort', 'stock', 'sales', 'add_time', 'is_del', 'is_show', 'browse', 'cost', 'is_show', 'start_time', 'stop_time', 'postage', 'is_postage', 'is_host', 'mer_use'])->toArray());
    }

    /**
     * 助力商品详情
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function detail(Request $request, $id)
    {
        if (!$id || !($assistanceOne = StoreAssistance::getAssistanceOne($id))) return app('json')->fail('助力不存在或已下架');
        $assistanceOne = $assistanceOne->hidden(['mer_id', 'attr', 'sort', 'add_time', 'is_host', 'is_show', 'is_del', 'mer_use', 'cost', 'assistance'])->toArray();
        $assistanceOne['images'] = json_decode($assistanceOne['images'], true);
        list($assistance, $assistanceAll) = StoreAssistanceActive::getAssistanceAll($id, true);//助力列表
        $siteUrl = sys_config('site_url');
        $assistanceOne['image'] = set_file_url($assistanceOne['image'], $siteUrl);
        $assistanceOne['image_base'] = set_file_url($assistanceOne['image'], $siteUrl);
        $assistanceOne['code_base'] = QrcodeService::getWechatQrcodePath($id . '_assistance_detail_wap.jpg', '/pages/activity/goods_assistance_status/index?id=' . $id);
        $assistanceOne['sale_stock'] = 0;
        if ($assistanceOne['stock'] > 0) $assistanceOne['sale_stock'] = 1;
        if (!strlen(trim($assistanceOne['unit_name']))) $assistanceOne['unit_name'] = '个';
        $uid = $request->uid();
        $assistanceOne['userCollect'] = StoreProductRelation::isProductRelation($assistanceOne['product_id'], $uid, 'collect');
        $assistanceOne['description'] = htmlspecialchars_decode(StoreDescription::getDescription($id, 4));
        $data['assistance'] = $assistance;
        $data['assistanceAll'] = $assistanceAll;
        $data['storeInfo'] = $assistanceOne;
        $data['assistance_ok_list'] = StoreAssistanceActive::getAssistanceOkList($uid);
        $data['assistance_ok_sum'] = StoreAssistanceActive::getAssistanceOkSumTotalNum($id);
        $data['reply'] = StoreProductReply::getRecProductReply($assistanceOne['product_id']);
        $data['replyCount'] = StoreProductReply::productValidWhere()->where('product_id', $assistanceOne['product_id'])->count();
        if ($data['replyCount']) {
            $goodReply = StoreProductReply::productValidWhere()->where('product_id', $assistanceOne['product_id'])->where('product_score', 5)->count();
            $data['replyChance'] = $goodReply;
            if ($goodReply) {
                $data['replyChance'] = bcdiv($goodReply, $data['replyCount'], 2);
                $data['replyChance'] = bcmul($data['replyChance'], 100, 3);
            }
        } else $data['replyChance'] = 100;
        list($productAttr, $productValue) = StoreProductAttr::getProductAttrDetail($id, $uid, 0, 4);
        foreach ($productValue as $k => $v) {
            $productValue[$k]['product_stock'] = StoreProductAttrValue::where('product_id', $assistanceOne['product_id'])->where('suk', $v['suk'])->where('type', 0)->value('stock');
            $productValue[$k]['subsidy'] = bcmul($v['price'], $assistanceOne['p_separate_account']/100, 2);
        }
        $data['productAttr'] = $productAttr;
        $data['productValue'] = $productValue;
        return app('json')->successful($data);
    }

    /**
     * 参与助力
     * @param Request $request
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function assistanceActive(Request $request, $id)
    {
        $is_ok = 0;//判断助力是否完成
        $userBool = 0;//判断当前用户是否在团内  0未在 1在
        $assitanceBool = 0;//判断助力是否成功  0未在 1在
        $user = $request->user();
        if (!$id) return app('json')->fail('参数错误');
        $assistance = StoreAssistanceActive::getAssistanceUserOne($id, $request->mer_id());
        if (!$assistance) return app('json')->fail('参数错误');
        if (isset($assistance['is_refund']) && $assistance['is_refund']) {
            if ($assistance['is_refund'] != $assistance['id']) {
                $id = $assistance['is_refund'];
                return $this->assistance($request, $id);
            } else {
                return app('json')->fail('订单已退款');
            }
        }
        list($assistanceAll, $assistanceT, $count, $idAll, $uidAll) = StoreAssistanceActive::getAssistanceMemberAndAssistanceK($assistance);
        if ($assistanceT['status'] == 2) {
            $assitanceBool = 1;
            $is_ok = 1;
        } else if ($assistanceT['status'] == 3) {
            $assitanceBool = -1;
            $is_ok = 0;
        } else {
            if ($count < 1) {//组团完成
                $is_ok = 1;
                $assitanceBool = StoreAssistanceActive::AssistanceComplete($uidAll, $idAll, $user['uid'], $assistanceT);
            } else {
                $assitanceBool = StoreAssistanceActive::AssistanceFail($assistanceAll, $assistanceT, $assitanceBool);
            }
        }
        if (!empty($assistanceAll)) {
            foreach ($assistanceAll as $v) {
                if ($v['uid'] == $user['uid']) $userBool = 1;
            }
        }
        if ($assistanceT['uid'] == $user['uid']) $userBool = 1;
        $assistanceOne = StoreAssistance::getAssistanceOne($assistance['cid'], $request->mer_id());
        if (!$assistanceOne) return app('json')->fail('助力不存在或已下架');
        $data['qrcode'] = sys_data('routine_wechat_qrcode', 0, $request->mer_id()) ?: [];
        $data['userInfo']['uid'] = $user['uid'];
        $data['userInfo']['nickname'] = $user['nickname'];
        $data['userInfo']['avatar'] = $user['avatar'];
        $data['is_ok'] = $is_ok;
        $data['userBool'] = $userBool;
        $data['assitanceBool'] = $assitanceBool;
        $data['store_assistance'] = $assistanceOne->hidden(['mer_id', 'images', 'attr', 'info', 'sort', 'sales', 'stock', 'add_time', 'is_host', 'is_show', 'is_del', 'assistance', 'mer_use', 'is_postage', 'postage', 'start_time', 'stop_time', 'cost', 'browse', 'product_price'])->toArray();
        $data['assistanceT'] = $assistanceT;
        $data['assistanceAll'] = $assistanceAll;
        $data['count'] = $count <= 0 ? 0 : $count;
        $data['helped'] = $assistanceT['people'] - $count;
        $data['store_assistance_host'] = StoreAssistance::getAssistanceHost(0, $request->mer_id());
        $data['current_assistance_order'] = StoreAssistanceActive::getCurrentAssistance($id, $user['uid']);
        list($productAttr, $productValue) = StoreProductAttr::getProductAttrDetail($assistanceOne['id'], $user['uid'], 0, 4);
        foreach ($productValue as $k => $v) {
            $productValue[$k]['product_stock'] = StoreProductAttrValue::where('product_id', $assistanceOne['product_id'])->where('suk', $v['suk'])->where('type', 0)->value('stock');
        }
        $data['store_assistance']['productAttr'] = $productAttr;
        $data['store_assistance']['productValue'] = $productValue;
        return app('json')->successful($data);
    }

    /**
     * 取消助力
     * @param Request $request
     * @return mixed
     * @throws Exception
     */
    public function remove(Request $request)
    {
        list($id, $cid) = UtilService::postMore([
            ['id', 0],
            ['cid', 0],
        ], $request, true);
        if (!$id || !$cid) return app('json')->fail('缺少参数');
        $res = StoreAssistanceActive::removeAssistance($request->uid(), $cid, $id);
        if ($res) {
            return app('json')->successful('取消成功');
        }
        $error = StoreAssistanceActive::getErrorInfo();
        if (is_array($error)) return app('json')->status($error['status'], $error['msg']);
        return app('json')->fail($error);
    }

    /**
     * 助力海报
     * @param Request $request
     * @return mixed
     * @throws Exception
     */
    public function poster(Request $request)
    {
        $mer_id = $request->mer_id();
        list($assistanceId, $from) = UtilService::postMore([['id', 0], ['from', 'wechat']], $request, true);
        if (!$assistanceId) return app('json')->fail('参数错误');
        $user = $request->user();
        $assistanceInfo = StoreAssistanceActive::getAssistanceUserOne($assistanceId, $request->mer_id());
        $storeAssistanceInfo = StoreAssistance::getAssistanceOne($assistanceInfo['cid']);
        $data['title'] = $storeAssistanceInfo['title'];
        $data['image'] = $storeAssistanceInfo['image'];
        $data['price'] = $assistanceInfo['total_price'];
        $data['label'] = $assistanceInfo['people'] . '人团';
        if ($assistanceInfo['k_id']) $assistanceAll = StoreAssistanceActive::getAssistanceMember($assistanceInfo['k_id']);
        else $assistanceAll = StoreAssistanceActive::getAssistanceMember($assistanceInfo['id']);
        $count = count($assistanceAll);
        $data['msg'] = '原价￥' . $storeAssistanceInfo['product_price'] . ' 还差' . (int)bcsub((int)$assistanceInfo['people'], $count, 0) . '人助力成功';
        try {
            $siteUrl = sys_config('site_url', '', $mer_id);
            if ($from == 'routine') {
                //小程序
                $name = $assistanceId . '_' . $user['uid'] . '_' . $user['is_promoter'] . '_assistance_share_routine.jpg';
                $imageInfo = SystemAttachment::getInfo($name, 'name');
                if (!$imageInfo) {
                    $valueData = 'id=' . $assistanceId;
                    if ($user['is_promoter'] || sys_config('store_brokerage_statu', '', $mer_id) == 2) $valueData .= '&pid=' . $user['uid'];
                    $res = RoutineCode::getPageCode('pages/activity/goods_assistance_status/index', $valueData, 280, $mer_id);
                    if (!$res) return app('json')->fail('二维码生成失败');
                    $uploadType = (int)sys_config('upload_type', 1, $mer_id);
                    $upload = UploadService::init(null, $mer_id);
                    $res = $upload->to('routine/activity/assistance/code')->validate()->stream($res, $name);
                    if ($res === false) {
                        return app('json')->fail($upload->getError());
                    }
                    $imageInfo = $upload->getUploadInfo();
                    $imageInfo['image_type'] = $uploadType;
                    if ($imageInfo['image_type'] == 1) $remoteImage = UtilService::remoteImage($siteUrl . $imageInfo['dir']);
                    else $remoteImage = UtilService::remoteImage($imageInfo['dir']);
                    if (!$remoteImage['status']) return app('json')->fail($remoteImage['msg']);
                    SystemAttachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
                    $url = $imageInfo['dir'];
                } else $url = $imageInfo['att_dir'];
                $data['url'] = $url;
                if ($imageInfo['image_type'] == 1)
                    $data['url'] = $siteUrl . $url;
                $posterImage = UtilService::setShareMarketingPoster($data, 'routine/activity/assistance/poster');
                if (!is_array($posterImage)) return app('json')->fail('海报生成失败');
                SystemAttachment::attachmentAdd($posterImage['name'], $posterImage['size'], $posterImage['type'], $posterImage['dir'], $posterImage['thumb_path'], 1, $posterImage['image_type'], $posterImage['time'], 2);
                if ($posterImage['image_type'] == 1) $posterImage['dir'] = $siteUrl . $posterImage['dir'];
                $routinePosterImage = set_http_type($posterImage['dir'], 0);//小程序推广海报
                return app('json')->successful(['url' => $routinePosterImage]);
            } else if ($from == 'wechat') {
                //公众号
                $name = $assistanceId . '_' . $user['uid'] . '_' . $user['is_promoter'] . '_assistance_share_wap.jpg';
                $imageInfo = SystemAttachment::getInfo($name, 'name');
                if (!$imageInfo) {
                    $codeUrl = set_http_type($siteUrl . '/pages/activity/goods_assistance_status/index?id=' . $assistanceId . '&spread=' . $user['uid'], 1);//二维码链接
                    $imageInfo = UtilService::getQRCodePath($codeUrl, $name);
                    if (is_string($imageInfo)) {
                        return app('json')->fail('二维码生成失败', ['error' => $imageInfo]);
                    }
                    SystemAttachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
                    $url = $imageInfo['dir'];
                } else $url = $imageInfo['att_dir'];
                $data['url'] = $url;
                if ($imageInfo['image_type'] == 1) $data['url'] = $siteUrl . $url;
                $posterImage = UtilService::setShareMarketingPoster($data, 'wap/activity/assistance/poster');
                if (!is_array($posterImage)) return app('json')->fail('海报生成失败');
                SystemAttachment::attachmentAdd($posterImage['name'], $posterImage['size'], $posterImage['type'], $posterImage['dir'], $posterImage['thumb_path'], 1, $posterImage['image_type'], $posterImage['time'], 2);
                if ($posterImage['image_type'] == 1) $posterImage['dir'] = $siteUrl . $posterImage['dir'];
                $wapPosterImage = set_http_type($posterImage['dir'], 1);//公众号推广海报
                return app('json')->successful(['url' => $wapPosterImage]);
            }
            return app('json')->fail('参数错误');
        } catch (Exception $e) {
            return app('json')->fail(['line' => $e->getLine(), 'message' => $e->getMessage()]);
        }


    }

    /**
     * 获取助力小程序二维码
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function code(Request $request, $id)
    {
        $url = QrcodeService::getRoutineQrcodePath($id, $request->uid(), 3, [], $request->mer_id());
        if ($url) {
            return app('json')->success(['code' => $url]);
        } else {
            return app('json')->success(['code' => '']);
        }
    }

    /**
     * 获取助力页面二维码
     */
    public function zhuli_code(Request $request, $id)
    {
        $url = QrcodeService::getRoutineQrcodePath($id, $request->uid(), 4, [], $request->mer_id());
        if ($url) {
            return app('json')->success(['code' => $url]);
        } else {
            return app('json')->success(['code' => '']);
        }
    }

    /**
     * 参与助力
     */
    public function attend(Request $request, $id)
    {
        // 从redis缓存attend_user获取某uid的值，如果存在，不允许助力，返回异常
        $attend_uid = CacheService::redisHandler()->get('attend_user'. $request->uid());
        if (self::checktime($attend_uid)) return app('json')->fail('您今天助力过一次了，请明天再来');

        $assistanceActive = StoreAssistanceActive::get($id);
        // 查询可助力人数
        $assistanceActiveAll = StoreAssistanceActive::getAssistanceMember($id);
        $count = count($assistanceActiveAll);
        $count = (int)bcsub($assistanceActive['people'], $count, 0);
        // 判断是否可助力：如果人已满，或已经超过了可助力的时间，返回false，即不可助力
        if($count <= 0) return app('json')->fail('该助力人数已满');
        if($assistanceActive['stop_time'] < time()) return app('json')->fail('该助力已超过了可参与的时间');
        foreach ($assistanceActiveAll as $key => $value) {
            if ($value['uid'] == $request->uid()) {
                return app('json')->fail('您已参与过该助力了');
            }
        }
        // 新增一条redis缓存记录
        CacheService::redisHandler()->set('attend_user'. $request->uid(), time(), 24*60*60);
        // 记录助力次数
        $assistance = StoreAssistance::get($assistanceActive['cid']);
        $assistance->assistance_times += 1;
        $assistance->save();
        // 先加入，再做是否已满的处理
        $res = StoreAssistanceActive::attendAssistance($request->uid(), $id);
        if ($res) {
            // 执行已满后的处理
            list($assistanceAll, $assistanceT, $count, $idAll, $uidAll) = StoreAssistanceActive::getAssistanceMemberAndAssistanceK($assistanceActive);
            if ($assistanceT['status'] == 1) {
                if (!$count){//组团完成
                    $this->isFull($assistanceActive['order_id_key'], $uidAll, $idAll, $request->uid(), $assistanceT, $request->mer_id());
                    return app('json')->successful('参与成功!');
                }
            }
            return app('json')->successful('参与成功');
        } else {
            return app('json')->fail('参与失败，请稍后再试');
        }
    }

    /**
     * 处理已满
     */
    private function isFull($order_id, $uidAll, $idAll, $uid, $assistanceT, $mer_id = '')
    {
        // 更改助力订单状态
        StoreAssistanceActive::changeAssistanceActiveStatus($uidAll, $idAll, $uid, $assistanceT);
        // 发送订阅消息
        // $this->sendMessage($order_id);
        $order = StoreOrder::get($order_id);
        if($order['pay_type'] == 'weixin'){
            // 处理奖励
            StoreAssistanceActive::treatmentAward($order_id, $mer_id);
            // 记录本次助力分账奖励
            StoreAssistanceActive::recordAssistanceMoney($order_id);
        }
    }

    public function checktime($time)
    {
        $start = strtotime(date("Y-m-d"),time());
        $end = $start + 60*60*24;

        if($start < $time && $time < $end){
            return true;
        }else{
           return false;
        }
    }

    //霸屏广告
    public function popScreen($url)
    {
        $where['domain_name']=$url;
        $info = PopScreenModel::getOne($where);
        $info["click"] = $info["click"] + 1;
        PopScreenModel::edit(['click'=>$info["click"]],$info['id']);//增加推广人次
        $data['info'] = $info;
        return app('json')->successful($data);
    }
}