<?php

namespace Tool\LoadTemplate\Tidy;

use Game\Constant\ConstTemplate\TemplateCar;
use Game\Constant\ConstTemplate\TemplateClothing;
use Game\Constant\ConstTemplate\TemplateGenerateAi;
use Game\Constant\ConstTemplate\TemplateItem;
use Game\Constant\TemplateDefine;
use Tool\LoadTemplate\ITidy;
use Tool\LoadTemplate\Util;

class GenerateAiTidy extends ITidy
{
    public function initTplInfo()
    {
        $this->oldTemplateType = TemplateDefine::TYPE_GENERATE_AI;
        $this->newTemplateType = TemplateDefine::TYPE_GENERATE_AI;
    }

    public function singleRowDeal($tpl): bool
    {
        $allItems = Util::getFormatArrayToSemicolon($tpl[TemplateGenerateAi::Dress]);
        $manCloth = $this->initClothData();
        $womenCloth = $this->initClothData();
        //检查服装
        foreach ($allItems as $itemId) {
            //检查是否为服装
            $configItemData = $this->getData( TemplateDefine::TYPE_ITEM, $itemId);
            if (is_null($configItemData) || $configItemData[TemplateItem::ItemType] != TemplateItem::ITEM_TYPE_CLOTH) {
                $this->addError("GenerateAi dress id error,id:".(string)$itemId);
                return false;
            }
            $configClothingData = $this->getData( TemplateDefine::TYPE_CLOTHING, $itemId);
            if (is_null($configClothingData)) {
                $this->addError("GenerateAi dress id error,id:".(string)$itemId);
                return false;
            }
            if ($configClothingData[TemplateClothing::Sex] == 1) {
                //男服装
                $manCloth[$configClothingData[TemplateClothing::Part] - 1][] = $itemId;
            } else {
                $womenCloth[$configClothingData[TemplateClothing::Part] - 1][] = $itemId;
            }
        }
        //赛车位置
        $carPosition = array(
            0 => $tpl[TemplateGenerateAi::Car]
        );
        foreach ($tpl[TemplateGenerateAi::Car] as $carId) {
            $carData = $this->getData(TemplateDefine::TYPE_CAR, $carId);
            $carPosition[$carData[TemplateCar::Positioning]][] = $carId;
        }
        //保存
        $data = $this->getData(TemplateDefine::TYPE_GENERATE_AI, $tpl[TemplateGenerateAi::Id]);
        foreach ($data as $key => $value) {
            $this->addDBArray($tpl[TemplateGenerateAi::Id], $key, $value);
        }
        $this->addDBArray(
            $tpl[TemplateGenerateAi::Id],
            TemplateGenerateAi::Dress,
            array(
                0 => $womenCloth,
                1 => $manCloth
                )
        );
        $this->addDBArray($tpl[TemplateGenerateAi::Id], TemplateGenerateAi::CAR_POSITION, $carPosition);
        return true;
    }

    private function initClothData(): array
    {
        return array_fill(0, 5, []);
    }
}
