<template>
  <div class="fc-style">
    <a-layout class="fc-container">
      <a-layout-content class="fc-main">
        <a-layout>
          <a-layout-sider theme="light" :width="250" class="cg-container">
            <div
              class="flex items-center justify-center h-full flex-col text-[18px] text-[#ccc] text-center leading-6"
            >
              <Icon icon="ant-design:stop-twotone" size="28" />
              <div>系统功能页面不允许操作组件</div>
              <div>只能针对组件进行排版布局及样式调整</div>
            </div>
          </a-layout-sider>
          <a-layout class="center-container">
            <a-layout-content id="layoutId" :class="{ 'widget-empty': widgetForm.list }">
              <MobileLayout>
                <template #designContent>
                  <AntdWidgetForm
                    ref="widgetFormRef"
                    v-model:widgetForm="widgetForm"
                    v-model:widgetFormSelect="widgetFormSelect"
                  />
                </template>
              </MobileLayout>
            </a-layout-content>
          </a-layout>
          <a-layout-sider theme="light" class="widget-config-container" :width="320">
            <a-layout class="layout-height">
              <a-tabs v-model:activeKey="configTab" centered style="background: #fff; height: 100%">
                <a-tab-pane key="widget" :tab="t('组件属性')">
                  <a-collapse
                    v-model:activeKey="chooseTab"
                    ghost
                    expandIconPosition="right"
                    v-if="widgetFormSelect"
                  >
                    <a-collapse-panel key="property">
                      <template #header><NodeHead nodeName="属性设置" /> </template>
                      <div class="widget-none" v-if="['grid'].includes(widgetFormSelect.type)">
                        <SvgIcon name="exclamation" :size="44" />
                        <p>{{ t(widgetFormSelect.label + '不允许配置属性设置') }}</p>
                      </div>

                      <TableLayoutOption
                        v-if="widgetFormSelect.type == 'table-layout'"
                        v-model:select="widgetFormSelect"
                        :widgetForm="widgetForm"
                      />
                      <PropertyOption
                        v-model:select="widgetFormSelect"
                        :widgetForm="widgetForm"
                        v-else
                      />
                    </a-collapse-panel>
                    <a-collapse-panel key="event">
                      <template #header><NodeHead nodeName="触发事件" /> </template>
                      <div
                        class="widget-none"
                        v-if="noConfigComponentEvent.includes(widgetFormSelect.type)"
                      >
                        <SvgIcon name="exclamation" :size="44" />
                        <p>{{ t('当前组件无法配置触发组件') }}</p>
                      </div>
                      <ComponentEvent
                        v-model:select="widgetFormSelect"
                        :widgetForm="widgetForm"
                        :disabled="true"
                        v-else
                      />
                    </a-collapse-panel>
                    <a-collapse-panel key="regular">
                      <template #header><NodeHead nodeName="正则校验" /> </template>
                      <div
                        class="widget-none"
                        v-if="noConfigRegularSetting.includes(widgetFormSelect.type)"
                      >
                        <SvgIcon name="exclamation" :size="44" />
                        <p>{{ t(widgetFormSelect.label + '无法配置正则检验') }}</p>
                      </div>
                      <RegularSetting v-model:select="widgetFormSelect" v-else />
                    </a-collapse-panel>
                  </a-collapse>
                  <div class="widget-none" v-else>
                    <SvgIcon name="tool" :size="44" />
                    <p>{{ t('点击组件后再查看组件属性') }}</p>
                  </div>
                </a-tab-pane>
                <!-- <a-tab-pane key="form" :tab="t('表单属性')">
                  <AntdFormConfig v-model:config="widgetForm.config" />
                </a-tab-pane> -->
              </a-tabs>
            </a-layout>
          </a-layout-sider>
        </a-layout>
      </a-layout-content>

      <a-modal
        v-model:visible="uploadJsonVisible"
        :title="t('导入JSON')"
        :width="800"
        @ok="handleUploadJson"
        :okText="t('确认')"
        :cancelText="t('取消')"
      >
        <a-alert
          type="info"
          :message="t('JSON格式如下，直接复制生成的json覆盖此处代码点击确定即可')"
          style="margin-bottom: 10px"
        />
        <CodeEditor v-model:value="jsonEg" language="json" />
      </a-modal>

      <a-modal
        v-model:visible="generateJsonVisible"
        :title="t('生成JSON')"
        :okText="t('复制')"
        :cancelText="t('取消')"
        :width="800"
        @ok="handleCopyClick(generateJsonTemplate)"
      >
        <CodeEditor :value="generateJsonTemplate" language="json" readonly />
      </a-modal>

      <a-modal
        v-model:visible="dataJsonVisible"
        :title="t('获取数据')"
        :okText="t('复制')"
        :cancelText="t('取消')"
        :width="800"
        @ok="handleCopyClick(dataJsonTemplate)"
      >
        <CodeEditor :value="dataJsonTemplate" language="json" readonly />
      </a-modal>

      <a-modal
        v-model:visible="dataCodeVisible"
        :title="t('生产代码')"
        :okText="t('复制')"
        :cancelText="t('取消')"
        :width="800"
        @ok="handleCopyClick(dataCodeTemplate)"
      >
        <a-tabs type="card" v-model:activeKey="codeLanguage" :tabBarStyle="{ margin: 0 }">
          <a-tab-pane tab="Vue Component" :key="codeType.Vue">
            <CodeEditor :value="dataCodeTemplate" language="html" readonly />
          </a-tab-pane>
          <a-tab-pane tab="HTML" :key="codeType.Html">
            <CodeEditor :value="dataCodeTemplate" language="html" readonly />
          </a-tab-pane>
        </a-tabs>
      </a-modal>
    </a-layout>
  </div>
