<template>
  <!-- 新增编辑 -->
  <a-modal
    style="min-width: 900px; height: calc(100% - 45px)"
    width="80%"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    title="绑定事件"
    :body-style="{ paddingBottom: '8px', height: 'calc(100% - 110px)', overflowY: 'auto' }"
    @update:visible="updateVisible"
    @ok="save"
    class="common-modal"
    @close="updateVisible(false)"
  >
    <a-row class="wh100" :gutter="12">
      <a-col :span="12" class="wh100">
        <a-tabs v-model:activeKey="activeKey" class="devops-tabs">
          <a-tab-pane key="1" tab="点击事件">
            <div class="js-code">JS代码：</div>
            <monaco-code-editor style="height: calc(100% - 32px)" v-model="onClickEventCode" language="js"></monaco-code-editor>
          </a-tab-pane>
          <a-tab-pane key="2" tab="数据改变">
            <div class="js-code">JS代码：</div>
            <monaco-code-editor style="height: calc(100% - 32px)" v-model="onChangeEventCode" language="js"></monaco-code-editor>
          </a-tab-pane>
          <a-tab-pane key="3" tab="失去焦点">
            <div class="js-code">JS代码：</div>
            <monaco-code-editor style="height: calc(100% - 32px)" v-model="onBlurEventCode" language="js"></monaco-code-editor>
          </a-tab-pane>
          <a-tab-pane key="4" tab="获取焦点">
            <div class="js-code">JS代码：</div>
            <monaco-code-editor style="height: calc(100% - 32px)" v-model="onFocusEventCode" language="js"></monaco-code-editor>
          </a-tab-pane>
          <a-tab-pane key="5" tab="输入值时">
            <div class="js-code">JS代码：</div>
            <monaco-code-editor style="height: calc(100% - 32px)" v-model="onInputEventCode" language="js"></monaco-code-editor>
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :span="12" class="wh100 right-tab">
        <a-tabs v-model:activeKey="leftActiveKey" class="devops-tabs">
          <a-tab-pane key="1" tab="数据结构">
            <json-editor-vue currentMode="view" class="editor wh100" v-model="setValueData" :modeList="[]"></json-editor-vue>
          </a-tab-pane>
          <a-tab-pane key="2" tab="事件说明">
            <a-collapse v-model:activeKey="eventActiveKey" accordion>
              <a-collapse-panel key="1" header="点击事件（Click Event）">
                <p>当用户对指定的组件进行点击操作时，点击事件被触发。这个事件可以用来处理各种用户交互，如按钮的提交操作、选项的选择等。</p>
              </a-collapse-panel>
              <a-collapse-panel key="2" header="数据改变事件（Data Change Event）">
                <p>
                  当表单中的输入数据发生变化时触发的事件。这通常发生在文本框、选择框或其他输入类型的组件中，用户的输入会引起组件的内部状态变化。可用于实现动态表单验证、自动填充或即时数据处理。
                </p>
              </a-collapse-panel>
              <a-collapse-panel key="3" header="失去焦点事件（Blur Event）">
                <p>
                  失去焦点事件发生在表单组件失去输入焦点时。这通常在用户从一个输入字段切换到另一个时发生，或者当用户点击了表单外的元素。失去焦点事件常用于执行字段的验证，或者在用户完成输入后关闭下拉列表等。
                </p>
              </a-collapse-panel>
            </a-collapse>
          </a-tab-pane>
          <a-tab-pane key="3" tab="用例参考">
            <a-collapse v-model:activeKey="referActiveKey" accordion>
              <a-collapse-panel key="1" header="1. 表单元素赋值">
                <h5 class="readme-padding">用法说明：</h5>
                <p>formObj.formData.{字段名称} = {具体值}</p>
                <h5 class="readme-padding">具体示例：</h5>
                <p>formObj.formData.user_real_name = '张三'</p>
              </a-collapse-panel>
              <a-collapse-panel key="2" header="2. 控制表单元素是否可编辑">
                <p>formObj.userName.itemEditFlag = true</p>
              </a-collapse-panel>
              <a-collapse-panel key="3" header="3. 控制表单元素是否禁用">
                <p>formObj.userName.itemEditFlag = false</p>
              </a-collapse-panel>
              <a-collapse-panel key="4" header="4. 控制表单元素是否隐藏">
                <p>formObj.userName.itemHiddenFlag = true</p>
              </a-collapse-panel>
              <a-collapse-panel key="5" header="5. 调用自定义接口获取数据">
                <p>Request.get(url, params).then(res => { console.log(res) })</p>
              </a-collapse-panel>
            </a-collapse>
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script setup name="FormCustomEvent">
import { pick } from 'lodash-es';
import { ref, onMounted } from 'vue';
import JsonEditorVue from 'json-editor-vue3';

const props = defineProps({
  visible: Boolean,
  currentItem: Object,
  formConfig: Object
});

const emits = defineEmits(['update:visible']);
// 弹框加载
const loading = ref(false);
// 左侧tab选中
const leftActiveKey = ref('1');
// tabs选中
const activeKey = ref('1');
// 使用参考key
const eventActiveKey = ref('1');
// 事件使用教程
const referActiveKey = ref('1');

// 元素点击后执行的代码
const onClickEventCode = ref('');

// 元素修改后执行的代码
const onChangeEventCode = ref('');

// 元素失去焦点后的代码
const onBlurEventCode = ref('');
// 元素获取焦点后的代码
const onFocusEventCode = ref('');
// 输入值时执行的代码
const onInputEventCode = ref('');
// 总数据
const formObj = ref({});

