<template>
  <div class="awc-containter">
    <a-form v-bind="layout" v-if="data" :key="data.key">
      <a-collapse v-model:activeKey="chooseTab" ghost expandIconPosition="right">
        <a-collapse-panel key="property" v-if="data.type !== 'button'">
          <template #header><NodeHead nodeName="基础配置" /> </template>
          <a-form-item
            :label="
              data.type == 'tree'
                ? t('树形名称')
                : data.type == 'search'
                ? t('查询按钮名称')
                : ['list', 'form', 'iframe', 'chart'].includes(data.type)
                ? t('组件名称')
                : t('布局名称')
            "
            v-if="hasKey('label')"
          >
            <a-input v-model:value="data.options.label" size="mini" />
          </a-form-item>
          <a-form-item :label="t('布局名称')" v-if="data.type == 'panel'">
            <a-input v-model:value="data.layout[0].title" size="mini" />
          </a-form-item>
          <a-form-item :label="t('组件类型')" v-if="data.type == 'list'">
            <a-select v-model:value="data.options.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('显示名称')" v-if="hasKey('showLabel')">
            <a-switch v-model:checked="data.options.showLabel" />
          </a-form-item>
          <a-form-item :label="t('图表类型')" v-if="hasKey('chartType')">
            <a-select
              v-model:value="data.options.chartType"
              style="width: 100%"
              :options="chartOptions"
              @change="changeChartType"
            />
          </a-form-item>
          <a-form-item :label="t('默认折叠方式')" v-if="hasKey('collapseType')">
            <a-select v-model:value="data.options.collapseType" :options="collapseTypeOption" />
          </a-form-item>
          <template v-if="data.type == 'tab'">
            <a-button type="primary" @click="addTabItem" class="w-full">{{
              t('添加选项卡')
            }}</a-button>
            <Draggable v-model:list="data.layout">
              <template #item="{ element: childElement, index: childIndex }">
                <div class="flex items-center justify-between mt-2">
                  <div>
                    <svg class="icon" aria-hidden="true">
                      <use xlink:href="#icon-fangxiang1" />
                    </svg>
                  </div>
                  <div> <a-input v-model:value="childElement.name" size="mini" /></div>
                  <div>
                    <DeleteTwoTone two-tone-color="#ff8080" @click="buttonRemove(childIndex)"
                  /></div>
                </div>
              </template>
            </Draggable>
          </template>
          <a-form-item :label="t('选择表单')" v-if="data.type == 'form'">
            <SettingForm
              v-model:formId="data.options.formId"
              v-model:formName="data.options.formName"
              v-model:systemComponent="data.options.systemComponent"
              @change="handleFormChange"
            >
              <a-input v-model:value="data.options.formName" placeholder="请选择表单" />
            </SettingForm>
          </a-form-item>
          <ChartBaseSetting v-if="data.type == 'chart'" />
          <a-form-item
            :label="t('刷新组件')"
            v-if="data.type == 'chart'"
            @click="handleRefreshClick"
          >
            <a-select
              v-model:value="data.options.refreshComponent"
              style="width: 100%"
              mode="multiple"
              :options="refreshComponentOption"
              @change="handleRefreshComp"
              @deselect="handleDeleteRelate"
            />
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel key="better" v-if="betterPropertyLayout.includes(data.type)">
          <template #header><NodeHead nodeName="高级属性" /> </template>
          <a-form-item :label="t('显示左侧')" v-if="hasKey('showLeft')">
            <a-switch v-model:checked="data.options.showLeft" />
          </a-form-item>
          <a-form-item :label="t('左侧宽度')" v-if="hasKey('leftWidth')">
            <a-input-number v-model:value="data.options.leftWidth" size="mini" :min="0" />
          </a-form-item>
          <a-form-item :label="t('显示右侧')" v-if="hasKey('showRight')">
            <a-switch v-model:checked="data.options.showRight" />
          </a-form-item>
          <a-form-item :label="t('显示顶部')" v-if="hasKey('showTop')">
            <a-switch v-model:checked="data.options.showTop" />
          </a-form-item>
          <a-form-item :label="t('顶部高度')" v-if="hasKey('topHeight')">
            <a-input-number v-model:value="data.options.topHeight" size="mini" :min="0" />
          </a-form-item>
          <a-form-item :label="t('显示底部')" v-if="hasKey('showBottom')">
            <a-switch v-model:checked="data.options.showBottom" />
          </a-form-item>
          <a-form-item :label="t('底部高度')" v-if="hasKey('bottomHeight')">
            <a-input-number v-model:value="data.options.bottomHeight" size="mini" :min="0" />
          </a-form-item>
          <a-form-item
            :label="t('刷新组件')"
            v-if="hasKey('refreshComponent') && data.type !== 'list'"
            @click="handleRefreshClick"
          >
            <a-select
              v-model:value="data.options.refreshComponent"
              style="width: 100%"
              mode="multiple"
              :options="refreshComponentOption"
              @change="handleRefreshComp"
              @deselect="handleDeleteRelate"
            />
          </a-form-item>
          <a-form-item label="按钮配置" v-if="data.type == 'list'">
            <a-input
              :value="data.options.buttonList?.length ? t('已配置') : ''"
              :placeholder="t('点击进行按钮配置')"
              @click="handleButtonConfig"
            >
              <template #suffix>
                <Icon icon="ant-design:ellipsis-outlined" />
              </template>
            </a-input>
          </a-form-item>
          <template v-if="data.type == 'iframe'">
            <a-form-item label="url">
              <a-textarea
                v-model:value="data.options.url"
                placeholder="请填写url,参数可用@代替。例如:https://www.learun.cn?id=@id"
              />
            </a-form-item>
            <a-form-item label="参数配置">
              <a-input
                :value="data.options.list?.length ? t('已配置') : ''"
                :placeholder="t('点击进行参数配置')"
                @click="handleIframeConfig"
              >
                <template #suffix>
                  <Icon icon="ant-design:ellipsis-outlined" />
                </template>
              </a-input>
            </a-form-item>
          </template>
          <a-form-item :label="t('组件宽度')" v-if="hasKey('width')">
            <a-input v-model:value="data.options.width" />
          </a-form-item>
          <a-form-item :label="t('组件高度')" v-if="hasKey('height')">
            <a-input v-model:value="data.options.height" />
          </a-form-item>
          <a-form-item :label="t('填充表单')" v-if="hasKey('setFormDatas')">
            <div @click="showFormDataDialog" class="inline-block w-full">
              <InputModel
                :value="data.options.setFormDatas.length > 0 ? t('已配置') : ''"
                :placeholder="t('点击进行配置')"
                style="width: 100%; min-width: 100px"
              />
            </div>
          </a-form-item>
          <template v-if="data.type == 'collapse'">
            <a-button type="primary" @click="addCollapse" class="w-full">{{
              t('添加折叠卡')
            }}</a-button>
            <Draggable v-model:list="data.layout">
              <template #item="{ element: childElement, index: childIndex }">
                <div class="flex items-center justify-between mt-2">
                  <div>
                    <svg class="icon" aria-hidden="true">
                      <use xlink:href="#icon-fangxiang1" />
                    </svg>
                  </div>
                  <div> <a-input v-model:value="childElement.title" size="mini" /></div>
                  <div>
                    <DeleteTwoTone two-tone-color="#ff8080" @click="buttonRemove(childIndex)"
                  /></div>
                </div>
              </template>
            </Draggable>
          </template>
        </a-collapse-panel>
        <ChartProperty v-if="data.type == 'chart'" />
        <a-collapse-panel key="dataSetting" v-if="data.type == 'tree'">
          <template #header><NodeHead nodeName="数据配置" /> </template>
          <a-form-item label="">
            <a-radio-group
              button-style="solid"
              v-model:value="data.options.datasourceType"
              size="small"
              class="w-full !flex text-center"
            >
              <a-radio-button value="static" class="flex-1">{{ t('树结构') }}</a-radio-button>
              <a-radio-button value="api" class="flex-1">API</a-radio-button>
              <a-radio-button value="dic" class="flex-1">{{ t('数据字典') }}</a-radio-button>
            </a-radio-group>
          </a-form-item>
          <a-form-item :label="t('选择已有树')" v-if="data.options.datasourceType == 'static'">
            <a-select
              v-model:value="data.options.treeConfig.id"
              style="width: 100%"
              :options="treeSelectOption"
              :field-names="{ label: 'name', value: 'id', options: 'children' }"
            />
          </a-form-item>
          <template v-if="data.options.datasourceType === 'api'">
            <a-form-item :label="t('API配置')" required>
              <div @click="showApiDialog" class="inline-block w-full">
                <InputModel
                  :value="data.options.apiConfig.path"
                  :placeholder="t('点击进行接口配置')"
                  style="width: 100%; min-width: 100px"
                />
              </div>
            </a-form-item>
            <a-form-item :label="t('父级图标')">
              <IconPicker
                v-model:value="data.options.parentIcon"
                :disabled="false"
                :readonly="false"
              />
            </a-form-item>
            <a-form-item :label="t('子级图标')">
              <IconPicker
                v-model:value="data.options.childIcon"
                :disabled="false"
                :readonly="false"
              />
            </a-form-item>
          </template>
          <template v-if="data.options.datasourceType === 'dic'">
            <a-form-item :label="t('数据选项')" required>
              <DicTreeSelect class="text-left" v-model:value="data.options.dictionaryItemId" />
            </a-form-item>
            <a-form-item :label="t('图标')">
              <IconPicker
                v-model:value="data.options.childIcon"
                :disabled="false"
                :readonly="false"
              />
            </a-form-item>
          </template>
        </a-collapse-panel>
        <a-collapse-panel key="dataSetting" v-if="data.type == 'search'">
          <template #header><NodeHead nodeName="查询配置" /> </template>
          <a-form-item label="">
            <div @click="showSearchDialog" class="inline-block w-full">
              <InputModel
                :value="data.options.config?.length > 0 ? t('已配置') : ''"
                :placeholder="t('点击进行配置')"
                style="width: 100%; min-width: 100px"
              />
            </div>
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel key="tableDataSetting" v-if="data.type == 'list'" class="relative">
          <template #header><NodeHead nodeName="数据配置" /> </template>
          <template v-if="data.options.type == TableType.API">
            <a-form-item :label="t('刷新组件')" @click="handleRefreshClick">
              <a-select
                v-model:value="data.options.refreshComponent"
                style="width: 100%"
                mode="multiple"
                :options="refreshComponentOption"
                @change="handleRefreshComp"
                @deselect="handleDeleteRelate"
              />
            </a-form-item>
            <a-form-item :label="t('数据视图')">
              <SelectApi
                v-model:value="data.options.apiConfig"
                :exampleStr="exampleStr"
                from="pageDesign"
                :refreshComponent="data.options.refreshComponent"
                @save="changeApiConfig"
              />
            </a-form-item>
            <a-form-item :label="t('关联表单')">
              <a-switch v-model:checked="data.options.associatedForm" />
            </a-form-item>

            <a-form-item :label="t('选择表单')">
              <template v-if="data.options.associatedForm">
                <SettingForm
                  v-model:formId="data.options.formId"
                  v-model:formName="data.options.formName"
                  v-model:systemComponent="data.options.systemComponent"
                  @change="changeSettingForm"
                >
                  <a-input v-model:value="data.options.formName" placeholder="请选择表单" />
                </SettingForm>
              </template>
              <template v-else>
                <a-input disabled v-model:value="data.options.formName" placeholder="请选择表单" />
              </template>
            </a-form-item>
            <a-form-item :label="t('选择主键')" v-if="data.options.type == TableType.API">
              <a-select v-model:value="data.options.primaryKey" style="width: 100%">
                <a-select-option
                  v-for="(item, index) in data.options.apiColumns"
                  :key="index"
                  :value="item.prop"
                  >{{ item.label ? item.label : item.prop }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </template>
          <template v-if="data.options.type == TableType.FORM">
            <a-form-item :label="t('选择表单')">
              <SettingForm
                v-model:formId="data.options.formId"
                v-model:formName="data.options.formName"
                v-model:systemComponent="data.options.systemComponent"
                @change="changeReleaseSettingForm"
              >
                <a-input v-model:value="data.options.formName" placeholder="请选择表单" />
              </SettingForm>
            </a-form-item>
            <a-form-item
              :label="t('查询配置')"
              v-if="data.options.formType == FormTypeEnum.CUSTOM_FORM"
            >
              <a-select
                v-model:value="data.options.releaseId"
                style="width: 100%"
                placeholder="请选择表单的查询配置（来源为表单发布）"
                @change="changeReleaseForm"
              >
                <a-select-option
                  v-for="(item, index) in releaseFormList"
                  :key="index"
                  :value="item.id"
                  >{{ item.menuName }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </template>
          <a-form-item :label="t('每页条数')">
            <a-select
              v-model:value="data.options.pageSize"
              style="width: 100%"
              :options="pageSizeOptions"
            />
          </a-form-item>
          <!-- 添加字段 -->
          <a-form-item :colon="false" labelAlign="left">
            <div class="card-box" v-if="data.options.columns && data.options.columns.length > 0">
              <div class="card-item" v-for="(item, index) in data.options.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.options.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" />
                </a-form-item>
                <a-form-item
                  :label="t('宽度')"
                  :label-col="{ style: { width: '112px' } }"
                  :colon="false"
                  required
                >
                  <a-input v-model:value="item.width" />
                </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%"
                    :options="alignOptions"
                  />
                </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" />
                </a-form-item>

                <div
                  class="close-icon"
                  v-if="data.options.columns && data.options.columns.length > 1"
                  @click="deleteColumn(index)"
                >
                  <IconFontSymbol
                    icon="chongzhishibai"
                    fillColor="rgb(255 84 97 / 50%)"
                    fontSize="14"
                  />
                </div>
              </div>
            </div>
          </a-form-item>
          <PlusCircleFilled class="add-custom" @click="addColumn" />
        </a-collapse-panel>
        <a-collapse-panel key="buttonSetting" v-if="data.type == 'button'">
          <template #header><NodeHead nodeName="按钮配置" /> </template>
          <a-button type="primary" @click="addButtons" class="w-full mb-3">{{
            t('添加按钮')
          }}</a-button>
          <a-form-item :colon="false" labelAlign="left">
            <div class="card-box" v-if="data.options.buttons && data.options.buttons.length > 0">
              <div class="card-item" v-for="(item, index) in data.options.buttons" :key="item.code">
                <a-form-item
                  :label="t('按钮名称')"
                  required
                  :label-col="{ style: { width: '80px' } }"
                  :colon="false"
                  :wrapperCol="{
                    style: { textAlign: 'right', paddingRight: '10px' },
                  }"
                >
                  <a-input
                    v-model:value="item.name"
                    :placeholder="t('请输入按钮名称')"
                    @blur="handleBlur(item)"
                  />
                </a-form-item>
                <a-form-item
                  :label="t('按钮图标')"
                  :label-col="{ style: { width: '80px' } }"
                  :colon="false"
                  :wrapperCol="{
                    style: { textAlign: 'right', paddingRight: '10px' },
                  }"
                >
                  <IconPicker v-model:value="item.icon" :disabled="false" :readonly="false" />
                </a-form-item>
                <a-form-item
                  :label="t('按钮样式')"
                  :label-col="{ style: { width: '80px' } }"
                  :colon="false"
                  :wrapperCol="{
                    style: { textAlign: 'right', paddingRight: '10px' },
                  }"
                >
                  <a-select v-model:value="item.style" :placeholder="t('请选择按钮样式')">
                    <a-select-option value="primary">主按钮</a-select-option>
                    <a-select-option value="default">默认按钮</a-select-option>
                    <a-select-option value="danger">危险按钮</a-select-option>
                    <a-select-option value="link">链接按钮</a-select-option>
                    <a-select-option value="text">文本按钮</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="按钮类型"
                  :name="['sights', index, 'label']"
                  :label-col="{ style: { width: '80px' } }"
                  :colon="false"
                  :wrapperCol="{
                    style: { textAlign: 'right', paddingRight: '10px' },
                  }"
                >
                  <a-select v-model:value="item.type" style="width: 100%">
                    <a-select-option :value="CustomButtonModalType.COMMON"
                      >普通按钮</a-select-option
                    >
                    <a-select-option :value="CustomButtonModalType.Modal">弹窗按钮</a-select-option>
                  </a-select>
                </a-form-item>
                <template v-if="item.type == CustomButtonModalType.Modal">
                  <a-form-item
                    :name="['sights', index, 'modal']"
                    label="弹窗配置"
                    :label-col="{ style: { width: '80px' } }"
                    :colon="false"
                    :wrapperCol="{
                      style: { textAlign: 'right', paddingRight: '10px' },
                    }"
                  >
                    <ButtonModalConfig v-model:modalData="item.modal" :formJson="[]">
                      <a-input
                        :value="item.modal?.bindModal ? t('已配置') : t('点击进行配置')"
                        :placeholder="t('点击进行配置')"
                      >
                        <template #suffix>
                          <Icon icon="ant-design:ellipsis-outlined" />
                        </template>
                      </a-input>
                    </ButtonModalConfig>
                  </a-form-item>
                </template>
                <template v-else>
                  <a-form-item
                    :label="t('事件配置')"
                    :label-col="{ style: { width: '80px' } }"
                    :colon="false"
                    :wrapperCol="{
                      style: { textAlign: 'right', paddingRight: '10px' },
                    }"
                  >
                    <ExecuteEvent v-model:processEvent="item.event">
                      <InputModel
                        :value="item.event.length > 0 ? t('已配置') : t('点击进行配置')"
                        :placeholder="t('点击进行配置')"
                        style="width: 100%; min-width: 100px"
                      />
                    </ExecuteEvent>
                  </a-form-item>
                  <a-form-item
                    :label="t('点击事件')"
                    :label-col="{ style: { width: '80px' } }"
                    :colon="false"
                    :wrapperCol="{
                      style: { textAlign: 'right', paddingRight: '10px' },
                    }"
                  >
                    <div @click="showScriptDialog(index)">
                      <InputModel
                        :value="item.clickEvent ? t('已配置') : t('点击进行配置')"
                        :placeholder="t('点击进行配置')"
                        style="width: 100%; min-width: 100px"
                      />
                    </div>
                  </a-form-item>
                </template>
                <div
                  class="close-icon"
                  v-if="data.options.buttons && data.options.buttons.length >= 1"
                  @click="deleteButtons(index)"
                >
                  <IconFontSymbol
                    icon="chongzhishibai"
                    fillColor="rgb(255 84 97 / 50%)"
                    fontSize="14"
                  />
                </div>
              </div>
            </div>
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel key="event" v-if="data.type == 'tree'">
          <template #header><NodeHead nodeName="事件配置" /> </template>
          <ComponentEvent :widgetForm="widgetForm" />
        </a-collapse-panel>
      </a-collapse>
    </a-form>
    <ApiConfig
      v-if="apiConfigDialog"
      :isLeftMenu="true"
      v-model:apiConfigDialog="apiConfigDialog"
      v-model:apiConfig="data.options.apiConfig"
      :title="t('API配置')"
    />
    <SearchConfigSetting
      v-if="searchConfigDialog"
      v-model:configDialog="searchConfigDialog"
      v-model:config="data.options.config"
      v-model:schemas="data.options.schemas"
      v-model:fieldMapToTime="data.options.fieldMapToTime"
    />
    <FormDatasSetting
      v-if="formDataDialog"
      v-model:configDialog="formDataDialog"
      v-model:config="data.options.setFormDatas"
      :formProps="formProps"
      :refreshComponent="data.options.refreshComponent"
    />
    <IframeConfig
      v-if="iframeConfigDia"
      v-model:iframeConfigDia="iframeConfigDia"
      v-model:list="data.options.list"
      :dataKey="data.options.refreshComponent"
    />
    <TableButtonSetting
      v-if="buttonConfigDia"
      v-model:configDia="buttonConfigDia"
      v-model:list="data.options.buttonList"
      :dataKey="data.options.refreshComponent"
    />
    <ButtonScript @register="registerModal" @success="submitConfig" />
  </div>