</template>

<script lang="ts">
  import {
    defineComponent,
    reactive,
    PropType,
    toRefs,
    watchEffect,
    provide,
    watch,
    inject,
    ref,
  } from 'vue';
  import { message } from 'ant-design-vue';
  import { cloneDeep, merge, debounce } from 'lodash-es';
  import { CodeEditor } from '/@/components/CodeEditor';

  import AntdWidgetForm from './AntdWidgetForm.vue';
  import PropertyOption from './PropertyOption.vue';
  import RegularSetting from '/@/components/Designer/src/components/componentProperty/RegularSetting.vue';
  import ComponentEvent from '/@/components/Designer/src/components/componentProperty/ComponentEvent.vue';
  import TableLayoutOption from './TableLayoutOption.vue';

  import * as antd from '/@/components/Designer/src/types';
  import { copy } from '/@/utils';
  import generateCode from '/@/components/Designer/src/util/generateCode';
  import { WidgetForm, CodeType, PlatformType, TableCell } from '/@/components/Designer/src/types';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { noConfigComponentEvent, noConfigRegularSetting } from '/@/components/Designer/src/types';
  import MobileLayout from '../../components/mobileLayout.vue';
  import { SvgIcon, Icon } from '/@/components/Icon';
  //import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  export default defineComponent({
    name: 'AntdDesignForm',
    components: {
      Icon,
      CodeEditor,
      AntdWidgetForm,
      TableLayoutOption,
      PropertyOption,
      RegularSetting,
      ComponentEvent,
      SvgIcon,
      MobileLayout,
      NodeHead,
    },
    props: {
      preview: {
        type: Boolean,
        default: true,
      },

      generateJson: {
        type: Boolean,
        default: true,
      },
      uploadJson: {
        type: Boolean,
        default: true,
      },
      clearable: {
        type: Boolean,
        default: true,
      },
      basicFields: {
        type: Array as PropType<Array<string>>,
        default: () => ['input', 'textarea', 'password', 'number', 'richtext-editor', 'auto-code'],
      },
      advanceFields: {
        type: Array as PropType<Array<string>>,
        default: () => [
          'select',
          'cascader',
          'associate-select',
          'multiple-popup',
          'associate-popup',
          'area',
          'checkbox',
          'radio',
          'switch',
          'slider',
          'time',
          'time-range',
          'date',
          'date-range',
          'rate',
          'picker-color',
          'upload',
          'image',
          'map',
          'qrcode',
        ],
      },
      buttonFields: {
        type: Array as PropType<Array<string>>,
        default: () => ['button'],
      },
      layoutFields: {
        type: Array as PropType<Array<string>>,
        default: () => ['form', 'one-for-one', 'title', 'grid', 'tab', 'card', 'divider'],
      },
      workFlowFields: {
        type: Array as PropType<Array<string>>,
        default: () => ['opinion'],
      },
      infoFields: {
        type: Array as PropType<Array<string>>,
        default: () => ['info', 'organization', 'user', 'role'],
      },
      financeFields: {
        type: Array as PropType<Array<string>>,
        default: () => ['computational', 'money-chinese'],
      },
    },
    setup(props) {
      const state = reactive({
        antd,
        codeType: CodeType,
        widgetForm: undefined as any,
        widgetFormSelect: undefined as any,
        generateFormRef: null as any,
        configTab: 'widget',
        chooseTab: 'property',
        previewVisible: false,
        uploadJsonVisible: false,
        dataJsonVisible: false,
        dataCodeVisible: false,
        generateJsonVisible: false,
        generateCodeVisible: false,
        generateJsonTemplate: JSON.stringify(antd.widgetForm, null, 2),
        dataJsonTemplate: '',
        dataCodeTemplate: '',
        codeLanguage: CodeType.Vue,
        jsonEg: JSON.stringify(antd.widgetForm, null, 2),
        componentGroupKey: ['1', '2', '3', '4', '5', '6'],
        componentList: [
          {
            title: t('输入型组件'),
            fields: props.basicFields,
            list: antd.basicComponents,
          },
          {
            title: t('选择型组件'),
            fields: props.advanceFields,
            list: antd.advanceComponents,
          },
          {
            title: t('按钮型组件'),
            fields: props.buttonFields,
            list: antd.buttonComponents,
          },
          {
            title: t('布局型组件'),
            fields: props.layoutFields,
            list: antd.layoutComponents,
          },
          {
            title: t('工作流组件'),
            fields: props.workFlowFields,
            list: antd.workFlowComponents,
          },
          {
            title: t('组织架构'),
            fields: props.infoFields,
            list: antd.infoComponents,
          },
          {
            title: t('财务组件'),
            fields: props.financeFields,
            list: antd.financeComponents,
          },
        ],
      });
      state.widgetForm = inject('widgetForm');
      const generatorConfig = inject<GeneratorConfig>('generatorConfig') as GeneratorConfig;
      //const { notification } = useMessage();
      const tableCell = ref<TableCell>();
      provide('tableCell', tableCell);
      //注入数据
      provide('state', state);

      const handleUploadJson = () => {
        try {
          setJson(JSON.parse(state.jsonEg));
          state.uploadJsonVisible = false;
          message.success(t('上传成功'));
        } catch (error) {
          message.error(t('上传失败'));
        }
      };

      const handleCopyClick = (text: string) => {
        copy(text);
        message.success(t('Copy成功'));
      };

      const handleGetData = () => {
        state.generateFormRef.getData().then((res: any) => {
          state.dataJsonTemplate = JSON.stringify(res, null, 2);
          state.dataJsonVisible = true;
        });
      };

      const handleGenerateJson = () => {
        (state.generateJsonTemplate = JSON.stringify(state.widgetForm, null, 2)) &&
          (state.generateJsonVisible = true);
      };

      const handleGenerateCode = () => {
        state.codeLanguage = CodeType.Vue;
        state.dataCodeVisible = true;
      };

      watchEffect(() => {
        if (state.dataCodeVisible) {
          state.dataCodeTemplate = generateCode(
            state.widgetForm,
            state.codeLanguage,
            PlatformType.Antd,
          )!;
        }
      });

      const handleClearable = () => {
        state.widgetForm.list = [];
        merge(state.widgetForm, JSON.parse(JSON.stringify(antd.widgetForm)));
        state.widgetFormSelect = undefined;
      };

      const handleReset = () => state.generateFormRef.reset();

      const getJson = () => state.widgetForm;

      const setJson = (json: WidgetForm) => {
        state.widgetForm.list = [];
        merge(state.widgetForm, json);
        if (json.list.length) {
          state.widgetFormSelect = json.list[0];
        }
      };
      // const designType = inject<string>('designType');

      const getTemplate = (codeType: CodeType) =>
        generateCode(state.widgetForm, codeType, PlatformType.Antd);

      const clear = () => handleClearable();

      //这里使用了防抖 包裹  因为监听 state.widgetForm 会执行2次
      watch(
        () => state.widgetForm,
        debounce((val) => {
          generatorConfig.formJson = cloneDeep(val);
        }, 50),
        { deep: true },
      );

      return {
        ...toRefs(state),
        handleUploadJson,
        handleCopyClick,
        handleGetData,
        handleGenerateJson,
        handleGenerateCode,
        handleClearable,
        handleReset,
        getJson,
        setJson,
        getTemplate,
        clear,
        noConfigComponentEvent,
        noConfigRegularSetting,
        t,
      };
    },
  });
