<?php

namespace app\admin\controller\company;

use app\admin\controller\AuthController;
use app\models\store\StoreProduct;
use app\models\system\SystemStore;
use app\models\system\SystemStoreStock;
use app\models\system\SystemStoreStockBill;
use app\admin\model\store\{StoreCategory as CategoryModel, StoreProduct as ProductModel, StoreProductAttrValue};
use crmeb\services\{FormBuilder,
    JsonService,
    JsonService as Json,
    UtilService as Util,
    FormBuilder as Form
};
use crmeb\traits\CurdControllerTrait;
use think\facade\Route as Url;


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

    use CurdControllerTrait;

    protected $bindModel = ProductModel::class;

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $type = $this->request->param('type', 1);
        //获取分类
        $this->assign('cate', CategoryModel::getTierList(null, 1));
        //出售中产品
        $onsale = ProductModel::where('is_del', 0)->where('is_consumer', 0)->where('is_show', 1)->count();
        //待上架产品
        $forsale = ProductModel::where('is_del', 0)->where('is_consumer', 0)->where('is_show', 0)->count();
        //仓库中产品
        $warehouse = ProductModel::where('is_del', 0)->where('is_consumer', 0)->count();
        //已经售馨产品
        $outofstock = ProductModel::getModelObject(['type' => 4])->where('is_consumer', 0)->count();
        //警戒库存
        $policeforce = ProductModel::getModelObject(['type' => 5])->where('is_consumer', 0)->count();
        //回收站
        $recycle = ProductModel::where('is_del', 1)->where('is_consumer', 0)->count();
        $this->assign(compact('type', 'onsale', 'forsale', 'warehouse', 'outofstock', 'policeforce', 'recycle'));
        $this->assign('type', $this->adminInfo['type']);
        if ($this->adminInfo['type'] == 0) {
            $this->assign('store', SystemStore::where('is_show', 1)->where('is_del', 0)->field('id,name')->select());
        }
        return $this->fetch();
    }

    public function consumer()
    {
        $type = $this->request->param('type', 1);
        //获取分类
        $this->assign('cate', CategoryModel::getTierList(null, 1, 1));
        //出售中产品
        $onsale = ProductModel::where('is_del', 0)->where('is_show', 1)->where('is_consumer', 1)->count();
        //待上架产品
        $forsale = ProductModel::where('is_del', 0)->where('is_show', 0)->where('is_consumer', 1)->count();
        //仓库中产品
        $warehouse = ProductModel::where('is_del', 0)->where('is_consumer', 1)->count();
        //已经售馨产品
        $outofstock = ProductModel::getModelObject(['type' => 4])->where('is_consumer', 1)->count();
        //警戒库存
        $policeforce = ProductModel::getModelObject(['type' => 5])->where('is_consumer', 1)->count();
        //回收站
        $recycle = ProductModel::where('is_del', 1)->where('is_consumer', 1)->count();
        $this->assign(compact('type', 'onsale', 'forsale', 'warehouse', 'outofstock', 'policeforce', 'recycle'));
        return $this->fetch();
    }

    /**
     * 异步查找产品
     *
     * @return json
     */
    public function product_ist()
    {
        $where = Util::getMore([
            ['page', 1],
            ['limit', 20],
            ['key', ''],
            ['excel', 0],
            ['store_id', $this->adminInfo['store_id']],
            ['is_warn', 0],
        ]);
        return Json::successlayui(SystemStoreStock::lst($where));
    }

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

    public function edit_stock($bar_code)
    {
        $f = [];
        $f[] = Form::hidden('bar_code', $bar_code);
        $f[] = Form::radio('type', '增减', 1)->setOptions([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
        $f[] = Form::number('in_stock', '数量', 0)->step(1)->min(1);
        $f[] = Form::textarea('info', '增减缘由', 0)->rows(10);
        $form = Form::make_post_form('添加用户通知', $f, Url::buildUrl('save'));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    public function save()
    {
        $where = Util::getMore([
            ['bar_code', 20],
            ['in_stock', 0],
            ['type', 1],
            ['info', ''],
        ]);
        if (!$this->adminInfo['store_id']) return app('json')->fail('门店铺货用通道');
        if ($where['in_stock'] < 1) return app('json')->fail('补货数量不能少于1');
        $info = SystemStoreStock::alias('a')->join("StoreProduct b", "a.product_id=b.id", "left")->where('a.bar_code', $where['bar_code'])->field('a.price,a.unique,a.in_stock,a.is_consumer,a.product_id,b.store_name,b.image,a.bar_code')->find();
        if (!$info && $where['type'] != 1) return app('json')->fail('门店尚无库存无法减少');
        if (!$info) {
            $store_product = StoreProductAttrValue::where('type', 0)->where('bar_code', $where['bar_code'])->find();
            if (!$store_product)
                return app('json')->fail('商品条形码不存在');
            SystemStoreStock::create([
                    'store_id' => $this->adminInfo['store_id'],
                    'product_id' => $store_product['product_id'],
                    'in_stock' => 0,
                    'store_sales' => 0,
                    'repair_sales' => 0,
                    'in_last_time' => 0,
                    'unique' => $store_product['unique'],
                    'bar_code' => $store_product['bar_code'],
                    'price' => $store_product['price'],
                    'image' => $store_product['image'],
                    'is_consumer' => StoreProduct::where('id', $store_product['product_id'])->value('is_consumer'),
                ]
            );
            $info = SystemStoreStock::alias('a')->join("StoreProduct b", "a.product_id=b.id", "left")->where('a.bar_code', $where['bar_code'])->field('a.price,a.unique,a.in_stock,a.is_consumer,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;
        $info['type'] = $where['type'] == 1 ? 1 : 2;
        $info['info'] = $where['info'];
        if (SystemStoreStockBill::order_create($this->adminInfo['store_id'], $info)) {
            return Json::successful('入库成功');
        } else {
            return Json::fail('入库失败');
        }

    }

    /**
     * 门店库存始初化
     * @param int $store_id
     * @param int $num
     */
    public function init($store_id = 0, $num = 10)
    {
        if ($store_id < 1) return app('json')->fail('参数错误!');
        if ($this->adminInfo['type'] == 1) return app('json')->fail('无权限!');
        SystemStoreStock::store_init($store_id, $num);
    }

    public function bill()
    {
        if ($this->adminInfo['type'] == 0) {
            $this->assign('store', SystemStore::where('is_show', 1)->where('is_del', 0)->field('id,name')->select());
        }
        $this->assign('type', $this->adminInfo['type']);
        return $this->fetch();
    }

    public function bill_lst()
    {
        $where = Util::getMore([
            ['store_id', $this->adminInfo['store_id']],
            ['key', ''],
            ['page', 0],
            ['limit', 0],
            ['status', -2],
        ]);
        return Json::successlayui(SystemStoreStockBill::lst($where));
    }

    public function bill_view($product_id, $store_id)
    {

        $this->assign('product_id', $product_id);
        $this->assign('store_id', $store_id);
        $this->assign('count', SystemStoreStockBill::where(compact('product_id', 'store_id'))->value('count(id)') ?: 0);
        return $this->fetch();
    }

    public function bill_view_lst()
    {
        $where = Util::getMore([
            ['store_id', 0],
            ['product_id', 0],
            ['key', ''],
            ['page', 0],
            ['limit', 0],
            ['status', -2],
        ]);
        return app('json')->successful(SystemStoreStockBill::lst($where));
    }

    public function audit($id)
    {
        if (!$id) return $this->failed('数据不存在');
        $Bill = SystemStoreStockBill::where('id', $id)->find();
        if (!$Bill) return Json::fail('数据不存在!');
        $f = array();
        $f[] = Form::radio('status', '状态', $Bill->getData('status'))->options([['value' => 1, 'label' => '通过'], ['value' => -1, 'label' => '拒绝']]);
        $f[] = Form::textarea('refuse_msg', '备注');
        $form = Form::make_post_form('入库审核', $f, Url::buildUrl('audit_save', array('id' => $id)), 2);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    public function batch_audit($id)
    {
        if (!$id) return $this->failed('数据不存在');

        $f = array();
        $f[] = Form::radio('status', '状态')->options([['value' => 1, 'label' => '通过'], ['value' => -1, 'label' => '拒绝']]);
        $f[] = Form::textarea('refuse_msg', '备注');
        $form = Form::make_post_form('入库审核', $f, Url::buildUrl('batch_audit_save', array('id' => $id)), 2);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    public function audit_save($id)
    {
        $where = Util::postMore([
            ['refuse_msg', ''],
            ['status', 1],
        ]);
        $rs = true;
        if ($where['status'] == 1) {
            if (!SystemStoreStockBill::be(['id' => $id, 'status' => 0])) Json::fail('数据不存在或已经审核');
            $info = SystemStoreStockBill::find($id)->toArray();
            $stock_info = SystemStoreStock::where(['store_id' => $info['store_id'], 'product_id' => $info['product_id'], 'bar_code' => $info['bar_code']])->find();
            if (!$stock_info && $info['type'] == 2) Json::fail('库存无法减少');
            if ($info['type'] == 2 && $info['in_stock'] > $stock_info['in_stock']) Json::fail('库存不足');
            $rs = SystemStoreStock::replenish($info['store_id'], $info);
        }
        if ($rs) {
            $where['audit_time'] = time();
            $where['audit_admin'] = $this->adminId;
            SystemStoreStockBill::edit($where, $id);
            Json::successful('审核成功');
        } else {
            Json::fail(SystemStoreStock::getErrorInfo());
        }
    }

    /**
     * 批量审核
     */
    public function batch_audit_save()
    {
        $where = Util::postMore([
            ['refuse_msg', ''],
            ['status', 1],
        ]);
        $ids = explode(',', input('id'));
        $msg = [];
        if ($where['status'] == 1) {
            foreach ($ids as $k => $v) {
                $info = SystemStoreStockBill::where('id', $v)->where('status', 0)->find();
                if (!$info) {
                    unset($ids[$k]);
                    $msg[] = $v . ':数据不存在或已经审核';
                }
                $stock_info = SystemStoreStock::where(['store_id' => $info['store_id'], 'product_id' => $info['product_id'], 'bar_code' => $info['bar_code']])->find();
                if (!$stock_info && $info['type'] == 2) {
                    unset($ids[$k]);
                    $msg[] = $v . ':库存无法减少';
                }
                if ($info['type'] == 2 && $info['in_stock'] > $stock_info['in_stock']) {
                    unset($ids[$k]);
                    $msg[] = $v . ':库存不足';
                }
                if ($info) {
                    $rs = SystemStoreStock::replenish($info['store_id'], $info);
                    if (!$rs) {
                        unset($ids[$k]);
                        $msg[] = $v . ':' . SystemStoreStock::getErrorInfo();
                    }
                }
            }
        }
        $where['audit_time'] = time();
        $where['audit_admin'] = $this->adminId;
        SystemStoreStockBill::where('id', 'in', join(",", $ids))->update($where);
        if (!count($msg)) {
            return Json::successful('批量审核成功');
        } else {
            return Json::successful('批量审核部分成功' . implode(',', $msg));
        }
    }

}
