<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ span: 6 }"
    :wrapper-col="{ span: 24 }"
    autocomplete="off"
    ref="FormRef"
    layout="vertical"
  >
    <NodeHead nodeName="基础信息" class="node-title" />
    <a-row>
      <a-col class="state" :span="12" style="padding-right: 32px">
        <a-form-item
          label="树结构编码"
          name="code"
          :rules="[{ required: true, message: '请填写树结构编码!' }]"
        >
          <a-input v-model:value="formState.code" placeholder="请填写" />
        </a-form-item>
      </a-col>
      <a-col class="state" :span="12" style="padding-right: 16px">
        <a-form-item
          label="树结构名称"
          name="name"
          :rules="[{ required: true, message: '请填写树结构名称!' }]"
        >
          <a-input v-model:value="formState.name" placeholder="请填写" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col class="state" :span="12" style="padding-right: 32px">
        <a-form-item label="父级图标" name="parentIcon">
          <IconPicker v-model:value="formState.parentIcon" />
        </a-form-item>
      </a-col>
      <a-col class="state" :span="12" style="padding-right: 16px">
        <a-form-item label="子级图标" name="childIcon">
          <IconPicker v-model:value="formState.childIcon" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="24" style="padding-right: 16px">
        <a-form-item
          label="备注"
          name="remark"
          :wrapper-col="{ span: 24 }"
          :rules="[{ required: true, message: '请填写备注!' }]"
        >
          <a-textarea v-model:value="formState.remark" placeholder="请填写备注" />
        </a-form-item>
      </a-col>
    </a-row>

    <NodeHead nodeName="树结构配置" class="node-title" />
    <a-row>
      <a-col class="state" :span="12" style="padding-right: 32px">
        <a-form-item label="树结构类型" name="remark" layout="vertical">
          <a-select v-model:value="formState.type" style="width: 100%" :options="typeOptions" />
        </a-form-item>
      </a-col>
      <a-col class="state" :span="12" style="padding-right: 16px">
        <template v-if="formState.type == TreeStructureType.API">
          <a-form-item label="接口配置" name="remark">
            <ApiSelect
              v-model="formState.config.apiData.apiConfig"
              @change="changeApiColumnOptions"
            />
          </a-form-item>
        </template>
      </a-col>
    </a-row>
  </a-form>
  <div class="config-box">
    <template v-if="formState.type == TreeStructureType.STATIC">
      <!-- 静态树 -->
      <div class="button-box">
        <PreviewTreeBtn :formState="formState" />
        <div class="add-btn" @click="addColumns">添加副选项</div>
      </div>
      <div class="table-box">
        <div class="table-item head">
          <div
            class="item"
            :style="getWidthStyle(columnItem.width)"
            v-for="(columnItem, columnIndex) in formState.columns"
            :key="columnIndex"
            >{{ columnItem.title }}
            <span
              class="delete-box"
              @click="deleteColumn(columnIndex)"
              v-if="!columnItem.dataIndex.includes('value') && columnItem.dataIndex != 'label'"
              >×</span
            >
          </div>
          <div class="icon-box" :style="getActionWidthStyle(120)">操作</div>
        </div>
        <template v-if="formState.config.staticData.length > 0">
          <DynamicTable
            :data="formState.config.staticData"
            :columns="formState.columns"
            @changeDataItem="changeDataItem"
            @deleteDataItem="deleteDataItem"
          />
        </template>
        <div class="kong-box" v-else> <EmptyBox /></div>
      </div>
      <div class="action-box" @click="modalOpen"
        ><PlusOutlined class="jia-icon" /><span class="action-text">新增</span></div
      >
    </template>
    <template v-else>
      <div class="button-box">
        <PreviewTreeBtn :formState="formState" />
      </div>
      <!-- api树 -->
      <ApiConfig
        :apiColumnOptions="apiData.apiColumnOptions"
        :apiColumns="formState.config.apiData.apiColumns"
        @change="setApiColumns"
        @deleteApiColumn="deleteApiColumn"
      />
    </template>
    <!-- 新增父级 -->
    <a-modal
      :visible="staticModalData.visible"
      :title="t('新增父级')"
      :width="600"
      :maskClosable="false"
      :okText="t('确定')"
      :cancelText="t('取消')"
      @ok="submitStaticData"
      @cancel="closeStaticData"
    >
      <div class="model-box">
        <NodeHead nodeName="基本信息" class="node-title" />
        <a-form
          :model="staticModalData"
          name="staticModal"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 24 }"
          layout="vertical"
          autocomplete="off"
          ref="StaticDataFormRef"
        >
          <a-form-item label="所属父级" name="parentLabel" v-if="staticModalData.parentLabel">
            <a-input v-model:value="staticModalData.parentLabel" disabled="" />
          </a-form-item>
          <a-form-item
            label="选项名"
            name="label"
            :rules="[{ required: true, message: '请填写选项名!' }]"
          >
            <a-input v-model:value="staticModalData.label" placeholder="请填写选项名" />
          </a-form-item>
          <a-form-item
            label="选项值"
            name="value"
            :rules="[{ required: true, message: '请填写选项值!' }]"
          >
            <a-input v-model:value="staticModalData.value" placeholder="请填写选项值" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <!-- 新增副选项 -->
    <a-modal
      :visible="staticColumnData.visible"
      :title="t('新增副选项')"
      :width="600"
      :maskClosable="false"
      :okText="t('确定')"
      :cancelText="t('取消')"
      @ok="submitStaticColumn"
      @cancel="closeStaticColumn"
    >
      <div class="model-box">
        <NodeHead nodeName="基本信息" class="node-title" />
        <a-form
          :model="staticColumnData"
          name="staticColumn"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 24 }"
          layout="vertical"
          autocomplete="off"
          ref="StaticColumnFormRef"
        >
          <a-form-item
            label="表头名称"
            name="label"
            :rules="[{ required: true, message: '请填写副选项表头名称!' }]"
          >
            <a-input v-model:value="staticColumnData.label" placeholder="请填写副选项表头名称" />
          </a-form-item>
          <div class="tip-box">
            <div class="tip-icon-box">
              <div class="icon-box">!</div>
              <div class="title-box">提示</div>
            </div>
            <div>
              新增列会自动在列表中添加选项名和选项值，在列表中进行删除选项名列操作也会同步删除选项值列。</div
            >
          </div>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { IconPicker } from '/@/components/Icon';
  import { getInfo } from '/@/api/system/generator/treeStructure';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { TreeStructureType } from '/@/enums/treeStructure';
  import {
    ApiColumnItem,
    StaticColumnItem,
    StaticDataItem,
  } from '/@/model/generator/treeStructure';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { EmptyBox } from '/@/components/ModalPanel/index';
  import PreviewTreeBtn from './Preview.vue';
  import ApiSelect from './ApiSelect.vue';
  import ApiConfig from './ApiConfig.vue';
  import DynamicTable from './dynamicTable/DynamicTable.vue';
  import { apiConfigFunc } from '/@/utils/event/design';
  import { NodeHead } from '/@/components/ModalPanel/index';
  const { t } = useI18n();
  const { notification } = useMessage();
  const FormRef = ref();
  const props = withDefaults(
    defineProps<{
      editId: string;
    }>(),
    {
      editId: '',
    },
  );
  const StaticDataFormRef = ref();
  const staticModalData = reactive({
    visible: false,
    label: '',
    value: '',
    parentLabel: '',
    key: '',
  });
  const StaticColumnFormRef = ref();
  const staticColumnData = reactive({
    visible: false,
    label: '',
  });
  const apiData = reactive({
    apiColumnOptions: [],
  });
  const formState = reactive({
    key: '',
    code: '',
    name: '',
    remark: '',
    parentIcon: '',
    childIcon: '',
    type: TreeStructureType.STATIC,
    columns: [
      {
        title: '选项名(默认)',
        dataIndex: 'label',
        key: 'label',
        width: 160,
      },
      {
        title: '选项值',
        dataIndex: 'value',
        key: 'value',
        width: 120,
      },
    ] as Array<StaticColumnItem>,
    config: {
      staticData: [] as Array<StaticDataItem>,
      apiData: {
        apiConfig: {
          id: '',
          name: '',
          method: '',
          requestParamsConfigs: [], //Query Params
          requestHeaderConfigs: [], //Header
          requestBodyConfigs: [], //Body
        },
        apiColumns: [] as Array<ApiColumnItem>,
      },
    },
  });
  const typeOptions = [
    {
      value: TreeStructureType.STATIC,
      label: t('静态树'),
    },
    {
      value: TreeStructureType.API,
      label: t('Api接口树'),
    },
  ];
  onMounted(async () => {
    formState.key = '';
    apiData.apiColumnOptions = [];
    formState.config.apiData.apiColumns = [
      {
        value: '',
        label: '主选项名',
        title: 'label-0',
        width: 120,
      },
      {
        value: '',
        label: '主选项值',
        title: 'value-0',
        width: 120,
      },
    ];
    if (props.editId) {
      await initEditData(props.editId);
    }
  });
  async function initEditData(editId) {
    let res = await getInfo(editId);
    formState.key = editId;
    if (res.code) formState.code = res.code;
    if (res.name) formState.name = res.name;
    if (res.remark) formState.remark = res.remark;
    if (res.parentIcon) formState.parentIcon = res.parentIcon;
    if (res.childIcon) formState.childIcon = res.childIcon;
    formState.type = res.type;
    if (formState.type == TreeStructureType.STATIC) {
      if (res.config) {
        let configObj = JSON.parse(res.config);
        formState.config.staticData = configObj.staticData;
      }
      if (res.columns) {
        let columnsObj = JSON.parse(res.columns);
        formState.columns = columnsObj;
      }
    } else {
      if (res.config) {
        let configObj = JSON.parse(res.config);
        formState.config.apiData.apiConfig = configObj.apiData.apiConfig;
        formState.config.apiData.apiColumns = configObj.apiData.apiColumns;
        await changeApiColumnOptions(formState.config.apiData.apiConfig);
      }
    }
  }
  function addColumns() {
    staticColumnData.visible = true;
  }
  function deleteColumn(index) {
    formState.columns.splice(index + 1, 1);
    formState.columns.splice(index, 1);
  }
  function getWidthStyle(width) {
    return 'min-width:' + width + 'px;flex-basis:' + width + 'px;flex:1;';
  }
  function getActionWidthStyle(width: number) {
    return 'min-width:' + width + 'px;';
  }
  function modalOpen() {
    staticModalData.parentLabel = '';
    staticModalData.key = '' + formState.config.staticData.length;
    staticModalData.visible = true;
  }
  function changeDataItem(dataItem) {
    // 子集添加
    if (dataItem && dataItem.label) {
      staticModalData.parentLabel = dataItem.label;
      staticModalData.key = dataItem.key + '-' + dataItem.children.length;
    }

    staticModalData.visible = true;
  }
  function deleteDataItem(dataItem) {
    let arr = dataItem.key.split('-'); //0 代表顶级  0-0 代表二级 0-0-0 代表三级 以此类推
    let index = arr[arr.length - 1];
    if (arr.length == 1) {
      formState.config.staticData.splice(index, 1);
    } else {
      const childArr = getChild(arr);
      childArr.splice(index, 1);
    }
  }
  async function submitStaticData() {
    try {
      await StaticDataFormRef.value.validate();
      let arr = staticModalData.key.split('-'); //0 代表顶级  0-0 代表二级 0-0-0 代表三级 以此类推
      let json = {
        key: staticModalData.key,
        value: staticModalData.value,
        label: staticModalData.label,
        expand: true,
        children: [],
      };
      if (arr.length == 1) {
        formState.config.staticData.push(json);
      } else {
        const childArr: Array<StaticDataItem> = getChild(arr);
        childArr.push(json);
      }
      closeStaticData();
    } catch (error) {}
  }

  function getChild(selectArray): Array<StaticDataItem> {
    let level = selectArray.length;
    let child: Array<StaticDataItem> = [];
    for (let i = 0; i < level - 1; i++) {
      if (child && child.length > 0) {
        child = child[selectArray[i]].children;
      } else {
        child = formState.config.staticData[selectArray[i]].children;
      }
    }
    return child;
  }

  function closeStaticData() {
    staticModalData.value = '';
    staticModalData.label = '';
    staticModalData.parentLabel = '';
    staticModalData.visible = false;
  }
  async function submitStaticColumn() {
    try {
      await StaticColumnFormRef.value.validate();
      let index = formState.columns.length;
      formState.columns.push(
        {
          title: '副选项名(' + staticColumnData.label + ')',
          dataIndex: 'label-' + index,
          key: 'label-' + index,
          width: 160,
        },
        {
          title: '选项值',
          key: 'value-' + index,
          dataIndex: 'value-' + index,
          width: 120,
        },
      );
      closeStaticColumn();
    } catch (error) {}
  }
  function closeStaticColumn() {
    staticColumnData.label = '';
    staticColumnData.visible = false;
  }
  function hasEmptyItem(elem) {
    let isEmpty = false;
    for (let index = 0; index < formState.columns.length; index++) {
      const element = formState.columns[index];
      if (!element.dataIndex || !elem[element.dataIndex]) {
        isEmpty = true;
      }
    }
    return isEmpty;
  }
  function validateStaticEmpty(array) {
    let val = false;
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      let hasEmpty = hasEmptyItem(element);
      if (hasEmpty) {
        return hasEmpty;
      } else {
        if (element.children.length > 0) {
          val = validateStaticEmpty(element.children);
          if (val) {
            return val;
          }
        }
      }
    }
    return val;
  }
  async function handleSubmit() {
    try {
      await FormRef.value.validate();
      if (formState.type == TreeStructureType.STATIC) {
        let val = validateStaticEmpty(formState.config.staticData);
        if (!val) {
          return formState;
        } else {
          notification.error({
            message: t('提示'),
            description: t('树结构数据未填写'),
          });
        }
      } else {
        return formState;
      }
    } catch (error) {
      notification.error({
        message: t('提示'),
        description: t('添加失败'),
      });
      return false;
    }
  }
  async function changeApiColumnOptions(apiConfig) {
    let res = await apiConfigFunc(apiConfig, false, {});
    apiData.apiColumnOptions = res.columns;
  }
  function setApiColumns(label) {
    let length = formState.config.apiData.apiColumns.length / 2;
    formState.config.apiData.apiColumns.push(
      {
        dataIndex: '',
        label: '副选项名' + length,
        title: label,
        width: 120,
      },
      {
        dataIndex: '',
        label: '副选项值' + length,
        title: 'value-' + length,
        width: 120,
      },
    );
  }
  function deleteApiColumn(index) {
    formState.config.apiData.apiColumns.splice(index + 1, 1);
    formState.config.apiData.apiColumns.splice(index, 1);
  }
  defineExpose({
    handleSubmit,
  });
