<?php

namespace app\admin\controller;


use think\Lang;
use think\Validate;

class Pointprod extends AdminControl
{
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'admin/lang/zh-cn/pointprod.lang.php');
    }

    /**
     * 积分礼品列表
     */
    public function index()
    {
        $pointprod_model = Model('pointprod');

        //获得兑换商品的上下架状态
        $pgoodsshowstate_arr = $pointprod_model->getPgoodsShowState();
        //获得兑换商品的推荐状态
        $pgoodsrecommendstate_arr = $pointprod_model->getPgoodsRecommendState();

        //条件
        $where = array();
        $pgoods_name = trim(input('param.pg_name'));
        if ($pgoods_name) {
            $where['pgoods_name'] = array('like', "%{$pgoods_name}%");
        }
        switch (trim(input('param.pg_state'))) {
            case 'show':
                $where['pgoods_show'] = $pgoodsshowstate_arr['show'][0];
                break;
            case 'nshow':
                $where['pgoods_show'] = $pgoodsshowstate_arr['unshow'][0];
                break;
            case 'commend':
                $where['pgoods_commend'] = $pgoodsrecommendstate_arr['commend'][0];
                break;
        }
        $prod_list = $pointprod_model->getPointProdList($where, '*', 'pgoods_sort asc,pgoods_id desc', 0, 10);
        //信息输出
        $this->assign('prod_list', $prod_list);
        $this->assign('show_page', $pointprod_model->page_info->render());
        $this->setAdminCurItem('index');
        return $this->fetch();
    }

    /**
     * 积分礼品添加
     */
    public function prod_add()
    {
        $hourarr = array(
            '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17',
            '18', '19', '20', '21', '22', '23'
        );
        $upload_model = Model('upload');
        if (request()->isPost()) {
            //验证表单
            $obj_validate = new Validate();
            $data = [
                'goodsname' => $_POST["goodsname"], 'goodsprice' => $_POST["goodsprice"],
                'goodspoints' => $_POST['goodspoints'], 'goodsserial' => $_POST['goodsserial'],
                'goodsstorage' => $_POST['goodsstorage'], 'sort' => $_POST['sort'],
            ];
            $rule=[
                ['goodsname','require',lang('admin_pointprod_add_goodsname_error')],
                ['goodsprice','require',lang('admin_pointprod_add_goodsprice_number_error')],
                ['goodspoints','require|number',lang('admin_pointprod_add_goodspoint_number_error')],
                ['goodsserial','require',lang('admin_pointprod_add_goodsserial_null_error')],
                ['goodsstorage','require|number',lang('admin_pointprod_add_storage_number_error')],
                ['sort','require|number',lang('admin_pointprod_add_sort_number_error')]
            ];
            if ($_POST['islimit'] == 1) {
                $data['limitnum'] = $_POST['limitnum'];
                $rule[]=['limitnum','number',lang('admin_pointprod_add_limitnum_digits_error')];
            }
            if ($_POST['islimittime']) {
                $data['starttime'] = $_POST['starttime'];
                $data['endtime'] = $_POST['endtime'];
                $rule[]=['starttime','require',lang('admin_pointprod_add_limittime_null_error')];
                $rule[]=['endtime','require',lang('admin_pointprod_add_limittime_null_error')];
            }
            
            $error = $obj_validate->check($data,$rule);
            if (!$error) {
                $this->error($obj_validate->getError());
            }
            $model_pointprod = Model('pointprod');
            $goods_array = array();
            $goods_array['pgoods_name'] = trim($_POST['goodsname']);
            $goods_array['pgoods_tag'] = trim($_POST['goodstag']);
            $goods_array['pgoods_price'] = trim($_POST['goodsprice']);

            $goods_array['pgoods_points'] = trim($_POST['goodspoints']);
            $goods_array['pgoods_serial'] = trim($_POST['goodsserial']);
            $goods_array['pgoods_storage'] = intval($_POST['goodsstorage']);


            $goods_array['pgoods_islimit'] = intval($_POST['islimit']);
            if ($goods_array['pgoods_islimit'] == 1) {
                $goods_array['pgoods_limitnum'] = intval($_POST['limitnum']);
            }
            else {
                $goods_array['pgoods_limitnum'] = 0;
            }
            $goods_array['pgoods_islimittime'] = intval($_POST['islimittime']);
            if ($goods_array['pgoods_islimittime'] == 1) {
                //如果添加了开始时间
                if (trim($_POST['starttime'])) {
                    $starttime = trim($_POST['starttime']);
                    $sdatearr = explode('-', $starttime);
                    $starttime = mktime(intval($_POST['starthour']), 0, 0, $sdatearr[1], $sdatearr[2], $sdatearr[0]);
                    unset($sdatearr);
                }
                if (trim($_POST['endtime'])) {
                    $endtime = trim($_POST['endtime']);
                    $edatearr = explode('-', $endtime);
                    $endtime = mktime(intval($_POST['endhour']), 0, 0, $edatearr[1], $edatearr[2], $edatearr[0]);
                }
                $goods_array['pgoods_starttime'] = $starttime;
                $goods_array['pgoods_endtime'] = $endtime;
            }
            else {
                $goods_array['pgoods_starttime'] = '';
                $goods_array['pgoods_endtime'] = '';
            }
            $goods_array['pgoods_show'] = trim($_POST['showstate']);
            $goods_array['pgoods_commend'] = trim($_POST['commendstate']);
            $goods_array['pgoods_add_time'] = time();

            //$goods_array['pgoods_state'] = trim($_POST['forbidstate']);

            $goods_array['pgoods_close_reason'] = trim($_POST['forbidreason']);
            $goods_array['pgoods_keywords'] = trim($_POST['keywords']);
            $goods_array['pgoods_description'] = trim($_POST['description']);

            $goods_array['pgoods_body'] = trim($_POST['pgoods_body']);
            $goods_array['pgoods_sort'] = intval($_POST['sort']);

            $goods_array['pgoods_limitmgrade'] = intval($_POST['limitgrade']);

            //添加礼品代表图片

            $indeximg_succ = false;

            if (!empty($_FILES['goods_images']['name'])) {

                $upload_file= BASE_UPLOAD_PATH . DS. ATTACH_POINTPROD;
                $file_name = date('YmdHis') . rand(10000, 99999);
                $file = request()->file('goods_images');
                $info = $file->move($upload_file,$file_name);
                if($info){
                    $indeximg_succ = true;
                    $file_name=$info->getSaveName();
                    $goods_array['pgoods_image'] =$file_name;
                }
                else {
                    $this->error($file->getError());
                }
            }

            $state = $model_pointprod->addPointGoods($goods_array);
            if ($state) {
                //礼品代表图片数据入库
                if ($indeximg_succ) {
                    $insert_array = array();
                    $insert_array['file_name'] = $file_name;
                    $insert_array['file_thumb'] = $file_name;
                    $insert_array['upload_type'] = 5;
                    $insert_array['file_size'] = filesize($upload_file. DS . $file_name);
                    $insert_array['item_id'] = $state;
                    $insert_array['upload_time'] = time();
                    $upload_model->add($insert_array);
                }
                //更新积分礼品描述图片
                $file_idstr = '';

                if (isset($_POST['file_id'])&&is_array($_POST['file_id']) && count($_POST['file_id']) > 0) {
                    $file_idstr = "'" . implode("','", $_POST['file_id']) . "'";
                }
                $upload_model->updatebywhere(array('item_id' => $state), array(
                    'upload_type' => 6, 'item_id' => '0', 'upload_id_in' => "{$file_idstr}"
                ));

                $this->log(lang('admin_pointprod_add_title') . '[' . $_POST['goodsname'] . ']');
                $this->success(lang('admin_pointprod_add_success'), 'pointprod/index');
            }
        }
        //模型实例化
        $where = array();
        $where['upload_type'] = '6';
        $where['item_id'] = '0';
        $file_upload = $upload_model->getUploadList($where);
        if (is_array($file_upload)) {
            foreach ($file_upload as $k => $v) {
                $file_upload[$k]['upload_path'] = UPLOAD_SITE_URL . '/' . ATTACH_POINTPROD . '/' . $file_upload[$k]['file_name'];
            }
        }
        $this->assign('file_upload', $file_upload);
        $this->assign('PHPSESSID', session_id());
        $hourarr = array(
            '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17',
            '18', '19', '20', '21', '22', '23'
        );
        $this->assign('hourarr', $hourarr);
        //会员级别
        $member_grade = Model('member')->getMemberGradeArr();

        $this->assign('member_grade', $member_grade);
        $this->setAdminCurItem('prod_add');
        return $this->fetch();
    }

    /**
     * 积分礼品编辑
     */
    public function prod_edit()
    {
        $hourarr = array(
            '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17',
            '18', '19', '20', '21', '22', '23'
        );
        $upload_model = Model('upload');
        $pg_id = intval(input('param.pg_id'));
        if (!$pg_id) {
            $this->error(lang('admin_pointprod_parameter_error'), 'pointprod/index');
        }
        $model_pointprod = Model('pointprod');
        //查询礼品记录是否存在
        $prod_info = $model_pointprod->getPointProdInfo(array('pgoods_id' => $pg_id));

        if (!$prod_info) {
            $this->error(lang('admin_pointprod_record_error'), 'pointprod/index');
        }
        if (request()->isPost()) {
            //验证表单
            $obj_validate = new Validate();
            $data = [
                'goodsname' => $_POST["goodsname"], 'goodsprice' => $_POST["goodsprice"],
                'goodspoints' => $_POST['goodspoints'], 'goodsserial' => $_POST['goodsserial'],
                'goodsstorage' => $_POST['goodsstorage'], 'sort' => $_POST['sort'],
            ];
            $rule=[
                ['goodsname','require',lang('admin_pointprod_add_goodsname_error')],
                ['goodsprice','require',lang('admin_pointprod_add_goodsprice_number_error')],
                ['goodspoints','require|number',lang('admin_pointprod_add_goodspoint_number_error')],
                ['goodsserial','require',lang('admin_pointprod_add_goodsserial_null_error')],
                ['goodsstorage','require|number',lang('admin_pointprod_add_storage_number_error')],
                ['sort','require|number',lang('admin_pointprod_add_sort_number_error')]
            ];
            if ($_POST['islimit'] == 1) {
                $data['limitnum'] = $_POST['limitnum'];
                $rule[]=['limitnum','number',lang('admin_pointprod_add_limitnum_digits_error')];
            }
            if ($_POST['islimittime']) {
                $data['starttime'] = $_POST['starttime'];
                $data['endtime'] = $_POST['endtime'];
                $rule[]=['starttime','require',lang('admin_pointprod_add_limittime_null_error')];
                $rule[]=['endtime','require',lang('admin_pointprod_add_limittime_null_error')];
            }

            $error = $obj_validate->check($data,$rule);
            if (!$error) {
                $this->error($obj_validate->getError());
            }
            //实例化店铺商品模型
            $model_pointprod = Model('pointprod');

            $goods_array = array();
            $goods_array['pgoods_name'] = trim($_POST['goodsname']);
            $goods_array['pgoods_tag'] = trim($_POST['goodstag']);
            $goods_array['pgoods_price'] = trim($_POST['goodsprice']);

            $goods_array['pgoods_points'] = trim($_POST['goodspoints']);
            $goods_array['pgoods_serial'] = trim($_POST['goodsserial']);
            $goods_array['pgoods_storage'] = intval($_POST['goodsstorage']);
            $goods_array['pgoods_islimit'] = intval($_POST['islimit']);
            if ($goods_array['pgoods_islimit'] == 1) {
                $goods_array['pgoods_limitnum'] = intval($_POST['limitnum']);
            }
            else {
                $goods_array['pgoods_limitnum'] = 0;
            }
            $goods_array['pgoods_islimittime'] = intval($_POST['islimittime']);
            if ($goods_array['pgoods_islimittime'] == 1) {
                //如果添加了开始时间
                if (trim($_POST['starttime'])) {
                    $starttime = trim($_POST['starttime']);
                    $sdatearr = explode('-', $starttime);
                    $starttime = mktime(intval($_POST['starthour']), 0, 0, $sdatearr[1], $sdatearr[2], $sdatearr[0]);
                    unset($sdatearr);
                }
                if (trim($_POST['endtime'])) {
                    $endtime = trim($_POST['endtime']);
                    $edatearr = explode('-', $endtime);
                    $endtime = mktime(intval($_POST['endhour']), 0, 0, $edatearr[1], $edatearr[2], $edatearr[0]);
                }
                $goods_array['pgoods_starttime'] = $starttime;
                $goods_array['pgoods_endtime'] = $endtime;
            }
            else {
                $goods_array['pgoods_starttime'] = '';
                $goods_array['pgoods_endtime'] = '';
            }
            $goods_array['pgoods_show'] = trim($_POST['showstate']);
            $goods_array['pgoods_commend'] = trim($_POST['commendstate']);

            $goods_array['pgoods_close_reason'] = trim($_POST['forbidreason']);
            $goods_array['pgoods_keywords'] = trim($_POST['keywords']);
            $goods_array['pgoods_description'] = trim($_POST['description']);

            $goods_array['pgoods_body'] = trim($_POST['pgoods_body']);

            $goods_array['pgoods_sort'] = intval($_POST['sort']);
            $goods_array['pgoods_limitmgrade'] = intval($_POST['limitgrade']);

            //添加礼品代表图片
            $indeximg_succ = false;

            if (!empty($_FILES['goods_images']['name'])) {

                $upload_file= BASE_UPLOAD_PATH . DS. ATTACH_POINTPROD;
                $file_name = date('YmdHis') . rand(10000, 99999);
                $file = request()->file('goods_images');
                $info = $file->move($upload_file,$file_name);
                if($info){
                    $indeximg_succ = true;
                    $file_name=$info->getSaveName();
                $goods_array['pgoods_image'] =$file_name;
                }
                else {
                    $this->error($file->getError());
                }
            }

            $state = $model_pointprod->editPointProd($goods_array, array('pgoods_id' => $prod_info['pgoods_id']));
            if ($state) {
                //礼品代表图片数据入库
                if ($indeximg_succ) {
                    //删除原有图片
                    $upload_list = $upload_model->getUploadList(array(
                                                                    'upload_type' => 5,
                                                                    'item_id' => $prod_info['pgoods_id']
                                                                ));

                    if (is_array($upload_list) && count($upload_list) > 0) {
                        $upload_idarr = array();
                        foreach ($upload_list as $v) {
                            @unlink($upload_file. DS . $v['file_name']);
                            @unlink($upload_file . DS . $v['file_thumb']);
                            $upload_idarr[] = $v['upload_id'];
                        }
                        //删除图片
                        $upload_model->dropUploadById($upload_idarr);
                    }
                    $insert_array = array();
                    $insert_array['file_name'] = $file_name;
                    $insert_array['file_thumb'] = $file_name;
                    $insert_array['upload_type'] = 5;
                    $insert_array['file_size'] = filesize($upload_file . DS . $file_name);
                    $insert_array['item_id'] = $prod_info['pgoods_id'];
                    $insert_array['upload_time'] = time();
                    $upload_model->add($insert_array);
                }
                //更新积分礼品描述图片
                $file_idstr = '';
                if (isset($_POST['file_id'])&&is_array($_POST['file_id']) && count($_POST['file_id']) > 0) {
                    $file_idstr = "'" . implode("','", $_POST['file_id']) . "'";
                }
                $upload_model->updatebywhere(array('item_id' => $prod_info['pgoods_id']), array(
                    'upload_type' => 6, 'item_id' => '0', 'upload_id_in' => "{$file_idstr}"
                ));
                $this->log(lang('ds_edit').lang('admin_pointprodp') . '[' . $_POST['goodsname'] . ']');
                $this->success(lang('admin_pointprod_edit_success'), 'pointprod/index');
            }
            $this->error(lang('admin_pointprod_edit_fail'));
        }
        else {
            $where = array();
            $where['upload_type'] = '6';
            $where['item_id'] = $prod_info['pgoods_id'];
            $file_upload = $upload_model->getUploadList($where);
            if (is_array($file_upload)) {
                foreach ($file_upload as $k => $v) {
                    $file_upload[$k]['upload_path'] = UPLOAD_SITE_URL . '/' . ATTACH_POINTPROD . '/' . $file_upload[$k]['file_name'];
                }
            }
            //会员级别
            $member_grade = Model('member')->getMemberGradeArr();
            $this->assign('member_grade', $member_grade);
            $this->assign('file_upload', $file_upload);
            $this->assign('PHPSESSID', session_id());
            $this->assign('hourarr', $hourarr);
            $this->assign('prod_info', $prod_info);
            $this->setAdminCurItem('prod_edit');
            return $this->fetch();
        }
    }

    /**
     * 删除积分礼品
     */
    public function prod_drop()
    {
        $pg_id = intval(input('param.pg_id'));
        if (!$pg_id) {
            $this->error(lang('admin_pointprod_parameter_error'), 'pointprod/index');
        }
        $model_pointprod = Model('pointprod');
        //查询礼品是否存在
        $prod_info = $model_pointprod->getPointProdInfo(array('pgoods_id' => $pg_id));
        if (!is_array($prod_info) || count($prod_info) <= 0) {
            $this->error(lang('admin_pointprod_record_error'), 'pointprod/index');
        }
        //查询积分礼品的下属信息（比如兑换信息）
        //删除操作
        $result = $model_pointprod->delPointProdById($pg_id);
        if ($result) {
            $this->log(lang('ds_del').lang('admin_pointprodp') . '[ID:' . $pg_id . ']');
            $this->success(lang('admin_pointprod_del_success'), 'pointprod/index');
        }
        else {
            $this->error(lang('admin_pointprod_del_fail'), 'pointprod/index');
        }
    }

    /**
     * 批量删除积分礼品
     */
    public function prod_dropall()
    {
        $pg_id = $_POST['pg_id'];
        if (!$pg_id) {
            $this->error(lang('admin_pointprod_parameter_error'), 'pointprod/index');
        }
        $result = Model('pointprod')->delPointProdById($pg_id);
        if ($result) {
            $this->log(lang('ds_del').lang('admin_pointprodp') . '[ID:' . implode(',', $pg_id) . ']');
            $this->success(lang('admin_pointprod_del_success'), 'pointprod/index');
        }
        else {
            $this->error(lang('admin_pointprod_del_fail'), 'pointprod/index');
        }
    }

    /**
     * 积分礼品异步状态修改
     */
    public function ajax()
    {
        //礼品上架,礼品推荐,礼品禁售
        $id = intval(input('param.id'));
        if ($id <= 0) {
            echo 'false';
            exit;
        }
        $model_pointprod = Model('pointprod');
        $update_array = array();
        $update_array[input('param.column')] = trim(input('param.value'));
        $model_pointprod->editPointProd($update_array, array('pgoods_id' => $id));
        echo 'true';
        exit;
    }

    /**
     * 积分礼品上传
     */
    public function pointprod_pic_upload()
    {
        /**
         * 上传图片
         */

        if (!empty($_FILES['fileupload']['name'])) {
            $upload_file= BASE_UPLOAD_PATH . DS. ATTACH_POINTPROD;
            $file_name = date('YmdHis') . rand(10000, 99999);
            $file = request()->file('fileupload');
            $info = $file->move($upload_file,$file_name);
            if($info){
                $file_name=$info->getSaveName();
                $pic =$file_name;
            }
            else {
                echo $file->getError();
                exit;
            }
        }
        /**
         * 模型实例化
         */
        $model_upload = Model('upload');
        /**
         * 图片数据入库
         */
        $insert_array = array();
        $insert_array['file_name'] = $pic;
        $insert_array['upload_type'] = '6';
        $insert_array['file_size'] = $_FILES['fileupload']['size'];
        $insert_array['upload_time'] = time();
        $insert_array['item_id'] = input('param.item_id');
        $result = $model_upload->add($insert_array);
        if ($result) {
            $data = array();
            $data['file_id'] = $result;
            $data['file_name'] = $pic;
            $data['file_path'] = $pic;
            /**
             * 整理为json格式
             */
            $output = json_encode($data);
            echo $output;
        }
    }

    /**
     * ajax操作删除已上传图片
     */
    public function ajaxdelupload()
    {
        //删除文章图片
        if (intval(input('param.file_id')) > 0) {
            $model_upload = Model('upload');
            /**
             * 删除图片
             */
            $file_array = $model_upload->getOneUpload(intval(input('param.file_id')));
            @unlink(BASE_UPLOAD_PATH . DS . ATTACH_POINTPROD . DS . $file_array['file_name']);
            /**
             * 删除信息
             */
            $model_upload->del(intval(input('param.file_id')));
            echo 'true';
            exit;
        }
        else {
            echo 'false';
            exit;
        }
    }

    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index', 'text' => '礼品列表', 'url' => url('Pointprod/index')
            ), array(
                'name' => 'prod_add', 'text' => '新增礼品', 'url' => url('Pointprod/prod_add')
            ), array(
                'name' => 'add', 'text' => '兑换列表', 'url' => url('pointorder/pointorder_list')
            ),
        );
        if (request()->action() == 'prod_edit') {
            $menu_array[] = array(
                'name' => 'prod_edit', 'text' => '编辑礼品', 'url' => '#'
            );
        }

        return $menu_array;
    }
}