<?php

namespace app\admin\controller;

use think\Lang;
use think\Validate;

class Voucher extends AdminControl {

    const SECONDS_OF_30DAY = 2592000;

    private $applystate_arr;
    private $quotastate_arr;
    private $templatestate_arr;

    public function _initialize() {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'admin/lang/zh-cn/voucher.lang.php');
        if (config('voucher_allow') != 1 || config('points_isuse') != 1) {
            $this->error(lang('admin_voucher_unavailable'), 'operation/point');
        }
        $this->applystate_arr = array(
            'new' => array(1, lang('admin_voucher_applystate_new')),
            'verify' => array(2, lang('admin_voucher_applystate_verify')),
            'cancel' => array(3, lang('admin_voucher_applystate_cancel'))
        );
        $this->quotastate_arr = array(
            'activity' => array(1, lang('admin_voucher_quotastate_activity')),
            'cancel' => array(2, lang('admin_voucher_quotastate_cancel')),
            'expire' => array(3, lang('admin_voucher_quotastate_expire'))
        );
        //代金券模板状态
        $this->templatestate_arr = array(
            'usable' => array(1, lang('admin_voucher_templatestate_usable')),
            'disabled' => array(2, lang('admin_voucher_templatestate_disabled'))
        );
        $this->assign('applystate_arr', $this->applystate_arr);
        $this->assign('quotastate_arr', $this->quotastate_arr);
        $this->assign('templatestate_arr', $this->templatestate_arr);
    }

    /**
     * 代金券设置
     */
    public function setting() {
        $setting_model = Model('config');
        if (request()->isPost()) {
            $obj_validate = new Validate();
            $data = [
                'promotion_voucher_price' => $_POST['promotion_voucher_price'],
                'promotion_voucher_storetimes_limit' => $_POST['promotion_voucher_storetimes_limit'],
                'promotion_voucher_buyertimes_limit' => $_POST['promotion_voucher_buyertimes_limit']
            ];
            $rule = [
                ['promotion_voucher_price', 'require|number', lang('admin_voucher_setting_price_error')],
                ['promotion_voucher_storetimes_limit', 'require|number', lang('admin_voucher_setting_storetimes_error')],
                ['promotion_voucher_buyertimes_limit', 'require|number', lang('admin_voucher_setting_buyertimes_error')]
            ];

            $error = $obj_validate->check($data, $rule);
            if (!$error) {
                $this->error($obj_validate->getError());
            }
            //每月代金劵软件服务单价
            $promotion_voucher_price = intval($_POST['promotion_voucher_price']);
            if ($promotion_voucher_price < 0) {
                $promotion_voucher_price = 20;
            }
            //每月店铺可以发布的代金劵数量
            $promotion_voucher_storetimes_limit = intval($_POST['promotion_voucher_storetimes_limit']);
            if ($promotion_voucher_storetimes_limit <= 0) {
                $promotion_voucher_storetimes_limit = 20;
            }
            //买家可以领取的代金劵总数
            $promotion_voucher_buyertimes_limit = intval($_POST['promotion_voucher_buyertimes_limit']);
            if ($promotion_voucher_buyertimes_limit <= 0) {
                $promotion_voucher_buyertimes_limit = 5;
            }
            $update_array = array();
            $update_array['promotion_voucher_price'] = $promotion_voucher_price;
            $update_array['voucher_storetimes_limit'] = $promotion_voucher_storetimes_limit;
            $update_array['voucher_buyertimes_limit'] = $promotion_voucher_buyertimes_limit;
            $result = $setting_model->updateConfig($update_array);
            if ($result) {
                $this->log(lang('admin_voucher_setting') . lang('ds_voucher_price_manage'));
                $this->success(lang('ds_common_save_succ'), '');
            } else {
                $this->error(lang('ds_common_save_fail'), '');
            }
        } else {
            $setting = $setting_model->GetListConfig();
            $this->setAdminCurItem('setting');
            $this->assign('setting', $setting);
            return $this->fetch();
        }
    }

    /*
     * 代金券面额列表
     */

    public function pricelist() {
        //获得代金券金额列表
        $voucherprice_list = db('voucherprice')->order('voucher_price asc')->paginate(10, false, ['query' => request()->param()]);
        $this->assign('list', $voucherprice_list);
        $this->assign('show_page', $voucherprice_list->render());
        $this->setAdminCurItem('pricelist');
        return $this->fetch();
    }

    /*
     * 添加代金券面额页面
     */

    public function priceadd() {
        if (request()->isPost()) {
            $obj_validate = new Validate();
            $data = [
                'voucher_price' => $_POST['voucher_price'],
                'voucher_price_describe' => $_POST['voucher_price_describe'],
                'voucher_points' => $_POST['voucher_points']
            ];
            $rule = [
                ['voucher_price', 'require', lang('admin_voucher_price_error')],
                ['voucher_price_describe', 'require', lang('admin_voucher_price_describe_error')],
                ['voucher_points', 'require', lang('admin_voucher_price_points_error')]
            ];

            $error = $obj_validate->check($data, $rule);

            //验证面额是否存在
            $voucher_price = intval($_POST['voucher_price']);
            $voucher_points = intval($_POST['voucher_points']);
            $voucherprice_info = db('voucherprice')->where(array('voucher_price' => $voucher_price))->find();
            if (!empty($voucherprice_info)) {
                $error .= lang('admin_voucher_price_exist');
            }
            if (!$error) {
                $this->error($obj_validate->getError());
            } else {
                //保存
                $insert_arr = array(
                    'voucher_price_describe' => trim($_POST['voucher_price_describe']),
                    'voucher_price' => $voucher_price, 'voucher_defaultpoints' => $voucher_points,
                );
                $rs = db('voucherprice')->insert($insert_arr);
                if ($rs) {
                    $this->log(lang('ds_add') . lang('admin_voucher_priceadd') . '[' . $_POST['voucher_price'] . ']');
                    $this->success(lang('ds_common_save_succ'), 'voucher/pricelist');
                } else {
                    $this->error(lang('ds_common_save_fail'), 'voucher/priceadd');
                }
            }
        } else {
            $voucherprice_info = array(
                'voucher_price_id' => '',
                'voucher_price' => '',
                'voucher_price_describe' => '',
                'voucher_defaultpoints' => '',
            );
            $this->assign('info', $voucherprice_info);
            $this->setAdminCurItem('priceadd');
            return $this->fetch();
        }
    }

    /*
     * 编辑代金券面额
     */

    public function priceedit() {
        $id = intval(input('param.priceid'));
        if ($id <= 0) {
            $id = intval($_POST['priceid']);
        }
        if ($id <= 0) {
            $this->error(lang('param_error'), 'voucher/pricelist');
        }
        if (request()->isPost()) {
            $obj_validate = new Validate();
            $data = [
                'voucher_price' => $_POST['voucher_price'],
                'voucher_price_describe' => $_POST['voucher_price_describe'],
                'voucher_points' => $_POST['voucher_points']
            ];
            $rule = [
                ['voucher_price', 'require', lang('admin_voucher_price_error')],
                ['voucher_price_describe', 'require', lang('admin_voucher_price_describe_error')],
                ['voucher_points', 'require', lang('admin_voucher_price_points_error')]
            ];

            $error = $obj_validate->check($data, $rule);
            //验证面额是否存在
            $voucher_price = intval($_POST['voucher_price']);
            $voucher_points = intval($_POST['voucher_points']);
            $voucherprice_info = db('voucherprice')->where(array('voucher_price' => $voucher_price, 'voucher_price_id' => array('neq', $id)))->find();
            if (!empty($voucherprice_info)) {
                $error .= lang('admin_voucher_price_exist');
            }
            if (!$error) {
                $this->error($obj_validate->getError());
            } else {
                $update_arr = array();
                $update_arr['voucher_price_describe'] = trim($_POST['voucher_price_describe']);
                $update_arr['voucher_price'] = $voucher_price;
                $update_arr['voucher_defaultpoints'] = $voucher_points;
                $rs = db('voucherprice')->where(array('voucher_price_id' => $id))->update($update_arr);
                if ($rs) {
                    $this->log(lang('ds_edit') . lang('admin_voucher_priceadd') . '[' . $_POST['voucher_price'] . ']');
                    $this->success(lang('ds_common_save_succ'), 'voucher/pricelist');
                } else {
                    $this->error(lang('ds_common_save_fail'), 'voucher/pricelist');
                }
            }
        } else {
            $voucherprice_info = db('voucherprice')->where(array('voucher_price_id' => $id))->find();
            if (empty($voucherprice_info)) {
                $this->error(lang('param_error'), 'voucher/pricelist');
            }
            $this->assign('info', $voucherprice_info);
            $this->setAdminCurItem('priceedit');
            return $this->fetch('priceadd');
        }
    }

    /*
     * 删除代金券面额
     */

    public function pricedrop() {
        $voucher_price_id = trim($_POST['voucher_price_id']);
        if (empty($voucher_price_id)) {
            $this->error(lang('param_error'), 'voucher/pricelist');
        }
        $rs = db('voucherprice')->where(array(
                    'voucher_price_id' => array(
                        'in', $voucher_price_id
                    )
                ))->delete();
        if ($rs) {
            $this->log(lang('ds_del') . lang('admin_voucher_priceadd') . '[ID:' . $voucher_price_id . ']');
            $this->success(lang('ds_common_del_succ'), 'voucher/pricelist');
        } else {
            $this->error(lang('ds_common_del_fail'), 'voucher/pricelist');
        }
    }

    /**
     * 套餐管理
     * */
    public function quotalist() {

        //更新过期套餐的状态
        $time = time();
        db('voucherquota')->where(array(
            'quota_endtime' => array('lt', $time),
            'quota_state' => "{$this->quotastate_arr['activity'][0]}"
        ))->update(array('quota_state' => $this->quotastate_arr['expire'][0]));

        $param = array();
        if (trim(input('param.store_name'))) {
            $param['quota_storename'] = array('like', "%{input('param.store_name')}%");
        }
        $state = intval(input('param.state'));
        if ($state) {
            $param['quota_state'] = $state;
        }
        $list = db('voucherquota')->where($param)->order('quota_id desc')->paginate(10, false, ['query' => request()->param()]);
        $this->assign('show_page', $list->render());
        $this->assign('list', $list);
        $this->setAdminCurItem('quotalist');
        return $this->fetch();
    }

    /**
     * 代金券列表
     */
    public function index() {
        $param = array();
        if (trim(input('param.store_name'))) {
            $param['voucher_t_storename'] = array('like', "%{input('param.store_name')}%");
        }
        if (trim(input('param.sdate')) && trim(input('param.edate'))) {
            $sdate = strtotime(input('param.sdate'));
            $edate = strtotime(input('param.edate'));
            $param['voucher_t_add_date'] = array('between', "$sdate,$edate");
        } elseif (trim(input('param.sdate'))) {
            $sdate = strtotime(input('param.sdate'));
            $param['voucher_t_add_date'] = array('egt', $sdate);
        } elseif (trim(input('param.edate'))) {
            $edate = strtotime(input('param.edate'));
            $param['voucher_t_add_date'] = array('elt', $edate);
        }
        $state = intval(input('param.state'));
        if ($state) {
            $param['voucher_t_state'] = $state;
        }
        if (input('param.recommend') === '1') {
            $param['voucher_t_recommend'] = 1;
        } elseif (input('param.recommend') === '0') {
            $param['voucher_t_recommend'] = 0;
        }
        $list = db('vouchertemplate')->where($param)->order('voucher_t_state asc,voucher_t_id desc')->paginate(10, false, ['query' => request()->param()]);
        $this->assign('show_page', $list->render());

        $this->assign('list', $list);

        // 输出自营店铺IDS
        $this->assign('flippedOwnShopIds', array_flip(model('store')->getOwnShopIds()));
        $this->setAdminCurItem('index');
        return $this->fetch();
    }

    /*
     * 代金券模版编辑
     */

    public function templateedit() {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            $t_id = intval($_POST['tid']);
        }
        if ($t_id <= 0) {
            $this->error(lang('param_error'), 'voucher/index');
        }
        $model = Model('voucher');
        //查询模板信息
        $param = array();
        $param['voucher_t_id'] = $t_id;
        $t_info = db('vouchertemplate')->where($param)->find();
        if (empty($t_info)) {
            $this->error(lang('param_error'), 'voucher/index');
        }
        if (request()->isPost()) {
            $points = intval($_POST['points']);
            if ($points < 0) {
                $this->error(lang('admin_voucher_template_points_error'));
            }
            $update_arr = array();
            $update_arr['voucher_t_points'] = $points;
            $update_arr['voucher_t_state'] = intval($_POST['tstate']) == $this->templatestate_arr['usable'][0] ? $this->templatestate_arr['usable'][0] : $this->templatestate_arr['disabled'][0];
            $update_arr['voucher_t_recommend'] = intval($_POST['recommend']) == 1 ? 1 : 0;
            $rs = db('vouchertemplate')->where(array('voucher_t_id' => $t_info['voucher_t_id']))->update($update_arr);
            if ($rs) {
                $this->log(lang('ds_edit') . lang('ds_voucher_price_manage') . lang('admin_voucher_styletemplate') . '[ID:' . $t_id . ']');
                $this->success(lang('ds_common_save_succ'), 'voucher/index');
            } else {
                $this->error(lang('ds_common_save_fail'), 'voucher/index');
            }
        } else {
            //查询店铺分类
            $store_class = rkcache('store_class', true);

            $this->assign('store_class', $store_class);

            if (!$t_info['voucher_t_customimg'] || !file_exists(BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER . DS . $t_info['voucher_t_customimg'])) {
                $t_info['voucher_t_customimg'] = '';
            } else {
                $t_info['voucher_t_customimg'] = UPLOAD_SITE_URL . DS . ATTACH_VOUCHER . DS . $t_info['voucher_t_customimg'];
            }

            $this->assign('t_info', $t_info);
            $this->setAdminCurItem('templateedit');
            return $this->fetch();
        }
    }

    /**
     * ajax操作
     */
    public function ajax() {
        $model_voucher = Model('voucher');
        switch (input('param.branch')) {
            case 'voucher_t_recommend':
                $model_voucher->editVoucherTemplate(array('voucher_t_id' => intval(input('param.id'))), array(input('param.column') => intval(input('param.value'))));
                $logtext = '';
                if (intval(input('param.value')) == 1) {//推荐代金券
                    $logtext = '推荐代金券';
                } else {
                    $logtext = '取消推荐代金券';
                }
                $this->log($logtext . '[ID:' . intval(input('param.id')) . ']', 1);
                echo 'true';
                exit;
                break;
        }
    }

    /**
     * 页面内导航菜单
     * @param string $menu_key 当前导航的menu_key
     * @param array $array 附加菜单
     * @return
     */
    protected function getAdminItemList() {
        $menu_array = array(
            array(
                'name' => 'index', 'text' => lang('admin_voucher_template_manage'),
                'url' => url('voucher/index')
            ), array(
                'name' => 'quotalist', 'text' => lang('admin_voucher_quota_manage'),
                'url' => url('voucher/quotalist')
            ), array(
                'name' => 'pricelist', 'text' => lang('admin_voucher_pricemanage'),
                'url' => url('voucher/pricelist')
            ), array(
                'name' => 'priceadd', 'text' => lang('admin_voucher_priceadd'), 'url' => url('voucher/priceadd')
            ), array(
                'name' => 'setting', 'text' => lang('admin_voucher_setting'), 'url' => url('voucher/setting')
            ),
        );


        if (request()->action() == 'priceedit') {
            $menu_array = array(
                array(
                    'name' => 'setting', 'text' => lang('admin_voucher_setting'), 'url' => url('voucher/setting')
                ), array(
                    'name' => 'pricelist', 'text' => lang('admin_voucher_pricemanage'),
                    'url' => url('voucher/pricelist')
                ), array(
                    'name' => 'priceedit', 'text' => lang('admin_voucher_priceedit'), 'url' => ''
                )
            );
        }

        if (request()->action() == 'templateedit') {
            $menu_array = array(
                array(
                    'name' => 'index', 'text' => lang('admin_voucher_template_manage'),
                    'url' => url('voucher/index')
                ), array(
                    'name' => 'templateedit', 'text' => lang('admin_voucher_template_edit'), 'url' => ''
                )
            );
        }
        return $menu_array;
    }

}