</script>

<style lang="less" scoped>
  .import-title {
    font-size: 16px;
    font-weight: bold;
    margin: 10px 0 20px;
  }

  .config-box {
    padding: 0 16px 0 0;
  }

  .button-box {
    display: flex;
    justify-content: flex-end;

    button {
      margin: 0 4px;
      font-size: 12px;
    }

    .add-btn {
      width: 94px;
      height: 32px;
      background: #1c8dff;
      border-radius: 4px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 16px;
    }
  }

  .table-box {
    width: 100%;
    margin-top: 20px;
    overflow-x: scroll;
    white-space: nowrap;

    .child1 {
      width: 100%;
      padding-left: 14px;
    }

    .table-item {
      width: 100%;
      display: flex;
      line-height: 50px;
      border-bottom: 1px solid #ececec;

      .item {
        height: 50px;
        color: #6e6a6e;
        font-size: 14px;
        margin: 0 4px;
        width: 120px;
        display: flex;
        // justify-content: center;
        padding-left: 20px;
        align-items: center;
      }

      .delete-icon {
        color: @clear-color;
        margin: 0 10px;
        font-size: 12px;
      }

      .jia-icon {
        color: @primary-color;
        font-weight: 700;
        margin: 0 10px;
        font-size: 12px;
      }
    }

    .head {
      background-color: #f9f9f9;
      border: none;
    }
  }

  .kong-box {
    margin: 10px 0;
    height: 200px;
  }

  .action-box {
    width: 100%;
    border: 1px dotted #d8d8d8;
    color: #65696b;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 10px;
  }

  .model-box {
    padding: 16px;
  }

  .tip-box {
    background: rgb(255 119 0 / 8%);
    border-radius: 4px;
    border: 1px solid #f70;
    font-size: 14px;
    color: #333;
    padding: 20px;
    margin-bottom: 120px;

    .tip-icon-box {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .icon-box {
        width: 18px;
        height: 18px;
        background: #f70;
        border-radius: 50%;
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .title-box {
        font-weight: bold;
        font-size: 16px;
        color: #333;
        margin-left: 10px;
      }
    }
  }

  .delete-box {
    font-size: 18px;
    font-weight: 700;
    color: #ee8d96;
    cursor: pointer;
  }

  .node-title {
    margin-bottom: 16px;
    padding-left: 0;
  }

  :deep(.table-box .head) {
    height: 50px;
    line-height: 50px;
    background: #f7fbff;
    border-radius: 0;
    border: 1px solid #ddd;
    font-weight: bold;
    font-size: 14px;
    color: #333;
  }
</style>
