<%_
const { formFieldLines, showInOneRelationships } = (bcEntityData || { formFieldLines: [] });
_%>
<script lang="tsx">
  import { getCurrentInstance, ref, reactive, h, resolveComponent, toRef, Component } from 'vue';
  import { Space, Button, Collapse, CollapsePanel, Card, Tabs, TabPane } from 'ant-design-vue';
  import { useRoute } from 'vue-router';
<%_ if (!useCommonTable) { _%>
  import config from './config/detail-config';
<%_ } _%>
  import { defineComponent } from 'vue';
  import { I<%= entityAngularName %> } from '@/models/<%= entityModelFileName %>.model';

<%_ if (useCommonTable) { _%>
  import { generateDataForDesigner } from '@/utils/jhipster/entity-form-utils';
<%_ } _%>
  import ServerProvider from '@/api-service/index';
<%_ if (addCustomMethod.indexOf('updateTemplate') !== -1) { _%>
  <%- include(`../common/entity-custom/${entityClass}.updateTemplate.ejs`, {position: 'import'}); -%>
<%_ } _%>
  import { PageWrapper, Icon, getButtonConfig, Description, DescList } from '@begcode/components';

<%_ let apiModuleName = this._.camelCase(clientRootFolder || microserviceName); _%>
  export default defineComponent({
    // begcode-please-regenerate-this-file 如果您不希望重新生成代码时被覆盖，将please修改为don't ！！！
    name: '<%= this._.upperFirst((moduleName || clientRootFolder) ? (moduleName || clientRootFolder) + entityAngularName : entityInstance) %>Detail',
    props: {
      entityId: {
        type: Number || String,
        default: 0,
      },
      containerType: {
        type: String,
        default: 'router',
      },
    },
    components: {
      DescList,
    },
    emits: ['cancel', 'refresh'],
    async setup(props) {
      const ctx = getCurrentInstance()?.proxy;
      const route = useRoute();
      // const pageControl = control(ctx);
      // const formConfig = pageControl.formRender();
      const activeNames = ref<any[]>([]);
      const handleChange = val => {
        activeNames.value = val;
        ctx?.$emit('change', activeNames.value);
      };
      const apiService = ctx?.$apiService as typeof ServerProvider;
      const <%= entityInstance %> = reactive<I<%= entityAngularName %>>({});
      let entityId: any = '';
      if (props.containerType === 'router') {
        entityId = route.params?.entityId;
      } else {
        entityId = props.entityId;
      }
      if (entityId) {
        const data = await apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.find(Number(entityId));
        if (data) {
          Object.assign(<%= entityInstance %>, data);
        }
      }
      <%_ if (useCommonTable) { _%>
      const commonTableData = await apiService.modelConfig.commonTableService.findByEntityName('<%= entityNameCapitalized %>');
      const formItemsConfig = generateDataForDesigner(commonTableData!);
      <%_ } else { _%>
      const formItemsConfig = reactive(config.fields);
      <%_ } _%>
      <%_
      const oneToOneNotOwnerSide =[];
      let hasUseJPADerivedIdentifier = false;
      _%>
      //获得关联表属性。
      <%_ if (useCommonTable) { _%>
      <%_
      showInOneRelationships.forEach(relationship => { _%>
      const <%= relationship.relationshipName %>Data = await apiService.modelConfig.commonTableService.findByEntityName('<%= relationship.otherEntityNameCapitalized %>');
      const <%= relationship.relationshipName %>Columns = xGenerateTableColumns(<%= relationship.relationshipName %>Data);
      // const <%= relationship.relationshipName %>ColumnsRender = pageControl.<%= relationship.relationshipName %>ColumnsRender();
      <%_ }); _%>
      <%_ } _%>
      const pageConfig = reactive({
        active: '0',
        operations: [
          {
            theme: 'close',
            click: () => {
              console.log('close');
            },
          },
        ],
        canExpand: false,
        title: '详情',
      });
      const formGroup = reactive([
        {
          title: '<%= bcTitle %>详情',
          operation: [],
          component: {
            name: 'a-desc',
            props: {
              schema: formItemsConfig,
              isEdit: () => false,
              // formConfig,
              labelWidth: '120px',
              data: <%= entityInstance %>,
              column: 1,
            },
          },
        },
        <%_ if (showInOneRelationships && showInOneRelationships.length) { _%>
        {
          title: '关联表',
          operation: [],
          component: [
            <%_
            showInOneRelationships.forEach(relationship => { _%>
              <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.includes('editByList')) { _%>
            {
              name: '<%= relationship.otherEntity.entityNameCapitalized %>List',
              title: '<%= relationship.bcTitle%>列表',
              props: {
                <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
                query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: entityId },
                <%_ } else { _%>
                query: {<%= relationship.otherRelationship.relationshipName%>Id: entityId },
                <%_ } _%>
                editIn: 'modal',
                <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
                baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: entityId },
                <%_ } else { _%>
                baseData: { <%= relationship.otherRelationship.relationshipName%>Id: entityId },
                <%_ } _%>
                gridOptions: {},
                searchFormOptions: {
                  disabled: false,
                  allowSwitch: false,
                },
                gridCustomConfig: {
                  hideOperations: false,
                  hideSlots: [],
                  columnsName: '',
                },
                modelName: '<%= relationship.otherEntity.entityNameCapitalized %>List',
              },
            },
              <%_ } else　if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.includes('editByFormList')) { _%>
            {
              name: 'FormList',
              title: '<%= relationship.bcTitle%>列表',
              props: {
                <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
                query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: entityId },
                <%_ } else { _%>
                query: {<%= relationship.otherRelationship.relationshipName%>Id: entityId },
                <%_ } _%>
                editIn: 'modal',
                <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
                baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: entityId },
                <%_ } else { _%>
                baseData: { <%= relationship.otherRelationship.relationshipName%>Id: entityId },
                <%_ } _%>
                configData: [
                  {
                    formConfig: config.<%= relationship.relationshipName %>Columns,
                    data: {},
                  }
                ],
                modelName: 'FormList',
              },
            },
              <%_ } else　if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.includes('editByDescList')) { _%>
            {
              name: 'DescList',
              title: '<%= relationship.bcTitle%>列表',
              props: {
                <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
                query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: entityId },
                <%_ } else { _%>
                query: {<%= relationship.otherRelationship.relationshipName%>Id: entityId },
                <%_ } _%>
                editIn: 'modal',
                <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
                baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: entityId },
                <%_ } else { _%>
                baseData: { <%= relationship.otherRelationship.relationshipName%>Id: entityId },
                <%_ } _%>
                data: <%= entityInstance %>.<%= relationship.relationshipName %>,
                savedOpen: true,
                toolButtons: [],
                editComponentPath: '@/views/<%= relationship.otherEntity.entityFolderName%>/<%= relationship.otherEntity.entityFileName%>-edit.vue',
                modelName: 'DescList',
              },
              slots: {
                default: (item) => {
                  return h(<%= relationship.otherEntity.entityNameCapitalized %>Desc, {entityId: item.id}, () => []);
                }
              },
            },
              <%_ } else { _%>
            {
              name: 'vxe-grid',
              title: '<%= relationship.bcTitle%>列表',
              props: {
                data: <%= entityInstance %>.<%= relationship.relationshipName%>,
                columns: <%= useCommonTable ? '' : 'config.'%><%= relationship.relationshipName%>Columns(),
                border: true,
                showOverflow: true,
                fieldMapToTime: [],
                compact: true,
                size: 'default',
                toolbarConfig: {
                  buttons: [],
                  tools: [],
                  import: false,
                  export: false,
                  print: false,
                  custom: false
                }
              },

            },
              <%_ } _%>
            <%_ }); _%>
          ]
        },
        <%_ } _%>
      ]);
      const getXGridSlots = component => {
        if (component.recordActions) {
          const buttons = reactive(component.recordActions.map(action => getButtonConfig(action)));
          buttons.filter(button => button.icon).forEach(button => (button.slots = { default: () => <Icon icon={button.icon} />}));
          buttons.filter(button => !button.icon).forEach(button => (button.slots = { default: () => button.text }));
          return {
            recordAction: row => (
              <div>
                <Space>
                  {buttons.map(button => {
                    return (
                      <Button
                        {...{
                          type: button.type || 'primary',
                          shape: button.shape || 'circle',
                          title: button.text || button.name,
                          onClick: () => {
                            if (button.onClick) {
                              button.onClick(row.row, button.name);
                            } else {
                              console.log(button.name, 'onClick事件未定义！');
                            }
                          },
                        }}
                        v-slots={button.slots}
                      ></Button>
                    );
                  })}
                </Space>
              </div>
            ),
          };
        } else {
          return {
            recordAction: () => <div />,
          };
        }
      };
      const renderChild = () => {
        const wrapperPros: any = {};
        if (!pageConfig?.canExpand) {
          wrapperPros.bordered = false;
          wrapperPros.size = 'small';
        }

        return formGroup.map(item => {
          var componentRef = toRef(item, 'component').value;
          if (componentRef && !(componentRef instanceof Array)) {
            if (componentRef.name === 'a-desc') {
              if (pageConfig?.canExpand) {
                return (<CollapsePanel><Description {...componentRef.props} /></CollapsePanel>);
              } else {
                return <Description {...componentRef.props} />;
              }
            } else {
              const component = resolveComponent(componentRef.name);
              return h(pageConfig?.canExpand ? CollapsePanel : Card, {...wrapperPros}, h(component,componentRef.props, ))
            }
          } else if (componentRef && componentRef instanceof Array) {
            return h(
              pageConfig?.canExpand ? CollapsePanel : Card,
              { ...wrapperPros },
              () => h(
                Tabs,
                {},
                () => componentRef.map((child, index) => {
                  return h(
                    TabPane,
                    { tab: child.title || index, key: index },
                    () => h(resolveComponent(child?.name) as Component, child.props, child?.name === 'vxe-grid' ? getXGridSlots(child) : {}),
                  );
                }),
              ),
            );
          } else {
            return <div>无内容</div>;
          }
        });
      };
      const slots = {
        rightFooter: () => (
          <div>
            <Space>
              {pageConfig.operations.map((operation: any) => {
                const buttonSlots: any = {};
                if (operation.icon) {
                  buttonSlots.icon = () => <Icon icon={operation.icon} />;
                }
                if (operation.text) {
                  buttonSlots.default = () => operation.text;
                }
                switch (operation.theme) {
                  case 'save':
                    if (!buttonSlots.icon) {
                      buttonSlots.icon = () => <Icon icon={'ant-design:save-outlined'}/>;
                    }
                    if (!buttonSlots.default) {
                      buttonSlots.default = () => '保存';
                    }
                    return (
                      <Button
                        {...{
                          type: 'primary',
                          onClick: operation.click,
                        }}
                        v-slots={buttonSlots}
                      ></Button>
                    );
                  case 'update':
                    if (!buttonSlots.icon) {
                      buttonSlots.icon = () => <Icon icon={'ant-design:check-outlined'} />;
                    }
                    if (!buttonSlots.default) {
                      buttonSlots.default = () => '更新';
                    }
                    return (
                      <Button
                        {...{
                          type: 'primary',
                          onClick: operation.click,
                        }}
                        v-slots={buttonSlots}
                      ></Button>
                    );
                  default:
                    return (
                      <Button
                        {...{
                          type: 'primary',
                          onClick: operation.click,
                        }}
                      >
                        {operation.title}
                      </Button>
                    );
                }
              })}
            </Space>
          </div>
        ),
        default: () => {
          if (pageConfig?.canExpand) {
            return (
              <div>
                <Collapse value={activeNames} onchange={handleChange} v-slots={{default: () => renderChild()}} />
              </div>
            );
          } else {
            return renderChild();
          }
        },
      };
<%_ if (addCustomMethod.indexOf('updateTemplate') !== -1) { _%>
  <%- include(`../common/entity-custom/${entityClass}.updateTemplate.ejs`, {position: 'field'}); -%>
<%_ } _%>
      return {
        // formConfig,
        pageConfig,
        // pageControl,
        formGroup,
        slots,
<%_ if (addCustomMethod.indexOf('detailTemplate') !== -1) { _%>
  <%- include(`../common/entity-custom/${entityClass}.updateTemplate.ejs`, {position: 'return'}); -%>
<%_ } _%>
      };
    },
    methods: {
<%_ if (addCustomMethod.indexOf('detailTemplate') !== -1) { _%>
  <%- include(`../common/entity-custom/${entityClass}.updateTemplate.ejs`, {position: 'method'}); -%>
<%_ } _%>
    },
    render() {
      if (this.containerType === 'modal' || this.containerType === 'drawer') {
        return this.slots.default();
      } else {
        return (
          <PageWrapper
            {...{
              props: {
                title: this.pageConfig?.title || '详情',
              },
            }}
            v-slots={this.slots}
          />
        );
      }
    },
  });
</script>
