Litestoregoods.php 20.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
<?php

namespace app\admin\controller\litestore;

use app\admin\model\litestore\Litestoregoodsspec;
use app\api\model\Goods;
use app\common\controller\Backend;
use app\admin\model\litestore\Litestorespec as SpecModel;
use app\admin\model\litestore\Litestorespecvalue as SpecValueModel;
use PHPExcel;
use PHPExcel_Style;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Border;
use PHPExcel_Style_Fill;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Litestoregoods extends Backend
{
    private $SpecModel;
    private $SpecValueModel;
    /**
     * Litestoregoods模型对象
     * @var \app\admin\model\litestore\Litestoregoods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->SpecModel      = new SpecModel;
        $this->SpecValueModel = new SpecValueModel;

        $this->model = new \app\admin\model\litestore\Litestoregoods;
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
        $this->view->assign("deductStockTypeList", $this->model->getDeductStockTypeList());
        $this->view->assign("goodsStatusList", $this->model->getGoodsStatusList());
        $this->view->assign("isDeleteList", $this->model->getIsDeleteList());
        $this->view->assign("makeforList", $this->model->getMakeforList());
        $this->view->assign("isIndexList", $this->model->getIsIndexList());

        $this->view->assign("spec_attr", '');
        $this->view->assign("spec_list", '');
    }

    /**
     * 默认生成的控制器所继承的父类中有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']);
        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(['category', 'activity'])
                ->where($where)
                ->order($sort, $order)
                ->count();

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

            foreach ($list as $row) {

                $row->getRelation('category')->visible(['name']);
                $row->getRelation('activity')->visible(['name']);
//				$row->getRelation('freight')->visible(['name']);
                $row->stock_num = Litestoregoodsspec::where('goods_id', $row['goods_id'])->sum('stock_num');
            }
            $list   = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

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

    public function addSpec($spec_name, $spec_value)
    {
        // 判断规格组是否存在
        if (!$specId = $this->SpecModel->getSpecIdByName($spec_name)) {
            // 新增规格组and规则值
            if ($this->SpecModel->add($spec_name)
                && $this->SpecValueModel->add($this->SpecModel['id'], $spec_value))
                return $this->success('', '', [
                    'spec_id'       => (int)$this->SpecModel['id'],
                    'spec_value_id' => (int)$this->SpecValueModel['id'],
                ]);
            return $this->error();
        }
        //return ;
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($specId, $spec_value)) {
            return $this->success('', '', [
                'spec_id'       => (int)$specId,
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($specId, $spec_value))
            return $this->success('', '', [
                'spec_id'       => (int)$specId,
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        return $this->error();
    }


    /**
     * 添加规格值
     */
    public function addSpecValue($spec_id, $spec_value)
    {
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($spec_id, $spec_value)) {
            return $this->success('', '', [
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($spec_id, $spec_value))
            return $this->success('', '', [
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        return $this->error();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if ($params['spec_type'] == '20' && !$this->request->post("spec_many/a")) {
                    $this->error('请添加规格');
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        $spec_many_params = $this->request->post("spec_many/a");
                        $this->model->addGoodsSpec($params, $spec_many_params, $this->request->post("spec/a"));
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk       = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list  = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                // 删除商品sku
                $v->removesku();

                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids, ['specRel', 'spec', 'spec_rel.spec']);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['spec_type'] == '20' && !$this->request->post("spec_many/a")) {
                    $this->error('请添加规格');
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        $spec_many_params = $this->request->post("spec_many/a");
                        $row->addGoodsSpec($params, $spec_many_params, $this->request->post("spec/a"), true);
                        // 删除购物车
                        Db::name('cart')->where('goods_id', $row->goods_id)->delete();
                        //删除我常买
                        Db::name('user_buylist')->where('goods_id', $row->goods_id)->delete();
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 多规格信息
        $specData = 'null';
        if ($row['spec_type'] === '20') {
            $specData = json_encode($this->model->getManySpecData($row['spec_rel'], $row['spec']));
        }
        $row['specData'] = $specData;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 导出
     */
    public function export()
    {
        //1.从数据库中导出需要进行要导出的数据
        $goods = new Goods();
        $list  = Db::name('litestore_goods_spec')->alias('c')
            ->join('fa_litestore_goods g', 'g.goods_id = c.goods_id', 'LEFT')
            ->select();
//            ->each(function (&$item) {
//            $item['goods'] = Db::name('litestore_goods')
//                ->where('goods_id', $item['goods_id'])->find();
//        });
        if (empty($list)) {
            $this->error('没有可导出的数据');
        }
        //重要补助
        //2.加载PHPExcle类库
        vendor('PHPExcel.PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头(即excel表格的第一行)
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '商品ID')
            ->setCellValue('B1', '商品名称')
            ->setCellValue('C1', '商品原价')
            ->setCellValue('D1', '折扣')
            ->setCellValue('E1', '商品现价')
            ->setCellValue('F1', '已销数量')
            ->setCellValue('G1', '导出时间');
//            ->setCellValue('G1', '院系')
//            ->setCellValue('H1', '专业');
        //设置A列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
        //6.循环刚取出来的数组,将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);

        for ($i = 0; $i < count($list); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['goods_id']);//ID
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['goods_name']);//商品名称
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['line_price']);//原价
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['discount']);//ID
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['goods_price']);//标签码
            $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['goods_sales']);//ID
            $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), datetime(time()));//标签码
        }
        //7.设置保存的Excel表格名称