</script>
<style scoped lang="less">
  .fc-style {
    height: 100%;
  }

  .layout-height {
    height: 100%;
    background-color: #f0f2f5;
  }

  :deep(.design-bg-box) {
    margin: 10px auto;

    .design-box {
      padding-top: 62px;
      padding-bottom: 22px;
      background: #fff;

      .design-content-box {
        padding: 0 80px;
      }
    }
  }

  :deep(.ant-tabs) {
    height: 100%;
  }

  //:deep(.ant-tabs-content-holder) {
  //overflow-y: auto;
  //padding: 0 10px 10px 0;
  //}

  :deep(.ant-tabs-content-top) {
    height: 100%;
  }

  :deep(.ant-radio-group) {
    display: flex;

    .ant-radio-button-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
      flex: 1;
      padding: 3px 0 !important;
    }
  }

  .widget-none {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    p {
      margin: 10px;
      color: #cecece;
    }
  }

  :deep(.ant-tabs-nav) {
    margin-bottom: 8px;
  }

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

  :deep(.ant-radio-group-small .ant-radio-button-wrapper) {
    padding: 3px 10px;
    box-sizing: content-box;
  }

  .fc-container {
    height: 100%;
  }

  .ant-layout.ant-layout-has-sider {
    height: 100%;
  }

  .center-container {
    height: 100%;
    background-color: #fff;
    padding-bottom: 20px;
    box-sizing: border-box;
    border-left: 8px solid #f0f2f5;
    border-right: 8px solid #f0f2f5;
  }

  .cg-container {
    overflow-y: scroll;
    padding-left: 10px;
    box-sizing: border-box;

    :deep(.ant-tabs-content-holder) {
      padding: 0 10px 10px 0;
    }

    :deep(.ant-collapse-content-box) {
      padding: 0 !important;
    }

    :deep(.ant-collapse-header) {
      padding-left: 5px !important;
      height: 24px;
      align-items: center !important;
      margin: 10px 0;
    }

    :deep(.ant-collapse-ghost > .ant-collapse-item) {
      border-bottom: 0 !important;
    }
  }

  :deep(.ant-collapse-no-arrow > .ant-collapse-header) {
    padding-left: 16px !important;
  }

  :deep(.ant-tabs-content-holder) {
    overflow-y: auto;
  }

  .add-btn {
    position: absolute;
    top: 35%;
    right: 16px;
    font-size: 15px;
    color: @primary-color;
  }

  .delete-btn {
    position: absolute;
    top: -7px;
    right: 0;
    color: #ff5461;
    cursor: pointer;
    font-size: 16px;
  }

  .coll-box {
    position: relative;
    background: #f3f3f3;
    padding: 10px 10px 3px;
    border-radius: 4px;
    margin-bottom: 10px;
  }

  .form-box {
    .form-border {
      position: absolute;
      right: 16px;
    }

    :deep(.ant-collapse-content-box) {
      padding-bottom: 0 !important;
    }
  }

  .search-com-box {
    border-bottom: 1px solid #f0f0f0;

    :deep(.ant-input-suffix) {
      color: #c3c8cf;
    }

    :deep(.ant-input) {
      height: 40px;
      width: 100%;
    }
  }

  :deep(.ant-input-affix-wrapper:not(.ant-input-affix-wrapper-disabled):hover) {
    border-bottom: 1px solid #f0f0f0;
  }
</style>
