<template>
  <div :class="$style.form">
    <sd-form-item name="name" />
    <sd-form-item name="moduleDesc" :input-props="{ type: 'textarea' }" />
    <sd-form-item name="sortNumber" />
    <sd-form-item name="isFlow" @change="flowChange" />
    <sd-form-item name="formType">
      <a-radio-group v-model="model.formType" @change="formTypeChange">
        <a-radio
          v-for="item in fields.formType.attr.selectListItem"
          :key="item.value"
          :value="item.value"
        >
          {{ item.label }}
          <a-tooltip>
            <template v-slot:title>
              {{
                item.value === '1'
                  ? '在浏览器中以可视化方式创建的表单'
                  : '在开发工具中以编写代码方式创建的表单，通常可视化设计无法满足的场景会采用此方式'
              }}
            </template>
            <a-icon type="question-circle-o" />
          </a-tooltip>
        </a-radio>
      </a-radio-group>
    </sd-form-item>
    <!-- 表单新建时可选择表单模板 -->
    <a-form-model-item
      v-if="!model.id && model.formType === '1'"
      label="表单模板"
      prop="formTemplate"
    >
      <SdFormTemplatePicker
        v-model="formTemplateSel"
        :templet-type="Number(model.isFlow)"
        @change="onTemplateChange"
      />
    </a-form-model-item>
    <a-form-model-item
      v-if="model.formType === '2'"
      label="页面名称"
      :rules="[
        {
          required: true,
          message: '不能为空',
          trigger: ['change', 'blur'],
        },
      ]"
      prop="pageId"
    >
      <sd-tree-picker
        v-model="relateFormSel"
        single
        :load-tree-data="loadEntityFormTreeData"
        @change="relateFormChange"
      />
    </a-form-model-item>
    <sd-form-item v-if="model.formType === '2'" name="usePermission">
      <a-radio-group v-model="model.usePermission">
        <a-radio
          v-for="item in fields.usePermission.attr.selectListItem"
          :key="item.value"
          :value="item.value"
        >
          {{ item.label }}
          <a-tooltip>
            <template v-slot:title>
              {{
                item.value === '1'
                  ? '以可视化方式配置权限'
                  : '以编写代码方式设置权限，通常可视化配置无法满足的场景会采用此方式。'
              }}
            </template>
            <a-icon type="question-circle-o" />
          </a-tooltip>
        </a-radio>
      </a-radio-group>
    </sd-form-item>
    <sd-form-item name="revisionHistory" />
    <sd-form-item name="formTemplate" hidden />
    <sd-form-item name="formId" hidden />
    <sd-form-item name="pageId" hidden />
    <sd-form-item name="appId" hidden :input-props="{ defaultValue: appId }" />
  </div>
</template>

<script>
import { sdLocalStorage } from '@/common/services/storage-service'
import SdFormTemplatePicker from '@/form-designer/form-template/sd-form-template-picker.vue'
import ApplicationService from './application-service'
import components from './_import-components/sd-form-info-import'

export default {
  name: 'SdFormInfo',
  components: {
    ...components,
    SdFormTemplatePicker,
  },
  props: {
    model: {
      type: Object,
      required: true,
    },
    fields: {
      type: Object,
      required: true,
    },
    appId: {
      type: String,
      default: '',
    },
    appName: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      relateFormSel: [],
      formTemplateSel: [],
      groupId: '',
    }
  },
  created() {
    this.groupId = JSON.parse(sdLocalStorage.getItem('hierarchicalInfo') || '{}')?.authGroupId || ''
    // 实体表单：获取页面名称
    if (this.model.formType === '2' && this.model.pageId) {
      ApplicationService.getPageInfo({ pageId: this.model.pageId }).then((res) => {
        this.relateFormSel = [{ id: this.model.pageId, name: res.data?.name }]
      })
    }
  },
  methods: {
    // 实体表单根节点默认为V-3
    loadEntityFormTreeData(parentCatId = 'V-3') {
      const params = {
        groupId: this.groupId,
        parentCatId: parentCatId,
        isFlow: this.model.isFlow === '1',
      }
      const cateParams = { ...params, isPage: false }
      const leafParams = { ...params, isPage: true }
      // 获取分类+页面
      return Promise.all([
        ApplicationService.getEntityFormData(cateParams),
        ApplicationService.getEntityFormData(leafParams),
      ]).then((items) => {
        return (items[0] || [])
          .map((item) => ({
            id: item.id,
            name: item.text,
            checkable: false,
            isLeaf: item.leaf,
          }))
          .concat(
            (items[1] || []).map((item) => ({
              id: item.id,
              name: item.text,
              checkable: true,
              isLeaf: item.leaf,
              props: item.props,
            }))
          )
      })
    },
    relateFormChange(data) {
      this.model.pageId = data[0]?.id.slice(1) || ''
      this.model.formId = data[0]?.props?.formId || ''
    },
    onTemplateChange(data) {
      this.model.formTemplate = data[0]?.id || ''
    },
    // 表单类型（流程/无流程）变更时
    flowChange() {
      // 可视化自定义表单
      if (this.model.formType === '1') {
        // 清空表单模板
        this.formTemplateSel = []
        this.model.formTemplate = ''
      } else {
        // 实体表单：清空页面名称
        this.relateFormSel = []
        this.model.pageId = ''
        this.model.formId = ''
      }
    },
    // 开发模式（builder/实体）变更时
    formTypeChange() {
      // 变更后为可视化自定义表单
      if (this.model.formType === '1') {
        // 清空页面名称
        this.relateFormSel = []
        this.model.pageId = ''
        this.model.formId = ''
      } else {
        // 变更后为实体表单：清空表单模板
        this.formTemplateSel = []
        this.model.formTemplate = ''
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.form {
  :global(> .ant-form-item .ant-form-item-label) {
    float: left;
    width: 19%;
  }
  :global(> .ant-form-item .ant-form-item-control-wrapper) {
    float: left;
    width: 75%;
  }
}
</style>
