<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item :label="$t('script.scriptKey')" prop="scriptKey">
        <el-input
          v-model="queryParams.scriptKey"
          :placeholder="$t('script.pleaseEnterScriptKey')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="脚本方法名称" prop="scriptFunctionName">
        <el-input
          v-model="queryParams.scriptFunctionName"
          placeholder="请输入脚本方法名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item :label="$t('script.scriptName')" prop="scriptName">
        <el-input
          v-model="queryParams.scriptName"
          :placeholder="$t('script.pleaseEnterScriptName')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('script.scriptType')" prop="scriptType">
        <el-select
          v-model="queryParams.scriptType"
          :placeholder="$t('script.pleaseSelectScriptType')"
          filterable
          clearable
        >
          <el-option
            v-for="item in dict.type.bpm_script_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('script.industryType')" prop="industryType">
        <el-select
          v-model="queryParams.industryType"
          :placeholder="$t('script.pleaseSelectIndustryType')"
          filterable
          clearable
        >
          <el-option
            v-for="item in dict.type.industry_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('tenant.tenant')" prop="tenantId">
        <el-select
          v-model="queryParams.tenantId"
          :placeholder="$t('script.pleaseSelectTenant')"
          filterable
          clearable
        >
          <el-option
            v-for="item in TenantAllList"
            :key="item.tenantId"
            :label="item.tenantName"
            :value="item.tenantId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="数据表" prop="tableName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.tableName"-->
      <!--          placeholder="请输入数据表"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >{{ $t('normal.search') }}
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >{{ $t('normal.reset') }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:script:add']"
        >{{ $t('normal.insert') }}
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:script:remove']"
        >{{ $t('normal.delete') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="downloadTheNodeTemplate"
          v-hasPermi="['system:script:remove']"
        >{{ $t('script.downloadNodeTemplate') }}
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-download"
          size="mini"
          @click="uploadTheNodeTemplate"
          v-hasPermi="['system:script:remove']"
        >{{ $t('script.uploadScriptFile') }}
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
  <el-button
    type="success"
    plain
    icon="el-icon-edit"
    size="mini"
    :disabled="single"
    @click="handleUpdate"
    v-hasPermi="['system:script:edit']"
    >修改</el-button
  >
</el-col> -->

      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:script:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="scriptList"
      @selection-change="handleSelectionChange"
      style="margin-top: 20px"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="编号" align="center" prop="id" />-->
      <el-table-column :label="$t('script.scriptKey')" align="center" prop="scriptKey" />
      <!-- <el-table-column label="脚本方法名称" align="center" prop="scriptFunctionName" /> -->
      <el-table-column :label="$t('script.scriptName')" align="center" prop="scriptName" />
      <!-- <el-table-column
        label="脚本方法体"
        align="center"
        prop="scriptFunctionCode"
      /> -->
      <el-table-column :label="$t('script.scriptType')" align="center" prop="scriptType">
        <template slot-scope="scope">
          {{ getDictLabel(scope.row.scriptType, dict.type.bpm_script_type) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('script.industryType')" align="center" prop="industryType">
        <template slot-scope="scope">
          {{ getDictLabel(scope.row.industryType, dict.type.industry_type) }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('script.scriptState')" align="center" prop="scriptState">
        <template slot-scope="scope">
          {{ getDictLabel(scope.row.scriptState, dict.type.zkqy_jbzt) }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('script.componentState')" align="center" prop="pageUpload">
        <template slot-scope="scope">
          {{ getDictLabel(scope.row.pageUpload, dict.type.isuploadpage) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('script.scriptDescription')"
        align="center"
        prop="scriptDescription"
      />


      <el-table-column
        :label="$t('normal.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template
          slot-scope="scope"
          v-if="
            $store.state.user.tenant.tenantId == scope.row.tenantId ||
            $store.state.user.userId == 1
          "
        >
          <el-dropdown>
            <el-button type="warning" plain size="small">
              {{ $t('normal.process') }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:script:edit']"
                >{{ $t('update') }}
                </el-button>
              </el-dropdown-item>

              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:script:remove']"
                >{{ $t('normal.delete') }}
                </el-button>
              </el-dropdown-item>

              <el-dropdown-item v-if="$store.state.user.userId == 1">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="examine(scope.row)"
                  v-hasPermi="['system:script:edit']"
                >{{ $t('script.examine') }}
                </el-button>
              </el-dropdown-item>

              <el-dropdown-item >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="updateLoadPage(scope.row)"
                  v-hasPermi="['system:script:edit']"
                >{{ $t('script.uploadComponentPage') }}
                </el-button>
              </el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改流程节点脚本对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="$t('script.scriptKey')" prop="scriptKey">
          <el-col :span="20">
            <el-input
              v-model="form.scriptKey"
              :placeholder="$t('script.pleaseEnterScriptKey')"
              :disabled="true"
            />
          </el-col>
          <el-col :span="4">
            <el-button
              icon="el-icon-document-copy"
              v-clipboard:copy="form.scriptKey"
              v-clipboard:success="onCopy"
              v-clipboard:error="onError"
            ></el-button>
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('script.scriptName')" prop="scriptName">
          <el-input v-model="form.scriptName" :placeholder="$t('script.pleaseEnterScriptName')" />
        </el-form-item>
        <el-form-item :label="$t('script.scriptType')" prop="scriptType">
          <!-- <el-input v-model="form.scriptName" placeholder="请输入脚本名称" /> -->
          <el-select
            v-model="form.scriptType"
            :placeholder="$t('script.pleaseSelectScriptType')"
            filterable
          >
            <el-option
              v-for="item in dict.type.bpm_script_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('script.industryType')" prop="industryType">
          <el-select
            v-model="form.industryType"
            :placeholder="$t('script.pleaseSelectIndustryType')"
            filterable
          >
            <el-option
              v-for="item in dict.type.industry_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="方法名:" prop="scriptFunctionName">-->
        <!--          <el-input-->
        <!--            v-model="form.scriptFunctionName"-->
        <!--            placeholder="请输入脚本方法名称"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="方法体:" prop="scriptFunctionCode">-->
        <!--          <el-input-->
        <!--            v-model="form.scriptFunctionCode"-->
        <!--            type="textarea"-->
        <!--            placeholder="请输入内容"-->
        <!--          />-->
        <!--          <div ref="container" class="monaco-container">-->
        <!--          </div>-->
        <!--          <el-button icon="el-icon-edit" @click="drawerOpenHandler"></el-button>-->
        <!--        </el-form-item>-->

        <el-form-item
          v-show="form.scriptType != '2'"
          :label="$t('script.tableName')"
          prop="tableName"
        >
          <el-select
            v-model="form.tableName"
            multiple
            :placeholder="$t('script.pleaseSelectTable')"
          >
            <el-option
              v-for="item in tableNameList"
              :key="item.tableName"
              :label="item.tableComment"
              :value="item.tableName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('script.scriptDescription')" prop="scriptDescription">
          <el-input
            v-model="form.scriptDescription"
            :placeholder="$t('script.pleaseEnterScriptDescription')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('normal.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('normal.cancel') }}</el-button>
      </div>
    </el-dialog>


    <!-- 审核脚本表单 -->
    <el-dialog :title="title" :visible.sync="openSH" width="500px" append-to-body>
      <el-form ref="form1" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="$t('script.examineState')" prop="scriptState">
          <el-radio-group v-model="form.scriptState">
            <el-radio label="1">{{ $t('script.pass') }}</el-radio>
            <el-radio label="2">{{ $t('script.notPass') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('normal.operation')" prop="scriptState">
          <el-button type="success" @click="xzcheck">{{ $t('script.downloadScript') }}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">{{ $t('normal.confirm') }}</el-button>
        <el-button @click="cancel1">{{ $t('normal.cancel') }}</el-button>
      </div>
    </el-dialog>

    <el-drawer
      :visible.sync="drawer"
      direction="rtl"
      :before-close="drawerHandleClose"
      :with-header="false"
    >
      <div ref="container" class="monaco-container"></div>
    </el-drawer>
    <!--节点上传 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept="*"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">{{ $t('script.uploadTip') }}</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">{{ $t('normal.confirm') }}</el-button>
        <el-button @click="upload.open = false">{{ $t('normal.cancel') }}</el-button>
      </div>
    </el-dialog>
    <!--页面上传 -->
    <el-dialog
      :title="upload1.title"
      :visible.sync="upload1.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload1"
        :limit="1"
        accept="*"
        :headers="upload1.headers"
        :action="upload1.url"
        :disabled="upload1.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess1"
        :auto-upload="false"
        :data="uploadObj"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">{{ $t('script.uploadTip') }}</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm1">{{ $t('normal.confirm') }}</el-button>
        <el-button @click="upload1.open = false">{{ $t('normal.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listScript,
  getScript,
  addScript,
  downloadTheNodeTemplate, checkDownloadTheNodeTemplate
} from '@/api/bpmprocess/process'
import { getTenantAllList } from '@/api/system/tenant'
import {
  updateScript,
  delScript,
  queryTemplateBaseTable
} from '@/api/bpmprocess/script'
import uuid from '@/utils/bpmn/uuid'
import Editor from 'vue2-ace-editor'
import { v4 as uuidv4 } from 'uuid'
import * as monaco from 'monaco-editor'
import Clipboard from 'clipboard'
import { Cog } from 'lucide-vue'
import { getToken } from '@/utils/auth'
export default {
  name: 'Script',
  dicts: ['bpm_script_type', 'industry_type', 'zkqy_jbzt','isuploadpage'],
  components: { Editor },
  data () {
    return {
      dqRow:null,
      openSH:false,
      uploadObj:{
        id:""
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/script/upload'
      },
      // 用户导入参数
      upload1: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/script/uploadPage'
      },
      openUpdate: true,
      // 脚本上传列表
      fileList: [], // 上传的文件列表
      TenantAllList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      iddq:"",
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程节点脚本表格数据
      scriptList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //表数据
      tableNameList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scriptKey: null,
        tenantId: null,
        scriptFunctionName: null,
        scriptName: null,
        scriptFunctionCode: null,
        scriptType: null,
        industryType: null,
        tableName: null,
        scriptDescription: null
      },
      // 表单参数
      form: {
        scriptKey: null,
        scriptName: null,
        scriptType: null,
        industryType: null,
        tableName: null,
        scriptDescription: null,
        scriptState:null
      },
      // 表单校验
      rules: {
        scriptName: [
          { required: true, message: this.$t('script.pleaseEnterScriptName'), trigger: 'blur' }
        ],
        scriptType: [
          { required: true, message: this.$t('script.pleaseSelectScriptType'), trigger: 'change' }
        ],
        industryType: [
          { required: true,message: this.$t('script.pleaseSelectScriptType'), trigger: 'change' }
        ],
        scriptState: [
          { required: true,message: this.$t('script.pleaseSelectExamineState'), trigger: "change" },
        ],
      },

      // 代码编辑器相关数据
      monacoEditor: null,
      codes: '',
      readOnly: false,
      drawer: false,
      editorOptions: {
        selectOnLineNumbers: true,
        roundedSelection: false,
        readOnly: this.readOnly, // 只读
        cursorStyle: 'line', // 光标样式
        automaticLayout: false, // 自动布局
        glyphMargin: true, // 字形边缘
        useTabStops: false,
        fontSize: 28, // 字体大小
        autoIndent: false // 自动布局
      }
    }
  },
  created () {
    this.getList()
    // this.editorInit();
    this.getTenantAllList()
  },
  methods: {
    xzcheck(){
      console.log("下载检查脚本")
      console.log(this.dqRow);
      let scriptKeyObj={"scriptKey":this.dqRow.scriptKey}
      checkDownloadTheNodeTemplate(scriptKeyObj)
        .then(response => {
          // Step 1: 检查响应类型是否为 blob（用于文件下载）
          console.log(response)
          if (response instanceof Blob) {
            const blob = new Blob([response], { type: 'application/zip' })
            const url = window.URL.createObjectURL(blob)

            // Step 2: 创建临时下载链接
            const a = document.createElement('a')
            a.href = url
            a.download = 'checkScripts.zip' // 下载的文件名
            document.body.appendChild(a)
            a.click()

            // Step 3: 清理临时对象
            window.URL.revokeObjectURL(url)
            document.body.removeChild(a)
            this.$message.success( this.$t('script.messages.downloadSuccessful'))
            this.openSH=false;
          } else {
            console.error(this.$t('script.messages.downloadError'), response.data)
            this.$message.error(this.$t('script.messages.downloadError'))
          }
        })
        .catch(error => {
          console.error('下载失败:', error)
          this.$message.error('下载失败，请稍后再试！')
        })
    },
    //上传组件页面
    updateLoadPage(row){
      this.upload1.open=true;
      this.upload1.title = this.$t('script.titles.uploadComponent')
      this.uploadObj.id="";
      this.uploadObj.id=row.id
      console.log(this.$t('script.comments.uploadComponent'), this.uploadObj)
    },
    //上传节点模版
    uploadTheNodeTemplate () {
      this.upload.title = this.$t('script.titles.uploadTenant')
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$modal.msgSuccess(this.$t('script.messages.uploadSuccess'))
      this.getList();
    },
    // 文件上传成功处理
    handleFileSuccess1 (response, file, fileList) {
      this.upload1.isUploading = false
      this.upload1.open=false;
      this.$refs.upload1.clearFiles()
      this.$modal.msgSuccess(this.$t('script.messages.uploadSuccess'))
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit()
    },
    submitFileForm1 () {
      this.$refs.upload1.submit()
    },
    // 编辑器初始化
    editorInit () {
      require('brace/theme/chrome')
      require('brace/ext/language_tools') //language extension prerequsite...
      require('brace/mode/yaml')
      require('brace/mode/json')
      require('brace/mode/less')
      require('brace/mode/java')
      require('brace/snippets/json')
      require('brace/mode/lua')
      require('brace/snippets/lua')
      require('brace/mode/javascript')
      require('brace/snippets/javascript')
    },
    // 复制成功
    onCopy () {
      this.$modal.msgSuccess(this.$t('script.messages.copySuccess'))
    },
    //复制失败
    onError () {
      this.$modal.msgError(this.$t('script.messages.copyError'))
    },
    /** 查询流程节点脚本列表 */
    getList () {
      this.loading = true
      listScript(this.queryParams).then(response => {
        this.scriptList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getTenantAllList () {
      getTenantAllList().then(response => {
        this.TenantAllList = response.rows
      })
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 取消按钮
    cancel1 () {
      this.openSH = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        scriptKey: null,
        scriptFunctionName: null,
        scriptName: null,
        scriptFunctionCode: null,
        scriptType: null,
        industryType: null,
        scriptDescription: null,
        tableName: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.$nextTick(() => {
        console.log(this.$refs['form'])
        this.$refs['form'].resetFields()
      })
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //下载节点模版
    downloadTheNodeTemplate () {
      console.log(this.ids, '选择的节点id')
      let s = this.ids.join('T')
      let idArray = {
        id: s
      }
      downloadTheNodeTemplate(idArray)
        .then(response => {
          // Step 1: 检查响应类型是否为 blob（用于文件下载）
          console.log(response)
          if (response instanceof Blob) {
            const blob = new Blob([response], { type: 'application/zip' })
            const url = window.URL.createObjectURL(blob)

            // Step 2: 创建临时下载链接
            const a = document.createElement('a')
            a.href = url
            a.download = 'scripts.zip' // 下载的文件名
            document.body.appendChild(a)
            a.click()

            // Step 3: 清理临时对象
            window.URL.revokeObjectURL(url)
            document.body.removeChild(a)

            this.$message.success(this.$t('script.messages.downloadSuccessful'))
          } else {
            console.error(this.$t('script.messages.responseDataNotValidFileFormat'), response.data)
            this.$message.error(this.$t('script.messages.downloadError'))
          }
        })
        .catch(error => {
          console.error('下载失败:', error)
          this.$message.error(this.$t('script.messages.downloadRetry'))
        })
    },

    /** 新增按钮操作 */
    handleAdd () {
      this.monacoEditor?.dispose()
      this.reset()
      this.$nextTick(() => {
        const newScriptKey = uuidv4()
        this.$set(this.form, 'scriptKey', 'script_'+newScriptKey)
        console.log('Generated scriptKey:', this.form.scriptKey)
        this.open = true
        this.title = this.$t('script.titles.addScript')
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.monacoEditor?.dispose()
      // this.open = true
      this.reset()
      queryTemplateBaseTable().then(response => {
        this.tableNameList = response.data
      })
      const id = row.id || this.ids
      getScript(id).then(response => {
        response.data.scriptType = response.data.scriptType.toString()
        response.data.tableName = response.data.tableName
          ? response.data.tableName.split(',')
          : []
        console.log(response.data.tableName)
        this.form = response.data
        this.open = true
        this.title = this.$t('script.titles.updateScript')
      })
    },
    examine(row){
      console.log(this.$t('script.comments.examine'), row.scriptState);
      this.dqRow=row;
      // this.form.id=row.id;
      this.$set(this.form,'scriptState',"1")
      this.$set(this.form,'id',row.id)
      this.openSH=true;
      this.title = this.$t('script.titles.examineScript')
      this.$nextTick(() => {
        console.log(this.$refs['form1'])
        this.$refs['form1'].resetFields()
      });
    },
    /** 提交按钮 */
    submitForm () {
      // console.log(this.monacoEditor?.getValue());
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.tableName = this.form.tableName?.join(',')
          if (this.form.id != null) {
            updateScript(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('script.messages.updateSuccess'))
              this.open = false
              this.openSH=false;
              this.getList()
            })
          } else {
            addScript(this.form).then(response => {
              console.log(this.form)
              this.$modal.msgSuccess(this.$t('script.messages.addSuccess'))
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm2 () {
      // console.log(this.monacoEditor?.getValue());
      this.$refs['form1'].validate(valid => {
        if (valid) {
          // this.form.tableName = this.form.tableName?.join(',')
          if (this.form.id != null) {
            updateScript(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('script.messages.updateSuccess'))
              this.open = false
              this.openSH=false;
              this.getList()
            })
          } else {
            addScript(this.form).then(response => {
              console.log(this.form)
              this.$modal.msgSuccess(this.$t('script.messages.addSuccess'))
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm(this.$t('script.messages.deleteConfirm') + ids + this.$t('script.messages.dataItem'))
        .then(function () {
          return delScript(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t('script.messages.deleteSuccess'))
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        'system/script/export',
        {
          ...this.queryParams
        },
        `script_${new Date().getTime()}.xlsx`
      )
    },
    // 获取字典对应label
    getDictLabel (value, dictLsit = []) {
      return dictLsit.find(item => {
        return item.value == value
      })?.label
    },
    // 抽屉打开回调
    drawerOpenHandler () {
      this.monacoEditor?.dispose()
      this.drawer = true
      this.$nextTick(() => {
        this.monacoEditor = monaco.editor.create(this.$refs.container, {
          value: this.form.scriptFunctionCode,
          language: 'java',
          theme: 'vs-dark', // 编辑器主题：vs, hc-black, or vs-dark，更多选择详见官网
          contextmenu: false, // 禁用右键菜单
          editorOptions: this.editorOptions // 同codes
        })
      })
    },
    // 抽屉关闭前回调
    drawerHandleClose (done) {
      this.$confirm(this.$t('script.messages.closeEditorConfirm'))
        .then(
          val => {
            this.form.scriptFunctionCode = this.monacoEditor?.getValue()
            done()
          },
          res => {
            done()
          }
        )
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.codeEditBox {
  width: 100%;
  height: 200px;
}

// ::v-deep div {
//   font-family: "新宋体", serif;
//   // font-family: Fira code, Fira Mono, Consolas, Menlo, Courier, monospace;
//   font-size: 16px;
// }
.monaco-container {
  width: 100%;
  height: 100%;
}
</style>
