<template>
  <div>
    <el-dialog
      title="创建流程模块"
      :visible.sync="dialogVisible"
      width="70%"
      @close="close"
    >
      <span>
        <el-row
          ><el-form data-vv-scope="moduleForm" :model="module">
            <el-row :span="10">
              <el-col :span="12">
                <ht-form-item
                  label="模块名称"
                  prop="name"
                  label-width="120px"
                  class="identity-input-width"
                >
                  <ht-input
                    v-model="module.name"
                    style="width: 250px"
                    autocomplete="off"
                    :validate="{required: true}"
                    placeholder="请输入模块名称"
                  ></ht-input>
                </ht-form-item>
              </el-col>
              <el-col :span="12">
                <ht-form-item
                  label="模块编码"
                  label-width="120px"
                  prop="code"
                  class="identity-input-width"
                >
                  <ht-input
                    v-if="module.id == ''"
                    v-model="module.code"
                    style="width: 250px"
                    v-pinyin="module.name"
                    autocomplete="off"
                    :validate="{
                      required: true,
                      alpha_dash: true,
                      isExist: '${portal}/sys/sysModule/v1/isExist?code='
                    }"
                    placeholder="请输入模块编码"
                  />
                  <ht-input v-else v-model="module.code" disabled="disabled" />
                </ht-form-item>
              </el-col>
            </el-row>
            <el-row :span="10">
              <el-col :span="12">
                <ht-form-item
                  label="选择分类"
                  prop="classifyName"
                  label-width="120px"
                >
                  <eip-sys-type-selector
                    placeholder="请选择分类"
                    class="identity-input-width"
                    typeKey="SYSMODULE"
                    style="width: 250px"
                    v-model="module.classifyName"
                    :sys-type-id.sync="module.classifyId"
                    :validate="{required: true}"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="12">
                <ht-form-item
                  v-if="module.type == 'form'"
                  label="选择表单"
                  prop="relName"
                  label-width="120px"
                >
                  <ht-input
                    v-if="module.id == ''"
                    type="text"
                    readonly="readonly"
                    @clear="clearForm"
                    style="width: 250px"
                    :validate="{required: true}"
                    placeholder="请选择表单"
                    v-model="module.relName"
                    disabled
                  >
                    <!-- <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="selectForm"
                  ></el-button> -->
                  </ht-input>
                  <ht-input
                    v-else
                    style="width: 250px"
                    v-model="module.relName"
                    disabled="disabled"
                  >
                  </ht-input>
                </ht-form-item>
                <ht-form-item
                  v-if="module.type == 'flow'"
                  label="选择流程"
                  prop="relName"
                  label-width="120px"
                >
                  <ht-input
                    v-if="module.id == ''"
                    type="text"
                    readonly="readonly"
                    style="width: 250px"
                    :validate="{required: true}"
                    v-model="module.relName"
                    @focus="selectFlow"
                  >
                    <el-button
                      slot="append"
                      icon="el-icon-search"
                      @click="selectFlow"
                    ></el-button>
                  </ht-input>
                  <ht-input
                    v-else
                    v-model="module.relName"
                    disabled="disabled"
                    style="width: 250px"
                  />
                </ht-form-item>
              </el-col>
            </el-row>

            <ht-form-item
              label="模块描述"
              prop="desc"
              label-width="120px"
              class="identity-input-width"
            >
              <ht-input
                type="textarea"
                style="width: 680px"
                :rows="3"
                v-model="module.desc"
              />
            </ht-form-item>
            <ht-form-item label="是否发布" label-width="120px">
              <el-checkbox v-model="isPublish"></el-checkbox>
            </ht-form-item>
          </el-form>
          <el-divider direction="horizontal"></el-divider>
          <el-form
            :model="publishMenuForm"
            data-vv-scope="addMenuForm"
            v-if="isPublish"
          >
            <ht-form-item label="菜单类型" prop="alias" label-width="120px">
              <el-radio
                v-model="menuType"
                label="manage"
                :validate="{required: true}"
                >后端菜单</el-radio
              >
              <el-radio
                v-model="menuType"
                label="front"
                :validate="{required: true}"
                >前端菜单</el-radio
              >
              <el-radio
                v-model="menuType"
                label="app"
                :validate="{required: true}"
                @change="change"
                >PC模块</el-radio
              >
            </ht-form-item>
            <ht-form-item
              label-width="120px"
              prop="parentMenuName"
              v-if="menuType !== 'app'"
            >
              <template slot="label">
                <span>父节点</span>
              </template>
              <Treeselect
                v-model="publishMenuForm.parentMenuName"
                :normalizer="normalizer"
                @select="handleNodeClick"
                :multiple="false"
                :options="menuTreeData"
                noOptionsText=" "
                noChildrenText=" "
                noResultsText="无对应节点"
                placeholder="请选择父节点"
                style="width: 80%"
              />
            </ht-form-item>
            <ht-form-item
              label="应用菜单"
              label-width="120px"
              prop="appTypeId"
              v-if="menuType === 'app'"
            >
              <template slot="label">
                <span>应用菜单</span>
              </template>
              <Treeselect
                v-model="publishMenuForm.appTypeId"
                :normalizer="normalizer"
                :multiple="false"
                :options="menus"
                noOptionsText=" "
                noChildrenText=" "
                style="width: 80%"
                placeholder="请选择父节点"
              />
            </ht-form-item>
            <ht-form-item
              :label="menuType === 'app' ? '应用名称' : '菜单名称'"
              prop="name"
              label-width="120px"
            >
              <ht-input
                v-model="publishMenuForm.name"
                :validate="{required: true}"
                style="width: 80%"
              ></ht-input>
            </ht-form-item>
          </el-form>
        </el-row>
      </span>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </el-dialog>
    <!-- 表单选择器 -->
    <EipFormDialog
      ref="eipFormDialog"
      :single="true"
      @onConfirm="dialogFormConfirm"
      formType="pc"
      appendToBody
    />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
