<?php

namespace app\system\controller\v1;

use app\BaseController;
use app\model\system\ProductRule;
use app\model\system\ProductAttr;
use app\model\system\ProductAttrValue;
use app\model\system\ProductAttrResult;
use app\model\system\Product as ProductModel;
use app\model\system\Category;
use library\services\UtilService;

class Product extends BaseController
{/**
 * 显示资源列表头部
 *
 * @return \think\Response
 */
    public function type_header()
    {
        //出售中商品
        $onsale = ProductModel::where('is_del', 0)->where('is_show', 1)->count();
        //仓库中商品
        $forsale = ProductModel::where('is_del', 0)->where('is_show', 0)->count();
        //已经售馨产品
        $outofstock = (new ProductModel)->getWhere(['type' => 4])->count();
        //警戒库存
        $policeforce = (new ProductModel)->getWhere(['type' => 5])->count();
        //回收站
        $recycle = ProductModel::where('is_del', 1)->count();
        $list = [
            ['type' => 1, 'name' => '出售中产品', 'count' => $onsale],
            ['type' => 2, 'name' => '仓库中产品', 'count' => $forsale],
            ['type' => 4, 'name' => '已经售馨产品', 'count' => $outofstock],
            ['type' => 5, 'name' => '警戒库存', 'count' => $policeforce],
            ['type' => 6, 'name' => '产品回收站', 'count' => $recycle],
        ];
        return app('json')->success(compact('list'));
    }

    /**
     * 显示资源列表
     * @return mixed
     */
    public function index()
    {
        $where = UtilService::getMore([
            ['page', 1],
            ['limit', 20],
            ['store_name', ''],
            ['cate_id', ''],
            ['excel', 0],
            ['type', 1]
        ]);
//        if($this->merId){
//            $where['mer_id'] = $this->merId;
//        }
        return app('json')->success(ProductModel::ProductList($where));
    }

    /**
     * 获取规则属性模板
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_rule()
    {
        return app('json')->success(ProductRule::field(['rule_name', 'rule_value'])->select()->each(function ($item) {
            $item['rule_value'] = json_decode($item['rule_value'], true);
        })->toArray());
    }

    /**
     * 生成属性
     * @param int $id
     */
    public function is_format_attr($id)
    {
        $data = UtilService::getMore([
            ['attrs', []],
            ['items', []]
        ]);
        $attr = $data['attrs'];
        $value = attr_format($attr)[1];
        $valueNew = [];
        $count = 0;
        foreach ($value as $key => $item) {
            $detail = $item['detail'];
            sort($item['detail'], SORT_STRING);
            $suk = implode(',', $item['detail']);
            if ($id) {
                $sukValue = ProductAttrValue::where('product_id', $id)->where('type', 0)->where('suk', $suk)->column('bar_code,cost,price,ot_price,stock,image as pic,weight,volume,brokerage,brokerage_two', 'suk');
                if (!count($sukValue)) {
                    $sukValue[$suk]['pic'] = '';
                    $sukValue[$suk]['price'] = 0;
                    $sukValue[$suk]['cost'] = 0;
                    $sukValue[$suk]['ot_price'] = 0;
                    $sukValue[$suk]['stock'] = 0;
                    $sukValue[$suk]['bar_code'] = '';
                    $sukValue[$suk]['weight'] = 0;
                    $sukValue[$suk]['volume'] = 0;
                    $sukValue[$suk]['brokerage'] = 0;
                    $sukValue[$suk]['brokerage_two'] = 0;
                }
            } else {
                $sukValue[$suk]['pic'] = '';
                $sukValue[$suk]['price'] = 0;
                $sukValue[$suk]['cost'] = 0;
                $sukValue[$suk]['ot_price'] = 0;
                $sukValue[$suk]['stock'] = 0;
                $sukValue[$suk]['bar_code'] = '';
                $sukValue[$suk]['weight'] = 0;
                $sukValue[$suk]['volume'] = 0;
                $sukValue[$suk]['brokerage'] = 0;
                $sukValue[$suk]['brokerage_two'] = 0;
            }
            foreach (array_keys($detail) as $k => $title) {
                $header[$k]['title'] = $title;
                $header[$k]['align'] = 'center';
                $header[$k]['minWidth'] = 120;
            }
            foreach (array_values($detail) as $k => $v) {
                $valueNew[$count]['value' . ($k + 1)] = $v;
                $header[$k]['key'] = 'value' . ($k + 1);
            }
            $valueNew[$count]['detail'] = $detail;
            $valueNew[$count]['pic'] = $sukValue[$suk]['pic'] ?? '';
            $valueNew[$count]['price'] = $sukValue[$suk]['price'] ? floatval($sukValue[$suk]['price']) : 0;
            $valueNew[$count]['cost'] = $sukValue[$suk]['cost'] ? floatval($sukValue[$suk]['cost']) : 0;
            $valueNew[$count]['ot_price'] = isset($sukValue[$suk]['ot_price']) ? floatval($sukValue[$suk]['ot_price']) : 0;
            $valueNew[$count]['stock'] = $sukValue[$suk]['stock'] ? intval($sukValue[$suk]['stock']) : 0;
            $valueNew[$count]['bar_code'] = $sukValue[$suk]['bar_code'] ?? '';
            $valueNew[$count]['weight'] = $sukValue[$suk]['weight'] ? floatval($sukValue[$suk]['weight']) : 0;
            $valueNew[$count]['volume'] = $sukValue[$suk]['volume'] ? floatval($sukValue[$suk]['volume']) : 0;
            $valueNew[$count]['brokerage'] = $sukValue[$suk]['brokerage'] ? floatval($sukValue[$suk]['brokerage']) : 0;
            $valueNew[$count]['brokerage_two'] = $sukValue[$suk]['brokerage_two'] ? floatval($sukValue[$suk]['brokerage_two']) : 0;
            $count++;
        }
        $header[] = ['title' => '图片', 'slot' => 'pic', 'align' => 'center', 'minWidth' => 80];
        $header[] = ['title' => '售价', 'slot' => 'price', 'align' => 'center', 'minWidth' => 95];
        $header[] = ['title' => '成本价', 'slot' => 'cost', 'align' => 'center', 'minWidth' => 95];
        $header[] = ['title' => '原价', 'slot' => 'ot_price', 'align' => 'center', 'minWidth' => 95];
        $header[] = ['title' => '库存', 'slot' => 'stock', 'align' => 'center', 'minWidth' => 95];
        $header[] = ['title' => '商品编号', 'slot' => 'bar_code', 'align' => 'center', 'minWidth' => 120];
        $header[] = ['title' => '重量(KG)', 'slot' => 'weight', 'align' => 'center', 'minWidth' => 95];
        $header[] = ['title' => '体积(m³)', 'slot' => 'volume', 'align' => 'center', 'minWidth' => 95];
        $header[] = ['title' => '操作', 'slot' => 'action', 'align' => 'center', 'minWidth' => 70];
        $info = ['attr' => $attr, 'value' => $valueNew, 'header' => $header];
        return app('json')->success(compact('info'));
    }

