<?php

namespace app\admin\controller\store;

use app\admin\controller\AuthController;
use app\models\store\SystemStockBill;
use app\models\system\SystemStoreStock;
use app\admin\model\store\{StoreDescription,
    StoreProductAttrValue,
    StoreProductAttr,
    StoreProductAttrResult,
    StoreCategory as CategoryModel,
    StoreProductCate,
    StoreProductCheck as ProductModel
};
use crmeb\services\{JsonService,
    JsonService as Json,
    UtilService as Util,
    FormBuilder as Form,
    UtilService
};
use crmeb\traits\CurdControllerTrait;
use think\facade\Route as Url;
use app\admin\model\system\{ShippingTemplates, SystemStore};
use think\Model;


/**
 * 产品管理
 * Class StoreProduct
 * @package app\admin\controller\store
 */
class StoreProductCheck extends AuthController
{

    use CurdControllerTrait;

    protected $bindModel = ProductModel::class;

    protected $store;

    protected $main_where = [];

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $store_id = $this->adminInfo['store_id'];
        $this->store = SystemStore::where('id', $store_id)->find();
        if ($this->store && $this->store['is_triple']) {
            $this->main_where['store_id'] = $store_id;
        }
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $type = $this->request->param('type', 1);
        //获取分类
        $this->assign('cate', CategoryModel::getTierList(null, 1));
        $checking = ProductModel::getModelObject(['type' => 2])->where($this->main_where)->count();
        $checkok = ProductModel::getModelObject(['type' => 3])->where($this->main_where)->count();
        $checkno = ProductModel::getModelObject(['type' => 4])->where($this->main_where)->count();
        $this->assign('user_store', $this->adminInfo['store_id']);
        $this->assign(compact('type', 'checking', 'checkok', 'checkno'));
        return $this->fetch();
    }


    /**
     * 异步查找产品
     *
     * @return void
     */
    public function product_ist()
    {
        $where = Util::getMore([
            ['page', 1],
            ['limit', 20],
            ['store_name', ''],
            ['cate_id', ''],
            ['excel', 0],
            ['order', ''],
            [['type', 'd'], $this->request->param('type/d')],
        ]);
        Json::successlayui(ProductModel::ProductList($where));
    }

    /**
     * 设置单个产品上架|下架
     *
     * @return void
     */
    public function check($id = '')
    {
        ($id == '') && Json::fail('缺少参数');
        $res = ProductModel::where($this->main_where)->where(['id' => $id])->update(['status' => 0]);
        if ($res) {
            Json::successful('提交成功');
        } else {
            Json::fail('提交失败');
        }
    }


    /**
     * 设置批量产品上架
     *
     * @return void
     */
    public function take_products()
    {
        $post = Util::postMore([
            ['ids', []]
        ]);
        if (empty($post['ids'])) {
            Json::fail('请选择需要提交的产品');
        } else {
            $res = ProductModel::where($this->main_where)->where('id', 'in', $post['ids'])->update(['status' => 0]);
            if ($res)
                Json::successful('提交成功');
            else
                Json::fail('提交失败');
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @param int $id
     * @param int $consumer
     * @return \think\Response
     * @throws \Exception
     */
    public function create($id = 0)
    {
        $this->assign('id', (int)$id);
        return $this->fetch();
    }


    /**
     * 获取产品详细信息
     * @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, $type = 0)
    {
        $list = CategoryModel::getTierList(null, 1, $type);
        $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['tempList'] = ShippingTemplates::order('sort', 'desc')->field(['id', 'name'])->select()->toArray();
        $data['cateList'] = $menus;
        $data['productInfo'] = [];
        if ($id) {
            $productInfo = ProductModel::where($this->main_where)->where('id', $id)->find();
            if (!$productInfo) {
                return Json::fail('修改的产品不存在');
            }
            $productInfo['cate_id'] = explode(',', $productInfo['cate_id']);
            $productInfo['description'] = htmlspecialchars_decode(StoreDescription::getDescription($id, 8));
            $productInfo['slider_image'] = is_string($productInfo['slider_image']) ? json_decode($productInfo['slider_image'], true) : [];
            if ($productInfo['spec_type'] == 1) {
                $result = StoreProductAttrResult::getResult($id, 8);
                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 = StoreProductAttrValue::where('product_id', $id)->where('type', 8)->find();
                if ($result) {
                    $single = $result->toArray();
                } else {
                    $single = [];
                }
                $productInfo['items'] = [];
                $productInfo['attrs'] = [];
                $productInfo['attr'] = [
                    'pic' => $single['image'] ?? '',
                    'price' => $single['price'] ?? 0,
                    'cost' => $single['cost'] ?? 0,
                    'ot_price' => $single['ot_price'] ?? 0,
                    'stock' => $single['stock'] ?? 0,
                    'bar_code' => $single['bar_code'] ?? '',
                    'weight' => $single['weight'] ?? 0,
                    'volume' => $single['volume'] ?? 0,
                    'brokerage' => $single['brokerage'] ?? 0,
                    'brokerage_two' => $single['brokerage_two'] ?? 0,
                ];
            }
            if ($productInfo['activity']) {
                $activity = explode(',', $productInfo['activity']);
                foreach ($activity as $k => $v) {
                    if ($v == 1) {
                        $activity[$k] = '秒杀';
                    } elseif ($v == 2) {
                        $activity[$k] = '砍价';
                    } elseif ($v == 3) {
                        $activity[$k] = '拼团';
                    }
                }
                $productInfo['activity'] = $activity;
            } else {
                $productInfo['activity'] = ['秒杀', '砍价', '拼团'];
            }
            $data['productInfo'] = $productInfo;
        }
        return JsonService::successful($data);
    }

    /**
     * 保存新建的资源
     *
     *
     */
    public function save($id)
    {
        if (!isset($this->store['is_triple']) || !$this->store['is_triple']) Json::fail('第三方门店专用通道');
        $data = Util::postMore([
            ['cate_id', []],
            'store_name',
            'store_info',
            'keyword',
            ['unit_name', '件'],
            ['image', []],
            ['slider_image', []],
            ['postage', 0],
            ['is_sub', 0],
            ['sort', 0],
            ['sales', 0],
            ['ficti', 100],
            ['give_integral', 0],
            ['max_use_integral', 0],
            ['is_show', 0],
            ['temp_id', 0],
            ['is_hot', 0],
            ['is_benefit', 0],
            ['is_suit', 0],
            ['is_award', 0],
            ['is_best', 0],
            ['is_new', 0],
            ['mer_use', 0],
            ['is_postage', 0],
            ['is_good', 0],
            ['description', ''],
            ['spec_type', 0],
            ['video_link', ''],
            ['items', []],
            ['attrs', []],
            ['activity', []],
            ['is_consumer', 0],
            ['bar_code', ''],
        ]);
        $data['store_id'] = $this->store['id'];
        foreach ($data['activity'] as $k => $v) {
            if ($v == '秒杀') {
                $data['activity'][$k] = 1;
            } elseif ($v == '砍价') {
                $data['activity'][$k] = 2;
            } else {
                $data['activity'][$k] = 3;
            }
        }
        $data['activity'] = implode(',', $data['activity']);
        $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 (count($data['cate_id']) < 1) return Json::fail('请选择产品分类');
        $cate_id = $data['cate_id'];
        $data['cate_id'] = implode(',', $data['cate_id']);
        if (!$data['store_name']) return Json::fail('请输入产品名称');
        if (count($data['image']) < 1) return Json::fail('请上传产品图片');
        if (count($data['slider_image']) < 1) return Json::fail('请上传产品轮播图');
        $data['image'] = $data['image'][0];
        $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['brokerage_two']) > $item['price']) {
                return Json::fail('一二级返佣相加不能大于商品售价');
            }
        }
        if ($id) {
            $info = ProductModel::get($id);
            if ($info['status'] != 2) $data['status'] = 0;
            unset($data['sales']);
            ProductModel::edit($data, $id);
            $description = $data['description'];
            unset($data['description']);
            StoreDescription::saveDescription($description, $id, 8);
            if ($data['spec_type'] == 0) {
                $attr = [
                    [
                        'value' => '规格',
                        'detailValue' => '',
                        'attrHidden' => '',
                        'detail' => ['默认']
                    ]
                ];
                $detail[0]['value1'] = '规格';
                $detail[0]['detail'] = ['规格' => '默认'];
            }

            $attr_res = StoreProductAttr::createProductAttr($attr, $detail, $id, 8);
            if ($attr_res) {
                ProductModel::commitTrans();
                return Json::success('修改成功!');
            } else {
                ProductModel::rollbackTrans();
                return Json::fail(StoreProductAttr::getErrorInfo());
            }
        } else {
            $data['add_time'] = time();
            $data['code_path'] = '';
            $data['status'] = 0;
            $res = ProductModel::create($data);
            $description = $data['description'];
            StoreDescription::saveDescription($description, $res['id'], 8);
            if ($data['spec_type'] == 0) {
                $attr = [
                    [
                        'value' => '规格',
                        'detailValue' => '',
                        'attrHidden' => '',
                        'detail' => ['默认']
                    ]
                ];
                $detail[0]['value1'] = '规格';
                $detail[0]['detail'] = ['规格' => '默认'];
            }
            $attr_res = StoreProductAttr::createProductAttr($attr, $detail, $res['id'], 8);
            if ($attr_res) {
                ProductModel::commitTrans();
                return Json::success('添加产品成功!');
            } else {
                ProductModel::rollbackTrans();
                return Json::fail(StoreProductAttr::getErrorInfo());
            }
        }
    }

    public function attr_save()
    {
        $where = Util::getMore([
            ['bar_code', 20],
            ['in_stock', 0],
        ]);
        if ($where['in_stock'] < 1) return app('json')->fail('补货数量不能少于1');
        $info = StoreProductAttrValue::alias('a')->join("StoreProduct b", "a.product_id=b.id", "left")->where('a.bar_code', $where['bar_code'])->field('a.price,a.unique,a.stock as in_stock,a.product_id,b.store_name,b.image,a.bar_code')->find();
        if (!$info) return app('json')->fail('商品条形码不存在');
        $info = $info->toarray();
        $info['in_stock'] = $where['in_stock'];
        $info['admin_id'] = $this->adminId;
        if (SystemStockBill::order_create($info)) {
            return Json::successful('入库成功');
        } else {
            return Json::fail('入库失败');
        }
    }

    /**
     * 生成属性
     * @param int $id
     */
    public function is_format_attr($id = 0, $type = 0)
    {
        $data = Util::postMore([
            ['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']);
            $types = 1;
            if ($id) {
                $sukValue = StoreProductAttrValue::where('product_id', $id)->where('type', 8)->where('suk', $suk)->column('bar_code,cost,price,ot_price,stock,image as pic,weight,volume,brokerage,brokerage_two', 'suk');
                if (!count($sukValue)) {
                    if ($type == 0) $types = 0; //编辑商品时，将没有规格的数据不生成默认值
                    $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;
            }
            if ($types) { //编辑商品时，将没有规格的数据不生成默认值
                foreach (array_keys($detail) as $k => $title) {
                    $header[$k]['title'] = $title;
                    $header[$k]['align'] = 'center';
                    $header[$k]['minWidth'] = 130;
                }
                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'] ?? 0;
                $valueNew[$count]['volume'] = $sukValue[$suk]['volume'] ?? 0;
                $valueNew[$count]['brokerage'] = $sukValue[$suk]['brokerage'] ?? 0;
                $valueNew[$count]['brokerage_two'] = $sukValue[$suk]['brokerage_two'] ?? 0;
                $count++;
            }
        }
        $header[] = ['title' => '图片', 'slot' => 'pic', 'align' => 'center', 'minWidth' => 80];
        $header[] = ['title' => '售价', 'slot' => 'price', 'align' => 'center', 'minWidth' => 120];
        $header[] = ['title' => '成本价', 'slot' => 'cost', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '原价', 'slot' => 'ot_price', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '库存', 'slot' => 'stock', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '产品编号', 'slot' => 'bar_code', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '重量(KG)', 'slot' => 'weight', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '体积(m³)', 'slot' => 'volume', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '操作', 'slot' => 'action', 'align' => 'center', 'minWidth' => 70];
        $info = ['attr' => $attr, 'value' => $valueNew, 'header' => $header];
        return Json::successful($info);
    }

    public function check_no($id)
    {
        $info = ProductModel::get($id);
        if (!$info || $info['status'] != 0 || $this->adminInfo['store_id'] != 0) {
            $this->failed('参数或身份错误');
        }
        $from = [];
        $from['reason'] = Form::textarea('reason', '驳回原因', '')->rows(10);
        $form = Form::make_post_form('添加用户通知', $from, Url::buildUrl('save_check_no', array('id' => $id)));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    public function save_check_no($id)
    {
        $info = ProductModel::get($id);
        if (!$info || $info['status'] != 0 || $this->adminInfo['store_id'] != 0) {
            Json::fail('参数或身份错误');
        }
        $data = UtilService::postMore([
            ['reason', ''],
        ]);
        if (ProductModel::where('id', $id)->update(['reason' => $data['reason'], 'status' => 2])) {
            JsonService::success('驳回成功');
        } else {
            JsonService::fail('驳回失败');
        }
    }

    public function check_ok($id)
    {
        $info = ProductModel::get($id);
        if (!$info || $info['status'] != 0 || $this->adminInfo['store_id'] != 0) {
            Json::fail('参数或身份错误');
        }
        $info = $info->toArray();
        $description = StoreDescription::getDescription($id, 8);
        $cate_id = explode(',', $info['cate_id']);
        ProductModel::beginTrans();
        $product = \app\admin\model\store\StoreProduct::where('check_id', $id)->find();
        try {
            if ($product) {
                unset($info['id']);
                unset($info['add_time']);
                \app\admin\model\store\StoreProduct::edit($info, $product['id']);
                StoreDescription::saveDescription(htmlspecialchars_decode($description), $product['id'], 0);
                StoreProductCate::where('product_id', $product['id'])->delete();
                $cateData = [];
                foreach ($cate_id as $cid) {
                    $cateData[] = ['product_id' => $product['id'], 'cate_id' => $cid, 'add_time' => time()];
                }
                StoreProductCate::insertAll($cateData);
                $attr_res = StoreProductAttr::reSaveFromOtherType($id, $product['id'], 8, 0);
                if ($attr_res) {
                    ProductModel::where('id', $id)->update(['status' => 1]);
                    ProductModel::commitTrans();
                    Json::success('审核完成');
                } else {
                    ProductModel::rollbackTrans();
                    Json::fail(StoreProductAttr::getErrorInfo());
                }
            } else {
                //新增
                unset($info['id']);
                $info['check_id'] = $id;
                $info['add_time'] = time();
                $res = \app\admin\model\store\StoreProduct::create($info);
                StoreDescription::saveDescription(htmlspecialchars_decode($description), $res['id'], 0);
                $cateData = [];
                foreach ($cate_id as $cid) {
                    $cateData[] = ['product_id' => $res['id'], 'cate_id' => $cid, 'add_time' => time()];
                }
                StoreProductCate::insertAll($cateData);
                $attr_res = StoreProductAttr::reSaveFromOtherType($id, $res['id'], 8, 0);
                if ($attr_res) {
                    ProductModel::where('id', $id)->update(['status' => 1]);
                    ProductModel::commitTrans();
                    Json::success('审核完成');
                } else {
                    ProductModel::rollbackTrans();
                    Json::fail(StoreProductAttr::getErrorInfo());
                }
            }
        } catch (\Exception $e) {
            ProductModel::rollbackTrans();
            Json::fail($e->getMessage());
        }
    }
}
