<template>
  <div class="system-edit-post-container">
    <el-form ref="formRef" :model="model" :rules="rules" size="default" label-width="80px">
      <el-card shadow="hover" :header="ModelTypeName[modelType]+'摊位配置'">
        <template #header>
          {{ModelTypeName[modelType]+'摊位配置'}} {{modelType}}
          <el-button v-show="item.show == false" @click="item.show = true" class="button-caret" type="text">
            <el-icon>
              <ele-CaretBottom/>
            </el-icon>
          </el-button>
          <el-button v-show="item.show == true" @click="item.show = false" class="button-caret" type="text">
            <el-icon>
              <ele-CaretTop/>
            </el-icon>
          </el-button>
        </template>
        <div v-show="item.show">
          <div class="flex-warp">
            <el-form-item label="摊位ID:" prop="stallId">
              <el-input v-model="model.stallId" placeholder="请输入摊位ID"
                        onkeyup="this.value=this.value.replace(/\D/g,'');"
                        onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
            </el-form-item>
            <span v-show="check&&!Number(model.stallId)" style="color: red">*</span>
            <el-form-item label="NPCID:" prop="NPCId">
              <el-select v-model="model.NPCId" placeholder="请选择" filterable>
                <el-option v-for="item in NPC" :key="item.Id" :label="item.Id+' '+item.Name" :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <span v-show="check&&!model.NPCId" style="color: red">*</span>
            <el-form-item label="规模:" prop="scale">
              <el-select v-model="model.scale" filterable placeholder="请输入规模">
                <el-option :key="-1" label="无" :value="-1"/>
                <el-option
                    v-for="item in Scale"
                    :key="item.Id"
                    :label="item.Id +' '+ item.ScaleName"
                    :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <span v-show="check&&!Number(model.scale)" style="color: red">*</span>
            <el-form-item label="村落条件:" prop="village">
              <el-select v-model="model.village" filterable placeholder="请输入村落条件">
                <el-option :key="-1" label="无" :value="-1"/>
                <el-option
                    v-for="item in Region"
                    :key="item.Id"
                    :label="item.Id +' '+ item.Region"
                    :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <span v-show="check&&!Number(model.village)" style="color: red">*</span>
            <el-form-item prop="renown" style="margin-left: -80px;width: 200px">
              <el-input v-model="model.renown" placeholder="请输入声望值"
                        onkeyup="this.value=this.value.replace(/\D/g,'');"
                        onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
            </el-form-item>
            <!--            <span v-show="check&&!model.renown" style="color: red">*</span>-->
            <el-form-item label="建筑条件:" prop="structure">
              <el-select v-model="model.structure" filterable placeholder="请输入建筑条件">
                <el-option :key="-1" label="无" :value="-1"/>
                <el-option
                    v-for="item in Structure"
                    :key="item.Id"
                    :label="item.Id +' '+ item.Name +' '+ item.LvMark+'级 '"
                    :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <span v-show="check&&!Number(model.structure)" style="color: red">*</span>
            <el-form-item label="种类数量:" prop="num">
              <el-input v-model="model.num" placeholder="请输入内容"
                        onkeyup="this.value=this.value.replace(/\D/g,'');"
                        onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
            </el-form-item>
            <span v-show="check&&!Number(model.num)" style="color: red">*</span>
          </div>
          <div class="flex-warp">
            <el-table :data="model.items" :inline="true" :cell-style="{padding:'0'}" :row-style="{height:'40px'}">
              <el-table-column width="30">
                <template #default="scope">
                  <el-button size="small" type="text" @click="delModelItem(scope.$index)">
                    <el-icon>
                      <ele-Minus/>
                    </el-icon>
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="物品名称" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.id" filterable placeholder="请选择物品" style="width: 90%">
                    <el-option v-for="item in ItemConfig" :key="item.Id" :label="item.Id +' '+ item.DetailsPageName"
                               :value="item.Id"/>
                  </el-select>
                  <span v-show="check&&!Number(scope.row.id)" style="color: red">*</span>
                </template>
              </el-table-column>
              <el-table-column label="物品数量区间(min;max)" width="250">
                <template #default="scope">
                  <el-input v-model="scope.row.numRangeMin" placeholder="请输入数量" style="width: 40%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  <span v-show="check&&!Number(scope.row.numRangeMin)" style="color: red">*</span>
                  ;
                  <el-input v-model="scope.row.numRangeMax" placeholder="请输入数量" style="width: 40%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  <span v-show="check&&!Number(scope.row.numRangeMax)" style="color: red">*</span>
                </template>
              </el-table-column>
              <el-table-column label="货币类型">
                <template #default="scope">
                  <el-select v-model="scope.row.currencyType" filterable placeholder="请选择货币类型" style="width: 80%">
                    <el-option v-for="item in currencyType" :key="item.Id" :label="item.Name" :value="item.Id"/>
                  </el-select>
                  <span v-show="check&&!Number(scope.row.currencyType)" style="color: red">*</span>
                </template>
              </el-table-column>
              <el-table-column label="权重">
                <template #default="scope">
                  <el-input v-model="scope.row.weight" placeholder="请输入权重" style="width: 80%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  <span v-show="check&&!Number(scope.row.weight)" style="color: red">*</span>
                </template>
              </el-table-column>
              <el-table-column label="价格">
                <template #default="scope">
                  <el-input v-model="scope.row.price" placeholder="请输入价格" style="width: 80%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  <span v-show="check&&!Number(scope.row.price)" style="color: red">*</span>
                </template>
              </el-table-column>
              <el-table-column label="折扣">
                <template #default="scope">
                  <el-input v-model="scope.row.discount" placeholder="请输入折扣" style="width: 80%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  <span style="margin: 10px 0">%</span>
                  <span v-show="check&&!scope.row.discount" style="color: red">*</span>
                </template>
              </el-table-column>
              <el-table-column label="折扣概率">
                <template #default="scope">
                  <el-input v-model="scope.row.discountProb" placeholder="请输入折扣概率" style="width: 80%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  <span style="margin:10px 0">%</span>
                  <span v-show="check&&!scope.row.discountProb" style="color: red">*</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #header>
                  <div class="flex-warp-item" style="float: right;">
                    <div class="flex-warp-item-box">
                      <el-button size="default" type="primary" @click="onQuickFillingModelItem()" v-waves>
                        快速复制
                      </el-button>
                    </div>
                    <span style="font-size: 8px">*全部使用第一行数据</span>
                  </div>
                </template>
                <template #default="scope">
                  <el-button size="small" type="text" @click="onCopyModelItem(scope.row)">复制</el-button>
                  <el-button size="small" type="text" @click="onPasteModelItem(scope.$index)">粘贴</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin: 10px 0">
              <el-button size="default" type="primary" @click="addModelItem()">
                <el-icon>
                  <ele-Plus/>
                </el-icon>
                添加
              </el-button>
            </div>
          </div>
          <el-form label-width="90px">
            <el-form-item label="摊位介绍:" prop="introduce">
              <el-input v-model="model.introduce" type="textarea" placeholder="请输入摊位介绍" style="width: 90%"/>
              <span v-show="check&&!model.introduce" style="color: red">*</span>
            </el-form-item>
            <el-form-item label="摊位名称:" prop="remark">
              <el-input v-model="model.remark" type="textarea" placeholder="请输入摊位名称" style="width: 90%"/>
              <span v-show="check&&!model.remark" style="color: red">*</span>
            </el-form-item>
          </el-form>
          <div style="justify-content: center">
            <el-button size="default" type="primary" class="ml10" @click="saveModel">
              <el-icon>
                <ele-RefreshRight/>
              </el-icon>
              保存配置
            </el-button>
          </div>
        </div>
      </el-card>

      <el-card shadow="hover" :header="ModelTypeName[modelType]+'配置记录'">
        <template #header>
          {{ModelTypeName[modelType]+'配置记录'}}
          <el-button v-show="item.listShow == false" @click="item.listShow = true" class="button-caret" type="text">
            <el-icon size="20">
              <ele-CaretBottom/>
            </el-icon>
          </el-button>
          <el-button v-show="item.listShow == true" @click="item.listShow = false" class="button-caret" type="text">
            <el-icon>
              <ele-CaretTop/>
            </el-icon>
          </el-button>
        </template>
        <div v-show="item.listShow">
          <el-form class="flex-warp" style="margin: 2px 0;">
            <el-form-item label="摊位ID:" prop="name">
              <el-input v-model="modelId" placeholder="请输入摊位ID" style="width: 100px"/>
              <el-button type="primary" @click="getModel" style="margin: 2px">查找</el-button>
            </el-form-item>
          </el-form>
          <div v-show="stalls.length == 0">暂无摊位配置</div>
          <div v-for="model in stalls">
            <el-form class="flex-warp">
              <el-divider style="margin: 4px 0;"></el-divider>
              <el-form-item prop="name" style="padding: 1px">
                摊位ID: {{model.StallId}},NPCID: {{model.NPCId?(NPC.find(r=>r.Id==model.NPCId)?NPC.find(r=>r.Id==model.NPCId).Name:model.NPCId):"无"}},规模条件:{{Scale.find(r=>r.Id==model.ScaleId)?
                (model.ScaleId+ " " + Scale.find(r=>r.Id==model.ScaleId).ScaleName): (model.ScaleId==-1?"无":"")}},
                村落条件:{{Region.find(r=>r.Id==model.VillageId)?
                (model.VillageId+ " " + Region.find(r=>r.Id==model.VillageId).Region):""}} {{model.Renown}},建筑条件:
                {{Structure.find(r=>r.Id==model.StructureId)?
                (model.StructureId+" "+Structure.find(r=>r.Id==model.StructureId).Name):""}},种类数量:{{model.Num}}
              </el-form-item>
              <el-table style="margin-top:-30px;" :data="model.Items" :row-style="{height:1+'px'}"
                        :cell-style="{padding:1+'px'}">
                <el-table-column label="物品名称">
                  <template #default="scope">
                    {{ItemConfig.find(r=>r.Id==scope.row.ItemId)?ItemConfig.find(r=>r.Id==scope.row.ItemId).DetailsPageName:''}}
                  </template>
                </el-table-column>
                <el-table-column label="物品数量区间(min;max)" width="200">
                  <template #default="scope">
                    {{scope.row.ItemNums[0]}};{{scope.row.ItemNums[1]}}
                  </template>
                </el-table-column>
                <el-table-column label="货币类型">
                  <template #default="scope">
                    {{currencyType.find(r=>r.Id==scope.row.CurrencyType)?currencyType.find(r=>r.Id==scope.row.CurrencyType).Name:""}}
                  </template>
                </el-table-column>
                <el-table-column label="权重">
                  <template #default="scope">
                    {{scope.row.Weight}}
                  </template>
                </el-table-column>
                <el-table-column label="价格">
                  <template #default="scope">
                    {{scope.row.Price}}
                  </template>
                </el-table-column>
                <el-table-column label="折扣">
                  <template #default="scope">
                    {{scope.row.Discount}}%
                  </template>
                </el-table-column>
                <el-table-column label="折扣概率">
                  <template #default="scope">
                    {{scope.row.DiscountProb}}%
                  </template>
                </el-table-column>
              </el-table>
              <div style="width: 9000px;margin: 10px 0;">
                摊位介绍: {{model.Introduce}}
                摊位名称:{{model.Remark}}
                <el-form-item style="float: right">
                  <el-button size="small" type="primary" @click="makeStall(model.Type, model.StringId)">修改</el-button>
                  <el-button size="small" type="danger" @click="delModel(model.StringId, model.StallId)">删除</el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
          <el-row justify="space-evenly">
            <el-pagination :hide-on-single-page="true" v-model:page-size="pageSize"
                           :pager-count="5" @current-change="handleCurrentChange" layout="total, prev, pager, next"
                           :total="stallTotal"/>
          </el-row>
        </div>
      </el-card>

      <el-dialog v-model="editModelVisible" width="90%" :show-close="false"
                 :header="ModelTypeName[modelType]+'摊位配置'"
                 :body-style="{backgroundColor:'#fff'}" style="background-color:#009999;" @close="destroyEditData">
        <template #header>
          {{ModelTypeName[modelType]+'摊位配置'}}
          <el-button v-show="item.show == false" @click="item.show = true"
                     style="float: right;min-width: 20px;height: 17px;line-height: 17px;color: white" type="text">
            <el-icon size="20">
              <ele-CaretBottom/>
            </el-icon>
          </el-button>
          <el-button v-show="item.show == true" @click="item.show = false"
                     style="float: right;min-width: 20px;height: 17px;line-height: 17px;color: white" type="text">
            <el-icon>
              <ele-CaretTop/>
            </el-icon>
          </el-button>
        </template>
        <div v-show="item.show">
          <div class="flex-warp">
            <el-form-item label="摊位ID:" prop="stallId">
              <el-input v-model="model.stallId" placeholder="请输入摊位ID" disabled
                        onkeyup="this.value=this.value.replace(/\D/g,'');"
                        onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
            </el-form-item>
            <el-form-item label="NPCID:" prop="NPCId">
              <el-select v-model="model.NPCId" placeholder="请选择" filterable>
                <el-option v-for="item in NPC" :key="item.Id" :label="item.Id+' '+item.Name" :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="规模条件:" prop="scale">
              <el-select v-model="model.scale" filterable placeholder="请输入村落条件">
                <el-option
                    v-for="item in Scale"
                    :key="item.Id"
                    :label="item.Id +' '+ item.ScaleName"
                    :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="村落条件:" prop="village">
              <el-select v-model="model.village" filterable placeholder="请输入村落条件">
                <el-option
                    v-for="item in Region"
                    :key="item.Id"
                    :label="item.Id +' '+ item.Region"
                    :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="renown" style="margin-left: -80px;width: 200px">
              <el-input v-model="model.renown" placeholder="请输入声望值"
                        onkeyup="this.value=this.value.replace(/\D/g,'');"
                        onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
            </el-form-item>
            <el-form-item label="建筑条件:" prop="structure">
              <el-select v-model="model.structure" filterable placeholder="请输入建筑条件">
                <el-option
                    v-for="item in Structure"
                    :key="item.Id"
                    :label="item.Id +' '+ item.Name +' '+ item.LvMark+'级 '"
                    :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="种类数量:" prop="num">
              <el-input v-model="model.num" placeholder="请输入内容"
                        onkeyup="this.value=this.value.replace(/\D/g,'');"
                        onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
            </el-form-item>
          </div>
          <div class="flex-warp">
            <el-table :data="model.items" :inline="true" :cell-style="{padding:'0'}" :row-style="{height:'40px'}">
              <el-table-column width="30">
                <template #default="scope">
                  <el-button size="small" type="text" @click="delModelItem(scope.$index)">
                    <el-icon>
                      <ele-Minus/>
                    </el-icon>
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="物品名称" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.id" filterable placeholder="请选择物品">
                    <el-option v-for="item in ItemConfig" :key="item.Id" :label="item.Id +' '+ item.DetailsPageName"
                               :value="item.Id"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="物品数量区间(min;max)" width="250">
                <template #default="scope">
                  <el-input v-model="scope.row.numRangeMin" placeholder="请输入数量" style="width: 40%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  ;
                  <el-input v-model="scope.row.numRangeMax" placeholder="请输入数量" style="width: 40%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                </template>
              </el-table-column>
              <el-table-column label="货币类型">
                <template #default="scope">
                  <el-select v-model="scope.row.currencyType" filterable placeholder="请选择货币类型">
                    <el-option v-for="item in currencyType" :key="item.Id" :label="item.Name" :value="item.Id"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="权重">
                <template #default="scope">
                  <el-input v-model="scope.row.weight" placeholder="请输入权重"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                </template>
              </el-table-column>
              <el-table-column label="价格">
                <template #default="scope">
                  <el-input v-model="scope.row.price" placeholder="请输入价格"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                </template>
              </el-table-column>
              <el-table-column label="折扣">
                <template #default="scope">
                  <el-input v-model="scope.row.discount" placeholder="请输入折扣" style="width: 80%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  <span style="margin: 10px 0">%</span>
                </template>
              </el-table-column>
              <el-table-column label="折扣概率">
                <template #default="scope">
                  <el-input v-model="scope.row.discountProb" placeholder="请输入折扣概率" style="width: 80%"
                            onkeyup="this.value=this.value.replace(/\D/g,'');"
                            onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
                  <span style="margin:10px 0">%</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #header>
                  <div class="flex-warp-item" style="float: right;">
                    <div class="flex-warp-item-box">
                      <el-button size="default" type="primary" @click="onQuickFillingModelItem()" v-waves>
                        快速复制
                      </el-button>
                    </div>
                    <span style="font-size: 8px">*全部使用第一行数据</span>
                  </div>
                </template>
                <template #default="scope">
                  <el-button size="small" type="text" @click="onCopyModelItem(scope.row)">复制</el-button>
                  <el-button size="small" type="text" @click="onPasteModelItem(scope.$index)">粘贴</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin: 10px 0">
              <el-button size="default" type="primary" @click="addModelItem()">
                <el-icon>
                  <ele-Plus/>
                </el-icon>
                添加
              </el-button>
            </div>
          </div>
          <el-form label-width="90px">
            <el-form-item label="摊位介绍:" prop="introduce">
              <el-input v-model="model.introduce" type="textarea" placeholder="请输入摊位介绍"/>
            </el-form-item>
            <el-form-item label="摊位名称:" prop="remark">
              <el-input v-model="model.remark" type="textarea" placeholder="请输入摊位名称"/>
            </el-form-item>
          </el-form>
          <div style="width: 100%;display: flex;justify-content: space-between;padding: 0 50px;">
            <el-button size="default" type="success" @click="destroyEditData">
              <el-icon>
                <ele-Close/>
              </el-icon>
              取消修改
            </el-button>
            <el-button size="default" type="primary" @click="saveModel">
              <el-icon>
                <ele-RefreshRight/>
              </el-icon>
              保存修改
            </el-button>
          </div>
        </div>
      </el-dialog>

    </el-form>
  </div>
