<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\exception\PDOException;
use think\Db;
/**
 * 免费预约管理
 *
 * @icon fa fa-circle-o
 */
class Free extends Backend
{
    
    /**
     * Free模型对象
     * @var \app\admin\model\Free
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Free;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname','avatar']);
                $row->user->nickname = \app\admin\model\User::emoji_decode($row->user->nickname);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    //处理申请
    public function applyHandle($ids){
        if ($ids) {
            $pk = $this->model->getPk();
            $res = $this->model->where($pk, '=', $ids)->update(['status'=>1]);//已处理
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }

        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 导入
     */
    public function import(){
        return parent::import();
    }

    //导出excel
    public function export(){//导出Excel
        $ids = $this->request->param('ids');
        if(!$ids){
            return;
        }
        $ids = explode(',',$ids);
        $xlsData = Db::name('free')
            ->whereIn('id',$ids)
            ->field('id,user_name,mobile,province,city,district,address,advice,status,createtime')
            ->select();
        $xlsName  = "预约体验表";
        $xlsCell  = [
            ['id','ID'],
            ['user_name','姓名'],
            ['mobile','电话'],
            ['province','省'],
            ['city','市'],
            ['district','区'],
            ['address','详细地址'],
            ['status','申请状态'],
            ['advice','所属顾问'],
            ['createtime','申请时间'],
        ];

        foreach ($xlsData as &$v) {
            $v['status'] = $v['status'] == 0?'未处理':'已处理';
            $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        $this->exportExcel($xlsName,$xlsCell,$xlsData);
    }

    //导出表格
    public function exportExcel($expTitle,$expCellName,$expTableData){

        $fileName = '预约体验表';//or $xlsTitle 文件名称可根据自己情况设定
//        $filePath = 'upload/user/'.date('Y-m-d',time()).'.xlsx';
        $topNumber = 1;//表头有几行占用
        $cellKey = array(
            'A','B','C','D','E','F','G','H','I','J','K','L','M',
            'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM',
            'AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
        );
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle($expTitle);
//         $spreadsheet->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
        //处理表头
        foreach ($expCellName as $k=>$v) {
            $sheet->setCellValue($cellKey[$k].$topNumber, $v[1]);//设置表头数据
//            $spreadsheet->getActiveSheet()->freezePane($cellKey[$k].($topNumber+1));//冻结窗口
            $sheet->getStyle($cellKey[$k].$topNumber)->getFont()->setBold(true);//设置是否加粗
        }
        //处理数据
        //设置单元格居中显示
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        //表头居中
        foreach ($expCellName as $k2=>$v2) {
            $sheet->getStyle($cellKey[$k2].'1')->applyFromArray($styleArray);
        }
        foreach ($expTableData as $k=>$v) {
            foreach ($expCellName as $k1=>$v1) {
                $sheet->setCellValue($cellKey[$k1].($k+1+$topNumber), $v[$v1[0]]);
                $sheet->getColumnDimension($cellKey[$k1])->setWidth(30);//每列宽度
                $sheet->getStyle($cellKey[$k1].($k+1+$topNumber))->applyFromArray($styleArray);
            }
        }
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');//告诉浏览器将要输出excel03文件
        header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xls'); //按照指定格式生成Excel文件
        $writer->save('php://output');
        exit;
    }
}