<template>
  <div>
    <el-dialog
      title="发布流程模块"
      :visible.sync="dialogVisible"
      width="64%"
      @close="handleClose"
    >
      <div style="padding: 30px; width: 860px; background: #fff">
        <el-form data-vv-scope="modelForm" :model="formData">
          <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="formData.name"
                  :maxlength="50"
                  show-word-limit
                  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-model="formData.code"
                  style="width: 250px"
                  v-pinyin="formData.name"
                  :maxlength="50"
                  autocomplete="off"
                  :validate="{
                    required: true,
                    alpha_dash: true,
                    isExist: '${portal}/sys/sysModule/v1/isExist?code='
                  }"
                  placeholder="请输入模块编码"
                />
              </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="formData.classifyName"
                  :sys-type-id.sync="formData.classifyId"
                  :validate="{required: true}"
                />
              </ht-form-item>
            </el-col>
            <el-col :span="12">
              <ht-form-item label="选择流程" prop="relName" label-width="120px">
                <ht-input
                  v-model="formData.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"
              :maxlength="200"
              v-model="formData.desc"
            />
          </ht-form-item>
          <ht-form-item label="是否发布" label-width="120px">
            <el-switch
              v-model="isPublish"
              :active-value="true"
              :inactive-value="false"
              active-text="是"
              inactive-text="否"
              @change="handlePublishSwitch"
            >
            </el-switch>
          </ht-form-item>
        </el-form>
        <el-form
          :model="publishMenuForm"
          data-vv-scope="addMenuForm"
          v-if="isPublish"
        >
          <ht-form-item label="菜单类型" prop="alias" label-width="120px">
            <el-radio v-model="type" label="manage" :validate="{required: true}"
              >后端菜单</el-radio
            >
            <el-radio v-model="type" label="front" :validate="{required: true}"
              >前端菜单</el-radio
            >
            <el-radio
              v-model="type"
              label="app"
              :validate="{required: true}"
              @change="change"
              >PC模块</el-radio
            >
          </ht-form-item>
          <ht-form-item
            label-width="120px"
            prop="parentMenuName"
            v-if="type !== '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="type === 'app'"
          >
            <template slot="label">
              <span>应用菜单</span>
            </template>
            <Treeselect
              v-model="publishMenuForm.appTypeId"
              @select="handleAppTypeSelect"
              :normalizer="normalizer"
              :multiple="false"
              :options="menus"
              noOptionsText=" "
              noChildrenText=" "
                noResultsText="无对应节点"     
              style="width: 80%"
              placeholder="请选择父节点"
            />
          </ht-form-item>
          <ht-form-item
            :label="type === 'app' ? '应用名称' : '菜单名称'"
            prop="name"
            label-width="120px"
          >
            <ht-input
              v-model="publishMenuForm.name"
              :validate="{required: true}"
              :maxlength="10"
              show-word-limit
              style="width: 80%"
            ></ht-input>
          </ht-form-item>
        </el-form>
      </div>

      <span slot="footer" style="text-align: right;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
const EipSysTypeSelector = () =>
  import('@/components/selector/EipSysTypeSelector.vue')
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import portal from '@/api/portal.js'
import utils from '@/hotent-ui-util.js'