</template>
<script lang="ts">
  import {reactive, toRefs, defineComponent, ref, unref, onMounted} from 'vue';
  import {
    gameGMDelModel,
    gameGMUpdateModel,
    gameGMInsertModel,
    gameGMGetModel
  } from '/@/api/game';
  import AllItemConfigCategory from "/@/api/config/AllItemConfigCategory.json";
  import StructureConfigCategory from "/@/api/config/StructureConfigCategory.json";
  import RegionConfigCategory from "/@/api/config/RegionConfigCategory.json";
  import ScaleConfigCategory from "/@/api/config/ScaleConfigCategory.json";
  import NpcConfigCategory from "/@/api/config/NpcConfigCategory.json";
  import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
  import type {Action} from 'element-plus'
  import {MODEL_TYPE, MODEL_TYPE_NAME} from "/@/api/common/consts";

  interface TableDataState{
    model: object;
    Scale: object[];
    Region: object[];
    Structure: object[];
    ItemConfig: object;
    currencyType: object;
    rules: object;
    dbs: object[];
    stallDbs: object[];
    stalls: object[];
    modelItem: object;
    listModelVisible: boolean;
    editModelVisible: boolean;
    modelType: number;
    stallTotal: number;
    modelId: number;
    page: number;
    check: boolean;
    pageSize: number;
    item: object;
    NPC: object;
  }

  export default defineComponent({
    name: 'systemGameMarketSellModel',
    setup: function(){
      const formRef = ref<HTMLElement|null>(null);
      const menuRef = ref();
      const state = reactive<TableDataState>({
        ModelType: MODEL_TYPE,
        ModelTypeName: MODEL_TYPE_NAME,
        check: false,
        model: {
          stallId: 1,
          scale: -1,
          village: -1,
          structure: -1,
        },
        item: {show: true, listShow: true},
        Region: RegionConfigCategory,
        Structure: StructureConfigCategory,
        Scale: ScaleConfigCategory,
        listModelVisible: false,
        editModelVisible: false,
        modelType: 0,
        stallTotal: 0,
        stallDbs: [{type: 1}, {type: 2}],
        stalls: [],
        dbs: [],
        ItemConfig: AllItemConfigCategory,
        currencyType: [{Id: 1, Name: "铜币"}, {Id: 2, Name: "桃花石"}],
        rules: {},
        modelItem: {},
        modelId: "",
        page: 0,
        pageSize: 5,
        NPC: NpcConfigCategory.filter((r: {Type: number;}) => r.Type == 4),
      });

      onMounted(() => {
        getDBModel();
      });
      var getDBModel = () => {
        gameGMGetModel({mType: 0}).then((res) => {
          console.log("gameGMGetModel: ", res);
          state.stallDbs = res.data.model;
          listStall(MODEL_TYPE.sell);
        }).finally(() => {
        });
      };
      var listStall = (type: number) => {
        if(state.stallDbs) state.stallDbs.sort((a, b) => {
          return a.StallId < b.StallId ? -1:1;
        });
        if(!type){
          return
        }
        state.listModelVisible = true;
        state.modelType = type;
        if(state.stallDbs){
          state.stalls = state.stallDbs.filter(r => r.Type == type);
          state.stallTotal = state.stalls.length;
          state.stalls = state.stalls.slice(state.page * state.pageSize, (state.page + 1) * state.pageSize);
          let id = 0;
          for(let i in state.stallDbs){
            if(state.stallDbs[i].StallId > id){
              id = state.stallDbs[i].StallId;
            }
          }
          state.model.stallId = id + 1;
        }
        console.log(state.stalls, state.page, (state.page + 1) * state.pageSize);
      };
      var makeStall = (type: number, id: string) => {
        state.editModelVisible = true;
        state.modelType = type;
        state.model = {
          stallId: 1,
          scale: -1,
          village: -1,
          structure: -1,
        };
        if(!id){
          return;
        }
        let model = state.stallDbs.find(r => r.StringId == id);
        if(model){
          describeModel(model);
        }
      };
      var getModel = () => {
        if(state.modelId){
          state.stalls = state.stallDbs.filter(r => r.StallId == state.modelId && r.Type == state.modelType);
          state.stallTotal = state.stalls.length;
          return;
        }
        state.stalls = state.stallDbs.filter(r => r.Type == state.modelType);
        state.stallTotal = state.stalls.length;
      };
      var delModel = (id: number, stallId: number) => {
        ElMessageBox.alert('是否确认删除该配置？', '提示', {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          callback: (action: Action) => {
            if (action == "confirm"){
              gameGMDelModel({id: id, stallId: stallId}).then(() => {
                gameGMGetModel({mType: 0}).then((res) => {
                  console.log("gameGMGetModel: ", res);
                  state.stallDbs = res.data.model;
                  listStall(state.modelType);
                }).finally(() => {
                });
                ElMessage({
                  type: 'success',
                  message: `删除成功`,
                })
              }).finally(() => {
              });
            }
          },
        })
      };
      var saveModel = () => {
        const loading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
        });
        state.check = true;
        let model = dbModel();
        if(!model.Items || !model.Introduce || !model.Num || !model.Remark
            || !model.StallId || !model.ScaleId || !model.StructureId || !model.VillageId || !model.Type){
          ElMessage.error("保存失败，请检查表单是否填写完整");
          loading.close();
          return;
        }
        for(let i in model.Items){
          let item = model.Items[i];
          if(!item.CurrencyType || (!item.Discount && item.Discount != 0) || (!item.DiscountProb && item.DiscountProb != 0) || !item.ItemId || !item.ItemNums || !item.Price
              || !item.Weight || !item.Weight || item.ItemNums.length < 2){
            ElMessage.error("保存失败，请检查表单是否填写完整");
            loading.close();
            return;
          }
        }
        state.editModelVisible = false;
        if(state.model._id){
          gameGMUpdateModel({model: model}).then(() => {
            let index = state.stallDbs.findIndex(r => r._id == model._id);
            state.stallDbs.splice(index, 1, model);
            model.StringId = state.model._id;
            console.log(model, index);
            state.check = false;
            state.model = {
              stallId: 1,
              scale: -1,
              village: -1,
              structure: -1,
            };
            listStall(state.modelType);
            ElMessage({
              type: 'success',
              message: `更新成功`,
            });
          }).finally(() => {
            loading.close();
          })
        }else{
          gameGMInsertModel({model: model}).then(() => {
            gameGMGetModel({mType: 0}).then((res) => {
              console.log("gameGMGetModel: ", res);
              state.stallDbs = res.data.model;
              state.check = false;
              state.model = {
                stallId: 1,
                scale: -1,
                village: -1,
                structure: -1,
              };
              listStall(state.modelType);
              ElMessage({
                type: 'success',
                message: `添加成功`,
              })
            })
          }).finally(() => {
            loading.close();
          });
        }
      };
      var dbModel = () => {
        let items = [];
        for(let i in state.model.items){
          let item = state.model.items[i];
          if(item){
            items.push({
              ItemId: Number(item.id),
              ItemNums: [Number(item.numRangeMin), Number(item.numRangeMax)],
              CurrencyType: Number(item.currencyType),
              Weight: Number(item.weight),
              Price: Number(item.price),
              Discount: Number(item.discount),
              DiscountProb: Number(item.discountProb)
            })
          }
        }
        let model = {
          _id: state.model._id,
          StallId: Number(state.model.stallId),
          NPCId: Number(state.model.NPCId),
          VillageId: Number(state.model.village),
          ScaleId: Number(state.model.scale),
          Renown: Number(state.model.renown),
          StructureId: Number(state.model.structure),
          Num: Number(state.model.num),
          Items: items,
          Introduce: state.model.introduce,
          Remark: state.model.remark,
          Type: state.modelType
        };

        return model
      };
      var describeModel = (stall: any) => {
        state.modelType = stall.Type;
        state.model = {
          _id: stall.StringId,
          items: [],
          stallId: stall.StallId,
          NPCId: stall.NPCId,
          scale: stall.ScaleId || -1,
          village: stall.VillageId || -1,
          structure: stall.StructureId || -1,
          renown: stall.Renown,
          num: stall.Num,
          introduce: stall.Introduce,
          remark: stall.Remark,
          mType: stall.Type
        };
        for(let i in stall.Items){
          let item = stall.Items[i];
          if(item){
            state.model.items.push({
              id: item.ItemId,
              numRangeMin: item.ItemNums[0],
              numRangeMax: item.ItemNums[1],
              currencyType: item.CurrencyType,
              weight: item.Weight,
              price: item.Price,
              discount: item.Discount,
              discountProb: item.DiscountProb
            })
          }
        }
      };
      var delModelItem = (index: number) => {
        state.model.items.splice(index, 1);
      };
      var onQuickFillingModelItem = () => {
        for(let i = 1; i < state.model.items.length; i++){
          state.model.items[i].id = state.model.items[0].id;
          state.model.items[i].currencyType = state.model.items[0].currencyType;
          state.model.items[i].numRangeMin = state.model.items[0].numRangeMin;
          state.model.items[i].numRangeMax = state.model.items[0].numRangeMax;
          state.model.items[i].weight = state.model.items[0].weight;
          state.model.items[i].price = state.model.items[0].price;
          state.model.items[i].discount = state.model.items[0].discount;
          state.model.items[i].discountProb = state.model.items[0].discountProb;
        }
      };
      var onCopyModelItem = (modelItem: any) => {
        state.modelItem = modelItem;
        console.log("onCopyModelItem", state.modelItem);
      };
      var onPasteModelItem = (index: number) => {
        if(!state.modelItem){
          console.log("onPasteModelItem", state.modelItem);
          return;
        }
        state.model.items[index].id = state.modelItem.id;
        state.model.items[index].currencyType = state.modelItem.currencyType;
        state.model.items[index].numRangeMin = state.modelItem.numRangeMin;
        state.model.items[index].numRangeMax = state.modelItem.numRangeMax;
        state.model.items[index].weight = state.modelItem.weight;
        state.model.items[index].price = state.modelItem.price;
        state.model.items[index].discount = state.modelItem.discount;
        state.model.items[index].discountProb = state.modelItem.discountProb;
      };
      var addModelItem = () => {
        if(!state.model.items){
          state.model.items = [];
        }
        state.model.items.push({});
      };
      const handleCurrentChange = (val: number) => {
        console.log(`current page: ${val}`);
        state.page = val - 1;
        listStall(state.modelType);
      };
      const destroyListData = () => {
        state.page = 0;
        state.modelType = 0;
        state.modelId = "";
        state.stalls = [];
        state.stallTotal = 0;
      };
      const destroyEditData = () => {
        state.model = {};
        state.editModelVisible = false;
      };
      const onTableRowClassName = ({row, rowIndex}) => {
        console.log("onTableRowClassName", row, rowIndex);
        if(row.Day % 2 == 0 || row.day % 2 == 0){
          return 'warning-row';
        }else{
          return '';
        }
      };
      return {
        menuRef,
        formRef,
        listStall,
        getModel,
        makeStall,
        saveModel,
        delModelItem,
        onQuickFillingModelItem,
        onCopyModelItem,
        onPasteModelItem,
        addModelItem,
        delModel,
        getDBModel,
        handleCurrentChange,
        destroyListData,
        destroyEditData,
        onTableRowClassName,
        ...toRefs(state),
      };
    },
  });
