<?php


namespace App\Form\Services;

use App\Services\CommonUserBaseService;
use App\Form\Facades\FormItemDetailFacade;

class FormItemService extends CommonUserBaseService
{
    const TYPE_RADIO = 200;
    const TYPE_CHECKBOX = 201;
    const TYPE_SELECT = 202;
    protected $cache = true;
    protected $cacheBucket = 'FormItem:';
    protected $tokenBucket = 'Token:';
    protected $activeBucket = "Active:";

    /**
     * 添加多项数据
     * @param $formId
     * @param array $items
     * @param null $userId
     * @return array
     */
    public function addList($formId, $items = [], $userId = null)
    {
        if (!empty($items)) {
            $sort = 1;
            foreach ($items as $k => $item) {
                $item['sort'] = $sort++;
                $item['id'] = $this->addData($formId, $item, $userId);
                if (!empty($item['content']) && is_array($item['content'])) {
                    $item['content'] = FormItemDetailFacade::addList($formId, $item['id'], $item['content'], $userId);
                }
                $items[$k] = $item;
            }
            $ids = array_column($items, 'id');
            $allIds = $this->getData($formId);
            $allIds = array_column($allIds, 'id');
            $delIds = array_diff($allIds, $ids);
            if (!empty($delIds)) {
                //删除已取消的数据
                $this->delData($formId, $delIds);
            }
        }
        return $items;
    }

    /**
     * 添加表单项数据
     * @param $formId
     * @param $item
     * @param null $userId
     * @return mixed
     */
    public function addData($formId, $item, $userId = null)
    {
        $userId = $userId ?? $this->getAuthUserId();
        $add = [];
        $add['form_id'] = $formId;
        if (isset($item['type'])) {
            $add['type'] = $item['type'];
        }
        if (isset($item['sort'])) {
            $add['sort'] = $item['sort'];
        }
        if (isset($item['name'])) {
            $add['name'] = $item['name'];
        }
        if (isset($item['is_required'])) {
            $add['is_required'] = empty($item['is_required']) ? '0' : $item['is_required'];
        }
        if (isset($item['is_email'])) {
            $add['is_email'] = empty($item['is_email']) ? '0' : '1';
        }
        if (isset($item['is_phone'])) {
            $add['is_phone'] = $item['is_phone'];
        }
        if (isset($item['is_url'])) {
            $add['is_url'] = $item['is_url'];
        }
        if (isset($item['is_min'])) {
            $add['is_min'] = $item['is_min'];
        }
        if (isset($item['is_max'])) {
            $add['is_max'] = $item['is_max'];
        }
        if (isset($item['min_val'])) {
            $add['min_val'] = $item['min_val'];
        }
        if (isset($item['max_val'])) {
            $add['max_val'] = $item['max_val'];
        }
        if (isset($item['status'])) {
            $add['status'] = $item['status'];
        }
        if (!empty($item['id']) && $item['id'] > 0) {
            $id = $item['id'];
            $this->model->where('id', '=', $id)->update($add);
        } else {
            $add['user_id'] = $userId;
            $id = $this->save($add)->id;
        }
        return $id;
    }

    /**
     * 获取表单项数据
     * @param $formId
     * @return array
     */
    public function getData($formId)
    {
        $map = [];
        $map['form_id'] = $formId;
        $map['status'] = $this->model::STATUS_ENABLED;
        $items = $this->model->buildQuery($map)
            ->selectRaw('id,form_id,type,sort,name,is_required,is_email,is_phone,is_url,is_min,is_max,min_val,max_val,is_code_valid,create_time')
            ->orderBy('sort', 'desc')
            ->get()->toArray();
        if (!empty($items)) {
            foreach ($items as &$item) {
                if ($item['type'] == self::TYPE_RADIO || $item['type'] == self::TYPE_CHECKBOX || $item['type'] == self::TYPE_SELECT) {
                    $itemDetail = FormItemDetailFacade::getData($formId, $item['id']);
                    if (!empty($itemDetail)) {
                        usort($itemDetail, function($a, $b) {
                            return $a['sort'] <=> $b['sort'];
                        });
                        $item['item_options'] = $itemDetail;
                    }
                }
            }
        }
        return $items;
    }

    /**
     * 删除数据
     * @param $formId
     * @param $itemId
     * @return bool
     */
    public function delData($formId, $itemId)
    {
        $map = [];
        $map['form_id'] = $formId;
        //删除整个表单项
        if (isset($itemId) && !empty($itemId)) {
            if (is_array($itemId)) {
                $map['id'] = [['in', $itemId]];
            } else {
                $map['id'] = $itemId;
            }
        }
        FormItemDetailFacade::delItemDetails($formId, $itemId);
        return $this->updateBy($map,
            ['status' => $this->model::STATUS_DELETED]
        );
    }

    /**
     * 排序
     * @param $ids
     * @return array|int
     */
    public function sortItem($ids)
    {
        $sort = 1;
        foreach ($ids as $id) {
            $this->updateBy([
                'id' => $id,
                'status' => $this->model::STATUS_ENABLED
            ], ['sort' => $sort++]);
        }
        return [
            'code' => 0,
            'msg' => '排序成功'
        ];
    }

    public function getItemsByFromId($fromId)
    {
        $data = $this->model->where(['form_id' => $fromId, 'status' => 0])->orderBy('sort')->get()->toArray();
        return $data;
    }

}
