<?php


namespace App\ExcelData\Services;


use App\Form\Facades\FormInfoFacade;
use App\Form\Facades\FormItemFacade;
use App\Form\Facades\FormRecordFacade;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithTitle;

class FormService implements FromArray, WithTitle, WithHeadings, WithMapping
{
    use Exportable;
    const DEFAULT_TITLE = 'sheet';

    protected $params;
    protected $title = '';
    protected $items = [];
    protected $heads = [];
    protected $website = [];
    protected $websiteLanguage = '';
    protected $reverseHead = [];
    protected $timeKey = '提交时间';
    protected $languageKey = '网站语言';

    /**
     * 设置参数
     * @param $params 详见: FormInfoFacade::getList
     * @return $this
     */
    public function setParams($params)
    {
        $this->params = $params;
        $title = '';
        $items = [];
        $heads = [];
        if (!empty($this->params['form_id'])) {
            $form = FormInfoFacade::findOneBy(['id' => $this->params['form_id']], 'id,name');
            if (!empty($form)) {
                $title = $form['name'] ?: self::DEFAULT_TITLE.$this->params['form_id'];
                //获取items
                $items =  FormItemFacade::getData($this->params['form_id']);
                empty($items) && $items = [];
                $heads = array_column($items, 'name');
                $heads = array_unique($heads);
                !empty($heads) && array_unshift($heads, $this->timeKey, $this->languageKey);
                //获取语言信息
                $this->websiteLanguage ='自定义表单';
            }
        }
        //超出31表单导不出
        if(strlen($title) > 31){
            $title = substr($title, -17).uniqid();
        }
        $this->title = $title;
        $this->items = mapByKey($items, 'id');
        $this->heads = $heads;
        !empty($heads) && $this->reverseHead = array_flip($heads);
        return $this;
    }

    /**
     * 查询query
     * @return \Illuminate\Database\Query\Builder
     */
    public function array():array
    {
        $items = FormRecordFacade::getList($this->params);
        FormRecordFacade::formatList($items);
        return $items;
    }

    /**
     * 标题
     * @return string
     */
    public function title(): string
    {
        return $this->title;
    }

    /**
     * 字段名
     * @return array
     */
    public function headings(): array
    {
        return $this->heads;
    }

    /**
     * 遍历数据
     * @param mixed $row
     * @return array
     */
    public function map($row): array
    {
        $defaultValue = '';
        $defaultGlue = ',';

        //根绝head排序数据，若为空，不进行处理
        $items = $row['items'];
        $data = [];
        $tmp = [];
        //设置提交时间
        $index = $this->reverseHead[$this->timeKey];
        $data[$index] = $row['create_time']?:'';
        //设置语言
        $index = $this->reverseHead[$this->languageKey];
        $data[$index] = $this->websiteLanguage;
        foreach ($items as &$item) {
            $id = $item['form_item_id'];
            is_array($item['content']) && $item['content'] = implode($defaultGlue, $item['content']);
            if (isset($this->items[$id])) {
                //获取在heads中的位置
                $name = $this->items[$id]['name'];
                $index = $this->reverseHead[$name];
                if (!empty($data[$index])) {
                    $data[$index] .= $defaultGlue.$item['content'];
                } else {
                    $data[$index] = $item['content'];
                }
            }
            $tmp[] = $item['content'];
        }

        if (empty($this->heads)) {
            return $tmp;
        }

        //默认值处理
        $returnData = [];
        foreach ($this->heads as $key => $v) {
            $returnData[] = $data[$key] ?? $defaultValue;
        }

        return $returnData;
    }
}
