<template>
  <div :class="$style.form">
    <sd-form-item name="text" />
    <a-form-model-item
      label="上级菜单"
      :rules="[
        {
          required: true,
          message: '不能为空',
          trigger: ['change', 'blur'],
        },
      ]"
      prop="parentId"
    >
      <sd-tree-picker
        v-model="parentSel"
        single
        :load-tree-data="loadTreePickerData"
        @change="parentChange"
      />
    </a-form-model-item>
    <a-form-model-item label="关联表单" prop="appModuleId">
      <sd-tree-picker
        v-model="relateModule"
        single
        :load-tree-data="loadModuleTreePickerData"
        :search-tree-data="searchModuleTreeData"
        @change="moduleChange"
      />
    </a-form-model-item>
    <sd-form-item name="url">
      <a-input v-model="model.url" />
      <div :class="$style.preurls">
        <a-tag v-for="(item, index) in preUrls" :key="index" @click="model.url = item.url">
          {{ item.name }}
        </a-tag>
      </div>
    </sd-form-item>
    <sd-form-item name="index" />
    <sd-form-item name="icon">
      <sd-icon :type="model.icon || 'sd-module'" :class="$style.iconclass" />
      <a-button @click="selectIcon(model.icon || 'sd-module')">更改图标</a-button>
    </sd-form-item>
    <sd-form-item name="tooltip" :input-props="{ type: 'textarea' }" />
    <sd-form-item name="status" />
    <sd-form-item name="appModuleId" hidden />
    <sd-form-item name="parentId" hidden :input-props="{ defaultValue: category && category.id }" />
    <sd-form-item name="appId" hidden :input-props="{ defaultValue: appId }" />
  </div>
</template>

<script>
import PageService from '@/common/services/page-service'
import pickValues from '@/common/services/pick-values'
import sdIconPicker from '@/common/components/sd-icon-picker.vue'
import ApplicationService from './application-service'
import components from './_import-components/sd-menu-form-import'

export default {
  name: 'SdMenuForm',
  components,
  props: {
    model: {
      type: Object,
      required: true,
    },
    category: {
      type: Object,
      default: () => {},
    },
    appId: {
      type: String,
      default: '',
    },
    appNodeId: {
      type: String,
      default: undefined,
    },
  },
  data() {
    return {
      parentSel: [],
      relateModule: [],
      preUrls: [],
      allModules: [],
    }
  },
  created() {
    if (this.category.id) {
      this.parentSel = [{ id: this.category.id, name: this.category.text }]
    }
    // 获取模块名称
    if (this.model.appModuleId) {
      PageService.get({ id: this.model.appModuleId }, 'app/appmodule/weAppModule').then((res) => {
        let moduleName
        res.data?.pageFormData?.pageFieldInfos?.forEach((f) => {
          if (f.name === 'name') {
            moduleName = f.value
          }
        })
        this.relateModule = [{ id: this.model.appModuleId, name: moduleName }]
      })
    }
    this.$emit('formCreated')
  },
  methods: {
    selectIcon(icon) {
      pickValues(sdIconPicker, {
        theme: 'outlined',
        value: [{ id: `${icon}/outlined`, name: icon, theme: 'outlined' }],
      }).then((icons) => {
        if (icons?.[0]) {
          this.model.icon = icons[0].name
        }
      })
    },
    loadTreePickerData(parentCatId) {
      const params = { appId: this.appId }
      if (parentCatId) {
        // 非根节点
        params.parentId = parentCatId
      }
      return ApplicationService.getAppMenuCategoryTree(params).then((res) =>
        this.transformTreePickerData(res.data)
      )
    },
    transformTreePickerData(treeData) {
      return treeData.map((d) => {
        const { children } = d
        const node = {
          id: d.id,
          name: d.text,
          checkable: true,
          isLeaf: d.leaf,
        }
        if (!d.leaf && children) {
          node.children = this.transformTreePickerData(children)
        }
        return node
      })
    },
    parentChange(data) {
      this.model.parentId = data[0]?.id || ''
    },
    loadModuleTreePickerData(parentCatId) {
      const params = { appId: this.appId }
      if (parentCatId) {
        // 非根节点
        params.parentId = parentCatId
      }
      if (this.appNodeId) {
        params.appNodeId = this.appNodeId
      }
      return ApplicationService.getModuleTree(params).then((res) => {
        this.allModules = res.data.map((d) => {
          return {
            id: d.id,
            name: d.text,
            checkable: d.props?.isChoice === 'true',
            isLeaf: d.leaf,
            props: d.props,
          }
        })
        return this.allModules
      })
    },
    searchModuleTreeData(text) {
      return new Promise((resolve) => {
        resolve(this.allModules.filter((m) => m.name.indexOf(text) !== -1))
      })
    },
    moduleChange(data) {
      let urls = []
      const oModule = data[0]
      if (oModule) {
        this.model.appModuleId = oModule.id
        if (oModule.props?.isFlow === '1') {
          // 流程模块，提供新建和查询地址
          urls = [{ name: '新建地址', url: `/sd-flow-guide?moduleId=${oModule.id}` }]
          // 列表地址
          this.getFormListUrls(oModule.id, true).then((listUrls) => {
            urls = urls.concat(listUrls)

            // 配置了统计地址
            if (oModule.props?.isStatis === 'true') {
              urls.push({
                name: '统计地址',
                url: `/sd-frame/sd-business-statis?headId=${oModule.props.formId}`,
              })
            }

            this.preUrls = urls
          })
        } else {
          // 非流程 且为自定义表单
          if (oModule.props?.formType === '1') {
            // 列表地址
            this.getFormListUrls(oModule.id, false).then((listUrls) => {
              urls = listUrls

              // 配置了统计地址
              if (oModule.props?.isStatis === 'true') {
                urls.push({
                  name: '统计地址',
                  url: `/sd-frame/sd-business-statis?headId=${oModule.props.formId}`,
                })
              }
              // 只有一个地址，直接赋值
              if (urls.length === 1) {
                this.model.url = urls[0].url
              }

              this.preUrls = urls
            })
          }
        }
      } else {
        this.model.appModuleId = ''
      }
    },
    getFormListUrls(moduleId, isFlow) {
      const path = isFlow ? 'sd-task-list' : 'sd-business-list'
      const params = {
        startPosition: 0,
        maxResults: -1,
        expressions: [
          {
            dataType: 'str',
            name: 'appModuleId',
            op: 'eq',
            stringValue: moduleId,
          },
        ],
        formId: 'weAppFormList',
        orderBy: 'sortNumber asc,id asc',
        columns: 'name',
      }
      return PageService.getList(params).then((res) => {
        return (res.data.data || []).map((l) => ({
          name: `[列表] ${l.name}`,
          url: `/sd-frame/${path}?moduleId=${moduleId}&formListId=${l.id}`,
        }))
      })
    },
  },
}
</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%;
  }
}
.preurls {
  line-height: normal;
  :global(.ant-tag) {
    cursor: pointer;
  }
}
.iconclass {
  margin-right: 8px;
  font-size: $font-size-base * 2;
  vertical-align: middle;
}
</style>
