<template>
  <div @click.stop="open">
    <InputModel
      :value="state.apiConfigInfo.path"
      :placeholder="t('配置API')"
      style="width: 100%; min-width: 100px"
    />
  </div>
  <a-modal
    :width="900"
    v-model:visible="state.apiConfigDia"
    :title="t('API配置')"
    :maskClosable="false"
    :bodyStyle="state.modalBodyStyle"
    destroyOnClose
    @cancel="handleClose"
  >
    <NodeHead nodeName="API信息" />
    <a-row type="flex" align="middle" gutter="20" class="mt-2.5">
      <a-col flex="90px"><em class="required-icon">*</em>{{ t('接口地址') }}</a-col>
      <a-col flex="auto">
        <a-input
          v-model:value="state.apiConfigInfo.path"
          :placeholder="t('点击选择接口')"
          @click="state.apiSelectDialog = true"
        >
          <template #addonAfter>
            <Icon icon="ant-design:ellipsis-outlined" />
          </template>
        </a-input>
      </a-col>
      <a-col flex="90px">{{ t('请求方式') }}</a-col>
      <a-col flex="auto">
        <a-input
          v-model:value="state.apiConfigInfo.method"
          :placeholder="t('选择接口后自动显示接口请求方式')"
          disabled
        />
      </a-col>
    </a-row>
    <a-tabs v-model:activeKey="state.activeKey">
      <a-tab-pane :key="item.key" :tab="item.title" v-for="item in state.apiConfigInfo.apiParams">
        <a-table
          :dataSource="item.tableInfo"
          :columns="state.apiConfigColumns"
          :pagination="false"
          :scroll="{ y: '400px' }"
        >
          <template #emptyText>
            <div class="table-empty">
              <img :src="emptyPng" />
              <div>暂无数据</div>
            </div>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'bindType'">
              <a-select
                v-model:value="record.bindType"
                style="width: 100%"
                :placeholder="t('请选择赋值类型')"
                :options="state.bindType"
                allowClear
                @change="record.value = ''"
              />
            </template>
            <template v-else-if="column.key === 'value'">
              <a-tree-select
                v-model:value="record.value"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :placeholder="t('点击选择表单数据')"
                allow-clear
                tree-default-expand-all
                :tree-data="state.dataInfo"
                @select="(_, node) => handleSelect(node, record)"
                v-if="record.bindType === 'data'"
              />
              <a-input
                v-model:value="record.value"
                :placeholder="record.bindType ? t('请填写值') : t('请先选择赋值类型后再配置值')"
                v-else
              />
            </template>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>

    <template #footer>
      <div class="footer-container">
        <div>
          <a-button key="back" @click="handleCancel" class="cancel-api">{{
            '取消API配置'
          }}</a-button>
          <a-button key="back" @click="handleClose">{{ t('取消') }}</a-button>
          <a-button key="submit" type="primary" @click="handleSubmit">{{ t('确定') }}</a-button>
        </div>
      </div>
    </template>
  </a-modal>
  <ApiSelect
    v-if="state.apiSelectDialog"
    v-model:apiSelectDialog="state.apiSelectDialog"
    v-model:selectedApiId="state.apiConfigInfo.apiId"
    @success="handleSuccess"
  />
</template>