</script>

<style scoped lang="scss">
  .el-table {
    --el-table-border-color: var(--el-border-color-lighter);
    --el-table-border: 0px solid var(--el-table-border-color);
  }

  .el-table .el-table__cell {
    padding: 0;
    min-width: 0;
    box-sizing: border-box;
    text-overflow: ellipsis;
    vertical-align: middle;
    position: relative;
    text-align: left;
    z-index: 1;
  }

  .tree-border {
    margin-top: 5px;
    border: 1px solid #e5e6e7 !important;
    background: #fff none !important;
    border-radius: 4px;
  }

  .system-edit-post-container {
    .menu-data-tree {
      border: var(--el-input-border, var(--el-border-base));
      border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
      padding: 5px;
    }
  }

  .editable-cell__input {
    display: inline;
    width: 10%;

    .el-input__inner {
      padding: 0 8px;
      font-size: 12px;
    }
  }

  .table-item {
    margin-top: 10px;
    margin-bottom: -10px;
  }

  .left-block {
    margin-left: -20px;
  }

  .table-num-left {
    margin-left: -80px;
  }

  .num-left {
    margin-left: -30px;
  }

  .table-item {
    margin-top: 10px;
    margin-bottom: -10px;
  }

  .title-label-block {
    margin-left: -20px;
  }

  .label-block {
    padding-left: 10px;
  }

  .box-card .el-card__header {
    background-color: #409EFF;
    color: #fff;
  }

  .change-icon {
    font-size: 20px;
  }


  ::v-deep .warning-row {
    background: #ffffd5;
  }

  ::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
    background: #ffffd5;
  }

  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: inherit;
  }
</style>
