<?php
namespace app\admin\controller\life;

use app\admin\controller\BaseController;
use app\admin\server\life\GoodsServer;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use app\admin\model\LifeGoods;

class Goods extends BaseController
{

    /**
     * Notes:获取健康超市商品列表
     * @return \support\Response
     * User: ZQ
     * Date: 2022/10/09
     */
    public function getGoodsList()
    {
        [$page, $limit] = $this->getPage();
        $keywords = $this->request->get('keywords');
        $result         = GoodsServer::getGoodsList($page, $limit, $keywords);
        return json_success($result, '成功');
    }

    /**
     * Notes:获取所有角色
     * @return \support\Response
     * User: ZQ
     * Date: 2022/9/19
     */
    public function getGoodsAll()
    {
        $result         = GoodsServer::getGoodsAll();
        return json_success($result, '成功');
    }

    /**
     * Notes:修改健康超市商品
     * @return \support\Response
     * User: ZQ
     * Date: 2022/10/09
     */
    public function updateGoods()
    {
        $goods_id      = $this->request->post('goods_id');
        $goods_name    = $this->request->post('goods_name','');
        $goods_img   = $this->request->post('goods_img','');
        $goods_category_id    = $this->request->post('goods_category_id','');
        $goods_shop_id = $this->request->post('goods_shop_id');
        $goods_is_new = $this->request->post('goods_is_new');
        $goods_price = $this->request->post('goods_price');
        $goods_oldprice = $this->request->post('goods_oldprice',1);
        $goods_content = $this->request->post('goods_content');
        $goods_sell_num = $this->request->post('goods_sell_num');
        $goods_postage_id = $this->request->post('goods_postage_id');
        $goods_status = $this->request->post('goods_status');
        $goods_weight = $this->request->post('goods_weight');
        $goods_sort = $this->request->post('goods_sort');
        $goods_slide = $this->request->post('goods_slide','');
        $goods_pack_price = $this->request->post('goods_pack_price','');
        $food_attr = $this->request->post('goods_attr','');
        $food_varieties = $this->request->post('goods_varieties','');
        $food_packaging = $this->request->post('goods_packaging','');
        $food_storage = $this->request->post('goods_storage','');
        $goods_delivery_type = $this->request->post('goods_delivery_type','');
        $goods_inventory = $this->request->post('goods_inventory',0);
        $admin_id = $this->request->admin_id;
        $this->validateCheck('life\GoodsValidate', ['goods_id' => $goods_id, 'goods_name' => $goods_name, 'goods_img' => $goods_img, 'goods_category_id' => $goods_category_id, 'goods_shop_id' => $goods_shop_id, 'goods_is_new' => $goods_is_new, 'goods_price' => $goods_price, 'goods_content' => $goods_content, 'goods_status' => $goods_status, 'goods_postage_id' => $goods_postage_id], 'update');
        $result       = GoodsServer::updateGoods($goods_id,$goods_name,$goods_img,$goods_category_id,$goods_shop_id,$goods_is_new,$goods_price,$goods_oldprice,$goods_content,$goods_sell_num,$goods_postage_id,$goods_status,$goods_weight,$goods_sort,$goods_slide,$goods_pack_price,$food_attr,$food_varieties,$food_packaging,$food_storage,$goods_delivery_type,$goods_inventory,$admin_id);
        return json_success($result, '修改成功');

    }

    /**
     * Notes:删除商品
     * @return \support\Response
     * User: ZQ
     * Date: 2022/9/13
     */
    public function delGoods()
    {
        $goods_id = $this->request->get('goods_id');
        $admin_id = $this->request->admin_id;
        $this->validateCheck('life\GoodsValidate', ['goods_id' => $goods_id], 'info');
        $result         = GoodsServer::delGoods($goods_id,$admin_id);
        if ($result){
            return json_success($result, '删除成功');
        }else{
            throw new \Exception('删除失败!');
        }

    }

    /**
     * Notes:添加商品
     * @return \support\Response
     * User: ZQ
     * Date: 2022/9/13
     */
    public function addGoods()
    {
        $goods_name    = $this->request->post('goods_name','');
        $goods_img   = $this->request->post('goods_img');
        $goods_category_id    = $this->request->post('goods_category_id');
        $goods_shop_id = $this->request->post('goods_shop_id');
        $goods_is_new = $this->request->post('goods_is_new');
        $goods_price = $this->request->post('goods_price');
        $goods_oldprice = $this->request->post('goods_oldprice',1);
        $goods_content = $this->request->post('goods_content');
        $goods_sell_num = $this->request->post('goods_sell_num');
        $goods_postage_id = $this->request->post('goods_postage_id');
        $goods_status = $this->request->post('goods_status');
        $goods_weight = $this->request->post('goods_weight');
        $goods_sort = $this->request->post('goods_sort');
        $goods_slide = $this->request->post('goods_slide','');
        $goods_pack_price = $this->request->post('goods_pack_price','');
        $food_attr = $this->request->post('goods_attr','');
        $food_varieties = $this->request->post('goods_varieties','');
        $food_packaging = $this->request->post('goods_packaging','');
        $food_storage = $this->request->post('goods_storage','');
        $goods_delivery_type = $this->request->post('goods_delivery_type','');
        $goods_inventory = $this->request->post('goods_inventory',0);
        $admin_id = $this->request->admin_id;
        $this->validateCheck('life\GoodsValidate', ['goods_name' => $goods_name, 'goods_img' => $goods_img, 'goods_category_id' => $goods_category_id, 'goods_shop_id' => $goods_shop_id, 'goods_is_new' => $goods_is_new, 'goods_price' => $goods_price, 'goods_content' => $goods_content, 'goods_status' => $goods_status, 'goods_postage_id' => $goods_postage_id], 'create');
        $result         = GoodsServer::insertGoods($goods_name,$goods_img,$goods_category_id,$goods_shop_id,$goods_is_new,$goods_price,$goods_oldprice,$goods_content,$goods_sell_num,$goods_postage_id,$goods_status,$goods_weight,$goods_sort,$goods_slide,$goods_pack_price,$food_attr,$food_varieties,$food_packaging,$food_storage,$goods_delivery_type,$goods_inventory,$admin_id);
        return json_success($result, '添加成功');
    }

