<template>
  <DesignPropertiesBox v-if="data.show">
    <a-tabs v-model:activeKey="tabActiveKey" type="editable-card" @edit="onEdit">
      <a-tab-pane
        v-for="pane in data.info.config.panes"
        :key="pane.key"
        :tab="pane.title"
        :closable="data.info.config.panes.length <= 1 ? false : pane.closable"
      >
        <a-collapse v-model:activeKey="activeKey" ghost expandIconPosition="right">
          <a-collapse-panel key="1" :header="t('基础配置')">
            <FormItem :label="t('选项卡标题')">
              <a-input v-model:value="pane.title" />
            </FormItem>
            <FormItem :label="t('总数量统计')">
              <div class="text-right"
                ><a-switch v-model:checked="pane.count" @change="resetDisplay"
              /></div>
            </FormItem>
            <FormItem :label="t('组件类型')">
              <a-select v-model:value="pane.type" style="width: 100%" @change="changeType(pane)">
                <a-select-option :value="TableType.API">{{ t('API型表格') }}</a-select-option>
                <a-select-option :value="TableType.FORM">{{ t('表单表格') }}</a-select-option>
              </a-select>
            </FormItem>
            <FormItem :label="t('显示新增按钮')">
              <div class="text-right"> <a-switch v-model:checked="pane.isShowAdd" /></div>
            </FormItem>
          </a-collapse-panel>
          <a-collapse-panel key="2" :header="t('数据配置')">
            <template v-if="pane.type == TableType.API">
              <FormItem
                tip="
            1.刷新组件是取复杂列表页中已添加的表格组件供开发人员选择，注意，此处是支持多选表格。
            2.选择了刷新组件之后，才会在API参数里面添加相应表格显示的字段。
            3.当刷新组件中的表格进行了数据选择之后，会相应刷新当前的这个组件。"
                :label="t('刷新组件')"
              >
                <a-select
                  v-model:value="pane.updateIds"
                  mode="multiple"
                  style="width: 100%"
                  placeholder="请选择刷新组件"
                >
                  <a-select-option
                    v-for="(item, index) in props.allTableList"
                    :key="index"
                    :value="item.value"
                    :disabled="data.info.i == item.value ? true : false"
                    >{{ item.title }}</a-select-option
                  >
                </a-select>
              </FormItem>
              <FormItem :label="t('数据视图')">
                <SelectApi
                  v-model:value="pane.apiConfig"
                  :exampleStr="exampleStr"
                  :updateIds="pane.updateIds"
                  @save="
                    (val) => {
                      changeApiConfig(pane, val);
                    }
                  "
                />
              </FormItem>
              <FormItem :label="t('关联表单')">
                <div class="text-right">
                  <a-switch v-model:checked="pane.associatedForm" @change="resetDisplay"
                /></div>
              </FormItem>

              <FormItem :label="t('选择表单')">
                <template v-if="pane.associatedForm">
                  <SettingForm
                    v-model:formId="pane.formId"
                    v-model:formName="pane.formName"
                    v-model:systemComponent="pane.systemComponent"
                    @change="
                      (val) => {
                        changeSettingForm(pane, val);
                      }
                    "
                  >
                    <a-input v-model:value="pane.formName" placeholder="请选择表单" />
                  </SettingForm>
                </template>
                <template v-else>
                  <a-input disabled v-model:value="pane.formName" placeholder="请选择表单" />
                </template>
              </FormItem>
              <FormItem :label="t('选择主键')" v-if="pane.formType == FormTypeEnum.CUSTOM_FORM">
                <a-select v-model:value="pane.primaryKey" style="width: 100%">
                  <a-select-option
                    v-for="(item, index) in pane.apiColumns"
                    :key="index"
                    :value="item.prop"
                    >{{ item.label ? item.label : item.prop }}</a-select-option
                  >
                </a-select>
              </FormItem>
            </template>
            <template v-if="pane.type == TableType.FORM">
              <FormItem :label="t('选择表单')">
                <SettingForm
                  v-model:formId="pane.formId"
                  v-model:formName="pane.formName"
                  v-model:systemComponent="pane.systemComponent"
                  @change="
                    (val) => {
                      changeReleaseSettingForm(pane, val);
                    }
                  "
                >
                  <a-input v-model:value="pane.formName" placeholder="请选择表单" />
                </SettingForm>
              </FormItem>
              <FormItem :label="t('查询配置')" v-if="pane.formType == FormTypeEnum.CUSTOM_FORM">
                <a-select
                  v-model:value="pane.releaseId"
                  style="width: 100%"
                  placeholder="请选择表单的查询配置（来源为表单发布）"
                  @change="changeReleaseForm"
                >
                  <a-select-option
                    v-for="(item, index) in data.releaseFormList"
                    :key="index"
                    :value="item.id"
                    >{{ item.menuName }}</a-select-option
                  >
                </a-select>
              </FormItem>
            </template>
            <FormItem :label="t('每页条数')">
              <a-select v-model:value="pane.pageSize" style="width: 100%" @change="resetDisplay">
                <a-select-option :value="5">5</a-select-option>
                <a-select-option :value="10">10</a-select-option>
                <a-select-option :value="15">15</a-select-option>
                <a-select-option :value="20">20</a-select-option>
                <a-select-option :value="25">25</a-select-option>
                <a-select-option :value="30">30</a-select-option>
                <a-select-option :value="35">35</a-select-option>
                <a-select-option :value="40">40</a-select-option>
                <a-select-option :value="45">45</a-select-option>
                <a-select-option :value="50">50</a-select-option>
              </a-select>
            </FormItem>
            <!-- 添加字段 -->
            <a-form-item
              :colon="false"
              labelAlign="left"
              :wrapperCol="{
                style: { paddingLeft: '10px', paddingRight: '10px' },
              }"
            >
              <div
                :key="pane.renderKey"
                class="card-box"
                v-if="pane && pane.columns && pane.columns.length > 0"
              >
                <div class="card-item" v-for="(item, index) in pane.columns" :key="index">
                  <a-form-item
                    :label="t('绑定字段')"
                    :label-col="{ style: { width: '112px' } }"
                    :colon="false"
                    required
                  >
                    <a-select
                      v-model:value="item.dataIndex"
                      style="width: 100%"
                      @change="changeDataIndex(pane, item)"
                    >
                      <a-select-option
                        v-for="(item2, index2) in pane.apiColumns"
                        :key="index2"
                        :value="item2.prop"
                        >{{ item2.label ? item2.label : item2.prop }}</a-select-option
                      >
                    </a-select>
                  </a-form-item>
                  <a-form-item
                    :label="t('列名')"
                    :label-col="{ style: { width: '112px' } }"
                    :colon="false"
                    required
                  >
                    <a-input v-model:value="item.title" @blur="resetDisplay" />
                  </a-form-item>
                  <a-form-item
                    :label="t('宽度')"
                    :label-col="{ style: { width: '112px' } }"
                    :colon="false"
                    required
                  >
                    <a-input v-model:value="item.width" @blur="resetDisplay" />
                  </a-form-item>
                  <a-form-item
                    :label="t('对齐')"
                    :label-col="{ style: { width: '112px' } }"
                    :colon="false"
                    required
                  >
                    <a-select v-model:value="item.align" style="width: 100%" @change="resetDisplay">
                      <a-select-option value="left">左对齐</a-select-option>
                      <a-select-option value="center">中间对齐</a-select-option>
                      <a-select-option value="right">右边对齐</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item
                    :label="t('显示')"
                    :label-col="{ style: { width: '112px' } }"
                    :colon="false"
                    required
                    :wrapperCol="{
                      style: { textAlign: 'right', paddingRight: '10px' },
                    }"
                    style="margin-bottom: 0"
                  >
                    <a-switch v-model:checked="item.show" @change="resetDisplay" />
                  </a-form-item>
                  <div
                    class="close-icon"
                    v-if="pane.columns && pane.columns.length > 1"
                    @click="deleteColumn(pane, index)"
                  >
                    <IconFontSymbol
                      icon="chongzhishibai"
                      style="fill: rgb(255 84 97 / 50%)"
                      :size="14"
                    />
                  </div>
                </div>
              </div>
            </a-form-item>
            <PlusCircleFilled class="add-custom" @click="addColumn(pane)" />
          </a-collapse-panel>
        </a-collapse>
      </a-tab-pane>
    </a-tabs>
  </DesignPropertiesBox>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, watch, nextTick } from 'vue';
  import { DesignPropertiesBox } from '/@/components/Desktop';
  import { tabsTableInfo } from '../config/info';
  import SettingForm from './collapse/form/SettingForm.vue';
  import { TabsTableInfo } from '/@/model/desktop/designer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { TableType } from '/@/enums/desktop';
  import SelectApi from './collapse/complex/SelectApi.vue';
  import { getReleaseInfo, getTableInfo } from '/@/api/form/design';
  import useApiRequest from '/@/hooks/event/useApiRequest';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';
  import { PlusCircleFilled } from '@ant-design/icons-vue';
  import { cloneDeep } from 'lodash-es';
  import { tableDefaultColumnItem } from '../config/properties';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import FormItem from '/@bpmn/layout/FormItem.vue';
  const { changeApiOptions } = useApiRequest();
  const { t } = useI18n();
  const props = withDefaults(
    defineProps<{
      info: TabsTableInfo;
      allTableList?: Array<any>;
    }>(),
    {
      info: () => {
        return tabsTableInfo;
      },
    },
  );
  watch(
    () => props.info,
    (val) => {
      if (val) data.info = val;
    },
    {
      deep: true,
    },
  );
  const data: {
    show: boolean;
    info: TabsTableInfo;
    releaseFormList: Array<any>;
    updateList: Array<any>;
  } = reactive({
    show: false,
    info: tabsTableInfo,
    releaseFormList: [],
    updateList: [],
  });
  const activeKey = ref(['1', '2']);
  const tabActiveKey = ref();
  const newTabIndex = ref(0);
  onMounted(async () => {
    data.info = props.info;
    data.show = true;
    newTabIndex.value = data.info.config.panes.length - 1;
    tabActiveKey.value = data.info.config.panes
      ? data.info.config.panes[0].key
      : `newTab${++newTabIndex.value}`;
    data.info.config.panes?.forEach(async (pane) => {
      await changeForm(pane);
      await changeReleaseForm(pane);
      await changeApiConfig(pane, pane.apiConfig);
    });
  });
  const add = () => {
    tabActiveKey.value = `newTab${++newTabIndex.value}`;
    data.info.config.panes?.push({
      title: 'New Tab' + newTabIndex.value,
      key: tabActiveKey.value,
      type: TableType.API,
      pageSize: 5,
      current: 1,
      total: 0,
      formType: FormTypeEnum.CUSTOM_FORM,
      renderKey: 0,
      closable: true,
      count: false,
      isShowAdd: true,
      columns: [],
    });
  };

  const remove = (targetKey: string) => {
    let lastIndex = 0;
    data.info.config.panes?.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    data.info.config.panes = data.info.config.panes?.filter((pane) => pane.key !== targetKey);
    if (data.info.config.panes?.length && tabActiveKey.value === targetKey) {
      if (lastIndex >= 0) {
        tabActiveKey.value = data.info.config.panes[lastIndex].key;
      } else {
        tabActiveKey.value = data.info.config.panes[0].key;
      }
    }
  };
  const onEdit = (targetKey: string | MouseEvent, action: string) => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey as string);
    }
  };
  function addColumn(config) {
    config.columns.push(cloneDeep(tableDefaultColumnItem));
    resetDisplay();
  }
  function deleteColumn(config, index) {
    config.columns.splice(index, 1);
    resetDisplay();
  }
  async function changeSettingForm(config, setting) {
    config.formType = setting.checkFormType;
    await changeForm(config);
  }
  async function changeReleaseSettingForm(config, setting) {
    config.formType = setting.checkFormType;
    config.apiColumns = [];
    config.columns = [];
    config.releaseId = '';
    data.releaseFormList = [];
    config.columns.push(cloneDeep(tableDefaultColumnItem));
    await changeForm(config);
  }
  async function changeForm(config) {
    if (config.formId) {
      try {
        const templateResult = await getReleaseInfo(config.formId);
        if (templateResult && Array.isArray(templateResult) && templateResult.length > 0) {
          data.releaseFormList = templateResult;
        }
        changeReleaseForm(config);
      } catch (error) {
        console.log('error: ', error);
      }
    }
    resetDisplay();
  }
  async function changeReleaseForm(config) {
    if (config.type == TableType.FORM && config.formId) {
      try {
        const res = await getTableInfo(config.formId);
        if (res.pkName) {
          config.primaryKey = res.pkName;
        }
        if (
          res.deskColumnsVoList &&
          Array.isArray(res.deskColumnsVoList) &&
          res.deskColumnsVoList.length > 0
        ) {
          config.apiColumns = cloneDeep(res.deskColumnsVoList);
        }
      } catch (error) {
        console.log('error: ', error);
      }
    }
    resetDisplay();
  }
  async function changeApiConfig(config, val) {
    if (config.type == TableType.API) {
      if (val && val.path) {
        let res = await changeApiOptions(val);
        if (res && res.columns) config.apiColumns = res.columns;
      }
      await nextTick();
      resetDisplay();
    }
  }
  function resetDisplay() {
    data.info.config.panes.forEach((o) => {
      if (o.key == tabActiveKey.value) {
        o.renderKey += 1;
      }
    });
    data.info.config.renderKey++;
  }
  function changeDataIndex(config, item) {
    if (item.dataIndex && item.title == '') {
      let val = config.apiColumns.find((ele) => {
        return ele.prop == item.dataIndex;
      });
      item.title = val.label ? val.label : val.prop;
    }
    resetDisplay();
  }
  function changeType(config) {
    if (config.type == TableType.API) {
      config.apiColumns = [];
      config.columns = [];
      config.apiConfig = {
        id: '',
        name: '',
        method: '',
        path: '',
        requestParamsConfigs: [], //Query Params
        requestHeaderConfigs: [], //Header
        requestBodyConfigs: [], //Body
      };
    } else {
      data.releaseFormList = [];
      config.formId = '';
      config.formName = '';
      config.releaseId = '';
      config.apiColumns = [];
      config.columns = [];
    }
    config.columns.push(cloneDeep(tableDefaultColumnItem));
    resetDisplay();
  }
  const exampleStr = ` {
      code: 0,
      msg: 'success',
      data: {
        total:20,
        columns: [
          {prop:'name',label:'测试1'},
          {prop:'value',label:'测试2'}
        ],
        list: [
          {name:'demo1',value:10},
          {name:'demo2',value:30}
        ],
      },
    }`;
</script>

<style lang="less" scoped></style>
