<?php

namespace App\Admin\Extensions\ToolBar\Forms\Shop;

use App\Models\Shop\ShopModule;
use App\Models\Shop\ShopProduct;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Alert;
use Dcat\Admin\Widgets\Form;

class EditProductForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function form()
    {
        $info = '1、只修改想要修改的项，不填则不会修改，批量修改要非常小心<br />2、仅修改商品，不修改SKU信息';
        $this->html(Alert::make($info, '注意事项')->warning());
        $this->disableResetButton();
        $this->textarea('product_ids', '已勾选商品ID')->attribute('id', 'batch-ids'); //批量选择的行的id通过隐藏元素 提交时一并传递过去
        $this->select('alipay_cat_id_origin', '选择类目')->attribute(['id' => 'alipay_cat_id_origin'])->help('同一个小程序的商品才能选择支付宝类目，不同小程序只能手动在下方填写支付宝类目编号');
        $this->text('alipay_cat_id', '支付宝类目')->attribute(['id' => 'alipay_cat_id']);
        Admin::script(<<<'JS'
            var productIds = $('#batch-ids').val();
            $.ajax({
                url: '/api/get-alipayitemcat',
                method: 'post',
                data: {product_ids: productIds},
                success: function(data) {
                    var select = $('#alipay_cat_id_origin');
                    select.empty(); // 清空select
                    select.append('<option value="">请选择...</option>');
                    $.each(data, function(cat_id, cat_name) {
                        var option = '<option value="' + cat_id + '">' + cat_name + '</option>';
                        select.append(option); // 添加到select
                    });
                }
            });
            $('#alipay_cat_id_origin').on('change', function() {
                    var sceneId = $('#alipay_cat_id_origin').val();
                    $('#alipay_cat_id').val(sceneId);
                });
        JS);
        $this->text('pre_title', '标题前缀')->width(6);
        $this->text('title', __('商品标题'))->width(6);
        $this->currency('crossed_price', __('划线价'))->symbol('￥')->width(6);
        $this->currency('mini_price', __('小程序价'))->symbol('￥')->width(6);
        $this->currency('mini_coup_price', __('券后价'))->symbol('￥')->width(6);
        $this->currency('delivery_fee', __('快递费'))->symbol('￥')->width(6);
        $this->text('remark', __('备注'));
        $this->number('point', '积分');
        $this->radio('edit_module', '是否绑定模块')
            ->when(1, function (Form $form) {
                $modMap = (new ShopModule())->getIdMap();
                $form->checkbox('module_ids', __('商品绑定模块'))->options($modMap);
            })
            ->options([
                1 => '修改',
                2 => '全部取消',
            ])
            ->default(1)->help('勾选了全部取消，则会取消掉商品中的模块绑定');
        $this->radio('edit_selling_tag', '导购标签')
            ->when(1, function (Form $form) {
                $form->checkbox('selling_tag', '导购标签')->options(ShopProduct::SELLING_TAG_MAP);
            })
            ->options([
                1 => '修改',
                2 => '全部取消',
            ])
            ->default(1)->help('勾选了全部取消，则会取消掉商品中的导购标签');
        $this->radio('edit_service_commitment', '修改服务承诺')
            ->when(1, function (Form $form) {
                $form->checkbox('service_commitment', '服务承诺')->options(ShopProduct::SERVICE_COMMITMENT_MAP);
            })
            ->options([
                1 => '修改',
                2 => '全部取消',
            ])
            ->default(1)->help('勾选了全部取消，则会取消掉商品中的服务承诺');
        $onlineStatus = ShopProduct::ROW_STATUS_ONLINE_MAP;
        // if (Admin::user()->isAdministrator()) {
        //     $onlineStatus = ShopProduct::ROW_STATUS_ONLINE_MAP;
        // }
        $this->select('row_status', __('小程序上架状态'))->options($onlineStatus)->width(6);
    }

    public function handle(array $input)
    {
        $productIds = $input['product_ids'];
        $productIdsArray = clean_ids($productIds, true);
        if (! $productIdsArray) {
            return $this->response()->error('请选择至少一个商品')->refresh();
        }
        $data = [];
        if ($input['alipay_cat_id']) {
            $data['alipay_cat_id'] = trim($input['alipay_cat_id']);
        }
        if ($input['title']) {
            $data['title'] = trim($input['title']);
        }
        if ($input['crossed_price']) {
            $data['crossed_price'] = yuan_2_fen($input['crossed_price']);
        }
        if ($input['mini_price']) {
            $data['mini_price'] = yuan_2_fen($input['mini_price']);
        }
        if ($input['mini_coup_price']) {
            $data['mini_coup_price'] = yuan_2_fen($input['mini_coup_price']);
        }
        if ($input['delivery_fee']) {
            $data['delivery_fee'] = yuan_2_fen($input['delivery_fee']);
        }
        if ($input['remark']) {
            $data['remark'] = $input['remark'];
        }
        if ($input['point']) {
            $data['point'] = $input['point'];
        }
        if ($input['row_status']) {
            $data['row_status'] = $input['row_status'];
        }
        // 模块ID，数组转化成','连接的字符串
        if ($input['module_ids'] && is_array($input['module_ids'])) {
            $moduleIds = implode(',', $input['module_ids']);
            $data['module_ids'] = strtolower($moduleIds);
        }
        if ($input['edit_module'] == 2) {
            $data['module_ids'] = '';
        }
        // 导购标签ID，数组转化成','连接的字符串
        if ($input['selling_tag'] && is_array($input['selling_tag'])) {
            $moduleIds = implode(',', $input['selling_tag']);
            $data['selling_tag'] = strtolower($moduleIds);
        }
        if ($input['edit_selling_tag'] == 2) {
            $data['selling_tag'] = '';
        }
        // 服务承诺ID，数组转化成','连接的字符串
        if ($input['service_commitment'] && is_array($input['service_commitment'])) {
            $moduleIds = implode(',', $input['service_commitment']);
            $data['service_commitment'] = strtolower($moduleIds);
        }
        if ($input['edit_service_commitment'] == 2) {
            $data['service_commitment'] = '';
        }
        if (! $data && ! $input['pre_title']) {
            return $this->response()->error('请至少修改一个内容');
        }
        if ($data) {
            $res = ShopProduct::whereIn('id', $productIdsArray)->update($data);
            if (! $res) {
                return $this->response()->error('批量修改商品失败')->refresh();
            }
        }
        // 为每个产品标题添加前缀
        if ($input['pre_title']) {
            $prefix = $input['pre_title'];
            $products = ShopProduct::whereIn('id', $productIdsArray)->get();
            foreach ($products as $product) {
                $product->title = $prefix.$product->title;
                $product->save();
            }
        }

        return $this->response()->success('批量修改商品成功')->refresh();
    }
}
