<?php

namespace app\admin\controller;
use think\facade\View;
use think\facade\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Rechargecard extends AdminControl
{
    const EXPORT_SIZE = 100;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'admin/lang/'.config('lang.default_lang').'/rechargecard.lang.php');
    }

    public function index()
    {
        $rechargecard_model = model('rechargecard');
        $condition = array();

        if (request()->isGet()) {
            $sn = trim((string)input('param.sn'));
            $batchflag = trim((string)input('param.batchflag'));
            $state = input('param.state');
            if (strlen($sn) > 0) {
                $condition[]=array('rc_sn','like', "%{$sn}%");
            }

            if (strlen($batchflag) > 0) {
                $condition[]=array('rc_batchflag','like', "%{$batchflag}%");
            }

            if ($state == '0' || $state == '1') {
                $condition[]=array('rc_state','=',$state);
            }
        }

        $cardList = $rechargecard_model->getRechargecardList($condition, 20);

        View::assign('card_list', $cardList);
        View::assign('show_page', $rechargecard_model->page_info->render());
        $this->setAdminCurItem('index');
        return View::fetch();
    }

    public function add_card()
    {
        if (!request()->isPost()) {
            return View::fetch();
        }
        else {
            $denomination = (float)input('post.denomination');
            if ($denomination < 0.01) {
                $this->error(lang('rechargecard_denomination_min'));
            }
            if ($denomination > 1000) {
                $this->error(lang('rechargecard_denomination_max'));
            }

            $snKeys = array();

            switch (input('post.type')) {
                case '0':
                    $total = (int)input('post.total');
                    if ($total < 1 || $total > 5000) {
                        $this->error(lang('r0total_message'));
                    }
                    $prefix = (string)input('post.prefix');
                    if (!preg_match('/^[0-9a-zA-Z]{0,16}$/', $prefix)) {
                        $this->error(lang('r0prefix_message'));
                    }
                    while (count($snKeys) < $total) {
                        $snKeys[$prefix . md5(uniqid(mt_rand(), true))] = null;
                    }
                    break;

                case '1':
                    $f = $_FILES['_textfile'];
                    if (!$f || $f['error'] != 0) {
                        $this->error(lang('file_upload_fail'));
                    }
                    if (!is_uploaded_file($f['tmp_name'])) {
                        $this->error(lang('file_empty'));
                    }
                    foreach (file($f['tmp_name']) as $sn) {
                        $sn = trim($sn);
                        if (preg_match('/^[0-9a-zA-Z]{1,50}$/', $sn))
                            $snKeys[$sn] = null;
                    }
                    break;

                case '2':
                    foreach (explode("\n", (string)input('post.manual')) as $sn) {
                        $sn = trim($sn);
                        if (preg_match('/^[0-9a-zA-Z]{1,50}$/', $sn))
                            $snKeys[$sn] = null;
                    }
                    break;

                default:
                    $this->error(lang('param_error'));
                    exit;
            }

            $totalKeys = count($snKeys);
            if ($totalKeys < 1 || $totalKeys > 9999) {
                $this->error(lang('recharge_number_error'));
            }

            if (empty($snKeys)) {
                $this->error(lang('recharge_number_invalid'));
            }

            $snOccupied = 0;
            $rechargecard_model = model('rechargecard');

            // chunk size = 50
            foreach (array_chunk(array_keys($snKeys), 50) as $snValues) {
                foreach ($rechargecard_model->getOccupiedRechargecardSNsBySNs($snValues) as $sn) {
                    $snOccupied++;
                    unset($snKeys[$sn]);
                }
            }

            if (empty($snKeys)) {
                $this->error(lang('recharge_number_exist'));
            }

            $batchflag = input('post.batchflag');
            $adminName = $this->admin_info['admin_name'];
            $ts = TIMESTAMP;

            $snToInsert = array();
            foreach (array_keys($snKeys) as $sn) {
                $snToInsert[] = array(
                    'rc_sn' => $sn, 'rc_denomination' => $denomination, 'rc_batchflag' => $batchflag, 'rc_admin_name' => $adminName,
                    'rc_tscreated' => $ts,
                );
            }

            if (!$rechargecard_model->addRechargecardAll($snToInsert)) {
                $this->error(lang('ds_common_op_fail'));
            }

            $countInsert = count($snToInsert);
            $this->log("新增{$countInsert}张充值卡（面额￥{$denomination}，批次标识“{$batchflag}”）");

            $msg = lang('ds_common_op_succ');
            if ($snOccupied > 0)
                $msg .= sprintf(lang('rechargecard_number_exist_error'),$snOccupied);

            dsLayerOpenSuccess($msg);
        }
    }


    /**
     * 删除平台充值卡
     */
    public function del_card() {
        $rechargecard_model= model('rechargecard');
        $rc_id = input('param.rc_id');
        $rc_id_array = ds_delete_param($rc_id);
        if($rc_id_array === FALSE){
            ds_json_encode(10001, lang('param_error'));
        }
        $condition = array(array('rc_id','in', $rc_id_array));
        $condition[]=array('rc_state','=',0);
        $result =$rechargecard_model->delRechargecard($condition);
        if ($result) {
            ds_json_encode(10000, lang('ds_common_del_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_del_fail'));
        }
    }


    /**
     * 导出
     */
    public function export_step1()
    {
        $rechargecard_model = model('rechargecard');
        $condition = array();

        if (request()->isPost()) {
            $sn = trim((string)input('param.sn'));
            $batchflag = trim((string)input('param.batchflag'));
            $state = trim((string)input('param.state'));

            if (strlen($sn) > 0) {
                $condition[]=array('rc_sn','like', "%{$sn}%");
                View::assign('sn', $sn);
            }

            if (strlen($batchflag) > 0) {
                $condition[]=array('rc_batchflag','like', "%{$batchflag}%");
                View::assign('batchflag', $batchflag);
            }

            if ($state === '0' || $state === '1') {
                $condition[]=array('rc_state','=',$state);
                View::assign('state', $state);
            }
        }

        if (!is_numeric(input('param.page'))) {
            $count = $rechargecard_model->getRechargecardCount($condition);
            $export_list = array();
            if ($count > self::EXPORT_SIZE) {    //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $export_list[]=array($i,'=',$limit1 . ' ~ ' . $limit2);
                }
                View::assign('export_list', $export_list);
                return View::fetch('/public/excel');
            }
            else {    //如果数量小，直接下载
                $data = $rechargecard_model->getRechargecardList($condition, 0,self::EXPORT_SIZE);

                $this->createExcel($data);
            }
        }
        else {    //下载
            $limit1 = (input('param.page') - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;

            $data = $rechargecard_model->getRechargecardList($condition, $limit2);

            $this->createExcel($data);
        }
    }

    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array())
    {
        $excel_obj = new \excel\Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array(
                                 'id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')
                             ));
        //header
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('rc_sn'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('rc_batchflag'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('rc_denomination'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('rc_admin_name'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('rc_tscreated'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('receive_user'));

        //data
        foreach ((array)$data as $k => $v) {
            $tmp = array();
            $tmp[] = array('data' => "\t" . $v['rc_sn']);
            $tmp[] = array('data' => "\t" . $v['rc_batchflag']);
            $tmp[] = array('data' => "\t" . $v['rc_denomination']);
            $tmp[] = array('data' => "\t" . $v['rc_admin_name']);
            $tmp[] = array('data' => "\t" . date('Y-m-d H:i:s', $v['rc_tscreated']));
            if ($v['rc_state'] == 1 && $v['member_id'] > 0 && $v['rc_tsused'] > 0) {
                $tmp[] = array('data' => "\t" . $v['member_name']);
            }
            else {
                $tmp[] = array('data' => "\t-");
            }
            $excel_data[] = $tmp;
        }
        $excel_data = $excel_obj->charset($excel_data, CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset(lang('rechargecard'), CHARSET));
        $excel_obj->generateXML($excel_obj->charset(lang('rechargecard'), CHARSET) . input('param.page') . '-' . date('Y-m-d-H', TIMESTAMP));
    }


    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index', 'text' => lang('ds_list'), 'url' => (string)url('Rechargecard/index')
            ), array(
                'name' => 'add_card', 'text' => lang('ds_new'),'url' => "javascript:dsLayerOpen('" . (string)url('Rechargecard/add_card') . "','".lang('ds_new')."')"
            ),
        );
        return $menu_array;
    }
}