<template>
    <div class="app-container">
    <div class="display-module">
      <dynamic-component-wrapper
        v-if="vueCode"
        :code="vueCode"
        @button-click="handleButtonClick"
      />
    </div>
    <div class="operation-module">
      <div class="current-button">
        当前选择按钮: {{ currentButtonName || '未选择按钮 或 按钮不支持绑定脚本'}}
      </div>
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="绑定脚本" prop="select1">
          <el-select v-model="formData.select1" placeholder="请选择">
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="脚本类型" prop="select2">
          <el-select v-model="formData.select2" placeholder="请选择">
            <el-option
              v-for="item in options2" 
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  </template>
  
  <script>
  import {  getVuePage, listBusinessFlowScript, queryBtnScriptApi, addBtnScriptApi, updateBtnScriptApi } from "@/api/businessFlow/vuePage";
  import DynamicComponentWrapper from '@/components/BusinessFlow/DynamicComponentWrapper.vue'
  import { parseComponent } from '@/utils/templateParser'
  
  export default {
    name: 'BindingPageScript',
    components: {
        DynamicComponentWrapper
    },
    data () {
      return {
        // 跳转页面-路由传递的row中的Id的值
        rowId: null,
        // 获取到的所有数据
        vuePageData: {},
        //获取到的vueCode, vue代码值
        vueCode: '',
        //获取到的tenantId值
        tenantId: null,
        // 获取到的vueKey值--uuid
        vueKey:'',
        loading:false,
        formData:{
          select1:'',
          select2:''
        },
        // 脚本下拉
        options1:[],
        // 脚本类型
        options2:[
          {
            value: "query",
            label: this.$t('excuteBtn.query'),
          },
          {
            value: "add",
            label: this.$t('excuteBtn.insert'),
          },
          {
            value: "update",
            label: this.$t('excuteBtn.update'),
          },
          {
            value: "delete",
            label: this.$t('excuteBtn.delete'),
          },
          {
            value: "other",
            label: this.$t('excuteBtn.otherMethod'),
          },
        ],
        btnScriptFlag:false,//按钮是否绑定脚本
        currentButtonName:'',//当前选择按钮名字
        // 添加防抖标记
        isQuerying: false,
        queryTimer: null,
        // 添加表单验证规则
        rules: {
          select1: [
            { required: true, message: '请选择绑定脚本', trigger: 'change' }
          ],
          select2: [
            { required: true, message: '请选择脚本类型', trigger: 'change' }
          ]
        },
      }
    },
    created () {
      // 获取路由传递的参数
      const rowId = this.$route.query.mode
      console.log('路由传递的rowId:', rowId)
      if(rowId){
        this.rowId = rowId
        this.getList()
        this.getScriptList()
      }
    },
    methods: {
      getList() {
        this.loading = true;
        let id = this.rowId
        console.log('this.rowId:', this.rowId)
        getVuePage(id).then(response => {
          if(response.code == 200){
            this.vuePageData = response.data;
            const vueCodeStr = decodeURIComponent(response.data?.vueCode)
            this.vueCode = vueCodeStr 
            this.vueKey = response.data?.vueKey 
            this.tenantId = response.data?.tenantId
            console.log('[this.vuePageData]',  this.vuePageData)
            console.log('[this.vueCode]',  this.vueCode)
            console.log('[this.tenantId]',  this.tenantId)
          }else{
            this.vuePageData = {}
          }
          this.loading = false;
        });
      },
      getScriptList(){
        listBusinessFlowScript({ isEnablePaging: false }).then(response => {
          console.log('[response]',  response)
          if(response.code == 200){
            this.options1 = response.rows.map(row=>{
              return{
                ...row,
                label: row.remark,
                value: row.businessKey
              }
            })
          }
        })
      },
      handleButtonClick(buttonData) {
        console.log('按钮点击事件:', buttonData);
        this.currentButtonName = buttonData.text
        let data = {
          vueKey: this.vueKey,
          vueContent: buttonData.text,  // 使用按钮的文本内容
        }
        // 使用防抖处理查询请求
        this.debounceQueryBtnScript(data);
      },
      // 添加防抖方法
      debounceQueryBtnScript(data) {
        if (this.isQuerying) {
          return;
        }
        
        if (this.queryTimer) {
          clearTimeout(this.queryTimer);
        }

        this.queryTimer = setTimeout(() => {
          this.isQuerying = true;
          this.queryBtnScript(data).finally(() => {
            this.isQuerying = false;
          });
        }, 300);
      },
      // 修改查询方法返回 Promise
      queryBtnScript(data){
        console.log('[data]', data)
        return queryBtnScriptApi(data).then(response => {
          console.log('[response]',  response)
          if(response.code ===200 ){
            if(response.msg == '未绑定'){
                this.btnScriptFlag = false
                this.formData = {
                  select1:'',
                  select2:''
                }
            }else{
              console.log('[response.data]',  response.data)
              let data =  response.data
              this.btnScriptFlag = true
              this.formData = {
                  select1:data.businessKey,
                  select2:data.businessType
                }
            }
          }
        }).catch(error => {
          console.error('查询按钮脚本失败:', error);
        });
      },
      // 表单提交
      onSubmit(){
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            console.log('[this.vueKey]',this.vueKey,)
            console.log('[this.currentButtonName]',this.currentButtonName,)
            console.log('[this.formData]',this.formData,)
            let data = {
              vueKey: this.vueKey,
              vueContent: this.currentButtonName,
              businessKey: this.formData.select1,
              businessType: this.formData.select2
            }
            console.log('[data]',data)
            addBtnScriptApi(data).then(response => {
              console.log('[response]',  response)
              if (response.code === 200) {
                this.$message.success('绑定成功');
                // 重置表单
                // this.$refs.formRef.resetFields();
              } else {
                this.$message.error(response.msg || '绑定失败');
              }
            })
          } else {
            this.$message.warning('请填写必填项');
            return false;
          }
        });
      },
    }
  }
  </script>
  <style lang="scss">
  // 全局样式，确保下拉框在最上层
  .el-select-dropdown {
    z-index: 99999 !important;
  }
  </style>
  <style lang="scss" scoped>
  .app-container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
  }
  .display-module {
    flex: 70%;
    position: relative;
    z-index: 1;
    // 添加样式隔离
    :deep(.dynamic-component-container) {
      height: 100%;
      overflow: auto;
      // 重置一些可能影响全局的样式
      * {
        box-sizing: border-box;
      }
      // 确保Element UI组件样式正确
      .el-button,
      .el-input,
      .el-select,
      .el-table {
        font-family: inherit;
      }
    }
  }
  .operation-module {
    flex: 30%;
    position: relative;
    z-index: 9999;
    background: #fff;
    padding: 20px;
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
    :deep(.el-select) {
      width: 100%;
    }
  }
  </style>
  