<script setup>
import {ElNotification} from "element-plus";
import {resourceDelete, resourceList, resourcePost, resourcePut} from "@/api/resource.js";
import {ref, toRaw} from "vue";
import {useRoute} from 'vue-router';
import LocalCache from "@/stores/project.js";

const cachedResource = LocalCache.getCache("resource");

const listRsp = ref({fields_desc: [], rows: []})
const listDataOK = ref(false)
const resource_raw_node = cachedResource;
const resource_url = cachedResource.meta.resource_url;
const fieldsDescInfo = ref([])
const rows = ref([])
const rules = ref({})

const item = ref({
  id: 0,
  number: 1,
})

// console.log("enter table, resource:", cachedResource)

const listData = async () => {
  try {
    let listParams = {
      page_no: 0,
      page_len: 100,
    }
    // console.log("list params:", listParams)
    const rspData = await resourceList(resource_url, listParams);
    listRsp.value = rspData;
    if (listRsp.value.code !== 200) throw new Error("请求失败，错误码:", listRsp.code);
    fieldsDescInfo.value = listRsp.value.data.fields_desc
    rows.value = listRsp.value.data.rows


    for (let i = 0; i < fieldsDescInfo.value.length; i++) {
      var field = fieldsDescInfo.value[i]
      dialogAddForm.value[field.key] = ''
      if (field.required == true) {
        rules.value[field.key] = [{required: true, message: field.name + "不能为空", trigger: "blur"}]
      }

      if (field.type == "items") {
        for (let j = 0; j < rows.value.length; j++) {
          rows.value[j].jsonValue = JSON.stringify(rows.value[j][field.key])
        }
      }
    }

    // console.log('await list  rsp:', listRsp.value, fieldsDescInfo.value, toRaw(rows.value), toRaw(rules.value))

    listDataOK.value = true
  } catch (err) {
    console.log(err)
  } finally {

  }
}

onMounted(() => {
  listData();
})

const dialogAddVisible = ref(false)
const dialogEditVisible = ref(false)
const dialogAddFormRef = ref(null)
const dialogEditFormRef = ref(null)

const dialogAddForm = ref({
  ServerIDs: [],
})
const dialogEditForm = ref({})


const submitAdd = async () => {
  try {
    await dialogAddFormRef.value.validate(valid => {
      if (valid) {
        console.log("commit add form:", dialogAddForm.value)
        resourcePost(resource_url, dialogAddForm.value).then((res) => {
          ElNotification({
            title: "添加结果通知",
            message: "添加成功！",
            type: 'success',
            duration: 4000,
            "show-close": true,
          })
          rows.value.push(res.data.dto)
          dialogAddVisible.value = false
        }, (err) => {
          console.log("添加报错：", err)
        })
        console.log("提交数据：", dialogAddForm.value)
      }
    })
  } catch (error) {
    console.log("校验失败:", error)
  }
}

const submitEdit = async () => {
  try {
    await dialogEditFormRef.value.validate(valid => {
      if (valid) {
        resourcePut(resource_url, dialogEditForm.value).then((res) => {
          ElNotification({
            title: "编辑结果通知",
            message: "编辑成功！",
            type: 'success',
            duration: 4000,
            "show-close": true,
          })
          dialogEditVisible.value = false
          rows.value[dialogEditForm.value.oldIndex] = res.data.dto
        }, (err) => {
          console.log("添加报错：", err)
        })
        console.log("提交数据：", dialogEditForm.value)
      }
    })
  } catch (error) {
    console.log("校验失败:", error)
  }
}

const handleEdit = (index, row) => {
  dialogEditForm.value.oldData = row
  dialogEditForm.value.oldIndex = index
  dialogEditForm.value = row
  console.log("edit data:", row)
  dialogEditVisible.value = true
}

