<?php

namespace app\mobile\logic;

use app\model\AddrModel;
use app\model\CommonModel;
use app\model\CompanyGoodModel;
use app\model\GoodModel;
use app\model\GroupModel;
use app\model\InventoryExchangeModel;
use app\model\OrderExchangeModel;
use think\Exception;
use think\facade\Db;
use think\response\Json;

class ExchangeLogic extends BaseLogic
{

    //商品列表
    public static function goodList(array $data = []): Json
    {
        $db = CompanyGoodModel::alias('a')
            ->leftJoin('good b', 'b.id=a.good_id AND b.is_del=' . CommonModel::$del_normal)
            ->leftJoin('inventory_exchange c', 'c.account_id=' . self::$aid . ' AND c.good_id=a.good_id')
            ->where(['a.is_del' => CommonModel::$del_normal, 'a.group_id' => self::$group_id, 'b.type' => GoodModel::$type_exchange]);

        $count = $db->count('a.id');

        $list = $db
            ->field('a.id,a.code,a.good_id,b.good_cover_img,b.good_name,b.moq,b.step,c.inventory')
            ->page($data['page'], $data['size'])
            ->order(['a.is_top' => 'desc', 'a.weight' => 'desc', 'a.id' => 'desc'])
            ->select()
            ->toArray();

        return json_show(CommonModel::$success, '获取兑换商品列表成功', ['count' => $count, 'list' => $list]);

    }

    //商品详情
    public static function goodInfo(string $code = ''): Json
    {
        $rs = CompanyGoodModel::alias('a')
            ->field('a.id,a.code,a.good_id,b.good_cover_img,b.good_code,b.good_name,b.moq,b.step,b.good_banner_img,b.good_img,b.good_param,b.status,c.inventory,d.unit')
            ->leftJoin('good b', 'b.id=a.good_id AND b.is_del=' . CommonModel::$del_normal)
            ->leftJoin('inventory_exchange c', 'c.account_id=' . self::$aid . ' AND c.good_id=a.good_id')
            ->leftJoin('unit d', 'd.id=b.unit_id AND d.is_del=' . CommonModel::$del_normal)
            ->where(['a.is_del' => CommonModel::$del_normal, 'a.code' => $code])
            ->withAttr('good_param', function ($val) {
                return json_decode($val, true);
            })
            ->withAttr('good_img', function ($val) {
                return explode(',', $val);
            })->withAttr('good_banner_img', function ($val) {
                return explode(',', $val);
            })
            ->findOrEmpty()
            ->toArray();

        return json_show(CommonModel::$success, '获取兑换商品详情成功', $rs);

    }

    //兑换商品下单
    public static function orderAdd(array $data = []): Json
    {
        Db::startTrans();

        try {

            //判断收货地址

            $rs = AddrModel::field('id')
                ->where(['is_del' => CommonModel::$del_normal, 'id' => $data['addr_id'], 'uid' => self::$aid])
                ->findOrEmpty()
                ->isEmpty();
            if ($rs) throw new Exception('该地址不存在');


            //判断商品
            $rs = CompanyGoodModel::alias('a')
                ->field('a.id,a.good_id,b.good_code,b.good_name,b.status,b.moq,c.id inventory_id,c.inventory')
                ->leftJoin('good b', 'b.id=a.good_id AND b.is_del=' . CommonModel::$del_normal)
                ->leftJoin('inventory_exchange c', 'c.account_id=' . self::$aid . ' AND c.good_id=a.good_id')
                ->where(['a.is_del' => CommonModel::$del_normal, 'a.group_id' => self::$group_id, 'a.good_id' => $data['good_id']])
                ->findOrEmpty();

            if ($rs->isEmpty()) throw new Exception('该商品不存在或不允许兑换');
            if ($rs->status != CommonModel::$status_normal) throw new Exception('该商品已被禁用');
            if ($rs->moq > $data['num']) throw new Exception('不满足该商品的起订量,' . $rs->moq);
            if ($rs->inventory < $data['num']) throw new Exception('库存数不足');

            $date = date('Y-m-d H:i:s');

            $after_inventory = bcsub($rs->inventory, $data['num']);

            //添加库存变动记录
            Db::name('inventory_exchange_log')
                ->insert([
                    'inventory_exchange_id' => $rs->inventory_id,
                    'before_inventory' => $rs->inventory,
                    'after_inventory' => $after_inventory,
                    'good_id' => $rs->good_id,
                    'good_code' => $rs->good_code,
                    'good_name' => $rs->good_name,
                    'source' => CommonModel::$source_account,
                    'createrid' => self::$aid,
                    'creater' => self::$aname,
                    'addtime' => $date
                ]);

            //扣减库存
            InventoryExchangeModel::where('id', $rs->inventory_id)
                ->save(['inventory' => $after_inventory, 'updaterid' => self::$aid, 'updater' => self::$aname, 'updatetime' => $date]);

            //生成兑换订单
            OrderExchangeModel::create([
                'orderCode' => make_no('DH'),
                'company_id' => self::$company_id,
                'card_id' => self::$card_id,
                'uid' => self::$aid,
                'good_id' => $rs->good_id,
                'num' => $data['num'],
                'addr_id' => $data['addr_id'],
                'remark' => $data['remark'],
                'status' => CommonModel::$status_not_deliver,
                'is_del' => CommonModel::$del_normal,
                'creater' => self::$aname,
                'createrid' => self::$aid,
                'addtime' => $date,
                'updater' => self::$aname,
                'updaterid' => self::$aid,
                'updatetime' => $date,
            ])->save();

            Db::commit();

            return json_show(CommonModel::$success, '兑换商品成功');
        } catch (Exception $exception) {
            Db::rollback();
            return json_show(CommonModel::$error_param, '兑换失败,' . $exception->getMessage());
        }

    }

    //兑换订单列表
    public static function orderList(array $data = []): Json
    {
        $db = OrderExchangeModel::alias('a')
            ->leftJoin('good b', 'b.id=a.good_id AND b.is_del=' . CommonModel::$del_normal)
            ->where('a.is_del', CommonModel::$del_normal);

        if ($data['status'] != '') $db->where('a.status', $data['status']);

        $count = $db->count('a.id');

        $list = $db
            ->field('a.id,a.orderCode,b.good_name,a.num,a.status,a.addtime')
            ->page($data['page'], $data['size'])
            ->order('a.id', 'desc')
            ->select()
            ->toArray();

        return json_show(CommonModel::$success, '获取兑换订单列表成功', ['count' => $count, 'list' => $list]);

    }

    //兑换订单详情
    public static function orderInfo(int $id = 0): Json
    {
        $rs = OrderExchangeModel::alias('a')
            ->field('a.id,a.orderCode,a.status,a.addtime,b.good_name,a.num,c.contactor,c.mobile,c.addr,c.addr_code')
            ->leftJoin('good b', 'b.id=a.good_id AND b.is_del=' . CommonModel::$del_normal)
            ->leftJoin('addr c', 'c.id=a.addr_id AND c.is_del=' . CommonModel::$del_normal)
            ->where(['a.is_del' => CommonModel::$del_normal, 'a.id' => $id])
            ->withAttr('addr', function ($val, $da) {
                return $da['addr_code'] ? get_addr_name($da['addr_code']) . $val : $val;
            })
            ->findOrEmpty()
            ->toArray();

        return $rs ? json_show(CommonModel::$success, '获取兑换订单详情成功', $rs) : json_show(CommonModel::$error_param, '该订单不存在');

    }


}