<script lang="ts" setup>
  import { reactive, inject } from 'vue';
  import { Icon } from '/@/components/Icon';
  import { ColumnProps } from 'ant-design-vue/lib/table/Column';
  import ApiSelect from '/@/components/ApiConfig/src/components/ApiConfigSelect.vue';
  import { cloneDeep } from 'lodash-es';
  import { message } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isValidJSON } from '/@/utils/event/design';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import emptyPng from '/@/assets/images/empty.png';
  import { InputModel } from '/@/components/ApiConfig';

  const { t } = useI18n();

  const props = defineProps({
    apiConfig: {
      type: Object as PropType<any>,
    },
    from: String,
    formTableName: String, // 子表或孙表表名
    formList: Object, //子表或孙表内组件
  });
  const emit = defineEmits(['update:apiConfig']);
  const widgetForm = inject('widgetForm') as any;

  const state = reactive({
    apiSelectDialog: false as boolean,
    apiConfigDia: false as boolean,
    activeKey: '1' as string,
    modalBodyStyle: {
      padding: '15px 15px 10px 10px',
      minHeight: '400px',
    },
    apiConfigColumns: [
      {
        title: t('API入参名称'),
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: t('API入参类型'),
        dataIndex: 'dataType',
        key: 'dataType',
        align: 'center',
      },
      {
        title: t('赋值类型'),
        dataIndex: 'bindType',
        key: 'bindType',
        align: 'center',
      },
      {
        title: t('赋值配置'),
        dataIndex: 'value',
        key: 'value',
        align: 'center',
      },
    ] as ColumnProps[],
    bindType: [
      {
        label: t('值'),
        value: 'value',
      },
      {
        label: t('表单数据'),
        value: 'data',
      },
    ],
    dataInfo: [
      {
        title: t('表单数据'),
        value: 'formData',
        disabled: true,
        children: [],
      },
      {
        title: '隐藏组件',
        value: 'hiddenComponents',
        disabled: true,
        children: [],
      },
      {
        title: '当前信息',
        value: 'currentInfo',
        disabled: true,
        children: [
          {
            title: t('当前人员名称'),
            value: '3-name',
          },
          {
            title: t('当前人员ID'),
            value: '3-id',
          },
          {
            title: t('当前人员编码'),
            value: '3-code',
          },
          {
            title: t('当前人员手机号'),
            value: '3-mobile',
          },
          {
            title: t('当前人员所属组织架构名称'),
            value: '3-departmentName',
          },
          {
            title: t('当前人员所属组织架构ID'),
            value: '3-departmentId',
          },
          {
            title: t('当前人员岗位ID'),
            value: '3-postId',
          },
          {
            title: t('当前人员角色ID'),
            value: '3-roles.id',
          },
        ],
      },
    ] as any[],
    interfaceInfo: [
      {
        key: '1',
        title: 'Query Params',
        tableInfo: [],
      },
      {
        key: '2',
        title: 'Header',
        tableInfo: [],
      },
      {
        key: '3',
        title: 'Body',
        tableInfo: [],
      },
    ],
    apiConfigInfo: props.apiConfig,
  });

  function open() {
    state.dataInfo[0].children = [];
    if (props.from == 'table') {
      if (state.dataInfo[2].value !== 'tableComp') {
        state.dataInfo.splice(2, 0, {
          title: '当前表格内组件',
          value: 'tableComp',
          disabled: true,
          children: [],
        });
      }
      if (props.formList?.list) {
        props.formList.list.forEach((item) => {
          let obj: any = handleData(item, props.formTableName);
          if (props.formList.type == 'sun-form') {
            obj.parentTable = props.formList.parentTable;
          }
          state.dataInfo[2].children.push({
            title: item.label,
            value: JSON.stringify(obj),
          });
        });
      }
    }
    if (!!widgetForm?.value) {
      if (widgetForm?.value?.list.length) {
        getSelectedList(widgetForm.value.list);
      }
    }
    if (!!props.apiConfig) {
      state.apiConfigInfo = cloneDeep(props.apiConfig);
      if (!props.apiConfig?.apiParams?.length) {
        state.apiConfigInfo.apiParams = [];
        state.apiConfigInfo.apiParams = state.interfaceInfo;
      }
    }
    state.apiConfigDia = true;
  }
  const filtercomps = [
    'divider',
    'upload',
    'image',
    'qrcode',
    'button',
    'map',
    'opinion',
    'title',
    'ai-answer',
  ];

  const getSelectedList = (list, bindTable?, key?) => {
    list?.map((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.layout!) {
          getSelectedList(child.list);
        }
      } else if (item.type === 'table-layout') {
        for (const child of item.layout!) {
          for (const list of child.list) {
            getSelectedList(list.children);
          }
        }
      } else if (item.type !== 'form' && !filtercomps.includes(item.type)) {
        let obj = handleData(item, bindTable, key);
        state.dataInfo[0].children.push({
          title: item.label,
          value: JSON.stringify(obj),
        });
      }
    });
  };
  function handleData(item, bindTable?, key?) {
    let params: string[] = [];
    if (item.options?.datasourceType == 'api' && item.options.apiConfig.apiParams) {
      item.options.apiConfig.apiParams.forEach((p) => {
        p.tableInfo &&
          p.tableInfo.forEach((o) => {
            const value = isValidJSON(o.value);
            if (value) params.push(value.fieldKey);
          });
      });
    }
    let bindField = item.bindField;
    if (item.type == 'time-range' || item.type == 'date-range') {
      bindField = item.bindStartTime + ',' + item.bindEndTime;
    }
    let obj = {
      bindField: bindField,
      bindTable: bindTable,
      tableKey: key,
      fieldKey: item.key,
    };
    return obj;
  }
  const handleSelect = ({ value }, record) => {
    if (!value) {
      message.error(t('请先选择该组件的绑定表及绑定字段'));
      record.value = null;
    }
  };

  const handleCancel = () => {
    state.apiConfigInfo.apiId = '';
    state.apiConfigInfo.path = '';
    state.apiConfigDia = false;
    emit('update:apiConfig', state.apiConfigInfo);
  };

  const handleClose = () => {
    state.apiConfigDia = false;
  };

  const handleSubmit = () => {
    state.apiConfigDia = false;
    emit('update:apiConfig', state.apiConfigInfo);
  };

  const handleSuccess = (config) => {
    state.apiConfigInfo = config;
    state.apiConfigInfo?.apiParams.forEach((para) => {
      if (!!para.tableInfo && para.tableInfo.length) {
        para.tableInfo?.map((item) => {
          return (item.bindType = !!item.value && !item.bindType ? 'value' : '');
        });
      }
    });
  };
</script>

<style lang="less" scoped>
  .required-icon {
    color: red;
  }

  .footer-container {
    display: flex;
    justify-content: flex-end;
  }

  :deep(.ant-tabs-nav) {
    margin: 10px 0 5px 10px;
  }

  .editor-box {
    width: 300px;
    position: absolute;
    height: 350px;
    left: 140px;
    bottom: 13px;
    border: 1px solid #ccc;
    box-shadow: 0 0 6px 3px #ccc;

    .editor-close {
      position: absolute;
      top: -3px;
      right: 13px;
      font-size: 16px;
      cursor: pointer;
    }

    .editor-copy {
      position: absolute;
      bottom: 5px;
      right: 15px;
      cursor: pointer;
      z-index: 999;
      color: #5e95ff;
    }
  }

  .cancel-api {
    background: #f70;
    border-color: #f70;
    color: #fff;
  }

  .table-empty {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .ant-table-thead > tr > th {
    background: #f7fbff;
    border-bottom: 1px solid #ddd;
    font-weight: bold;

    &:not(
        :last-child,
        .ant-table-selection-column,
        .ant-table-row-expand-icon-cell,
        [colspan]
      )::before {
      background-color: #ddd;
    }
  }

  :deep(.ant-table-empty .ant-table-tbody > tr.ant-table-placeholder td) {
    border-bottom: 0;
  }
</style>
