<?php
declare(strict_types=1);
namespace app\api\service;

use app\common\model\ShopList;
use app\common\model\StockConfig;
use app\common\model\ProductConfig;
use app\common\model\StockDetail;
use app\common\model\ShopDelivery;
use app\common\model\CustomerSpec;
/**
 * 录入发货
 */
class SpecService{


    //判断价格为空
    public static function getIsZeroSpecsPrice(array $data): bool
    {
        $result = false;
        foreach ($data as $item) {
            if(empty($item['price'])) return false;
        }
        return $result;
    }



    //获取规格列表
    public static function getSpecsList(int $type_id, array $data): array
    {
        $result = [];
        foreach ($data as $item) {

            if($item['type_id'] == $type_id){
                $result[] = $item;
            }
        }
        return $result;
    }


    //录入规格列表
    public static function getDeliveryList(int $uid, array $data): array
    {
        $result = [];
        $stockData = [];
        //获取店铺客户信息
        $customer = ShopList::getCustomerByShopId((int)$data['shop_id']);
        if(!$customer) throw new \Exception('店铺客户信息不存在！');
        //计算结算周期
        $settlement_data = SpecService::getDeliverySettlement($customer, $data['ship_date']);
        foreach ($data['variety'] as $item) {
            if(count($item) < 7 || empty(floatval($item['num']))){
                throw new \Exception('参数有误！' . json_encode($item));
            }
            if($item['box_id'] == 0) $item['box_name'] = '';
            $specsWeight = ProductConfig::where('id', $item['spec_id'])->value('weight');
            $weight = bcmul((string)$specsWeight, $item['num'], 2);
            $result[] = [
                'user_id'         => $uid,
                'customer_id'     => $customer->id,
                'shop_id'         => $data['shop_id'],
                'plat_id'         => $data['plat_id'],
                'variety_id'      => $item['variety_id'],
                'variety_name'    => $item['variety_name'],
                'spec_id'         => $item['spec_id'],
                'box_id'          => $item['box_id'],
                'box_name'        => $item['box_name'],
                'spec_name'       => $item['spec_name'],
                'num'             => $item['num'],
                'weigh'           => $weight,
                'price'           => $item['price'],
                'ship_date'       => $data['ship_date'],
                'settlement_data' => $settlement_data,
                'total_price'     => bcmul($item['price'], $item['num'], 2)
            ];

            //根据品种扣除库存
            if($weight){
                $varietyNum = StockDetail::setStockConfigNum((int)$item['variety_id'], (string)-$weight, StockConfig::VarietyName);
                $stockData[] = [
                    'user_id'         => $uid,
                    'type_id'         => StockConfig::VarietyName,
                    'type'            => 1,
                    'variety_id'      => $item['variety_id'],
                    'change'          => -$weight,
                    'after'           => $varietyNum,
                    'remark'          => '录入出库'
                ];
            }

            //根据规格扣除包装箱
            if($item['box_id']){
                $boxNum = StockDetail::setStockConfigNum((int)$item['box_id'], (string)-$item['num'], StockConfig::PackingBox);
                $stockData[] = [
                    'user_id'         => $uid,
                    'type_id'         => StockConfig::PackingBox,
                    'type'            => 1,
                    'variety_id'      => $item['box_id'],
                    'change'          => -$item['num'],
                    'after'           => $boxNum,
                    'remark'          => '录入出库'
                ];
            }

        }
        return [$result, $stockData];
    }

    public static function getDeliveryEdit(int $user_id, array $data)
    {
        //查询发货记录
        $delivery = ShopDelivery::where('user_id', $user_id)->where('id', $data['ids'])->find();
        if(!$delivery) throw new \Exception('参数有误！');

        //判断是否当天
        if(substr($delivery->createtime, 0, 10) != date('Y-m-d')) throw new \Exception('只能修改当日发货记录！');

        //修改库存
        $specs = ProductConfig::where('id', $delivery->spec_id)->value('weight');
        if(!$specs) throw new \Exception('参数有误！');

        //根据品种扣除库存
        $weight = bcmul((string)$specs, $data['num'], 2); //总重

        //扣除品种
        StockDetail::setStockConfigNum($delivery->variety_id, bcsub($delivery->weigh, $weight, 2), StockConfig::VarietyName);

        //根据规格扣除包装箱
        if($delivery->box_id){
            StockDetail::setStockConfigNum($delivery->box_id, bcsub((string)$delivery->num, $data['num'], 2), StockConfig::PackingBox);
        }
        //修改数量
        $price  = bcdiv($delivery->total_price, (string)$delivery->num, 2); //单价
        $delivery->weigh = $weight; //总重
        $delivery->num   = $data['num'];
        $delivery->total_price = bcmul($price, $data['num'], 2);
        return $delivery->save();
    }


    //删除
    public static function getDeliveryDel(int $user_id, array $data)
    {
        //查询发货记录
        $delivery = ShopDelivery::where('user_id', $user_id)->where('id', $data['ids'])->find();
        if(!$delivery) throw new \Exception('参数有误！');

        //判断是否当天
        if(substr($delivery->createtime, 0, 10) != date('Y-m-d')) throw new \Exception('只能修改当日发货记录！');

        //修改库存
        $box_id = ProductConfig::where('id', $delivery->spec_id)->value('box_id');
        if(!$box_id)  throw new \Exception('参数有误！');

        //扣除品种
        StockDetail::setStockConfigNum($delivery->variety_id, $delivery->weigh, StockConfig::VarietyName);

        //根据规格扣除包装箱
        StockDetail::setStockConfigNum($box_id, (string)$delivery->num, StockConfig::PackingBox);

        //删除
        return $delivery->delete();
    }

    //结算周期
    public static function getDeliverySettlement(object $customer, string $ship_date)
    {
        $result = $ship_date;
        switch ($customer->account_term) {
            case 2:
                $result = getNextWeekDates($ship_date, $customer->cycle);
                break;
            case 3:
                $result = date('Y-m-d', strtotime($ship_date . ' +15 days'));
                break;
        }
        return  $result;

    }

}