<template>
  <div class="app-container">

    <TableSearch
        :queryParams="queryParams"
        :showSearch="showSearch"
        queryRef="queryRef"
        @refresh="resetQuery"
        @search="handleQuery"
    >
      <template #one>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="厂商" prop="manufacturer">
            <el-input
                v-model="queryParams.manufacturer"
                clearable
                placeholder="请输入厂商"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="车型" prop="vehType">
            <el-input
                v-model="queryParams.vehType"
                clearable
                placeholder="请输入车型"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </template>

    </TableSearch>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:vehOper:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:vehOper:edit']"
            :disabled="single"
            icon="Edit"
            plain
            type="success"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:vehOper:remove']"
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            v-hasPermi="['system:vehOper:export']"-->
      <!--            icon="Download"-->
      <!--            plain-->
      <!--            type="warning"-->
      <!--            @click="handleExport"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vehOperList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <!--      <el-table-column align="center" label="配置ID" prop="configId"/>-->
      <el-table-column align="center" label="厂商" prop="manufacturer" show-overflow-tooltip/>
      <el-table-column align="center" label="车型" prop="vehType" show-overflow-tooltip/>
      <!--      <el-table-column label="json文件数据" align="center" prop="jsonData" />-->
      <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template #default="scope">
          <el-button v-hasPermi="['system:vehOper:edit']" icon="Edit" link type="primary"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-hasPermi="['system:vehOper:remove']" icon="Delete" link type="primary"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 添加或修改车机操作配置对话框 -->
    <el-drawer v-model="open" :size="650" :title="title" append-to-body @close="cancel">
      <el-form ref="vehOperRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="厂商" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入厂商"/>
        </el-form-item>
        <el-form-item label="车型" prop="vehType">
          <el-input v-model="form.vehType" placeholder="请输入车型"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark"  placeholder="请输入备注"
                    type="textarea" :autosize="{ minRows: 2, maxRows: 2 }"/>
        </el-form-item>
        <el-form-item label="JSON数据" prop="jsonData">
          <div style="
          width: 100%;
          display: flex;
          justify-content: flex-end;
          border-bottom: 1px solid #E9E9E9;
          padding-bottom: 5px;"
          >
            <el-button size="small" @click="jsonFormat">格式化</el-button>
          </div>
          <v-ace-editor v-model:value="jsonStr"
                        :lang="language"
                        :options="editorOptions"
                        :readonly="false"
                        :theme="theme"
                        style="height: calc(100vh - 340px); width: 100%;"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script name="VehOper" setup>
import {addVehOper, delVehOper, getVehOper, listVehOper, updateVehOper} from "@/api/system/vehOper"
import {VAceEditor} from 'vue3-ace-editor';
import 'ace-builds/src-noconflict/mode-javascript'; // 引入 JavaScript 模式支持
import 'ace-builds/src-noconflict/theme-github';
import {ElMessage} from "element-plus";
import TableSearch from "@/components/TableSearch/index.vue";

const language = ref('javascript'); // 设置默认语言为 JavaScript
const theme = ref('github'); // 设置默认主题为 GitHub 风格

// 编辑器的配置选项，如字体大小、是否显示打印边距等
const editorOptions = ref({
  fontSize: '14px', // 设置字体大小
  showPrintMargin: false, // 是否显示打印边距
  enableLiveAutocompletion: true, // 启用实时自动补全功能
});

const jsonStr = ref("")
const jsonError = (e) => {
  console.log(e.message)
  //Uncaught SyntaxError: Unexpected token o in JSON at position 1
  if (e.message.includes("is not valid JSON")) {
    ElMessage.error("未识别JSON，请检查")
    return
  }
  //Expected double-quoted property name in JSON at position 13 (line 2 column 12)
  if (e.message.includes("at position")) {
    const line = parseInt(e.message.match(/line (\d+)/)[1])
    ElMessage.error(`第 ${line} 行上下文存在格式错误，请检查`)
  }
}

const jsonFormat = () => {
  try {
    jsonStr.value = JSON.stringify(JSON.parse(jsonStr.value), null, 4)
    ElMessage.success("格式化成功")
  } catch (e) {
    jsonError(e)
  }
}

const {proxy} = getCurrentInstance()

const vehOperList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manufacturer: null,
    vehType: null,
    jsonData: null,
  },
  rules: {
    manufacturer: [
      {required: true, message: "厂商数据不能为空", trigger: "blur"}
    ],
    vehType: [
      {required: true, message: "车型数据不能为空", trigger: "blur"}
    ],
  }
})

const {queryParams, form, rules} = toRefs(data)

/** 查询车机操作配置列表 */
function getList() {
  loading.value = true
  listVehOper(queryParams.value).then(response => {
    vehOperList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  jsonStr.value = ""
  reset()
}

// 表单重置
function reset() {
  form.value = {
    // configId: null,
    // manufacturer: null,
    // vehType: null,
    // jsonData: null,
    // createBy: null,
    // createTime: null,
    // updateBy: null,
    // updateTime: null,
    // remark: null
  }
  proxy.resetForm("vehOperRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.configId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加车机操作配置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _configId = row.configId || ids.value
  getVehOper(_configId).then(response => {
    form.value = response.data
    jsonStr.value = response.data.jsonData
    open.value = true
    title.value = "修改车机操作配置"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["vehOperRef"].validate(valid => {
    if (valid) {
      if (form.value.configId != null) {
        updateVehOper({
          configId: form.value.configId,
          manufacturer: form.value.manufacturer,
          vehType: form.value.vehType,
          jsonData: jsonStr.value,
          remark: form.value.remark
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addVehOper({
          manufacturer: form.value.manufacturer,
          vehType: form.value.vehType,
          jsonData: jsonStr.value,
          remark: form.value.remark
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _configIds = row.configId || ids.value
  proxy.$modal.confirm('是否确认删除选中的数据项？').then(function () {
    return delVehOper(_configIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/vehOper/export', {
    ...queryParams.value
  }, `vehOper_${new Date().getTime()}.xlsx`)
}

getList()
</script>
