<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/4/6
 * Time: 下午1:51
 */

namespace fcode;

use Log;

class generator
{
    private $mCommonId;
    private $mNumber;
    private $mBatchCode;
    private $mUserKey;
    private $mUsableDays;

    public function __construct($commonid, $num, $batch_code, $usable_days)
    {
        $this->mCommonId = $commonid;
        $this->mNumber = intval($num);

        if(empty($batch_code)) {
            $this->mBatchCode = 'XMMZ';
        } else {
            $this->mBatchCode = $batch_code;
        }

        $this->mUserKey = mt_rand(1000, 9999);

        if(intval($usable_days) <= 0) {
            $usable_days = 60;
        }
        $this->mUsableDays = $usable_days;
    }

    public function make()
    {
        $mod_fcode = Model('goods_fcode');
        for ($i = 0; $i < $this->mNumber;)
        {
            $fc_code = sprintf("%06s%04d%06d",$this->mBatchCode,$this->mCommonId,mt_rand(100000, 999999));

            $data = [];
            $data['fc_state'] = 0;
            $data['user_key'] = $this->mUserKey;
            $data['goods_commonid'] = $this->mCommonId;
            $data['fc_code'] = $fc_code;
            $data['usable_days'] = $this->mUsableDays;
            $data['batch_code']  = $this->mBatchCode;

            $ret = $mod_fcode->insert($data);
            $affect_rows = $mod_fcode->affected_rows();
            Log::record("fcode make i={$i} ret={$ret} rows={$affect_rows}",Log::DEBUG);
            if($ret != false && $affect_rows > 0) {
                ++$i;
            }
        }

        $url = BASE_SITE_URL . "/mobile/index.php?act=fcode&op=index&common_id={$this->mCommonId}&batch_code={$this->mBatchCode}";
        return $url;
    }
}