export default {
  components: {
    EipSysTypeSelector,
    Treeselect
  },
  name: 'sys-module-publish',
  props: {
    isShowTopMenu: {type: Boolean, default: false}
  },
  data() {
    return {
      data: {},
      dialogVisible: false,
      formData: {
        name: '',
        deploy: false,
        menu: 'workspace',
        moduleDetail: [],
        classifyId: '',
        classifyName: '',
        relCode: '',
        relName: '',
        type: 'flow',
        code: ''
      },
      isPublish: false,
      showMenuForm: false,
      publishMenuForm: {},
      type: 'manage',
      menuTreeData: [],
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children,
          isDefaultExpanded: false
        }
      },
      menus: []
    }
  },
  methods: {
    showDialog(row) {
      this.formData = {
        creator: this.$store.state.login.currentUser.username,
        name: '',
        deploy: false,
        menu: 'workspace',
        moduleDetail: [],
        classifyId: '',
        classifyName: '',
        relCode: row.defKey,
        relName: row.name,
        type: 'flow',
        code: ''
      }
      this.type = 'manage'
      this.isPublish = false
      this.showMenuForm = false
      this.getMenuDataByType()
      this.dialogVisible = true
    },
    handleClose() {},
    async handleConfirm() {
      let result = await this.$validator.validateAll('modelForm')
      if (!result) {
        let arr = this.$validator.errors.items
        this.$message.warning(
          `有${arr.length}个字段未通过校验，请正确填写表单内容`
        )
        return
      }

      if (this.type) {
        let sysModule = this.formData
        let templateToMenuVo = this.publishMenuForm
        delete templateToMenuVo.parentMenuName
        let vo = {
          sysModule,
          templateToMenuVo: this.isPublish ? templateToMenuVo : null
        }
        this.$http
          .post(
            `${
              window.context.portal
            }/sys/sysModule/v1/saveAndPublishModule?type=${this.type}`,
            vo
          )
          .then(resp => {
            if (resp.data && resp.data.state) {
              this.$message.success(resp.data.message)
              this.dialogVisible = false
            }
          })
      }
    },
    async handlePublishSwitch(val) {
      if (val) {
        let result = await this.$validator.validateAll('modelForm')
        if (!result) {
          this.$message.warning('请先完善菜单信息')
          this.$nextTick(() => {
            //todo
            //this.isPublish = false
          })
          //return
        }
        this.$set(this, 'publishMenuForm', {
          alias: '',
          href: '',
          menuId: '',
          name: '',
          parentAlias: '',
          appTypeAlias: '',
          appTypeId: null
        })
      }
    },
    change(data) {
      
      this.$set(
        this.publishMenuForm,
        'href',
        window.context.front + '/sysModulePreview/'
      )
    },
    getMenuDataByType() {
      let frontUrl = 'front_menu&filterMenuAlias=appCenter1,personal'
      let manageUrl = 'manage_menu'
      this.isShowTopMenu = this.type == 'front' ? true : false
      if (this.isShowTopMenu) {
        frontUrl = frontUrl + '&isNeedTop=true'
        manageUrl = manageUrl + '&isNeedTop=true'
      }
      let menuAlias = this.type == 'front' ? frontUrl : manageUrl
      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.type != '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
          this.filterMenuByMenuType(menus)
        }
      })
    },
     filterMenuByMenuType(menuData) {
      const data = _.cloneDeep(menuData)
      let newMenus = []
      //let limit = this.type == 'front'? 4:5
      if (data && data.length) {
        newMenus = utils
          .nest2tile(data, 'children', false)
          .filter(
            item =>
              item.type !== 'page' &&
              !item.href &&
              item.path.split('.').slice(0, -1).length <= 5
          )
        this.menuTreeData = utils.tile2nest(newMenus)
      }
    },
    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
    },
    handleAppTypeSelect(node) {
   
      this.publishMenuForm.appTypeAlias = node.alias
    },
    loadMenus() {
      portal.getCurrentMenuByAlias('app_menu').then(data => {
        if (data.state) {
          this.menus = data.value
          this.removeEmptyChildren(this.menus)
        }
      })
    }
  },
  created() {},
  mounted() {
    this.$validator = this.$root.$validator
  },
  watch: {
    type: {
      handler(newVal, oldVal) {
        if (!newVal) {
          return
        }
        if (newVal == 'manage' || newVal == 'front') {
          this.getMenuDataByType()
        } else if (newVal == 'app' && this.menus.length == 0) {
          this.loadMenus()
        }
      }
    }
  }
}
</script>

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