<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-06-28
 */

namespace weapp\Coupons\controller;

use think\Page;
use think\Db;
use app\common\controller\Weapp;
use weapp\Coupons\model\CouponsModel;

/**
 * 插件的控制器
 */
class Coupons extends Weapp
{
    /**
     * 实例化模型
     */
    private $model;

    /**
     * 实例化对象
     */
    private $db;

    /**
     * 插件基本信息
     */
    private $weappInfo;

    /**
     * 构造方法
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new CouponsModel;
        $this->db = Db::name('WeappCoupons');
        $this->coupon_use_db = Db::name('WeappCouponsUse');
        // 商品数据表
        $this->archives_db = Db::name('archives');
        // 商品分类数据表
        $this->arctype_db = Db::name('arctype');
        // 默认商品模型
        $this->channeltype = 2;
        $this->assign('channeltype', $this->channeltype);

        /*插件基本信息*/
        $this->weappInfo = $this->getWeappInfo();
        $this->assign('weappInfo', $this->weappInfo);
        /*--end*/
    }

    /**
     * 插件使用指南
     */
    public function doc()
    {
        return $this->fetch('doc');
    }

    /**
     * 插件配置
     */
    public function conf()
    {
        if (IS_POST) {
            $post = input('post.');
            if (!empty($post['code'])) {
                $data = array(
                    'tag_weapp' => $post['tag_weapp'],
                    'update_time' => getTime(),
                );
                $r = M('weapp')->where('code', 'eq', $post['code'])->update($data);
                if ($r) {
                    \think\Cache::clear('hooks');
                    adminLog('编辑' . $this->weappInfo['name'] . '：插件配置'); // 写入操作日志
                    $this->success("操作成功!", weapp_url('Coupons/Coupons/conf'));
                }
            }
            $this->error("操作失败!");
        }

        $row = M('weapp')->where('code', 'eq', 'Coupons')->find();
        $this->assign('row', $row);

        return $this->fetch('conf');
    }


    // 优惠券列表
    public function index()
    {
        $condition = [
            'is_del' => 0
        ];

        $keywords = input('keywords/s');
        // 应用搜索条件
        if (!empty($keywords)) $condition['coupon_name'] = ['LIKE', "%{$keywords}%"];

        // 分页
        $count = $this->db->where($condition)->count();
        $Page = new Page($count, config('paginate.list_rows'));
        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('pager', $Page);

        // 数据查询
        $list = $this->db
            ->where($condition)
            ->order('sort_order asc, coupon_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        if (!empty($list)) {
            $ids = [];
            foreach ($list as $k => $v) {
                $ids[] = $v['coupon_id'];
            }
            //已领数量
            $getedArr = $this->coupon_use_db->field('count(*) as count,coupon_id')->where('coupon_id', 'in', $ids)->group('coupon_id')->getAllWithIndex('coupon_id');
            foreach ($list as $k => $v) {
                $list[$k]['geted'] = $getedArr[$v['coupon_id']]['count'];
            }
        }

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

        return $this->fetch();
    }

    // 新增优惠券
    public function add()
    {
        if (IS_POST) {
            $post = input('post.');

            // 数据判断处理
            if (empty($post['coupon_name'])) $this->error('请填写优惠券名称');
            $post['coupon_name'] = htmlspecialchars_decode($post['coupon_name']);
            if (1 == $post['coupon_form']) {
                if (empty($post['coupon_price'])) $this->error('请填写优惠规则-减免金额');
            } elseif (2 == $post['coupon_form']) {
                if (empty($post['coupon_discount'])) $this->error('请填写优惠规则-折扣');
            }
            if (empty($post['coupon_stock'])) $this->error('请填写库存');
            if (2 == $post['level_form']) {
                $post['redeem_authority'] = !empty($post['level_id']) ? implode(',', $post['level_id']) : '';
            }
            if (!empty($post['use_limit_num'])) {
                if (empty($post['use_limit_num_value'])) $this->error('请填写每人限领张数');
                $post['use_limit_num'] = $post['use_limit_num_value'];
            }
            if (1 == $post['use_type']) {
                if (empty($post['use_start_time'])) $this->error('请填写优惠券有效开始时间');
                if (empty($post['use_end_time'])) $this->error('请填写优惠券有效结束时间');
            } else if (2 == $post['use_type'] || 3 == $post['use_type']) {
                if (empty($post['valid_days'])) $this->error('请填写优惠券有效天数');
            }
            if (empty($post['start_date'])) $this->error('请选择优惠券发放日期');
            if (empty($post['end_date'])) $this->error('请选择优惠券结束日期');
            if (2 == $post['coupon_type']) {
                if (empty($post['product_id'])) $this->error('请选择指定商品');
            } elseif (3 == $post['coupon_type']) {
                if (empty($post['arctype_id'])) $this->error('请选择指定分类');
            }
            $post['start_date'] = strtotime($post['start_date']);
            $post['end_date'] = strtotime($post['end_date']);

            $post['use_start_time'] = strtotime($post['use_start_time']);
            $post['use_end_time'] = strtotime($post['use_end_time']);

            $post['add_time'] = getTime();
            $post['update_time'] = getTime();

            if (1 == $post['coupon_type']) {
                $post['product_id'] = '';
                $post['arctype_id'] = '';
            } else if (2 == $post['coupon_type']) {
                $post['arctype_id'] = '';
                // 去除重复项
                $post['product_id'] = implode(',', array_unique(explode(',', $post['product_id'])));
            } else if (3 == $post['coupon_type']) {
                $post['product_id'] = '';
            }

            // 添加新优惠券
            $ResultID = $this->db->insertGetId($post);
            if (false !== $ResultID) {
                $ResultID = 2 > strlen($ResultID) ? '0' . $ResultID : $ResultID;
                $coupon_code = date('Ymd') . $ResultID;
                $update_where = [
                    'coupon_id' => $ResultID,
                ];
                $this->db->where($update_where)->update(['coupon_code' => $coupon_code]);
                $this->success('操作成功', weapp_url('Coupons/index'));
            } else {
                $this->error('操作失败');
            }
        }

        // 会员级别
        $users_level = model('UsersLevel')->getList();
        $this->assign('users_level', $users_level);

        // 开始时间
        $start_date = date("Y-m-d H:i:s", strtotime("-0 day"));
        $this->assign('start_date', $start_date);

        // 结束时间
        $end_date = date("Y-m-d H:i:s", strtotime("+15 day"));
        $this->assign('end_date', $end_date);
        return $this->fetch();
    }

    // 优惠券编辑
    public function edit()
    {
        if (IS_POST) {
            $post = input('post.');
            $post['coupon_id'] = intval($post['coupon_id']);
            if (empty($post['coupon_id'])) $this->error('缺少必要参数');
            // 数据判断处理
            if (empty($post['coupon_name'])) $this->error('请填写优惠券名称');
            $post['coupon_name'] = htmlspecialchars_decode($post['coupon_name']);
            if (1 == $post['coupon_form']) {
                if (empty($post['coupon_price'])) $this->error('请填写优惠规则-减免金额');
            } elseif (2 == $post['coupon_form']) {
                if (empty($post['coupon_discount'])) $this->error('请填写优惠规则-折扣');
            }
            if (empty($post['coupon_stock'])) $this->error('请填写库存');
            if (2 == $post['level_form']) {
                $post['redeem_authority'] = !empty($post['level_id']) ? implode(',', $post['level_id']) : '';
            }else{
                $post['redeem_authority'] = '';
            }
            if (!empty($post['use_limit_num'])) {
                if (empty($post['use_limit_num_value'])) $this->error('请填写每人限领张数');
                $post['use_limit_num'] = $post['use_limit_num_value'];
            }
            if (1 == $post['use_type']) {
                if (empty($post['use_start_time'])) $this->error('请填写优惠券有效开始时间');
                if (empty($post['use_end_time'])) $this->error('请填写优惠券有效结束时间');
            } else if (2 == $post['use_type'] || 3 == $post['use_type']) {
                if (empty($post['valid_days'])) $this->error('请填写优惠券有效天数');
            }
            if (empty($post['start_date'])) $this->error('请选择优惠券发放日期');
            if (empty($post['end_date'])) $this->error('请选择优惠券结束日期');
            if (2 == $post['coupon_type']) {
                if (empty($post['product_id'])) $this->error('请选择指定商品');
            } elseif (3 == $post['coupon_type']) {
                if (empty($post['arctype_id'])) $this->error('请选择指定分类');
            }

            $post['start_date'] = strtotime($post['start_date']);
            $post['end_date'] = strtotime($post['end_date']);
            $post['use_start_time'] = strtotime($post['use_start_time']);
            $post['use_end_time'] = strtotime($post['use_end_time']);
            $post['update_time'] = getTime();
            if (1 == $post['coupon_type']) {
                $post['product_id'] = '';
                $post['arctype_id'] = '';
            } else if (2 == $post['coupon_type']) {
                $post['arctype_id'] = '';
            } else if (3 == $post['coupon_type']) {
                $post['product_id'] = '';
            }
            $update_where = [
                'coupon_id' => $post['coupon_id'],
            ];
            unset($post['coupon_id']);
//            dump($post);exit;
            // 更新优惠券
            $ResultID = $this->db->where($update_where)->update($post);
            if (false !== $ResultID) {
                $this->success('更新成功', weapp_url('Coupons/index'));
            } else {
                $this->error('更新失败');
            }
        }
        $coupon_where = [
            'coupon_id' => input('id/d'),
        ];
        // 优惠券数据
        $coupon = $this->db->where($coupon_where)->find();
        $coupon['redeem_authority'] = !empty($coupon['redeem_authority']) ? explode(',', $coupon['redeem_authority']) : '';
        $coupon['product_id_num'] = !empty($coupon['product_id']) ? count(explode(',', $coupon['product_id'])) : 0;
        $coupon['arctype_id_num'] = !empty($coupon['arctype_id']) ? count(explode(',', $coupon['arctype_id'])) : 0;
        $this->assign('info', $coupon);

        // 会员级别
        $users_level = model('UsersLevel')->getList();
        $this->assign('users_level', $users_level);
        return $this->fetch();
    }

    // 优惠券删除
    public function del()
    {
        $coupon_id = input('del_id/a');
        $coupon_id = eyIntval($coupon_id);
        if (IS_AJAX_POST && !empty($coupon_id)) {
            // 删除统一条件
            $Where = [
                'coupon_id' => ['IN', $coupon_id],
            ];
            $result = $this->db->field('coupon_name')->where($Where)->select();
            $coupon_name_list = get_arr_column($result, 'coupon_name');

            $return = $this->db->where($Where)->update(['is_del' => 1, 'update_time' => getTime()]);
            if ($return) {
                adminLog('删除优惠券：' . implode(',', $coupon_name_list));
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('参数有误');
    }

    // 选择商品
    public function select_product()
    {
        // 查询条件
        $where['a.channel'] = $this->channeltype;
        $where['a.status'] = 1;
        $where['a.is_del'] = 0;

        $keywords = input('keywords/s');
        if (!empty($keywords)) $where['a.title'] = ['LIKE', "%{$keywords}%"];

        // 指定商品ID查询
        $product_ids = input('product_ids/s');
        if (!empty($product_ids)) $where['a.aid'] = ['IN', explode(',', $product_ids)];

        // 指定分类查询
        $typeid = input('typeid/d') ? input('typeid/d') : 0;
        if (!empty($typeid)) {
            $hasRow = model('Arctype')->getHasChildren($typeid);
            $typeids = get_arr_column($hasRow, 'id');
            $stypeid_where = "";
            $typeid_arr = array_unique($typeids);
            foreach ($typeid_arr as $_k => $_v) {
                if (!empty($_k)) $stypeid_where .= " OR ";
                $stypeid_where .= "CONCAT(',', a.stypeid, ',') LIKE '%,{$_v},%' ";
            }
            $where[] = Db::raw(" ({$stypeid_where}) ");
        }

        $count = $this->archives_db->alias('a')->where($where)->count();
        $pageObj = new Page($count, config('paginate.list_rows'));
        $this->assign('page', $pageObj->show());
        $this->assign('pager', $pageObj);

        $field = 'a.aid, a.litpic, a.aid as product_id, a.title, a.users_price, b.typename';
        $ResultData = $this->archives_db
            ->alias('a')
            ->field($field)
            ->join('__ARCTYPE__ b', 'a.typeid = b.id', 'LEFT')
            ->where($where)
            ->order('a.sort_order asc, a.users_price desc, a.aid desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();
        $array_new = get_archives_data($ResultData, 'aid');
        foreach ($ResultData as $key => $value) {
            $ResultData[$key]['arcurl'] = get_arcurl($array_new[$value['aid']]);
            $ResultData[$key]['litpic'] = handle_subdir_pic($value['litpic']);
        }

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

        /*允许发布文档列表的栏目*/
        $arctype_html = allow_release_arctype($typeid, [$this->channeltype]);
        $this->assign('arctype_html', $arctype_html);
        $this->assign('typeid', $typeid);
        /*--end*/
        return $this->fetch();
    }

    // 获取指定分类或查询后的所有商品ID
    public function ajax_get_product_id()
    {
        if (IS_AJAX_POST) {
            // 查询条件
            $where['a.channel'] = $this->channeltype;
            $where['a.status'] = 1;
            $where['a.is_del'] = 0;

            $keywords = input('keywords/s');
            if (!empty($keywords)) $where['a.title'] = ['LIKE', "%{$keywords}%"];

            // 指定商品ID查询
            $product_ids = input('product_ids/s');
            if (!empty($product_ids)) $where['a.aid'] = ['IN', explode(',', $product_ids)];

            // 指定分类查询
            $typeid = input('typeid/d') ? input('typeid/d') : 0;
            if (!empty($typeid)) {
                $hasRow = model('Arctype')->getHasChildren($typeid);
                $typeids = get_arr_column($hasRow, 'id');
                $where['a.typeid'] = ['IN', $typeids];
            }

            $field = 'a.aid, a.aid as product_id';
            $ResultData = $this->archives_db
                ->alias('a')
                ->field($field)
                ->where($where)
                ->order('a.sort_order asc, a.users_price desc, a.aid desc')
                ->select();

            $product_ids = get_arr_column($ResultData, 'product_id');
            $ReturnData['ProductNum'] = count($ResultData);
            $ReturnData['ProductIDS'] = implode(',', $product_ids);
            $this->success('', null, $ReturnData);
        }
    }

    /**
     * 选择分类
     * @return [type] [description]
     */
    public function select_arctype()
    {
        $assign_data = [];
        // 目录列表
        $where = [];
        $where['current_channel'] = $this->channeltype;
        $where['is_del'] = 0; // 回收站功能
        $arctypeLogic = new \app\common\logic\ArctypeLogic;
        $arctype_list = $arctypeLogic->arctype_list(0, 0, false, 0, $where, false);
        $assign_data['arctype_list'] = $arctype_list;

        /*获取所有有子栏目的栏目id*/
        $parent_ids = Db::name('arctype')->where([
            'parent_id' => ['gt', 0],
            'is_del' => 0,
        ])->group('parent_id')->cache(true, EYOUCMS_CACHE_TIME, 'arctype')->column('parent_id');
        $cookied_treeclicked = json_decode(cookie('coupontypeids-treeClicked-Arr'));
        empty($cookied_treeclicked) && $cookied_treeclicked = [];
        $all_treeclicked = cookie('coupontypeids-treeClicked_All');
        empty($all_treeclicked) && $all_treeclicked = [];
        $tree = [
            'has_children' => !empty($parent_ids) ? 1 : 0,
            'parent_ids' => json_encode($parent_ids),
            'all_treeclicked' => $all_treeclicked,
            'cookied_treeclicked' => $cookied_treeclicked,
            'cookied_treeclicked_arr' => json_encode($cookied_treeclicked),
        ];
        $assign_data['tree'] = $tree;
        /* end */

        // 分类
        $typeids = input('param.typeids/s');
        $typeids = trim($typeids, ',');
        $typeids_arr = explode(',', $typeids);
        $assign_data['typeids'] = $typeids;
        $assign_data['typeids_arr'] = $typeids_arr;

        $this->assign($assign_data);

        return $this->fetch();
    }
    
    //手工发券
    public function manual_grant()
    {
        if (IS_AJAX){
            $post = input();
            $coupon = $this->db->where('coupon_id',$post['coupon_id'])->find();
            if (empty($coupon)){
                $this->error('优惠券不存在!');
            }
            if (1 == $post['type']){
                //指定用户id
                $users_id_arr = explode(",",$post['users_id']);
            }else if (2 == $post['type']){
                //指定用户等级
                $users_id_arr = Db::name('users')->where('level','in',$post['level_id'])->where(['is_lock'=>0,'is_del'=>0])->column('users_id');
            }else if (3 == $post['type']){
                //全部用户
                $users_id_arr = Db::name('users')->where(['is_lock'=>0,'is_del'=>0])->column('users_id');
            }
            //检查优惠券库存
            $count = count($users_id_arr);
            if ($count > $coupon['coupon_stock']){
                $this->error('优惠券库存不足,库存至少应该为'.$count.'张!');
            }
            $insertAll = [];
            $uid_arr = [];
            $total = 0;
            foreach ($users_id_arr as $k){
                $uid_arr[] = $k;
                $insert['coupon_id']   = $post['coupon_id'];
                $insert['coupon_code'] = $coupon['coupon_code'];
                $insert['users_id']    = $k;
                $insert['source']      = 3;
                $insert['use_status']  = 0;
                $insert['get_time']    = getTime();
                $insert['add_time']    = getTime();
                $insert['update_time'] = getTime();
                //根据使用期限不同插入开始/结束使用时间
                if (1 == $coupon['use_type']) {//固定期限
                    $insert['start_time'] = $coupon['use_start_time'];
                    $insert['end_time']   = $coupon['use_end_time'];
                } else if (2 == $coupon['use_type']) {//当日开始N天有效
                    $insert['start_time'] = strtotime(date("Y-m-d", time()));
                    $insert['end_time']   = $insert['start_time'] + $coupon['valid_days'] * 86400;
                } else if (3 == $coupon['use_type']) {//次日开始N天有效
                    $insert['start_time'] = strtotime(date("Y-m-d", time())) + 86400;
                    $insert['end_time']   = $insert['start_time'] + $coupon['valid_days'] * 86400;
                }
                $insertAll[] = $insert;
                $total++;
                //50条数据写入一次
                if (50 == count($insertAll)){
                    Db::name('weapp_coupons_use')->insertAll($insertAll);
                    $uid_str = implode(',',$uid_arr);
                    $log_info = '管理员发放优惠券,用户:'.$uid_str;
                    adminLog($log_info);
                    $insertAll = $uid_arr = [];
                }
            }
            if (!empty($insertAll)) {
                Db::name('weapp_coupons_use')->insertAll($insertAll);
                $uid_str = implode(',', $uid_arr);
                $log_info = '管理员发放优惠券,用户:' . $uid_str;
                adminLog($log_info);
            }
            //减库存
            $this->db->where('coupon_id', $post['coupon_id'])->update(['coupon_stock'=>Db::Raw('coupon_stock-'.$total),'update_time'=>getTime()]);
            $this->success('发放成功！',url('Coupon/index'));
        }
        // 会员级别
        $users_level = model('UsersLevel')->getList('*');
        $this->assign('users_level', $users_level);

        return $this->fetch();
    }

    // 选择优惠券
    public function select_coupon()
    {
        $keywords = input('keywords/s');
        if (!empty($keywords)) $condition['coupon_name'] = ['LIKE', "%{$keywords}%"];

        $condition['end_date'] = ['>',getTime()];
        $condition['is_del'] = 0;
        // 分页
        $count = $this->db->where($condition)->count();
        $Page  = new Page($count, config('paginate.list_rows'));
        $show  = $Page->show();
        $this->assign('page', $show);
        $this->assign('pager', $Page);

        // 数据查询
        $list = $this->db
            ->where($condition)
            ->order('sort_order asc, coupon_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        foreach ($list as $k => $v){
            if (1 == $v['coupon_form']){
                $v['condition'] = "满{$v['conditions_use']}减{$v['coupon_price']}";
            }else{
                if (0 == $v['conditions_use']){
                    $v['condition'] = "无门槛{$v['coupon_discount']}折";
                }else{
                    $v['condition'] = "满{$v['conditions_use']}享{$v['coupon_discount']}折";
                }
            }
            $list[$k] = $v;
        }
        $this->assign('list', $list);

        return $this->fetch();
    }

    //领券记录
    public function log()
    {
        $post = input();
        $where = [];
        if (!empty($post['keywords'])){
            $where['c.coupon_name|b.nickname|b.username'] = ['like','%'.$post['keywords'].'%'];
        }
        if (!empty($post['source'])){
            $where['a.source'] = $post['source'];
        }
        if (!empty($post['use_status'])){
            if (-1 == $post['use_status']){
                $where['a.use_status'] = 0;
            }else{
                $where['a.use_status'] = $post['use_status'];
            }
        }
        if (!empty($post['get_time'])){
            $get_time_arr = explode(' - ',$post['get_time']);
            $where['a.get_time'] = ['between',[strtotime($get_time_arr[0]),strtotime($get_time_arr[1])]];
        }
        if (!empty($post['end_time'])){
            $end_time_arr = explode(' - ',$post['end_time']);
            $where['a.end_time'] = ['between',[strtotime($end_time_arr[0]),strtotime($end_time_arr[1])]];
        }
        if (!empty($post['use_time'])){
            $use_time_arr = explode(' - ',$post['use_time']);
            $where['a.use_time'] = ['between',[strtotime($use_time_arr[0]),strtotime($use_time_arr[1])]];
        }

        $count = Db::name('weapp_coupons_use')
            ->join('users b','a.users_id = b.users_id','left')
            ->join('weapp_coupons c','a.coupon_id = c.coupon_id','left')
            ->alias('a')->where($where)->count();
        $Page = new Page($count, config('paginate.list_rows'));
        $list =  $list = Db::name('weapp_coupons_use')
            ->alias('a')
            ->field('a.*,b.nickname,b.username,b.head_pic,c.coupon_name,c.coupon_type,c.coupon_price,c.conditions_use')
            ->join('users b','a.users_id = b.users_id','left')
            ->join('weapp_coupons c','a.coupon_id = c.coupon_id','left')
            ->where($where)
            ->order('use_id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

        foreach ($list as $k => $v){
            if (1 == $v['coupon_form']){
                $v['condition'] = "满{$v['conditions_use']}减{$v['coupon_price']}";
            }else{
                if (0 == $v['conditions_use']){
                    $v['condition'] = "无门槛{$v['coupon_discount']}折";
                }else{
                    $v['condition'] = "满{$v['conditions_use']}享{$v['coupon_discount']}折";
                }
            }
            $list[$k] = $v;
        }

        $show = $Page->show();
        $this->assign('page',$show);
        $this->assign('list',$list);
        $this->assign('pager',$Page);

        return $this->fetch();
    }

}