    /**
     * 获取商品详细信息
     * @param int $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_product_info($id = 0)
    {
        //$mer_id = $this->merId ?: '';
        $list = Category::getTierList(null, 1);
        $menus = [];
        foreach ($list as $menu) {
            $menus[] = ['value' => $menu['id'], 'label' => $menu['html'] . $menu['cate_name'], 'disabled' => $menu['pid'] == 0 ? 0 : 1];//'disabled'=>$menu['pid']== 0];
        }
        $data['cateList'] = $menus;
        $data['productInfo'] = [];
        if ($id) {
            $productInfo = ProductModel::get($id);
            if (!$productInfo) {
                return app('json')->fail('修改的商品不存在');
            }
            $productInfo['postage'] = floatval($productInfo['postage']);
            $productInfo['slider_image'] = is_string($productInfo['slider_image']) ? json_decode($productInfo['slider_image'], true) : [];
            if ($productInfo['spec_type'] == 1) {
                $result = ProductAttrResult::getResult($id);
                foreach ($result['value'] as $k => $v) {
                    $num = 1;
                    foreach ($v['detail'] as $dv) {
                        $result['value'][$k]['value' . $num] = $dv;
                        $num++;
                    }
                }
                $productInfo['items'] = $result['attr'];
                $productInfo['attrs'] = $result['value'];
                $productInfo['attr'] = ['pic' => '', 'price' => 0, 'cost' => 0, 'ot_price' => 0, 'stock' => 0, 'bar_code' => '', 'weight' => 0, 'volume' => 0, 'brokerage' => 0, 'brokerage_two' => 0];
            } else {
                $result = ProductAttrValue::where('product_id', $id)->where('type', 0)->find();
                $productInfo['items'] = [];
                $productInfo['attrs'] = [];
                $productInfo['attr'] = [
                    'pic' => $result['image'] ?? '',
                    'price' => $result['price'] ? floatval($result['price']) : 0,
                    'cost' => $result['cost'] ? floatval($result['cost']) : 0,
                    'ot_price' => $result['ot_price'] ? floatval($result['ot_price']) : 0,
                    'stock' => $result['stock'] ? floatval($result['stock']) : 0,
                    'bar_code' => $result['bar_code'] ?? '',
                    'weight' => $result['weight'] ? floatval($result['weight']) : 0,
                    'volume' => $result['volume'] ? floatval($result['volume']) : 0,
                    'brokerage' => $result['brokerage'] ? floatval($result['brokerage']) : 0,
                    'brokerage_two' => $result['brokerage_two'] ? floatval($result['brokerage_two']) : 0
                ];
            }
            $data['productInfo'] = $productInfo;
        }
        return app('json')->success($data);
    }

    /**
     * 保存新建或编辑
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function save($id)
    {
        $data = UtilService::getMore([
            'store_name',
            'cate_id',
            'keyword',
            'store_info',
            ['unit_name', '件'],
            ['postage', 0],
            ['image', []],
            ['slider_image', []],
            ['video_link', ''],
            ['spec_type', 0],
            ['ficti', 100],
            ['sales', 0],
            ['sort', 0],
            ['is_show', 0],
            ['is_best', 0],
            ['is_sub', 0],
            ['description', ''],
            ['items', []],
            ['attrs', []]
        ]);
        //$data['mer_id'] = $this->merId ?: '';
        $detail = $data['attrs'];
        $data['price'] = min(array_column($detail, 'price'));
        $data['ot_price'] = min(array_column($detail, 'ot_price'));
        $data['cost'] = min(array_column($detail, 'cost'));
        $attr = $data['items'];
        unset($data['items'], $data['video'], $data['attrs']);
        if (!$data['cate_id']) return app('json')->fail('请选择商品分类');
        if (!$data['store_name']) return app('json')->fail('请输入商品名称');
        if (empty($data['image'])) return app('json')->fail('请上传商品图片');
        if (count($data['slider_image']) < 1) return app('json')->fail('请上传商品轮播图');
        $data['slider_image'] = json_encode($data['slider_image']);
        $data['stock'] = array_sum(array_column($detail, 'stock'));
        ProductModel::beginTrans();
        foreach ($detail as &$item) {
            if ($item['brokerage'] > $item['price']) {
                return app('json')->fail('佣金不能大于商品售价');
            }
        }
        if ($id) {
            unset($data['sales']);
            ProductModel::where('id',$id)->save($data);
            if ($data['spec_type'] == 0) {
                $attr = [
                    [
                        'value' => '规格',
                        'detailValue' => '',
                        'attrHidden' => '',
                        'detail' => ['默认']
                    ]
                ];
                $detail[0]['value1'] = '规格';
                $detail[0]['detail'] = ['规格' => '默认'];
            }
            $attr_res = ProductAttr::createProductAttr($attr, $detail, $id);
            if ($attr_res) {
                ProductModel::commitTrans();
                return app('json')->success('修改成功!');
            } else {
                ProductModel::rollbackTrans();
                return app('json')->fail(ProductAttr::getErrorInfo());
            }
        } else {
            $data['add_time'] = time();
            $data['code_path'] = '';
            $res = ProductModel::create($data);
            if ($data['spec_type'] == 0) {
                $attr = [
                    [
                        'value' => '规格',
                        'detailValue' => '',
                        'attrHidden' => '',
                        'detail' => ['默认']
                    ]
                ];
                $detail[0]['value1'] = '规格';
                $detail[0]['detail'] = ['规格' => '默认'];
            }
            $attr_res = ProductAttr::createProductAttr($attr, $detail, $res['id']);
            if ($attr_res) {
                ProductModel::commitTrans();
                return app('json')->success('添加商品成功!');
            } else {
                ProductModel::rollbackTrans();
                return app('json')->fail(ProductAttr::getErrorInfo());
            }
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (!$id) return app('json')->fail('数据不存在');
        if (!ProductModel::be(['id' => $id])) return app('json')->fail('商品数据不存在');
        if (ProductModel::be(['id' => $id, 'is_del' => 1])) {
            $data['is_del'] = 0;
            if (!ProductModel::where('id',$id)->save($data))
                return app('json')->fail(ProductModel::getErrorInfo('恢复失败,请稍候再试!'));
            else
                return app('json')->success('成功恢复商品!');
        } else {
            $data['is_del'] = 1;
            $data['is_show'] = 0;
            if (!ProductModel::where('id',$id)->save($data))
                return app('json')->fail(ProductModel::getErrorInfo('删除失败,请稍候再试!'));
            else
                return app('json')->success('成功移到回收站!');
        }
    }

    /**
     * 修改状态
     * @param string $is_show
     * @param string $id
     * @return mixed
     */
    public function set_show($is_show = '', $id = '')
    {
        ($is_show == '' || $id == '') && app('json')->fail('缺少参数');
        if (ProductModel::be(['id' => $id, 'is_del' => 1])) return app('json')->fail('商品已删除，不能上架');
        $res = ProductModel::where(['id' => $id])->update(['is_show' => (int)$is_show]);
        if ($res) {
            return app('json')->success($is_show == 1 ? '上架成功' : '下架成功');
        } else {
            return app('json')->fail($is_show == 1 ? '上架失败' : '下架失败');
        }
    }

    /**
     * 设置批量商品上架
     * @return mixed
     */
    public function product_show()
    {
        $post = UtilService::getMore([
            ['ids', []]
        ]);
        if (empty($post['ids'])) {
            return app('json')->fail('请选择需要上架的商品');
        } else {
            $res = ProductModel::where('id', 'in', $post['ids'])->update(['is_show' => 1]);
            if ($res !== false)
                return app('json')->success('上架成功');
            else
                return app('json')->fail('上架失败');
        }
    }


}
