<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="t('列表样式配置')"
    @ok="handleSubmit"
    @visible-change="visibleChange"
    width="70%"
  >
    <div class="config-box">
      <div>
        <div class="box-top">
          <NodeHead nodeName="组件选择" />
        </div>
        <div class="component-list">
          <a-collapse v-model:activeKey="tableActiveKey" expand-icon-position="right">
            <a-collapse-panel
              v-for="(item, index) in widgetFormList"
              :key="index"
              :header="item.label"
            >
              <draggable
                v-model="item.children"
                item-key="item.key"
                :group="{ name: 'script', pull: false, put: false }"
                @end="dragEnd"
                :sort="false"
              >
                <template #item="{ element }">
                  <a-tag color="blue">{{ `${element.label}(${element.bindField})` }}</a-tag>
                </template>
              </draggable>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>
      <div>
        <div class="box-top">
          <NodeHead nodeName="JS示例区" />
        </div>
        <div style="height: calc(100% - 40px)">
          <CodeEditor :value="example[activeIndex].code" language="js" readonly />
        </div>
      </div>
      <div>
        <div class="box-top">
          <NodeHead nodeName="自定义JS编辑区" />
        </div>
        <div style="height: calc(100% - 40px)">
          <CodeEditor v-model:value="definedScript" language="js" :readonly="disabled" />
        </div>
      </div>
    </div>
    <a-drawer
      :title="t('组件列表(可将组件拖入自定义JS编辑区当中)')"
      placement="left"
      :visible="componentVisible"
      :get-container="false"
      :style="{ position: 'absolute' }"
      :mask="false"
      width="50%"
      :closable="false"
    >
      <Draggable
        v-model="widgetFormList"
        :group="{ name: 'script', pull: false, put: false }"
        item-key="key"
        @end="dragEnd"
        :sort="false"
      >
        <template #item="{ element }">
          <a-tag color="blue">{{ `${element.label}(${element.bindField})` }}</a-tag>
        </template>
      </Draggable>
      <template #extra>
        <CloseOutlined @click="componentVisible = false" />
      </template>
    </a-drawer>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, inject } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { CodeEditor } from '/@/components/CodeEditor';
  import Draggable from 'vuedraggable';
  import { CloseOutlined } from '@ant-design/icons-vue';
  import { camelCaseString } from '/@/utils/event/design';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { noHaveTableAndField } from '/@/components/Designer/src/types';
  import { NodeHead } from '/@/components/ModalPanel/index';

  defineProps({
    disabled: { type: Boolean, default: false },
  });

  const { t } = useI18n();
  const definedScript = ref(``);
  const emit = defineEmits(['success', 'register']);
  const activeIndex = ref(0);
  const componentVisible = ref<boolean>(false);
  const tableActiveKey = ref([0]);
  const widgetFormList = ref<any>([]); //整个表单json配置
  const isCustomForm = inject<boolean>('isCustomForm', false);
  const example = reactive([
    {
      title: t('读写组件值'),
      code: `
/* 1.直接赋值样式  */
    return 'color: red;'

/* 2.通过if条件判断，根据数据或者文本进行判断然后赋值样式
列表行数据 获取组件值 其中bindField: 组件的绑定字段 
*/
  const rowValue = record.bindField;
  if(rowValue=='张三'){
    return 'color: red;'
  }


/*  3.通过if条件判断，根据组件自身显示的值进行判断然后赋值样式
列表行数据 获取组件值 其中bindField: 组件的绑定字段 
*/
  const rowValue = record.bindField;
  const value = 2;
  if(rowValue==value){
    return 'color: red;'
  }

/* 4.通过if条件判断，根据列表中其他组件的值进行判断然后赋值样式
列表行数据 获取组件值 其中bindField: 组件的绑定字段
*/
  const rowValue1 = record.bindField1;
  const rowValue2 = record.bindField2;
  if(rowValue1==rowValue2){
    return 'color: red;'
  }
  /*
    样式提醒：
    字体大小："font-size:16px"
    字体样式: "font-style:normal"
    字体颜色："color: #cccccc;"
    边框样式: "width:100%;border:1px solid #ccc;"
    文本居中："display: inline-flex;text-align: center;justify-content: center;align-items: center;"
    背景色:"background-color: yellow;"
    列表配置高度："height:40px;",
    列表配置宽度:"width: 100%;"
  */
    `,
    },
  ]);

  const getTableComponents = (list, tableName, key?) => {
    list.forEach((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.layout!) {
          getTableComponents(child.list, tableName);
        }
      } else if (item.type === 'table-layout') {
        for (const child of item.layout!) {
          for (const list of child.list) {
            getTableComponents(list.children, key);
          }
        }
      } else if (item.type === 'one-for-one' || item.type === 'form' || item.type === 'sun-form') {
        widgetFormList.value.push({
          label: `${item.label}`,
          key: key,
          children: [],
        });
        getTableComponents(item.children, `${item.label}`, item.key);
      } else if (!noHaveTableAndField.includes(item.type)) {
        const index = widgetFormList.value.findIndex((x) => x.label === tableName);
        const isRange = ['time-range', 'date-range'].includes(item.type);
        let rangeItem: any = [];
        if (isRange) {
          //时间范围、日期范围需改为两个字段
          rangeItem = [
            {
              ...item,
              label: t(`{name}开始时间`, { name: item.label }),
              bindField: item.bindStartTime,
            },
            {
              ...item,
              label: t(`{name}结束时间`, { name: item.label }),
              bindField: item.bindEndTime,
            },
          ];
        }
        if (index !== -1) {
          if (isRange) {
            widgetFormList.value[index].children.push(...rangeItem);
          } else {
            widgetFormList.value[index].children.push(item);
          }
        } else {
          const tableChildren = isRange ? [...rangeItem] : [item];
          if (tableName === t('主表组件列表')) {
            widgetFormList.value.unshift({
              label: tableName,
              key: '1',
              children: tableChildren,
            });
          } else {
            widgetFormList.value.push({
              label: tableName,
              key: key,
              children: tableChildren,
            });
          }
        }
      }
    });
  };
  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    if (data.list.length) {
      widgetFormList.value = [];
      getTableComponents(data.list, t('主表组件列表'));
    }
    //如果已经设置过当前事件代码  则显示已经设置的值 反之  显示默认值
    definedScript.value = data.content;
    setModalProps({
      fixedHeight: true,
      destroyOnClose: true,
    });
  });

  const dragEnd = ({ item }) => {
    const component = item._underlying_vm_;
    const label = component.label;
    const bindField = component.bindField;

    if (component.isSubFormChild || component.isSingleFormChild) {
      const bindTable = component.bindTable;
      const transTable = isCustomForm ? bindTable + 'List' : camelCaseString(bindTable) + 'List';
      const transField = isCustomForm ? bindField : camelCaseString(bindField);

      definedScript.value = definedScript.value.replace(
        `${label}(${bindField})`,
        `${transTable}[0].${transField}`,
      );
    }
    //  else if (component.type === "form-view") {
    //   const key = component.key;
    //   definedScript.value = definedScript.value.replace(`${label}(${key})`, key);
    // }
    else {
      const replaceStr = isCustomForm ? bindField : `${camelCaseString(bindField)}`;
      definedScript.value = definedScript.value.replace(`${label}(${bindField})`, replaceStr);
    }
  };
  const handleSubmit = () => {
    emit('success', definedScript.value);
    closeModal();
  };

  const visibleChange = (visible: boolean) => {
    if (!visible) componentVisible.value = false;
  };
</script>

<style lang="less" scoped>
  .config-box {
    display: flex;
    height: 100%;

    > div:nth-child(1) {
      width: 30%;
      border-right: 1px solid #ddd;
    }

    > div:nth-child(2) {
      width: 35%;
      border-right: 1px solid #ddd;
    }

    > div:nth-child(3) {
      width: 35%;
    }

    .box-top {
      display: flex;
      justify-content: space-between;
      height: 30px;
      border-bottom: 1px solid #f0f0f0;
      padding: 25px 20px;
    }

    .component-list {
      padding: 10px;
      overflow: auto;
      height: calc(100% - 51px);
    }

    .script-name {
      cursor: pointer;
      padding: 10px 0 10px 15px;

      &:hover {
        background: #eef4ff;
      }
    }
  }

  :deep(.ant-tag) {
    padding: 8px;
    font-size: 13px;
    margin-bottom: 7px;
    cursor: move;
  }
</style>
