<?php

namespace app\home\controller;


use think\Lang;
use think\Validate;

class Sellervoucher extends BaseSeller
{
    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 . 'home/lang/zh-cn/sellervoucher.lang.php');
        if (config('voucher_allow') != 1) {
            $this->error(lang('voucher_unavailable'), 'seller/index');
        }
        //申请记录状态
        $this->applystate_arr = array(
            'new' => array(1, lang('voucher_applystate_new')), 'verify' => array(2, lang('voucher_applystate_verify')),
            'cancel' => array(3, lang('voucher_applystate_cancel'))
        );
        //套餐状态
        $this->quotastate_arr = array(
            'activity' => array(1, lang('voucher_quotastate_activity')),
            'cancel' => array(2, lang('voucher_quotastate_cancel')),
            'expire' => array(3, lang('voucher_quotastate_expire'))
        );
        //代金券模板状态
        $this->templatestate_arr = array(
            'usable' => array(1, lang('voucher_templatestate_usable')),
            'disabled' => array(2, lang('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 templatelist()
    {
        //检查过期的代金券模板状态设为失效
        $this->check_voucher_template_expire();
        $model = Model('voucher');

        if (checkPlatformStore()) {
            $this->assign('isOwnShop', true);
        }
        else {
            //查询是否存在可用套餐
            $current_quota = $model->getCurrentQuota(session('store_id'));
            $this->assign('current_quota', $current_quota);
        }
        //查询列表
        $param = array();
        $param['voucher_t_store_id'] = session('store_id');
        if (trim(input('param.txt_keyword'))) {
            $param['voucher_t_title'] = array('like', '%' . trim(input('param.txt_keyword')) . '%');
        }
        $select_state = intval(input('param.select_state'));
        if ($select_state) {
            $param['voucher_t_state'] = $select_state;
        }
        if (input('param.txt_startdate')) {
            $param['voucher_t_end_date'] = array('egt', strtotime(input('param.txt_startdate')));
        }
        if (input('param.txt_enddate')) {
            $param['voucher_t_start_date'] = array('elt', strtotime(input('param.txt_enddate')));
        }

        $list = db('vouchertemplate')->where($param)->order('voucher_t_id desc')->paginate(10,false,['query' => request()->param()]);
        $this->assign('show_page', $list->render());

        $list=$list->items();
            foreach ($list as $key => $val) {

                if (!$val['voucher_t_customimg'] || !file_exists(BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER  . DS . $val['voucher_t_customimg'])) {
                    $list[$key]['voucher_t_customimg'] = UPLOAD_SITE_URL .  DS . defaultGoodsImage(60);
                }
                else {
                    $list[$key]['voucher_t_customimg'] = UPLOAD_SITE_URL . DS . ATTACH_VOUCHER . DS  . $val['voucher_t_customimg'];
                }
            }
           
        $this->setSellerCurMenu('Sellervoucher');
        $this->setSellerCurItem('templatelist');
        $this->assign('list', $list);

        return $this->fetch($this->template_dir . 'index');
    }

    /**
     * 购买套餐
     */
    public function quotaadd()
    {
        if (request()->isPost()) {
            $quota_quantity = intval($_POST['quota_quantity']);
            if ($quota_quantity <= 0 || $quota_quantity > 12) {
                showDialog(lang('voucher_apply_num_error'));
            }
            //获取当前价格
            $current_price = intval(config('promotion_voucher_price'));

            $model_voucher = Model('voucher');

            //获取该用户已有套餐
            $current_quota = $model_voucher->getCurrentQuota(session('store_id'));
            $add_time = 86400 * 30 * $quota_quantity;
            if (empty($current_quota)) {
                //生成套餐
                $param = array();
                $param['quota_memberid'] = session('member_id');
                $param['quota_membername'] = session('member_name');
                $param['quota_storeid'] = session('store_id');
                $param['quota_storename'] = session('store_name');
                $param['quota_starttime'] = TIMESTAMP;
                $param['quota_endtime'] = TIMESTAMP + $add_time;
                $param['quota_state'] = 1;
                $reault = db('voucherquota')->insert($param);
            }
            else {
                $param = array();
                $param['quota_endtime'] = array('exp', 'quota_endtime + ' . $add_time);
                $reault = db('voucherquota')->where(array('quota_id' => $current_quota['quota_id']))->update($param);
            }

            //记录店铺费用
            $this->recordStoreCost($current_price * $quota_quantity, '购买代金券套餐');

            $this->recordSellerLog('购买' . $quota_quantity . '份代金券套餐，单价' . $current_price . lang('ds_yuan'));

            if ($reault) {
                showDialog(lang('voucher_apply_buy_succ'), url('Sellervoucher/templatelist'), 'succ');
            }
            else {
                showDialog(lang('ds_common_op_fail'), url('Sellervoucher/templatelist'));
            }
        }
        else {
            //输出导航
            $this->setSellerCurMenu('Sellervoucher');
            $this->setSellerCurItem('quotaadd');
            return $this->fetch($this->template_dir . 'quota_add');
        }
    }

    /*
     * 代金券模版添加
     */
    public function templateadd()
    {
        $model = Model('voucher');
        $isOwnShop = checkPlatformStore();
        $this->assign('isOwnShop', $isOwnShop);
        if (!$isOwnShop) {
            //查询当前可以套餐
            $quotainfo = $model->getCurrentQuota(session('store_id'));
            if (empty($quotainfo)) {
                $this->error(lang('voucher_template_quotanull'), 'Sellervoucher/quotaadd');
            }

            //查询该套餐下代金券模板列表
            $count = db('vouchertemplate')->where(array('voucher_t_quotaid' => $quotainfo['quota_id'], 'voucher_t_state' => $this->templatestate_arr['usable'][0]))->count();
            if ($count >= config('voucher_storetimes_limit')) {
                $message = sprintf(lang('voucher_template_noresidual'), config('voucher_storetimes_limit'));
                $this->error($message, 'Sellervoucher/templatelist');
            }
        }

        //查询面额列表
        $pricelist = db('voucherprice')->order('voucher_price asc')->select();
        if (empty($pricelist)) {
            $this->error(lang('voucher_template_pricelisterror'), 'Sellervoucher/templatelist');
        }
        if (request()->isPost()) {
            //验证提交的内容面额不能大于限额
            $obj_validate = new Validate();
            $data = [
                'txt_template_title' => $_POST['txt_template_title'],
                'txt_template_total' => $_POST['txt_template_total'],
                'select_template_price' => $_POST['select_template_price'],
                'txt_template_limit' => $_POST['txt_template_limit'],
                'txt_template_describe' => $_POST['txt_template_describe'],
            ];

            $rule = [
                ['txt_template_title', 'require|length:1,50', lang('voucher_template_title_error')],
                ['txt_template_total', 'require|number', lang('voucher_template_total_error')],
                ['select_template_price', 'require|number', lang('voucher_template_price_error')],
                ['txt_template_limit', 'require', lang('voucher_template_limit_error')],
                ['txt_template_describe', 'require|length:1,255', lang('voucher_template_describe_error')]
            ];

            $res = $obj_validate->check($data, $rule);
            $error = '';
            if (!$res) {
                $error .= $obj_validate->getError();
            }
            //金额验证
            $price = intval($_POST['select_template_price']) > 0 ? intval($_POST['select_template_price']) : 0;
            foreach ($pricelist as $k => $v) {
                if ($v['voucher_price'] == $price) {
                    $chooseprice = $v;//取得当前选择的面额记录
                }
            }
            if (empty($chooseprice)) {
                $error .= lang('voucher_template_pricelisterror');
            }
            $limit = intval($_POST['txt_template_limit']) > 0 ? intval($_POST['txt_template_limit']) : 0;
            if ($price >= $limit)
                $error .= lang('voucher_template_price_error');
            if ($error) {
                showDialog($error, 'reload', 'error');
            }
            else {
                $insert_arr = array();
                $insert_arr['voucher_t_title'] = trim($_POST['txt_template_title']);
                $insert_arr['voucher_t_desc'] = trim($_POST['txt_template_describe']);
                $insert_arr['voucher_t_start_date'] = time();//默认代金券模板的有效期为当前时间
                if ($_POST['txt_template_enddate']) {
                    $enddate = strtotime($_POST['txt_template_enddate']);
                    if (!$isOwnShop && $enddate > $quotainfo['quota_endtime']) {
                        $enddate = $quotainfo['quota_endtime'];
                    }
                    $insert_arr['voucher_t_end_date'] = $enddate;
                }
                else {//如果没有添加有效期则默认为套餐的结束时间
                    if ($isOwnShop)
                        $insert_arr['voucher_t_end_date'] = time() + 2592000; // 自营店 默认30天到期
                    else
                        $insert_arr['voucher_t_end_date'] = $quotainfo['quota_endtime'];
                }
                $insert_arr['voucher_t_price'] = $price;
                $insert_arr['voucher_t_limit'] = $limit;
                $insert_arr['voucher_t_store_id'] = session('store_id');
                $insert_arr['voucher_t_storename'] = session('store_name');
                $insert_arr['voucher_t_sc_id'] = intval($_POST['sc_id']);
                $insert_arr['voucher_t_creator_id'] = session('member_id');
                $insert_arr['voucher_t_state'] = $this->templatestate_arr['usable'][0];
                $insert_arr['voucher_t_total'] = intval($_POST['txt_template_total']) > 0 ? intval($_POST['txt_template_total']) : 0;
                $insert_arr['voucher_t_giveout'] = 0;
                $insert_arr['voucher_t_used'] = 0;
                $insert_arr['voucher_t_gettype'] = 1;
                $insert_arr['voucher_t_add_date'] = time();
                $insert_arr['voucher_t_quotaid'] = $quotainfo['quota_id'] ? $quotainfo['quota_id'] : 0;
                $insert_arr['voucher_t_points'] = $chooseprice['voucher_defaultpoints'];
                $insert_arr['voucher_t_eachlimit'] = intval($_POST['eachlimit']) > 0 ? intval($_POST['eachlimit']) : 0;
                //自定义图片
                if (!empty($_FILES['customimg']['name'])) {

                    $uploaddir = BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER  . DS;
                    $file_name = session('store_id') . '_' . date('YmdHis') . rand(10000, 99999);
                    $file_object = request()->file('customimg');
                    $info = $file_object->rule('uniqid')->validate(['ext' => 'jpg,png,gif'])->move($uploaddir,$file_name);
                    if ($info) {
                        $insert_arr['voucher_t_customimg'] = $info->getFilename();
                    }
                }
                $rs = db('vouchertemplate')->insert($insert_arr);
                if ($rs) {
                    showDialog(lang('ds_common_save_succ'), url('Sellervoucher/templatelist'), 'succ');
                }
                else {
                    showDialog(lang('ds_common_save_fail'), url('Sellervoucher/templatelist'), 'error');
                }
            }
        }
        else {
            //店铺分类
            $store_class = rkcache('storeclass', true);
            $this->assign('store_class', $store_class);
            //查询店铺详情
            $store_info = Model('store')->getStoreInfoByID(session('store_id'));
            $this->assign('store_info', $store_info);

            $this->assign('type', 'add');
            $this->assign('quotainfo', $quotainfo);
            $this->assign('pricelist', $pricelist);
            $this->setSellerCurMenu('Sellervoucher');
            $this->setSellerCurItem('templateadd');
            return $this->fetch($this->template_dir . 'templateadd');
        }
    }

    /*
     * 代金券模版编辑
     */
    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('wrong_argument'), url('Sellervoucher/templatelist'));
        }
        $model = Model('voucher');
        //查询模板信息
        $param = array();
        $param['voucher_t_id'] = $t_id;
        $param['voucher_t_store_id'] = session('store_id');
        $param['voucher_t_state'] = $this->templatestate_arr['usable'][0];
        $param['voucher_t_giveout'] = array('elt', '0');
        $param['voucher_t_end_date'] = array('gt', time());
        $t_info = db('vouchertemplate')->where($param)->find();
        if (empty($t_info)) {
            $this->error(lang('wrong_argument'), 'Sellervoucher/templatelist');
        }

        $isOwnShop = checkPlatformStore();
        $this->assign('isOwnShop', $isOwnShop);
        if (!$isOwnShop) {
            //查询套餐信息
            $quotainfo = db('voucherquota')->where(array(
                                                       'quota_id' => $t_info['voucher_t_quotaid'],
                                                       'quota_storeid' => session('store_id')
                                                   ))->find();
            if (empty($quotainfo)) {
                $this->error(lang('voucher_template_quotanull'), 'Sellervoucher/quotaadd');
            }
        }

        //查询面额列表
        $pricelist = db('voucherprice')->order('voucher_price asc')->select();
        if (empty($pricelist)) {
            $this->error(lang('voucher_template_pricelisterror'), 'Sellervoucher/templatelist');
        }
        if (request()->isPost()) {
            //验证提交的内容面额不能大于限额
            $obj_validate = new Validate();
            $data = [
                'txt_template_title' => $_POST['txt_template_title'],
                'txt_template_total' => $_POST['txt_template_total'],
                'select_template_price' => $_POST['select_template_price'],
                'txt_template_limit' => $_POST['txt_template_limit'],
                'txt_template_describe' => $_POST['txt_template_describe'],
            ];

            $rule = [
                ['txt_template_title', 'require|length:1,50', lang('voucher_template_title_error')],
                ['txt_template_total', 'require|number', lang('voucher_template_total_error')],
                ['select_template_price', 'require|number', lang('voucher_template_price_error')],
                ['txt_template_limit', 'require', lang('voucher_template_limit_error')],
                ['txt_template_describe', 'require|length:1,255', lang('voucher_template_describe_error')]
            ];

            $res = $obj_validate->check($data, $rule);
            $error = '';
            if (!$res) {
                $error .= $obj_validate->getError();
            }
            //金额验证
            $price = intval($_POST['select_template_price']) > 0 ? intval($_POST['select_template_price']) : 0;
            foreach ($pricelist as $k => $v) {
                if ($v['voucher_price'] == $price) {
                    $chooseprice = $v;//取得当前选择的面额记录
                }
            }
            if (empty($chooseprice)) {
                $error .= lang('voucher_template_pricelisterror');
            }
            $limit = intval($_POST['txt_template_limit']) > 0 ? intval($_POST['txt_template_limit']) : 0;
            if ($price >= $limit)
                $error .= lang('voucher_template_price_error');
            if ($error) {
                showDialog($error, 'reload', 'error');
            }
            else {
                $update_arr = array();
                $update_arr['voucher_t_title'] = trim($_POST['txt_template_title']);
                $update_arr['voucher_t_desc'] = trim($_POST['txt_template_describe']);
                if ($_POST['txt_template_enddate']) {
                    $enddate = strtotime($_POST['txt_template_enddate']);
                    if (!$isOwnShop && $enddate > $quotainfo['quota_endtime']) {
                        $enddate = $quotainfo['quota_endtime'];
                    }
                    $update_arr['voucher_t_end_date'] = $enddate;
                }
                else {//如果没有添加有效期则默认为套餐的结束时间
                    if ($isOwnShop)
                        $update_arr['voucher_t_end_date'] = time() + 2592000; // 自营店 默认30天到期
                    else
                        $update_arr['voucher_t_end_date'] = $quotainfo['quota_endtime'];
                }
                $update_arr['voucher_t_price'] = $price;
                $update_arr['voucher_t_limit'] = $limit;
                $update_arr['voucher_t_sc_id'] = intval($_POST['sc_id']);
                $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_total'] = intval($_POST['txt_template_total']) > 0 ? intval($_POST['txt_template_total']) : 0;
                $update_arr['voucher_t_points'] = $chooseprice['voucher_defaultpoints'];
                $update_arr['voucher_t_eachlimit'] = intval($_POST['eachlimit']) > 0 ? intval($_POST['eachlimit']) : 0;
                //自定义图片
                if (!empty($_FILES['customimg']['name'])) {
                    $uploaddir = BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER . DS;
                    $file_name = session('store_id') . '_' . date('YmdHis') . rand(10000, 99999);
                    $file_object = request()->file('customimg');
                    $info = $file_object->validate(['ext' => 'jpg,png,gif'])->move($uploaddir,$file_name);
                    if ($info) {
                        //删除原图
                        if (!empty($t_info['voucher_t_customimg'])) {//如果模板存在，则删除原模板图片
                            @unlink(BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER . DS  . $t_info['voucher_t_customimg']);
                        }
                        $update_arr['voucher_t_customimg'] = $info->getFilename();
                    }
                }

                $rs = db('vouchertemplate')->where(array('voucher_t_id' => $t_info['voucher_t_id']))->update($update_arr);
                if ($rs) {
                    showDialog(lang('ds_common_op_succ'), url('Sellervoucher/templatelist'), 'succ');
                }
                else {
                    showDialog(lang('ds_common_op_fail'), url('Sellervoucher/templatelist'), 'error');
                }
            }
        }
        else {
            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'] = UPLOAD_SITE_URL . DS . defaultGoodsImage(240);
            }
            else {
                $t_info['voucher_t_customimg'] = UPLOAD_SITE_URL . DS . ATTACH_VOUCHER . DS  .  $t_info['voucher_t_customimg'];
            }
            $this->assign('type', 'edit');
            $this->assign('t_info', $t_info);

            //店铺分类
            $store_class = rkcache('store_class', true);
            $this->assign('store_class', $store_class);
            //查询店铺详情
            $store_info = Model('store')->getStoreInfoByID(session('store_id'));
            $this->assign('store_info', $store_info);

            $this->assign('quotainfo', $quotainfo);
            $this->assign('pricelist', $pricelist);
            $this->setSellerCurMenu('Sellervoucher');
            $this->setSellerCurItem('templateedit');

            return $this->fetch($this->template_dir . 'templateadd');
        }
    }

    /**
     * 删除代金券
     */
    public function templatedel()
    {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            $this->error(lang('wrong_argument'), url('Sellervoucher/templatelist'));
        }
        //查询模板信息
        $param = array();
        $param['voucher_t_id'] = $t_id;
        $param['voucher_t_store_id'] = session('store_id');
        $param['voucher_t_giveout'] = array('elt', '0');//会员没领取过代金券才可删除
        $t_info = db('vouchertemplate')->where($param)->find();
        if (empty($t_info)) {
            $this->error(lang('wrong_argument'), 'Sellervoucher/templatelist');
        }
        $rs = db('vouchertemplate')->where(array('voucher_t_id' => $t_info['voucher_t_id']))->delete();
        if ($rs) {
            //删除自定义的图片
            if (trim($t_info['voucher_t_customimg'])) {
                @unlink(BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER . DS . session('store_id') . DS . $t_info['voucher_t_customimg']);
            }
            showDialog(lang('ds_common_del_succ'), 'reload', 'succ');
        }
        else {
            showDialog(lang('ds_common_del_fail'));
        }
    }

    /**
     * 查看代金券详细
     */
    public function templateinfo()
    {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            $this->error(lang('wrong_argument'), 'Sellervoucher/templatelist');
        }
        //查询模板信息
        $param = array();
        $param['voucher_t_id'] = $t_id;
        $param['voucher_t_store_id'] = session('store_id');
        $t_info = db('vouchertemplate')->where($param)->find();
        $this->assign('t_info', $t_info);
        $this->setSellerCurMenu('Sellervoucher');
        $this->setSellerCurItem('templateinfo');
        return $this->fetch($this->template_dir . 'template_info');
    }

    /*
     * 把代金券模版设为失效
     */
    private function check_voucher_template_expire($voucher_template_id = '')
    {
        $where_array = array();
        if (empty($voucher_template_id)) {
            $where_array['voucher_t_end_date'] = array('lt', time());
        }
        else {
            $where_array['voucher_t_id'] = $voucher_template_id;
        }
        $where_array['voucher_t_state'] = $this->templatestate_arr['usable'][0];
        db('vouchertemplate')->where($where_array)->update(array('voucher_t_state' => $this->templatestate_arr['disabled'][0]));
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string $menu_type 导航类型
     * @param string $menu_key 当前导航的menu_key
     * @return
     */
    protected function getSellerItemList()
    {
        $menu_array = array();
        switch (request()->action()) {
            case 'templatelist':
                $menu_array = array(
                    1 => array(
                        'name' => 'templatelist', 'text' => lang('ds_member_path_store_voucher'),
                        'url' => url('Sellervoucher/templatelist')
                    ),
                );
                break;
            case 'quotaadd':
                $menu_array = array(
                    array(
                        'name' => 'templatelist', 'text' => lang('ds_member_path_store_voucher'),
                        'url' => url('Sellervoucher/templatelist')
                    ), array(
                        'name' => 'quotaadd', 'text' => lang('voucher_applyadd'), 'url' => url('Sellervoucher/quotaadd')
                    )
                );
                break;
            case 'templateadd':
                $menu_array = array(
                    1 => array(
                        'name' => 'templatelist', 'text' => lang('ds_member_path_store_voucher'),
                        'url' => url('Sellervoucher/templatelist')
                    ), 2 => array(
                        'name' => 'templateadd', 'text' => lang('voucher_templateadd'),
                        'url' => url('Sellervoucher/templateadd')
                    ),
                );
                break;
            case 'templateedit':
                $menu_array = array(
                    1 => array(
                        'name' => 'templatelist', 'text' => lang('ds_member_path_store_voucher'),
                        'url' => url('Sellervoucher/templatelist')
                    ), 2 => array(
                        'name' => 'templateedit', 'text' => lang('voucher_templateedit'), 'url' => ''
                    ),
                );
                break;
            case 'templateinfo':
                $menu_array = array(
                    1 => array(
                        'name' => 'templatelist', 'text' => lang('ds_member_path_store_voucher'),
                        'url' => url('Sellervoucher/templatelist')
                    ), 2 => array(
                        'name' => 'templateinfo', 'text' => lang('voucher_templateinfo'), 'url' => ''
                    ),
                );
                break;
        }
        return $menu_array;
    }
}