// 可以设置的值
const setValueData = ref({});
// 是否是表格的子节点
const isTableChildren = ref(false);
// 需要展示的字段列表
const showFieldList = ref([
  'componentCode',
  'itemLabelName',
  'itemEditFlag',
  'itemRequiredFlag',
  'itemHiddenFlag',
  'fieldCode',
  'children',
  'itemId',
  'columnList',
  'dictList',
  'formItemDialog'
]);

onMounted(() => {
  // 设置
  formObj.value.formData = {};
  ergodicItem(props.formConfig.formItems, formObj.value);
  setValueData.value = { formObj: formObj.value };

  if (props.currentItem.formItemEvent?.onClickEventCode) {
    onClickEventCode.value = props.currentItem.formItemEvent.onClickEventCode;
  } else if (isTableChildren.value) {
    onClickEventCode.value = `
/**
  * 
  * @param {*} record 当前行数据
  * @param {*} rowColumn 当前行的配置
*/
function onClick(record, rowColumn) {}
onClick(record, rowColumn);`;
  }
  if (props.currentItem.formItemEvent?.onChangeEventCode) {
    onChangeEventCode.value = props.currentItem.formItemEvent.onChangeEventCode;
  } else if (isTableChildren.value) {
    onChangeEventCode.value = `
/**
  * 
  * @param {*} record 当前行数据
  * @param {*} rowColumn 当前行的配置
  */
function onChange(record, rowColumn) {}
onChange(record, rowColumn);`;
  }
  if (props.currentItem.formItemEvent?.onBlurEventCode) {
    onBlurEventCode.value = props.currentItem.formItemEvent.onBlurEventCode;
  } else if (isTableChildren.value) {
    onBlurEventCode.value = `
/**
  * 
  * @param {*} record 当前行数据
  * @param {*} rowColumn 当前行的配置
*/
function onBlur(record, rowColumn) {}
onBlur(record, rowColumn);`;
  }

  if (props.currentItem.formItemEvent?.onFocusEventCode) {
    onFocusEventCode.value = props.currentItem.formItemEvent.onFocusEventCode;
  } else if (isTableChildren.value) {
    onFocusEventCode.value = `
/**
  * 
  * @param {*} record 当前行数据
  * @param {*} rowColumn 当前行的配置
*/
function onFocus(record, rowColumn) {}
onFocus(record, rowColumn);`;
  }

  if (props.currentItem.formItemEvent?.onInputEventCode) {
    onInputEventCode.value = props.currentItem.formItemEvent.onInputEventCode;
  } else if (isTableChildren.value) {
    onInputEventCode.value = `
/**
  * 
  * @param {*} record 当前行数据
  * @param {*} rowColumn 当前行的配置
*/
function onInput(record, rowColumn) {}
onInput(record, rowColumn);`;
  }
});

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = () => {
  props.currentItem.formItemEvent = {
    onClickEventCode: onClickEventCode.value,
    onChangeEventCode: onChangeEventCode.value,
    onBlurEventCode: onBlurEventCode.value,
    onFocusEventCode: onFocusEventCode.value,
    onInputEventCode: onInputEventCode.value
  };
  updateVisible(false);
};

// 遍历每一项
const ergodicItem = (arr, formObj) => {
  let otherCode = ['grid', 'collapse', 'col'];
  if (arr?.length > 0) {
    arr.forEach(item => {
      if (!['title', 'divide-line', 'pure-text', 'carousel', 'breadcrumb'].includes(item.componentCode)) {
        if (['select', 'custom-select', 'tree', 'tree-select', 'link-select', 'transfer', 'select-modal'].includes(item.componentCode)) {
          item.dictList = [];
        }
        item = pick(item, showFieldList.value);
        if (otherCode.includes(item.componentCode)) {
          formObj[item.componentCode + '_' + item.itemId] = item;
        } else {
          formObj[item.fieldCode] = item;
        }
        if (item.componentCode == 'table') {
          if (item?.children?.length > 0) {
            item.children.forEach(cItem => {
              if (props.currentItem.itemId == cItem.itemId) {
                isTableChildren.value = true;
              }
            });
            item.children = item.children.map(d => pick(d, showFieldList.value));
            ergodicItem(item.children, formObj[item.fieldCode]);
          }
        } else if (item?.children?.length > 0) {
          item.children = item.children.map(d => pick(d, showFieldList.value));
          let itemKey = otherCode.includes(item.componentCode) ? item.componentCode + '_' + item.itemId : item.fieldCode;
          ergodicItem(item.children, formObj[itemKey]);
        }
      }
    });
  }
};
</script>

<style lang="less" scoped>
.wh100 {
  width: 100%;
  height: 100%;
}
:deep(.ant-tabs) {
  width: 100%;
  height: 100%;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 16px !important;
}

:deep(.ant-tabs-content) {
  width: 100%;
  height: 100%;
}

:deep(.ant-tabs-tab) {
  font-size: 16px;
}

:deep(.ant-tabs-content-holder) {
  overflow-y: auto;
  width: 100%;
  height: 100%;
}
.readme-padding {
  padding-top: 5px;
  padding-bottom: 10px;
}
:deep(.full-screen) {
  display: none;
}

.js-code {
  color: #60666b;
  font-size: 16px;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
  margin-bottom: 8px;
}

.right-tab {
  display: flex;
  padding: 16px 16px 0 16px !important;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  gap: 8px;
  flex: 1 0 0;
  align-self: stretch;
  border-radius: 6px;
  background: rgba(246, 246, 249, 0.85);
}
</style>
