<?php
declare (strict_types = 1);

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use app\admin\traits\Actions;
use think\annotation\route\Group;
use think\annotation\route\Route;
use think\facade\Db;
use app\common\model\FengsuSku;
use app\common\model\ShopList;
use app\common\model\StockConfig;
use app\common\model\ShopDelivery;
use app\admin\service\FengsuService;
use app\common\model\CustomerSpec;
use app\common\model\ProductConfig;
use app\common\model\FengsuShip as FengsuShipModel;

#[Group("goods/fengsu_ship")]
class FengsuShip extends Backend
{
    //app\admin\controller\goods\FengsuShip
    use Actions{
        index as private _index;
        del as private _del;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new FengsuShipModel();
        $this->assign('shopList', ShopList::where('status', 1)->where('shop_id', '')->column('name','id'));
        $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'));
    }

    //查看
    #[Route("GET,JSON","index")]
    public function index()
    {
        return $this->_index();
    }

    /**
     * 关联店铺
     */
    #[Route('GET,POST','shops')]
    public function shops()
    {
        if (false === $this->request->isPost()) {
            $ids =$this->request->get('ids/s', '');
            return $this->fetch();
        }
        $params = array_merge($this->request->post("row/a"),$this->postParams);
        if (empty($params)) {
            $this->error(__('提交的参数不能为空'));
        }
        if(!$this->request->checkToken('__token__',['__token__'=>$this->request->post('__token__')])){
            $this->error(__('token错误，请刷新页面重试'));
        }
        foreach ($params as &$value){
            if(is_array($value)){
                $value=implode(',',$value);
            }
            if($value===''){
                $value=null;
            }
        }
        $ids =$this->request->get('ids/s', '');
        if(empty($params['shop_id'])) $this->error(__('请选择店铺'));
        $result = false;
        Db::startTrans();
        try {
            //更新店铺
            ShopList::where('id', $params['shop_id'])->update(['shop_id' => $ids]);
            //更新状态
            $result = $this->model->where('shop_id', $ids)->update(['status' => 2]);
            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(__('没有新增任何数据'));
        }
        $this->success();
    }

    /**
     * 关联规格
     */
    #[Route('GET,POST','specs')]
    public function specs(mixed $row=null)
    {
        $ids = $this->request->param('ids');
        if(!$row || is_array($row)){
            $row = $this->model->find($ids);
        }
        if (!$row) {
            $this->error(__('没有找到记录'));
        }
        if(count($this->volidateFields)>0){
            foreach ($this->volidateFields as $field=>$value){
                if($row[$field]!=$value){
                    $this->error(__('没有操作权限'));
                }
            }
        }
        if (false === $this->request->isPost()) {
            $this->assign('row', $row);
            return $this->fetch();
        }
        $params = $this->request->post("");
        if (empty($params['all_data'])) $this->error(__('请选择规格'));
        $count = 0;
        Db::startTrans();
        try {

            //插入规格
            FengsuSku::insertSpecs($row['shop_id'], $row['sku_id'], (int)$params['all_data'][0]['type_id'], (int)$params['all_data'][0]['id']);
            
            //查看有多少规格
            $list = $this->model::where('shop_id', $row['shop_id'])->where('sku_id', $row['sku_id'])->where('status', 2)->select();
            $shopList = new ShopList();
            $productConfig = new ProductConfig();
            $shopDelivery = new ShopDelivery();
            $customerSpec = new CustomerSpec();
            foreach ($list as $item) {
                //插入发货数据
                FengsuService::setAdditionalPrice(
                    $shopList,
                    $productConfig,
                    $shopDelivery,
                    $customerSpec,
                    $row['shop_id'],
                    $params['all_data'][0]['type_id'],
                    $params['all_data'][0]['id'],
                    $params['all_data'][0]['name'],
                    $row
                );

                $count += $item->save(['status' => 3]);
            }
            if($this->callback){
                $callback=$this->callback;
                $callback($ids);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($count) {
            return resp_json(200,'操作成功');
        }
        $this->error(__('没有数据被更新'));
    }


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

}