const handleDelete = (index, row) => {
  resourceDelete(resource_url, {id: row.ID}).then((res) => {
    ElNotification({
      title: "删除结果通知",
      message: "删除指令服务器[" + row.name + "]成功！",
      type: 'success',
      duration: 4000,
      "show-close": true,
    })
    rows.value.splice(index, 1)
  }, (err) => {
    console.log("delet error:", err)
  })
}

function addItem(fieldDescInfo) {
  if (item.value.id == null || item.value.id == '' || item.value.id < 0) {
    ElMessage('请选择道具！')
    return;
  }
  if (item.value.num == null || item.value.num == '' || item.value.num <= 0) {
    ElMessage('请输入有效道具数量！')
    return;
  }

  let d = {id: item.value.id, num: Number(item.value.num)};

  for (let i = 0; i < fieldDescInfo.choices.length; i++) {
    const field = fieldDescInfo.choices[i]
    if (field.value === item.value.id) {
      d.item_type = field.type
      break
    }
  }

  console.log("add item:", d)

  if (typeof dialogAddForm.value.Attach === typeof "") {
    dialogAddForm.value.Attach = [];
  }
  dialogAddForm.value.Attach.push(d);
}

function deleteItem(row) {
  // 移除该对象
  let number = form.value.Attach.findIndex(item => item === row);
  dialogAddForm.value.Attach.splice(number, 1);
}

const handleCloseDialog = () => {
  dialogAddVisible.value = false
  dialogEditVisible.value = false
  dialogAddForm.value = {
    Attach: [],
  }
  dialogEditForm.value = {}
}

</script>

