<template>
  <div class="w-full h-full bg-white p-4">
    <p class="font-bold text-lg leading-10 border-b-2">脚本管理</p>
    <el-form class="pt-4" :inline="true" :model="formState">
      <el-form-item label="脚本名称">
        <el-input v-model="formState.title" placeholder="" />
      </el-form-item>
      <el-form-item label="脚本内容">
        <el-input v-model="formState.content" placeholder="" />
      </el-form-item>
      <el-form-item label="脚本说明">
        <el-input v-model="formState.mark" placeholder="" />
      </el-form-item>

      <el-form-item>
        <el-button type="default" @click="onReset">重置</el-button>
        <el-button type="primary" @click="onQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <div class="">
      <vxe-toolbar>
        <template #buttons>
          <!-- <vxe-button @click="allAlign = 'left'">居左</vxe-button> -->
          <el-button type="primary" @click="showEdit = true">新增</el-button>
          <el-button type="danger" @click="removeRows">删除</el-button>
          <el-button type="info" @click="showHelp">帮助</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        size="small"
        min-height="460"
        border
        :loading="loading"
        :data="tableData"
      >
        <vxe-column type="checkbox" width="50"></vxe-column>
        <vxe-column field="title" title="脚本名称" width="200px"></vxe-column>
        <vxe-column field="content" title="脚本内容" max-width="400px"></vxe-column>
        <vxe-column field="mark" title="脚本说明"></vxe-column>

        <vxe-column field="action" title="操作" width="80">
          <template #default="{ row }">
            <el-link type="primary" @click="editRow(row)">修改</el-link>
          </template>
        </vxe-column>
      </vxe-table>

      <vxe-pager
        size="small"
        background
        v-model:current-page="formState.currentPage"
        v-model:page-size="formState.pageSize"
        :total="formState.total"
        @page-change="onQuery"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
      >
      </vxe-pager>
    </div>

    <vxe-modal
      width="70%"
      height="90%"
      v-model="showEdit"
      title="编辑&保存"
      destroy-on-close
      esc-closable
      @hide="onHide"
      :top="50"
      show-footer
    >
      <template #default>
        <el-form ref="formRef" label-width="90px" :model="formEdit" :rules="formRules">
          <el-form-item label="脚本名称" prop="title">
            <el-input v-model="formEdit.title"> </el-input>
          </el-form-item>
          <el-form-item label="脚本内容" prop="content">
            <el-input type="textarea" rows="13" v-model="formEdit.content"></el-input>
            <el-button
              v-if="!visibleTest"
              class="mt-1"
              type="primary"
              size="small"
              @click="visibleTest = true"
              >测试</el-button
            >
          </el-form-item>
          <el-form-item label="测试内容" v-if="visibleTest" prop="cellValue">
            <el-row class="mt-1 w-full" :gutter="12">
              <el-col :span="8">
                <el-input
                  type="textarea"
                  rows="4"
                  v-model="formEdit.cellValue"
                  placeholder="请输入测试内容"
                ></el-input>
              </el-col>
              <el-col :span="8">
                <JsonEditorValue v-model="jsonStr" :options="editorOptions" />
              </el-col>
              <el-col :span="8" v-if="!!testResult.title">
                <el-alert v-bind="testResult" show-icon :closable="false" />
              </el-col>
            </el-row>
            <el-button class="mt-1" type="primary" size="small" @click="sendTest">执行</el-button>
          </el-form-item>
          <el-form-item label="脚本说明" prop="mark">
            <el-input type="textarea" rows="3" v-model="formEdit.mark"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" @click="onSubmit" :loading="saveLoading">提交</el-button>
        <el-button @click="showEdit = false">取消</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
import JsonEditorValue from 'json-editor-vue3'
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  getExcelScripts,
  addExcelScripts,
  editExcelScripts,
  deleteExcelScripts,
  testExcelScripts
} from '@/api/scripts'
import { ElMessage, type FormInstance } from 'element-plus'
import type { VxeTableInstance } from 'vxe-table'
import { apiGetScriptDesc, apiOrderVarGetVarField } from '@/api/common'
import {  useRouter } from 'vue-router'

const router = useRouter()
const visibleTest = ref(false)
const loading = ref(false)
const saveLoading = ref(false)
const showEdit = ref(false)
const formState = reactive({
  title: '',
  content: '',
  mark: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const formRef = ref<FormInstance>()
const xTable = ref<VxeTableInstance>()
const formRules = reactive({
  cellValue: [{ required: true, message: '请输入值', trigger: 'change' }],
  title: [{ required: true, message: '请输入脚本名称', trigger: 'change' }],
  content: [{ required: true, message: '请输入脚本内容', trigger: 'change' }]
})
const formEdit = reactive<Record<string, any>>({
  title: '',
  content: '',
  cellValue: '',
  mark: '',
  orders: []
})
const editorOptions = reactive({
  mode: 'code',
  history: false,
  search: false,
  mainMenuBar: false,
  navigationBar: false
})
const jsonStr = ref([{}])

const tableData = ref([])
const onHide = () => {
  // 重置表单
  Object.assign(formEdit, {
    scriptId: '',
    title: '',
    content: '',
    cellValue: '',
    mark: ''
  })

  // 重置测试结果
  visibleTest.value = false
  Object.assign(testResult, {
    title: '',
    description: ''
  })
}

const onReset = () => {
  Object.assign(formState, {
    title: '',
    content: '',
    mark: ''
  })
}

const editRow = (row) => {
  Object.assign(formEdit, row)
  showEdit.value = true
}

const testResult = reactive<any>({
  type: 'success',
  title: '',
  description: ''
})
const sendTest = async () => {
  try {
    await formRef.value?.validateField(['content', 'cellValue'])
    formEdit.orders = jsonStr.value instanceof Array ? jsonStr.value : [jsonStr.value]
    const res = await testExcelScripts(formEdit)
    if (res.data?.success) {
      // 创建一个测试成功的消息
      Object.assign(testResult, {
        type: 'success',
        title: '执行结果：',
        description: res.data.message
      })
    } else {
      // 创建一个测试失败的消息
      Object.assign(testResult, {
        type: 'error',
        title: '错误信息：',
        description: res.data.message
      })
    }
  } catch {}
}

const removeRows = async () => {
  const list = xTable.value?.getCheckboxRecords()
  if (list?.length) {
    const ids = list.map((item) => item.scriptId).join(',')
    await deleteExcelScripts(ids)
    ElMessage.success('删除成功！')
    onQuery()
  }
}
const showHelp = () => {
  router.push('/order/scripts-help')
}

// 表单提交
const onSubmit = async () => {
  await formRef.value?.validateField(['content', 'title'])
  saveLoading.value = true
  try {
    formEdit?.scriptId ? await editExcelScripts(formEdit) : await addExcelScripts(formEdit)
    ElMessage.success('操作成功！')
    showEdit.value = false
    onQuery()
  } catch {}
  saveLoading.value = false
}

const onQuery = async () => {
  loading.value = true
  try {
    const { data } = await getExcelScripts(formState)
    tableData.value = data.result.records
    formState.total = +data.result.total
  } catch {}
  loading.value = false
}


onMounted(() => {
  onQuery()
})
</script>
<style lang="scss" scoped></style>
