<template>
  <DesignPropertiesBox v-if="data.show">
    <a-collapse v-model:activeKey="activeKey" ghost expandIconPosition="right">
      <a-collapse-panel key="1" :header="t('基础配置')">
        <a-form-item :label="t('标题')" :colon="false" labelAlign="left">
          <a-input v-model:value="data.info.config.title" />
        </a-form-item>
        <a-form-item :label="t('组件类型')" :colon="false" labelAlign="left">
          <a-select v-model:value="data.info.config.type" style="width: 100%" @change="changeType">
            <a-select-option :value="TableType.API">{{ t('API型表格') }}</a-select-option>
            <a-select-option :value="TableType.FORM">{{ t('表单表格') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="t('显示新增按钮')">
          <div class="text-right"> <a-switch v-model:checked="data.info.config.isShowAdd" /></div>
        </a-form-item>
      </a-collapse-panel>
      <a-collapse-panel key="2" :header="t('数据配置')">
        <template v-if="data.info.config.type == TableType.API">
          <FormItem
            tip="
            1.刷新组件是取复杂列表页中已添加的表格组件供开发人员选择，注意，此处是支持多选表格。
            2.选择了刷新组件之后，才会在API参数里面添加相应表格显示的字段。
            3.当刷新组件中的表格进行了数据选择之后，会相应刷新当前的这个组件。"
            :label="t('刷新组件')"
          >
            <a-select
              v-model:value="data.info.config.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="data.info.config.apiConfig"
              :exampleStr="exampleStr"
              :updateIds="data.info.config.updateIds"
              @save="changeApiConfig"
            />
          </FormItem>
          <FormItem :label="t('关联表单')">
            <div class="text-right"
              ><a-switch v-model:checked="data.info.config.associatedForm" @change="resetDisplay"
            /></div>
          </FormItem>

          <FormItem :label="t('选择表单')">
            <template v-if="data.info.config.associatedForm">
              <SettingForm
                v-model:formId="data.info.config.formId"
                v-model:formName="data.info.config.formName"
                v-model:systemComponent="data.info.config.systemComponent"
                @change="changeSettingForm"
              >
                <a-input v-model:value="data.info.config.formName" placeholder="请选择表单" />
              </SettingForm>
            </template>
            <template v-else>
              <a-input
                disabled
                v-model:value="data.info.config.formName"
                placeholder="请选择表单"
              />
            </template>
          </FormItem>
          <FormItem
            :label="t('选择主键')"
            v-if="data.info.config.formType == FormTypeEnum.CUSTOM_FORM"
          >
            <a-select v-model:value="data.info.config.primaryKey" style="width: 100%">
              <a-select-option
                v-for="(item, index) in data.info.config.apiColumns"
                :key="index"
                :value="item.prop"
                >{{ item.label ? item.label : item.prop }}</a-select-option
              >
            </a-select>
          </FormItem>
        </template>
        <template v-if="data.info.config.type == TableType.FORM">
          <FormItem :label="t('选择表单')">
            <SettingForm
              v-model:formId="data.info.config.formId"
              v-model:formName="data.info.config.formName"
              v-model:systemComponent="data.info.config.systemComponent"
              @change="changeReleaseSettingForm"
            >
              <a-input v-model:value="data.info.config.formName" placeholder="请选择表单" />
            </SettingForm>
          </FormItem>
          <FormItem
            :label="t('查询配置')"
            v-if="data.info.config.formType == FormTypeEnum.CUSTOM_FORM"
          >
            <a-select
              v-model:value="data.info.config.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="data.info.config.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="data.info.config.renderKey"
            class="card-box"
            v-if="
              data.info.config && data.info.config.columns && data.info.config.columns.length > 0
            "
          >
            <div class="card-item" v-for="(item, index) in data.info.config.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(item)"
                >
                  <a-select-option
                    v-for="(item2, index2) in data.info.config.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="data.info.config.columns && data.info.config.columns.length > 1"
                @click="deleteColumn(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" />
      </a-collapse-panel>
    </a-collapse>
  </DesignPropertiesBox>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, watch, nextTick } from 'vue';
  import { DesignPropertiesBox } from '/@/components/Desktop';
  import { tableInfo } from '../config/info';
  import SettingForm from './collapse/form/SettingForm.vue';
  import { TableInfo } 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: TableInfo;
      allTableList?: Array<any>;
    }>(),
    {
      info: () => {
        return tableInfo;
      },
    },
  );
  watch(
    () => props.info,
    (val) => {
      if (val) data.info = val;
    },
    {
      deep: true,
    },
  );
  const data: {
    show: boolean;
    info: TableInfo;
    releaseFormList: Array<any>;
    updateList: Array<any>;
  } = reactive({
    show: false,
    info: tableInfo,
    releaseFormList: [],
    updateList: [],
  });
  const activeKey = ref(['1', '2']);
  onMounted(async () => {
    data.info = props.info;
    data.show = true;
    // changeList();
    await changeForm();
    await changeReleaseForm();
    await changeApiConfig(data.info.config.apiConfig);
  });
  function addColumn() {
    data.info.config.columns.push(cloneDeep(tableDefaultColumnItem));
    resetDisplay();
  }
  function deleteColumn(index) {
    data.info.config.columns.splice(index, 1);
    resetDisplay();
  }
  async function changeSettingForm(setting) {
    data.info.config.formType = setting.checkFormType;
    await changeForm();
  }
  async function changeReleaseSettingForm(setting) {
    data.info.config.formType = setting.checkFormType;
    data.info.config.apiColumns = [];
    data.info.config.columns = [];
    data.info.config.releaseId = '';
    data.releaseFormList = [];
    data.info.config.columns.push(cloneDeep(tableDefaultColumnItem));
    await changeForm();
  }
  async function changeForm() {
    if (data.info.config.formId) {
      try {
        const templateResult = await getReleaseInfo(data.info.config.formId);
        if (templateResult && Array.isArray(templateResult) && templateResult.length > 0) {
          data.releaseFormList = templateResult;
        }
        changeReleaseForm();
      } catch (error) {
        console.log('error: ', error);
      }
    }
    resetDisplay();
  }
  async function changeReleaseForm() {
    if (data.info.config.type == TableType.FORM && data.info.config.formId) {
      try {
        const res = await getTableInfo(data.info.config.formId);
        if (res.pkName) {
          data.info.config.primaryKey = res.pkName;
        }
        if (
          res.deskColumnsVoList &&
          Array.isArray(res.deskColumnsVoList) &&
          res.deskColumnsVoList.length > 0
        ) {
          data.info.config.apiColumns = cloneDeep(res.deskColumnsVoList);
        }
      } catch (error) {
        console.log('error: ', error);
      }
    }
    resetDisplay();
  }
  async function changeApiConfig(val) {
    if (data.info.config.type == TableType.API) {
      if (val && val.path) {
        let res = await changeApiOptions(val);
        if (res && res.columns) data.info.config.apiColumns = res.columns;
      }
      await nextTick();
      resetDisplay();
    }
  }
  function resetDisplay() {
    data.info.config.renderKey++;
  }
  function changeDataIndex(item) {
    if (item.dataIndex && item.title == '') {
      let val = data.info.config.apiColumns.find((ele) => {
        return ele.prop == item.dataIndex;
      });
      item.title = val.label ? val.label : val.prop;
      item.listStyle = val.listStyle ? val.listStyle : '';
      item.isMoneyChinese = val.isMoneyChinese ? val.isMoneyChinese : false;
    }
    resetDisplay();
  }
  function changeType() {
    if (data.info.config.type == TableType.API) {
      data.info.config.apiColumns = [];
      data.info.config.columns = [];
      data.info.config.apiConfig = {
        id: '',
        name: '',
        method: '',
        path: '',
        requestParamsConfigs: [], //Query Params
        requestHeaderConfigs: [], //Header
        requestBodyConfigs: [], //Body
      };
    } else {
      data.releaseFormList = [];
      data.info.config.formId = '';
      data.info.config.formName = '';
      data.info.config.releaseId = '';
      data.info.config.apiColumns = [];
      data.info.config.columns = [];
    }
    data.info.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>
