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

const props = defineProps({
  // rows: {},
  resource_url: '',
  row_click_handler: null,
})

const listRsp = ref({fields_desc: [], rows: []})
const getListOk = ref(false)
const resource_url = props.resource_url
const fieldsDescInfo = ref([])
const rows = ref([])
const rules = ref({})

const listData = async () => {
  try {
    const rspData = await resourceList(resource_url, {page_no: 0, page_len: 100});
    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.require == true) {
        rules.value[field.key] = [{required: true, message: field.name + "不能为空", trigger: "blur"}]
      }
    }

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

    getListOk.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({})
const dialogEditForm = ref({})


const submitAdd = async () => {
  try {
    await dialogAddFormRef.value.validate(valid => {
      if (valid) {
        resourcePost(resource_url, dialogAddForm.value).then((res) => {
          ElNotification({
            title: "添加结果通知",
            message: "添加成功！",
            type: 'success',
            duration: 4000,
            "show-close": true,
          })
          rows.value.push(dialogAddForm.value)
          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 = (oper, index, row) => {
  dialogEditForm.value.oldData = row
  dialogEditForm.value.oldIndex = index
  dialogEditForm.value = row
  console.log("edit data:", row)
  dialogEditVisible.value = true
}

const handleDelete = (oper, 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)
  })
}

const tableRowClick = (index, row) => {
  console.log("row is clicked:", row)
  if (props.row_click_handler != null) {
    props.row_click_handler(row)
  }
}

const handleCloseDialog = () => {
  dialogAddVisible.value = false
  dialogEditVisible.value = false
  dialogAddForm.value = {}
  dialogEditForm.value = {}
}

</script>

<template>
  <el-container v-if="getListOk">
    <el-header>
      <el-button @click="dialogAddVisible = true" size="large" type="primary">添加</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="fieldDescInfo.key" :label="fieldDescInfo.name"></el-table-column>
        </template>
        <el-table-column prop="func" label="功 能">
          <template #default="scope">
            <el-button size="large" type="primary" @click="tableRowClick(scope.$index, scope.row)">
              <el-icon style="vertical-align: middle">
                <ArrowRightBold/>
              </el-icon>
              <span>进入</span>
            </el-button>
            <el-button size="large" type="success" @click="handleEdit('operation', scope.$index, scope.row)">
              <el-icon style="vertical-align: middle">
                <Operation/>
              </el-icon>
              <span>编辑</span>
            </el-button>
            <el-button size="large" type="danger" @click="handleDelete('operation', scope.$index, scope.row)">
              <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">
            <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>
            <el-button @click="submitAdd(dialogAddFormRef)" size="large" type="primary">提交</el-button>
          </el-form-item>
        </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>

</style>