<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\ProductAttrModel;
use app\admin\model\v1\ProductAttrPropModel;
use app\admin\validate\v1\ProductAttrValidate;

/**
 * 产品属性管理控制器
 */
class ProductAttr
{
    /**
     * 属性列表
     */
    public function index()
    {
        $params = request()->param([
            'keywords' => '',
            'page/d' => 1,
            'size/d' => 10
        ]);
        $attrs = ProductAttrModel::withoutField([
                'language_id',
                'created_at',
                'updated_at',
                'deleted_at',
            ])
            ->with(['props' => function ($query) {
                $query->withoutField(['created_at'])->hidden(['attr_id']);
            }])
            ->language(request()->lang_id)
            ->withSearch(['attr_name_nullable'], [
                'attr_name_nullable' => $params['keywords']??null,
            ]);
        if (!request()->has('scene')) {
            $attrs = $attrs->paginate([
                'list_rows' => $params['size'],
                'page'      => $params['page'],
            ]);
        } else if ('all' == request()->param('scene')) {
            $attrs = $attrs->select();
        }

        return success("获取成功", $attrs);
    }

    /**
     * 属性详情
     */
    public function read()
    {
        $id = request()->param('id');

        $attr = ProductAttrModel::withoutField([
                'language_id',
                'created_at',
                'updated_at',
                'deleted_at',
            ])
            ->with(['props' => function ($query) {
                $query->withoutField(['created_at'])->hidden(['attr_id']);
            }])
            ->find($id);
        if (empty($attr)) {
            return error("获取失败");
        }
        
        return success("获取成功", $attr);
    }

    /**
     * 属性新增
     */
    public function save()
    {
        $post = request()->post([
            'attr_type' => 1,
            'attr_name' => '',
            'is_system' => 0,
        ]);
        $attr = array_merge($post, ['language_id' => request()->lang_id]);

        // $[*].prop_name
        // $[*].prop_value
        $props = json_decode(request()->post('props/s', ''), true);

        // 检验参数
        $validate   = new ProductAttrValidate;
        $check_data = array_merge($attr, ['props' =>  $props]);
        if (!$validate->check($check_data)) {
            return error($validate->getError());
        }

        ProductAttrModel::startTrans();
        try {
            // 添加属性
            $attr_ret = ProductAttrModel::create($attr);
            if ($attr_ret->isEmpty()) {
                throw new \Exception("操作失败");
            }

            // 添加属性特征
            if (!empty($props)) {
                foreach ($props as &$prop) {
                    $prop['attr_id'] = $attr_ret->id;
                }
                unset($prop);
                $props_ret = (new ProductAttrPropModel)->saveAll($props);
                if ($props_ret->isEmpty()) {
                    throw new \Exception("操作失败");
                } 
            }

            ProductAttrModel::commit();
        } catch (\Throwable $th) {
            ProductAttrModel::rollback();
            return error($th->getMessage());
        }
        
       return success("操作成功");
    }

    /**
     * 属性更新
     */
    public function update()
    {
        $id  = request()->param('id');
        $put = request()->put([
            'attr_type', 
            'attr_name',
            'is_system' => 0,
        ]);
        $attr = array_merge($put, ['language_id' => request()->lang_id]);

        // $[*].prop_name
        // $[*].prop_value
        $props = json_decode(request()->post('props/s', ''), true);

        // 检验参数
        $validate   = new ProductAttrValidate;
        $check_data = array_merge($attr, ['id' => $id], ['props' =>  $props]);
        if (!$validate->check($check_data)) {
            return error($validate->getError());
        }

        ProductAttrModel::startTrans();
        try {
            // 更新属性
            $attr_ret = ProductAttrModel::bypk($id)->find();
            if ($attr_ret->isEmpty()) {
                throw new \Exception("请确认操作对象是否正确");
            }
            if (!$attr_ret->save($attr)) {
                throw new \Exception("操作失败");
            }

            // 删除旧属性特征
            ProductAttrPropModel::attrId($attr_ret->id)->delete();
            // 保存新属性特征
            foreach ($props as &$prop) {
                $prop['attr_id'] = $attr_ret->id;
            }
            unset($prop);
            $props_ret = (new ProductAttrPropModel)->saveAll($props);
            if ($props_ret->isEmpty()) {
                throw new \Exception("操作失败");
            }

            ProductAttrModel::commit();
        } catch (\Throwable $th) {
            ProductAttrModel::rollback();
            return error($th->getMessage());
        }
        
       return success("操作成功");
    }

    /**
     * 属性删除
     */
    public function delete()
    {
        $id = request()->param('id');

        // 删除属性
        $attr = ProductAttrModel::bypk($id)->find();
        if (empty($attr)) {
            return error("请确认操作对象是否正确");
        }
        if (!$attr->delete()) {
            return error("操作失败");
        }

        return success("操作成功");
    }
}
