<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-31 20:43
// +----------------------------------------------------------------------

namespace app\admin\controller\v1;


use app\BaseController;
use app\model\admin\ExpCost;
use app\model\admin\MemberLevel;
use app\model\admin\Warehouse as WarehouseModel;
use app\model\admin\AdminRole;
use app\Request;
use library\services\UtilService;
use library\utils\Dtree;
use library\utils\MakeSite;

class Warehouse extends  BaseController
{

    /**
     * 获取管理列表
     * @param Request $request
     */
    public function list(Request $request) {
        $pageSize = 50;
        [$page,$name] =  UtilService::getMore(
            [
                ['page',1],
                ['name','']
            ],$request,true
        );
        $where = [];
        if(!empty($name)) {
            $where['name'] = ["%{$name}%",'whereLike'];
        }
        $platform = (new \app\model\admin\Platform());
        list($pageCount,$data) = (new WarehouseModel)->getList($page, $where,$pageSize,'id desc');
        foreach ($data as $k => $v) {
            $idsAr = explode(',',$v['platform_ids']);
            $platformAr = [];
            $data[$k]['platform']  = array_map(
                function ($item) use($platform){
                return  $platform->getPlatformId($item,'*');
            },$idsAr);
        }

        return app('json')->success([
            'list'      => $data,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $page
        ]);
    }


    /**
     * 保存数据
     * @param Request $request
     */
    public function  save(Request $request) {
        $post = UtilService::getMore(
            [
                ['id','0'],
                ['name','','empty','请输入仓库名称'],
                ['lx_name',''],
                ['lx_tel',''],
                ['address',''],
                ['status','0'],
                ['seq','0'],
                ['platform_ids','']
            ],
            $request
        );
        $bool = (new WarehouseModel)->saveModel($post);
        if($bool)
            return app('json')->success("操作成功", []);
        else
            return app('json')->fail(WarehouseModel::getErrorInfo());
    }

    /**
     * 获取详情数据
     * @param Request $request
     * @return mixed
     */
    public function info(Request $request) {
        [$id] = UtilService::getMore([
            ['id','','empty','参数错误']
        ],$request,true);
        $info = WarehouseModel::get(compact('id'))->toArray();
        return app('json')->success($info);
    }

    /**
     * 删除数据
     * @param Request $request
     */
    public function del(Request $request) {
        [$id] = UtilService::getMore(
            [
                ['id','0'],
            ],
            $request,true
        );
        WarehouseModel::del($id);
        return app('json')->success("删除成功", []);
    }


    /**
     * 快递配置[全部数据]
     * @param Request $request
     */
    public function exp(Request $request) {
        $pageSize = 20;
        [$page] = UtilService::getMore(
            [
                ['page','1']
            ]
            ,$request,true);
        $where = [];
        $where['sassid'] = $request->site['sassid'];
        $where['level_id'] = -1;
        $level = (new MemberLevel)->select()->toArray();
        $expCost = new ExpCost;
        list($pageCount,$data) = $expCost->getList2($page, $where,$pageSize,'id desc');
        foreach ($data as $k=>$v) {
            $expData = [];
            $d = $expCost
                ->field('id,money,level_id,status')
                ->where('warehouse_id',$v['warehouse_id'])
                ->where('express_id',$v['express_id'])
                ->where('sassid',$v['sassid'])
                ->select();

            $bool = false;
            foreach ($level as $v1) {
                $expData[$v1['id']] = ['money'=>0,'id'=>0,'status'=>0,'level_id'=>$v1['id']];
                foreach ($d as $v2) {
                    if($v1['id'] == $v2['level_id']) {
                        $expData[$v1['id']]['money'] = $v2['money'];
                        $expData[$v1['id']]['id'] = $v2['id'];
                        if($v2['status']) $bool = true;
                    }
                }
            }
            $data[$k]['status'] = $bool;
            $data[$k]['expData'] = $expData;
            $data[$k]['exp_money'] = empty($v['exp_money']) ? 0 : $v['exp_money'];
        }

        return app('json')->success([
            'list'      => $data,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $page,
            'level'     => $level
        ]);

    }



    /**
     * 保存数据
     * @param Request $request
     */
    public function expSave(Request $request) {
        $pageSize = 20;
        [$warehouse_id,$id,$expData,$status] = UtilService::getMore(
            [
                ['warehouse_id','','empty','参数错误'],
                ['id','','empty','参数错误'],
                ['expData',[]],
                ['status',false],
            ]
            ,$request,true);

        $expCost = (new ExpCost);

        $exp_money = $expCost
            ->where('warehouse_id',$warehouse_id)
            ->where('express_id',$id)
            ->where('sassid',$request->site['sassid'])
            ->where('level_id',-1)
            ->value('money');
        if(empty($exp_money)) $exp_money = 0;
        $isMoneyEr = false;
        $rePrice= [];
        foreach ($expData as $v) {
            $money = $v['money'];
            if($exp_money > $v['money']) {
                $money = $exp_money;
                $isMoneyEr = true;
            }
            $d['warehouse_id'] = $warehouse_id;
            $d['express_id'] = $id;
            $d['money'] = $money;
            $rePrice[] = $money;
            $d['level_id'] = $v['level_id'];
            $d['sassid'] = $request->site['sassid'];
            $d['status'] = $status ? 1 : 0;

            $count = $expCost
                ->where('sassid',$request->site['sassid'])
                ->where('warehouse_id',$warehouse_id)
                ->where('express_id',$id)
                ->where('level_id',$v['level_id'])
                ->count();
            if( $count <= 0 ) {
                $expCost->insert($d);
            } else {
                $expCost->where('id',$v['id'])->save($d);
            }
        }
        return app('json')->success([
            'msg'=>'操作成功',
            'err'=>($isMoneyEr ? ('快递费用低于' .$exp_money.'元,全部恢复成'.$exp_money ) : ''),
            'price'=>$rePrice]);
    }

    /**
     * 更新分站数据
     * @param Request $request
     */
    public function updateSiteExp(Request $request) {
        [$warehouse_id] = UtilService::getMore(
            [
                ['warehouse_id','']
            ]
            ,$request,true);
        $str = [];
        $sassid = $request->site['sassid'];
        $w = (new \app\model\system\Warehouse)->select();
        foreach ($w as $v) {
            $makeSite = new MakeSite($sassid);
            $makeSite->makeExpcos($v['id']);
            $str[] = $v['name'].'更新成功';
        }
        return app('json')->success(join(',',$str));
    }



}