<?php
declare (strict_types = 1);

namespace app\admin\controller\shop;

use app\common\controller\Backend;
use app\admin\traits\Actions;
use think\annotation\route\Group;
use think\annotation\route\Route;
use app\common\model\StockConfig;
use think\facade\Db;
use app\common\model\ProductConfig;
use app\common\model\CustomerSpec as CustomerSpecModel;

#[Group("shop/customer_spec")]
class CustomerSpec extends Backend
{
    use Actions{
        index as private _index;
        add as private _add;
        edit as private _edit;
        del as private _del;
        multi as private _multi;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new CustomerSpecModel();
        $this->assign('typeList',  StockConfig::where('type_id', 'variety_name')->order('sort desc')->column('title','id'));
        $this->assign('packingList', StockConfig::where('type_id', 'packing_box')->column('title','id'));
        $this->relationField=['customer'];
    }

    //查看
    #[Route("GET,JSON","index")]
    public function index()
    {
        return $this->_index();
    }
  /**
     * 添加
     */
    #[Route('GET,POST','add')]
    public function add()
    {
        if (false === $this->request->isPost()) {

            $ids =$this->request->get('ids/d', 0);
            $rows = $this->model->where('customer_id', $ids)->where('status', 1)->select();
            $this->assign('ids', $ids);
            $this->assign('row', $rows);
            return $this->fetch();
        }
    
        $params = $this->request->post();
        if(empty($params['ids']) || count($params['all_data']) == 0) return resp_json(0,'请填写完整信息');
   
        $result = 0;
        Db::startTrans();
        try {
            //状态设置为0
            $this->model->where('customer_id', $params['ids'])->save(['status'=>0]);

            //然后根据选中的规格ID逐个判断是否存在，存在的更新状态、包装箱及发货价，不存在的则创建。 type_id
            foreach ($params['all_data'] as $item) {
                $row = $this->model
                    ->where('customer_id',$params['ids'])
                    ->where('type_id',$item['type_id'])
                    ->where('product_id',$item['value'])
                    ->findOrEmpty();
                if($row->isEmpty()){
                    $this->model->create([
                        'customer_id' => $params['ids'],
                        'type_id'     => $item['type_id'],
                        'product_id'  => $item['value'],
                        'box_id'      => $item['packet']??0,
                        'price'       => $item['price']??0,
                        'fast_mail'   => $item['fast_mail']??0

                    ]);
                    $result++;
                }else{
                    $row->box_id = $item['packet']??0;
                    $row->price  = $item['price']??0;
                    $row->fast_mail  = $item['fast_mail']??0;
                    $row->status  = 1;
                    $row->save();
                    $result++;
                }
            }
            if($this->callback){
                $callback=$this->callback;
                $callback($this->model);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        return resp_json(200,'操作成功');
    }

    //删除
    #[Route("GET,POST","del")]
    public function del()
    {
        //通过定义callback回调函数来执行删除后的操作
        $this->callback=function ($ids){};
        return $this->_del();
    }

    //更新
    #[Route("GET,POST","multi")]
    public function multi()
    {
        //通过定义callback回调函数来执行更新后的操作
        $this->callback=function ($ids,$field,$value){};
        return $this->_multi();
    }

    #[Route('GET','get_box')]
    public function get_box()
    {
        if($this->request->isAjax()){
            $type_id = $this->request->get('type_id/d', 0);
            if(empty($type_id)) return resp_json(0, '参数错误');
            $list = ProductConfig::where('type_id', $type_id)->order('sort desc')->field('id, title')->select();
            return json($list, 200);
        }
    }

}