</template>

<script lang="ts" setup>
  import { inject, ref, watch, onMounted } from 'vue';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    betterPropertyLayout,
    collapseTypeOption,
    exampleStr,
    chartOptions,
    pageSizeOptions,
    alignOptions,
    chartType,
  } from '../types';
  import Draggable from 'vuedraggable';
  import { DeleteTwoTone } from '@ant-design/icons-vue';
  import { buildUUID } from '/@/utils/uuid';
  import { geList } from '/@/api/system/generator/treeStructure';
  import { InputModel, ApiConfig } from '/@/components/ApiConfig';
  import { IconPicker } from '/@/components/Icon';
  import { DicTreeSelect } from '/@/components/DicTreeSelect';
  import ComponentEvent from './property/ComponentEvent.vue';
  import SearchConfigSetting from './property/searchConfigSetting.vue';
  import FormDatasSetting from './property/formDatasSetting.vue';
  import SelectApi from '/@/views/generator/desktop/components/designer/properties/collapse/complex/SelectApi.vue';
  import SettingForm from '/@/views/generator/desktop/components/designer/properties/collapse/form/SettingForm.vue';
  import IframeConfig from './property/IframeConfig.vue';
  import ButtonScript from './property/ButtonScript.vue';
  import ChartProperty from './property/chartProperty/chartProperty.vue';
  import ChartBaseSetting from './property/chartProperty/baseSetting.vue';
  import { tableDefaultColumnItem } from '/@/views/generator/desktop/components/designer/config/properties';
  import TableButtonSetting from './property/tableButtonSetting.vue';
  import { getFormTemplate, getReleaseInfo, getTableInfo } from '/@/api/form/design';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import { TableType } from '/@/enums/desktop';
  import { cloneDeep, random } from 'lodash-es';
  import { PlusCircleFilled } from '@ant-design/icons-vue';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';
  import { changePageDesignApiOptions, getTableComponents } from '../types/tool';
  import { changeToPinyin } from '/@/utils/event/design';
  import ExecuteEvent from './property/ExecuteEvent.vue';
  import { useModal } from '/@/components/Modal';
  import {
    categoryStackProperties,
    chartBarProperties,
    chartLineProperties,
    funnelProperties,
    gaugeProperties,
    pieProperties,
    radarProperties,
  } from './property/chartProperty/properties';
  import ButtonModalConfig from '/@/components/CreateCodeStep/src/components/ButtonModalConfig.vue';

  import { CustomButtonModalType } from '/@/enums/userEnum';
  const { t } = useI18n();

  const props = defineProps({
    widgetForm: {
      type: Array,
    },
  });
  const data = inject('selectWidget', ref<any>({}));
  const widgetFormModel = inject('widgetFormModel', ref<any>({}));

  const chooseTab = ref(['property', 'buttonSetting']);
  const layout = {
    layout: 'horizontal',
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
    labelAlign: 'left',
    colon: false,
  };
  let treeSelectOption = ref([]);
  const apiConfigDialog = ref<boolean>(false);
  const searchConfigDialog = ref<boolean>(false);
  const formDataDialog = ref<boolean>(false);
  const iframeConfigDia = ref<boolean>(false);
  const buttonConfigDia = ref<boolean>(false);
  const btnClickEventIndex = ref();
  const releaseFormList = ref<any>([]);
  const refreshComponentOption = ref<any>([]);
  const formProps = ref<any>([]);
  const hasKey = (key: string) => Object.keys(data.value.options).includes(key);
  const [registerModal, { openModal }] = useModal();
  onMounted(() => {
    initTreeData();
    allComponents.value = [];
    getTableComponents(props.widgetForm, allComponents.value);
    getRefreshComponent();
  });
  watch(
    () => data.value,
    async (val) => {
      if (val.type === 'form') {
        handleFormChange();
      }
    },
    { deep: true },
  );
  watch(
    () => data.value.key,
    async () => {
      if (hasKey('refreshComponent')) {
        await getRefreshComponent();
        data.value.options.refreshComponent = data.value.options.refreshComponent?.filter((o) => {
          let obj = refreshComponentOption.value.find((k) => k.value == o);
          if (obj) {
            let item = allComponents.value.find((k) => k.key == o);
            if (item) obj.label = item.options.label;
            return o;
          } else {
            handleDeleteRelate(o);
          }
        });
      }
      if (data.value.type == 'list') {
        if (data.value.options.type == TableType.FORM) {
          changeForm();
        } else if (data.value.options.type == TableType.API) {
          if (data.value.options.columns.length <= 0) {
            changeApiConfig(data.value.options.apiConfig);
          }
        }
      }
    },
  );
  function handleRefreshClick() {
    if (['list', 'form', 'iframe', 'chart'].includes(data.value.type)) {
      getRefreshComponent();
      data.value.options.refreshComponent = data.value.options.refreshComponent?.filter((o) => {
        let obj = refreshComponentOption.value.find((k) => k.value == o);
        if (obj) {
          return o;
        } else {
          handleDeleteRelate(o);
        }
      });
    }
  }

  watch(
    () => data.value.options.apiConfig,
    async (val) => {
      let config = data.value.options;
      if (val?.path && data.value.type == 'chart' && config.chartType !== chartType.line) {
        config.apiData = [];
        config.apiColumns = [];
        if (config.chartType === chartType.pie) {
          // config.valueKey = '';
          // config.labelKey = '';
        } else if (config.chartType === chartType.radar) {
          // config.labelKey = '';
          // config.echarts.radar.indicator = config.echarts.radar.indicator.map((ele) => {
          //   ele.value = '';
          //   return ele;
          // });
        } else if (config.chartType === chartType.gauge) {
          // config.valueKey = '';
        } else if (config.chartType === chartType.funnel) {
          // config.valueKey = '';
          //  config.labelKey = '';
          config.echarts.legend.data = [];
          config.echarts.series[0].data = [];
        } else if ([chartType.barStack, chartType.barPercent].includes(config.chartType)) {
          // config.labelKey = '';
          // config.valueKey = '';
          // config.targetKey = '';
        }

        if (val) {
          let res = await changePageDesignApiOptions(val, widgetFormModel.value);

          if (res.list && Array.isArray(res.list)) {
            config.apiData = res.list;
          }
          if (res.columns && Array.isArray(res.columns)) config.apiColumns = res.columns;
        }
      }
    },
    { deep: true },
  );
  watch(
    () => props.widgetForm,
    (val) => {
      allComponents.value = [];
      getTableComponents(val, allComponents.value);
      getRefreshComponent();
    },
    { deep: true },
  );

  const allComponents = ref<any>([]);
  function getRefreshComponent() {
    refreshComponentOption.value = [];

    allComponents.value.forEach((item: any) => {
      if (['list', 'tree', 'search', 'form'].includes(item.type)) {
        if (item.key !== data.value.key) {
          refreshComponentOption.value.push({
            label: item.options.label,
            value: item.key,
          });
        }
      }
    });
  }
  function buttonRemove(Index) {
    data.value.layout.splice(Index, 1);
  }
  function addCollapse() {
    data.value.layout.push({
      key: buildUUID(),
      title: '',
      list: [],
    });
  }
  function addTabItem() {
    data.value.layout.push({
      name: 'tab3',
      span: 24,
      prefix: '',
      suffix: '',
      activeColor: '#1c8dff',
      folderId: '',
      imageUrl: '',
      conImageUrl: '',
      conFolderId: '',
      list: [],
    });
  }
  async function initTreeData() {
    let res: any = await geList();
    treeSelectOption.value = res;
  }
  const showApiDialog = () => {
    apiConfigDialog.value = true;
  };
  const showSearchDialog = () => {
    searchConfigDialog.value = true;
  };
  const showFormDataDialog = () => {
    formDataDialog.value = true;
  };
  const handleIframeConfig = () => {
    iframeConfigDia.value = true;
  };
  const handleButtonConfig = () => {
    buttonConfigDia.value = true;
  };
  const showScriptDialog = (index) => {
    btnClickEventIndex.value = index;
    openModal(true, {
      content: data.value.options.buttons[index].clickEvent,
    });
  };
  const submitConfig = (value) => {
    data.value.options.buttons[btnClickEventIndex.value].clickEvent = value;
  };
  async function changeApiConfig(val) {
    if (val && val.path) {
      let res = await changePageDesignApiOptions(val, widgetFormModel.value);
      if (res && res.columns) {
        data.value.options.apiColumns = res.columns;
        data.value.options.dataList = res.list;
        data.value.options.total = res.total;
        if (data.value.options.columns.length <= 0) {
          res.columns.forEach((o) => {
            data.value.options.columns.push({
              dataIndex: o.prop,
              title: o.label,
              width: 80,
              align: 'left',
              show: true,
            });
          });
        }
      } else {
        data.value.options.columns = [];
        data.value.options.apiColumns = [];
        data.value.options.dataList = [];
        data.value.options.total = 0;
      }
    }
  }
  async function handleFormChange(setting?) {
    if (setting) data.value.options.formType = setting.checkFormType;
    if (data.value.options.formId) {
      try {
        const templateResult = await getFormTemplate(data.value.options.formId);
        const formJson = JSON.parse(templateResult.formJson);
        formProps.value = formJson.formJson.list;
      } catch (error) {
        //console.log('error: ', error);
      }
    }
  }
  async function changeSettingForm(setting) {
    data.value.options.formType = setting.checkFormType;
    await changeForm();
  }
  async function changeReleaseSettingForm(setting) {
    data.value.options.formType = setting.checkFormType;
    data.value.options.apiColumns = [];
    data.value.options.columns = [];
    data.value.options.releaseId = '';
    releaseFormList.value = [];
    data.value.options.columns.push(cloneDeep(tableDefaultColumnItem));
    await changeForm();
  }
  async function changeForm() {
    if (data.value.options.formId) {
      try {
        const templateResult = await getReleaseInfo(data.value.options.formId);
        if (templateResult && Array.isArray(templateResult) && templateResult.length > 0) {
          releaseFormList.value = templateResult;
        }
        changeReleaseForm();
      } catch (error) {
        // console.log('error: ', error);
      }
    }
  }
  async function changeReleaseForm() {
    if (data.value.options.type == TableType.FORM && data.value.options.formId) {
      try {
        const res = await getTableInfo(data.value.options.formId);

        if (res.pkName) {
          data.value.options.primaryKey = res.pkName;
        }
        if (
          res.deskColumnsVoList &&
          Array.isArray(res.deskColumnsVoList) &&
          res.deskColumnsVoList.length > 0
        ) {
          data.value.options.apiColumns = cloneDeep(res.deskColumnsVoList);
        }
      } catch (error) {
        // console.log('error: ', error);
      }
    }
  }
  async function changeType() {
    if (data.value.options.type == TableType.API) {
      data.value.options.columns = [];
      await changeApiConfig(data.value.options.apiConfig);
    } else {
      releaseFormList.value = [];
      data.value.options.formId = '';
      data.value.options.formName = '';
      data.value.options.releaseId = '';
      data.value.options.apiColumns = [];
      data.value.options.columns = [];
    }
    data.value.options.columns.push(cloneDeep(tableDefaultColumnItem));
  }
  function changeDataIndex(item) {
    if (item.dataIndex && item.title == '') {
      let val = data.value.options.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;
    }
  }
  function deleteColumn(index) {
    data.value.options.columns.splice(index, 1);
  }
  function addColumn() {
    data.value.options.columns.push(cloneDeep(tableDefaultColumnItem));
  }
  const deleteButtons = (index: number) => {
    data.value.options.buttons.splice(index, 1);
  };
  const addButtons = () => {
    const com: any = {
      code: '',
      name: '按钮',
      style: 'primary',
      event: [],
      clickEvent: '',
      type: CustomButtonModalType.COMMON,
    };
    data.value.options.buttons.push(com);
  };
  function handleBlur(record) {
    record.code = changeToPinyin(record.name, false) + random(1000, 9999);
  }
  function changeChartType(val) {
    let base = {
      label: data.value.options.label,
      chartType: val,
      width: data.value.options.width,
      height: data.value.options.height,
      refreshComponent: data.value.options.refreshComponent,
    };
    if (val === chartType.line) {
      data.value.options = { ...cloneDeep(chartLineProperties), ...base };
    } else if (val === chartType.pie) {
      data.value.options = { ...pieProperties, ...base };
    } else if (val === chartType.radar) {
      data.value.options = { ...radarProperties, ...base };
    } else if (val === chartType.gauge) {
      data.value.options = { ...gaugeProperties, ...base };
    } else if (val === chartType.funnel) {
      data.value.options = { ...funnelProperties, ...base };
    } else if (val === chartType.barPercent) {
      data.value.options = { ...chartBarProperties, ...base };
    } else if (val === chartType.barStack) {
      data.value.options = { ...categoryStackProperties, ...base };
    }
  }

  function handleDeleteRelate(v) {
    let obj = allComponents.value.find((k: any) => k.key == v);

    if (obj && obj.options.events) {
      let str = `formActionType.refreshAPI('${data.value.key}')`;

      if (obj.options.events.refreshComp?.includes(str)) {
        obj.options.events.refreshComp = obj.options.events.refreshComp.replace(str, '');
      }
    }
    if (data.value.type == 'form') {
      data.value.options.setFormDatas.forEach((o) => {
        let value = JSON.parse(o.value);
        if (value?.parentKey == v) {
          o.value = null;
        }
      });
    } else if (data.value.type == 'list') {
      clearApiConfigData(data.value.options.apiConfig, v);
    } else if (data.value.type == 'iframe') {
      data.value.options.list.forEach((o) => {
        let value = JSON.parse(o.value);
        if (value?.parentKey == v) {
          o.value = null;
        }
      });
    } else if (data.value.type == 'chart') {
      if (data.value.options.chartType == chartType.line) {
        data.value.options.dataList.forEach((o) => {
          clearApiConfigData(o.apiConfig, v);
        });
      } else {
        clearApiConfigData(data.value.options.apiConfig, v);
      }
    }
  }
  function handleRefreshComp(v) {
    v.forEach((o) => {
      let obj: any = allComponents.value.find((k: any) => k.key == o);

      if (obj && obj.options.events) {
        if (!obj.options.events.refreshComp) obj.options.events.refreshComp = '';
        let str = `formActionType.refreshAPI('${data.value.key}')`;
        if (!obj.options.events.refreshComp.includes(str)) {
          obj.options.events.refreshComp += `${str};`;
        }
      }
    });
  }
  function clearApiConfigData(apiConfig, v) {
    if (apiConfig?.path) {
      if (apiConfig.requestHeaderConfigs.length > 0) {
        apiConfig.requestHeaderConfigs.forEach((element) => {
          let value = JSON.parse(element.value);
          if (value?.parentKey == v) {
            element.value = null;
          }
        });
      }

      if (apiConfig.requestParamsConfigs.length > 0) {
        apiConfig.requestParamsConfigs.forEach((element) => {
          let value = JSON.parse(element.value);
          if (value?.parentKey == v) {
            element.value = null;
          }
        });
      }

      if (apiConfig.requestBodyConfigs.length > 0) {
        apiConfig.requestBodyConfigs.forEach((element) => {
          let value = JSON.parse(element.value);
          if (value?.parentKey == v) {
            element.value = null;
          }
        });
      }
    }
  }
</script>
<style scoped lang="less">
  .awc-containter {
    height: calc(100% - 50px);
    overflow: auto;

    :deep(.ant-form-item) {
      margin-bottom: 10px;
    }
  }

  :deep(.ant-input-number) {
    width: 100%;
  }

  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentcolor;
    overflow: hidden;
  }

  :deep(.ant-form-item .ant-select) {
    text-align: left;
  }

  :deep(.add-custom) {
    color: #1c8dff;
    font-size: 14px;
    position: absolute;
    top: 18px;
    right: 38px;
  }

  :deep(.card-box) {
    .card-item {
      position: relative;
      margin: 0 0 12px;
      padding: 12px 10px 10px;
      background: #f3f3f3;
      border-radius: 4px;
    }

    .close-icon {
      position: absolute;
      top: -6px;
      right: -6px;

      .iconfont-svg {
        fill: rgb(255 84 97 / 50%);
      }
    }
  }
</style>