//        $filename = '商品信息' . date('ymd', time()) . '.xls';
//        //8.设置当前激活的sheet表格名称;
//        $objPHPExcel->getActiveSheet()->setTitle('商品信息');
//        //9.设置浏览器窗口下载表格
        ob_end_clean();
        ob_start();
//        header("Content-Type: application/force-download");
//        header("Content-Type: application/octet-stream");
//        header("Content-Type: application/download");
//        header('Content-Disposition:inline;filename="' . $filename . '"');
////        header("Pragma: public");
////        header("Expires: 0");
//////        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
//////        header("Content-Type:application/force-download");
//////        header("Content-Type:application/vnd.ms-execl");
//////        header("Content-Type:application/octet-stream");
//////        header("Content-Type:application/download");;
//////        header('Content-Disposition:attachment;filename='.$filename.'');
//////        header("Content-Transfer-Encoding:binary");
//////        //生成excel文件
//////        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//////        ini_set('display_errors', TRUE);
//////        ini_set('display_startup_errors', TRUE);
////        header('pragma:public');
////        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $filename . '.xls"');
////        header("Content-Disposition:inline;filename=$filename.xls"); //attachment新窗口打印inline本窗口打印
//        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//        $objWriter->save('php://output');
        $title = 'ahhah';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit();
    }

//    public function export()
//    {
//        if ($this->request->isPost()) {
//            set_time_limit(0);
//            $search  = $this->request->post('search');
//            $ids     = $this->request->post('ids');
//            $filter  = $this->request->post('filter');
//            $op      = $this->request->post('op');
//            $columns = $this->request->post('columns');
//
//            $excel = new PHPExcel();
//
//            $excel->getProperties()
//                ->setCreator("FastAdmin")
//                ->setLastModifiedBy("FastAdmin")
//                ->setTitle("标题")
//                ->setSubject("Subject");
//            $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
//            $excel->getDefaultStyle()->getFont()->setSize(12);
//
//            $this->sharedStyle = new PHPExcel_Style();
//            $this->sharedStyle->applyFromArray(
//                array(
//                    'fill'      => array(
//                        'type'  => PHPExcel_Style_Fill::FILL_SOLID,
//                        'color' => array('rgb' => '000000'),
//                    ),
//                    'font'      => array(
//                        'color' => array('rgb' => "000000"),
//                    ),
//                    'alignment' => array(
//                        'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
//                        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
//                        'indent'     => 1,
//                    ),
//                    'borders'   => array(
//                        'allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
//                    ),
//                ));
//
//            $worksheet = $excel->setActiveSheetIndex(0);
//            $worksheet->setTitle('标题');
//
//            $whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
//            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
//            $line = 1;
//            $list = [];
//            $this->model
//                ->field($columns)
//                ->where($where)
//                ->where($whereIds)
//                ->chunk(100, function ($items) use (&$list, &$line, &$worksheet) {
//                    $styleArray = array(
//                        'font' => array(
//                            'bold'  => true,
//                            'color' => array('rgb' => 'FF0000'),
//                            'size'  => 15,
//                            'name'  => 'Verdana',
//                        ));
//                    $list       = $items = collection($items)->toArray();
//                    foreach ($items as $index => $item) {
//                        $line++;
//                        $col = 0;
//                        foreach ($item as $field => $value) {
//
//                            $worksheet->setCellValueByColumnAndRow($col, $line, $value);
//                            $worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
//                            $worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
//                            $col++;
//                        }
//                    }
//                });
//            $first = array_keys($list[0]);
//            foreach ($first as $index => $item) {
//                $worksheet->setCellValueByColumnAndRow($index, 1, __($item));
//            }
//
//            $excel->createSheet();
//            // Redirect output to a client’s web browser (Excel2007)
//            $title = date("YmdHis");
//            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
//            header('Cache-Control: max-age=0');
//            // If you're serving to IE 9, then the following may be needed
//            header('Cache-Control: max-age=1');
//
//            // If you're serving to IE over SSL, then the following may be needed
//            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
//            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
//            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
//            header('Pragma: public'); // HTTP/1.0
//
//            $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
//            $objWriter->save('php://output');
//            return;
//        }
//    }
}