<?php
declare (strict_types = 1);

namespace app\admin\controller\shop;

use app\common\controller\Backend;
use think\annotation\route\Group;
use app\admin\traits\Actions;
use think\annotation\route\Route;
use think\facade\Db;
use app\common\model\ShopDelivery as ShopDeliveryModel;

#[Group("shop/shop_delivery")]
class ShopDelivery extends Backend
{
    use Actions;

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new ShopDeliveryModel();
        $this->assign('platformList', site_config('addonsd.platform_list'));
        //,'shops', 'variety', 'specs'
        $this->relationField=['customer','user', 'shops'];
    }


    /**
     * 查看
     */
    #[Route('GET,JSON','index')]
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if($this->request->post('selectpage')){
            return $this->selectpage();
        }
        [$where, $order, $limit, $with] = $this->buildparams();
        $list = $this->model
            ->withJoin($with,'left')
            //如果没有使用operate filter过滤的情况下,推荐使用with关联，可以提高查询效率
            // ->with($with)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        // $list = $this->model
        //     ->alias('d')
        //     ->join('user u',"d.user_id = u.id", "LEFT")
        //     ->field('d.*,COALESCE(u.nickname, "无") as nickname')
        //     ->where($where)
        //     ->order($order)
        //     ->paginate($limit);

        //表格底部要有汇总：发货数量汇总  重量汇总 总价汇总
        $count = $this->model
            ->withJoin($with,'left')
            ->where($where)
            ->field('sum(num) total_num, sum(weigh) total_weigh, sum(total_price) total_price')
            // ->group('shop_delivery.id')
            ->select()
            ->toArray();

        $result = ['total' => $list->total(), 'rows' => $list->items(), 
        'total_num'    => $count[0]['total_num']??0, 
        'total_weigh'  => $count[0]['total_weigh']??0, 
        'total_price'  => $count[0]['total_price']??0];
        return json($result);
    }



    /**
     * 结算
     */
    #[Route('GET,POST','settlement')]
    public function settlement()
    {
       
        $ids =$this->request->post('ids/a', []);
        if(empty($ids)) return resp_json(0, '请选着要结算记录');
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->whereIn('id', $ids)->save(['status'=>$this->model::StatusSettlement]);
            if($this->callback){
                $callback=$this->callback;
                $callback($this->model);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('没有新增任何数据'));
        }
        return resp_json(200,'操作成功');
    }
}