const EipSysTypeSelector = () =>
  import('@/components/selector/EipSysTypeSelector.vue')
const EipFormDialog = () => import('@/components/dialog/EipFormDialog.vue')
import portal from '@/api/portal.js'
export default {
  data() {
    return {
      module: {
        menu: 'datalist,chart,other',
        type: 'form',
        id: '',
        name: '',
        relName: '',
        relCode: '',
        reportName: '',
        code: ''
      },
      isPublish: false,
      dialogVisible: false,
      publishMenuForm: {},
      menuType: 'manage',
      menuTreeData: [],
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children,
          isDefaultExpanded: false
        }
      },
      menus: [],
      templateInfo: {}
    }
  },
  methods: {
    showDialog(templateData) {
      let {formName, formKey, alias, name} = templateData
      this.module.relName = formName
      this.module.relCode = formKey
      this.module.code = alias
      this.module.name = name
      this.dialogVisible = true
      this.templateInfo = templateData
      this.$nextTick(() => {
        this.getMenuDataByType()
      })
    },
    selectForm() {
      this.$refs.eipFormDialog.showDialog()
    },
    dialogFormConfirm(data) {
      if (data && data.length > 0) {
        this.$nextTick(() => {
          this.module.relCode = data[0].formKey
          this.module.relName = data[0].name
        })
      } else {
        this.clearForm()
      }
    },
    clearForm() {
      this.$nextTick(() => {
        this.module.relCode = ''
        this.module.relName = ''
      })
    },
    beforeSave() {
      this.module.moduleDetail = [
        {
          type: 'datalist',
          code: this.templateInfo.alias,
          name: this.templateInfo.name,
          chartType: this.templateInfo.typeName,
          url:
            '/statement/template/preview/' + this.templateInfo.alias + '/true',
          viewCode: this.templateInfo.boDefAlias
        }
      ]
    },
    save() {
      this.beforeSave()
      let this_ = this
      let forms = ['moduleForm']
      if (this.isPublish) {
        forms.push('addMenuForm')
      }
      let validateInstance = []
      forms.forEach(name => {
        validateInstance.push(this.$validator.validateAll(name))
      })
      Promise.all(validateInstance).then(result => {
        for (let i = 0; i < result.length; i++) {
          if (!result[i]) {
            this_.$message.error('校验失败')
            return
          }
        }
        let data = null
        let url = null
        let portal = window.context.portal
        if (result.length > 1) {
          data = {
            sysModule: this_.module,
            templateToMenuVo: this_.publishMenuForm
          }
          url =
            portal +
            `/sys/sysModule/v1/saveAndPublishModule?type=${this.menuType}`
        } else {
          data = this_.module
          url = portal + '/sys/sysModule/v1/saveModule'
        }
        this_.$http.post(url, data).then(resp => {
          if (resp.data && resp.data.state) {
            this_.$message.success(resp.data.message)
            this_.$nextTick(() => {
              this_.dialogVisible = false
            })
          }
        })
      })
    },
    getMenuDataByType() {
      let menuAlias = this.menuType == 'front' ? 'front_menu' : 'manage_menu'
      portal.getCurrentMenuByAlias(menuAlias).then(rep => {
        if (rep.state && rep.value.length > 0) {
          let menus = rep.value.filter(item => {
            if (item.alias !== 'appCenterFront') {
              return true
            }
            return false
          })
          this.removeEmptyChildren(menus)
          if (this.menuType != 'front') {
            //添加为后端菜单时如果二级菜单不是URL菜单则模块开发生成的菜单不能添加到这个菜单下面
            //如：设计中心->业务表单  设计中心下的业务表单菜单是下级菜单不是URL菜单则模块开发生成的菜单不能添加到这个菜单下面
            for (let i = 0; i < menus.length; i++) {
              if (menus[i].children) {
                for (let j = menus[i].children.length - 1; j >= 0; j--) {
                  if (
                    menus[i].children[j].alias.indexOf('href/template') == -1
                  ) {
                    menus[i].children.splice(j, 1)
                  }
                }
              }
            }
          }
          this.menuTreeData = menus
        }
      })
    },
    removeEmptyChildren(menus) {
      menus.forEach(m => {
        if (m.children) {
          if (m.children.length < 1) {
            delete m.children
          } else {
            //不允许选择4级菜单
            if (m.path.split('.').length == 6) {
              delete m.children
            } else {
              this.removeEmptyChildren(m.children)
            }
          }
        }
      })
    },
    handleNodeClick(node) {
      let menuAlias = ''
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      menuAlias = 'href/template/' + key
      this.publishMenuForm.alias = menuAlias
      this.publishMenuForm.href = window.context.front + '/sysModulePreview/'
      this.publishMenuForm.parentAlias = node.alias
    },
    loadMenus() {
      portal.getCurrentMenuByAlias('app_menu').then(data => {
        if (data.state) {
          this.menus = data.value
          this.removeEmptyChildren(this.menus)
        }
      })
    },
    change(data) {
      this.$set(
        this.publishMenuForm,
        'href',
        window.context.front + '/sysModulePreview/'
      )
    },
    close() {
      this.module = {
        menu: 'datalist,chart,other',
        type: 'form',
        id: '',
        name: '',
        relName: '',
        relCode: '',
        reportName: '',
        code: ''
      }
      this.publishMenuForm = {}
      this.menuType = 'manage'
      this.isPublish = false
    }
  },
  components: {
    EipSysTypeSelector,
    EipFormDialog,
    Treeselect
  },
  mounted() {
    this.$validator = this.$root.$validator
  },
  watch: {
    menuType(newValue, oldValue) {
      if (!newValue) {
        return
      }
      if (newValue == 'manage' || newValue == 'front') {
        this.getMenuDataByType()
      } else if (newValue == 'app' && this.menus.length == 0) {
        this.loadMenus()
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