    /**
     * Notes:查询商品详情
     * @return \support\Response
     * User: ZQ
     * Date: 2022/9/13
     */
    public function goodsInfo()
    {
        $goods_id = $this->request->get('goods_id');
        $this->validateCheck('life\GoodsValidate', ['goods_id' => $goods_id], 'info');
        $result         = GoodsServer::goodsInfo($goods_id);
        return json_success($result, '成功');
    }

    /**
     * Notes:商品上架下架
     * @return \support\Response
     * User: ZQ
     * Date: 2022/10/09
     */
    public function updateStatus()
    {
        $goods_id = $this->request->get('goods_id');
        $goods_status = $this->request->get('goods_status');
        $this->validateCheck('life\GoodsValidate', ['goods_id' => $goods_id], 'info');
        $result       = GoodsServer::updateStatus($goods_id, $goods_status);
        return json_success($result, '修改成功');
    }

    /**
     * Notes:批量导入商品
     * @return \support\Response
     * User: Ycp
     * Date: 2023/8/23
     */
    public function goodsImport()
    {
        $imageFilePath = public_path().'/uploads/imgs/'; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 0777, true);
        }
        try {
            $file = $this->request->get('excel_address');//文件地址;
            $objRead = IOFactory::createReader('Xlsx');
            $objSpreadsheet = $objRead->load($file);
            $objWorksheet = $objSpreadsheet->getSheet(0);
            $data = $objWorksheet->toArray();
            $img_data = [];// 图片数组
            foreach ($objWorksheet->getDrawingCollection() as $drawing) {
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                $imageFileName = $drawing->getCoordinates() . mt_rand(1000, 9999);
                switch ($drawing->getExtension()) {
                    case 'jpg':
                    case 'jpeg':
                        $imageFileName .= '.jpg';
                        $source = imagecreatefromjpeg($drawing->getPath());
                        imagejpeg($source, $imageFilePath . $imageFileName);
                        break;
                    case 'gif':
                        $imageFileName .= '.gif';
                        $source = imagecreatefromgif($drawing->getPath());
                        imagegif($source, $imageFilePath . $imageFileName);
                        break;
                    case 'png':
                        $imageFileName .= '.png';
                        $source = imagecreatefrompng($drawing->getPath());
                        imagepng($source, $imageFilePath . $imageFileName);
                        break;
                }
                $img_data[$startRow-1][$startColumn] = '/uploads/imgs/' . $imageFileName;
            }
            // 合并表格数据
            if(!empty($img_data)){
                foreach ($img_data as $key => $value){
                    //$data[$key][2] 是导入表格图片的哪一行
                    $data[$key][2] = $value['C'];
                }
            }
            unset($data[0]);
            $config = config('plugin.tinywan.storage.app.storage');
            foreach ($data as &$value) {
                $params['goods_name'] = $value[1];
                $params['goods_img'] = $config[$config['default']]['domain'].$value[2];
                $params['goods_slide'] = $config[$config['default']]['domain'].$value[2];
                if($value[16] == "健康检测"){
                    $params['goods_category_id'] = 252;
                }elseif($value[16] == "运动康复"){
                    $params['goods_category_id'] = 253;
                }elseif($value[16] == "健康食品"){
                    $params['goods_category_id'] = 254;
                }elseif($value[16] == "适老产品"){
                    $params['goods_category_id'] = 256;
                }elseif($value[16] == "健康产品"){
                    $params['goods_category_id'] = 289;
                }elseif($value[16] == "活动专区"){
                    $params['goods_category_id'] = 300;
                }elseif($value[16] == "理疗设备"){
                    $params['goods_category_id'] = 301;
                }elseif($value[16] == "医疗设备"){
                    $params['goods_category_id'] = 302;
                }
                $params['goods_shop_id'] = 1;
                $params['goods_price'] = $value[14];
                $params['goods_pack_price'] = 0;
                $params['goods_postage_id'] = 11;
                $params['goods_storage'] = $value['8'];
                $params['goods_packaging'] = '';
                $params['goods_attr'] = $value[4];
                $params['goods_varieties'] = $value[3];
                $params['goods_sort'] = $value[17];
                $params['goods_create_time'] = time();
                $params['goods_content'] = "<p>产品参数:".$value['6'].PHP_EOL."</p><p>产品功能:".$value['7'].PHP_EOL."</p><p>发货地:".$value['8'].PHP_EOL."</p><p>发货时间:".$value['9'].PHP_EOL."</p><p>质保期:".$value['11'].PHP_EOL."</p><p>退换货规则:".$value['12'].PHP_EOL."</p><p>主要卖点:".$value['13']."</p>";

                $result =  LifeGoods::insertGetId($params);
                if (!empty($result)){
                    $msg = '管理员:' . $this->request->admin_id . '在:' . date("Y-m-d H:i:s", time()) . '批量添加健康超市商品-编号: ' . $result;
                    plog('life-goods-create', '悦活-健康超市-批量添加商品', $msg);    
                }
            }
            return json_success($result, '导入成功');
        } catch (\Exception $e) {
            throw $e;
        }
    }


}