<template>
  <el-container v-if="listDataOK">
    <el-header>
      <el-button @click="dialogAddVisible = true" size="large" type="primary"
                 v-if="(resource_raw_node.meta.methods.post === true)">
        添加
      </el-button>
    </el-header>
    <el-main>
      <el-table :data="rows" style="width: 100%" table-layout="auto" stripe>
        <template v-for="fieldDescInfo in fieldsDescInfo">
          <el-table-column prop="jsonValue" :label="fieldDescInfo.name"
                           v-if="(fieldDescInfo.type === 'items')"></el-table-column>
          <el-table-column :prop="fieldDescInfo.key" :label="fieldDescInfo.name"
                           v-else></el-table-column>
        </template>
        <el-table-column prop="func" label="功 能">
          <template #default="scope">

            <!--            <el-button size="default" type="primary"-->
            <!--                       @click="tableRowClick(row_click_btn1, scope.$index, scope.row)"-->
            <!--                       v-if="(row_click_btn1.text !== '')">-->
            <!--              <el-icon style="vertical-align: middle">-->
            <!--                <component :is="row_click_btn1.icon"></component>-->
            <!--              </el-icon>-->
            <!--              <span>{{ row_click_btn1.text }}</span>-->
            <!--            </el-button>-->

            <!--            <el-button size="default" type="primary"-->
            <!--                       @click="tableRowClick(row_click_btn2, scope.$index, scope.row)"-->
            <!--                       v-if="(row_click_btn2.text !== '')">-->
            <!--              <el-icon style="vertical-align: middle">-->
            <!--                <component :is="row_click_btn2.icon"></component>-->
            <!--              </el-icon>-->
            <!--              <span>{{ row_click_btn2.text }}</span>-->
            <!--            </el-button>-->

            <el-button size="default" type="success" @click="handleEdit( scope.$index, scope.row)"
                       v-if="(resource_raw_node.meta.methods.put === true)">
              <el-icon style="vertical-align: middle">
                <Edit/>
              </el-icon>
              <span>编辑</span>
            </el-button>
            <el-button size="default" type="danger" @click="handleDelete( scope.$index, scope.row)"
                       v-if="(resource_raw_node.meta.methods.delete === true)">
              <el-icon style="vertical-align: middle">
                <Delete/>
              </el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="dialogAddVisible" :mask="true" title="添加" :modal="true" :before-close="handleCloseDialog"
                 destroy-on-close>
        <el-form ref="dialogAddFormRef" :model="dialogAddForm" :rules="rules">
          <template v-for="fieldDescInfo in fieldsDescInfo">
            <!--如何是items类型，就是物品下拉框+道具组合-->
            <!--如何是[]string类型，就是下拉框或多选框-->
            <template v-if="(fieldDescInfo.type === 'items')">
              <el-form :inline="true" :model="item">
                <el-form-item :label="fieldDescInfo.name" :prop="fieldDescInfo.key">
                  <el-tooltip effect="light" :content="fieldDescInfo.help_text" placement="bottom-start">
                    <el-select placeholder="可选项" v-model="item.id" style="width: 150px">
                      <el-option v-for="info in fieldDescInfo.choices" :key="info.desc" :label="info.desc"
                                 :value="info.value"></el-option>
                    </el-select>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="数量" prop="number">
                  <el-input type="number" v-model="item.num" placeholder="请输入数量" style="width: 150px"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="addItem(fieldDescInfo)">添加</el-button>
                </el-form-item>
              </el-form>
              <el-form-item label="奖励列表" prop="attachmentsList">
                <el-table :data="dialogAddForm.Attach" border>
                  <el-table-column label="道具id" prop="id"/>
                  <el-table-column label="数量" prop="num"/>
                  <el-table-column label="操作">
                    <template #default="scope">
                      <el-button type="danger" size="small" @click="deleteItem(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </template>

            <template v-else-if="(fieldDescInfo.type === '[]string')">
              <el-form-item :label="fieldDescInfo.name" :prop="fieldDescInfo.key">
                <el-tooltip effect="light" :content="fieldDescInfo.help_text" placement="bottom-start">
                  <el-select placeholder="可选项" v-model="dialogAddForm.ServerIDs" style="width: 150px"
                             :multiple="(fieldDescInfo.multi_choice === true)">
                    <el-option v-for="info in fieldDescInfo.choices" :key="info.desc" :label="info.desc"
                               :value="info.value"></el-option>
                  </el-select>
                </el-tooltip>
              </el-form-item>
            </template>

            <template v-else-if="(fieldDescInfo.readonly !== true)">
              <el-form-item :label="fieldDescInfo.name" :prop="fieldDescInfo.key">
                <el-input v-model="dialogAddForm[fieldDescInfo.key]" :placeholder="fieldDescInfo.name"></el-input>
              </el-form-item>
            </template>

            <!--            <el-form-item :label="fieldDescInfo.name" :prop="fieldDescInfo.key">-->
            <!--              <el-tooltip effect="light" :content="fieldDescInfo.help_text" placement="bottom-start"-->
            <!--                          v-if="(fieldDescInfo.type === 'items')">-->
            <!--                <el-select placeholder="可选项">-->
            <!--                  <el-option v-for="info in fieldDescInfo.choices" :key="info.desc" :label="info.desc"-->
            <!--                             :value="info.value"></el-option>-->
            <!--                </el-select>-->
            <!--              </el-tooltip>-->
            <!--              <el-input v-model="dialogAddForm[fieldDescInfo.key]" :placeholder="fieldDescInfo.name" v-else></el-input>-->
            <!--            </el-form-item>-->
          </template>

          <el-button @click="submitAdd(dialogAddFormRef)" size="large" type="primary">提交</el-button>

        </el-form>
      </el-dialog>

      <el-dialog v-model="dialogEditVisible" :mask="true" title="编辑" :modal="true" :before-close="handleCloseDialog"
                 destroy-on-close>
        <el-form ref="dialogEditFormRef" :model="dialogEditForm" :rules="rules">
          <template v-for="fieldDescInfo in fieldsDescInfo">
            <el-form-item :label="fieldDescInfo.name" :prop="fieldDescInfo.key">
              <el-input v-model="dialogEditForm[fieldDescInfo.key]"></el-input>
            </el-form-item>
          </template>

          <el-form-item>
            <el-button @click="submitEdit(dialogEditFormRef)" size="large" type="primary">提交</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </el-main>
  </el-container>
</template>

<style scoped lang="scss">

</style>