<template>
  <div class="app-container">
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="80%"
      top="4%"
    >
      <el-form
        ref="form"
        v-loading="loading"
        status-icon
        :model="formItem"
        :label-width="'120px'"
      >
        <ec-line></ec-line>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.resource.name')"
              prop="rsrcName"
              :rules="[
                {required: true, message: $t('ec.resource.name') + $t('ec.table.emptyError'), trigger:'blur'}
              ]"
            >
              <el-input
                v-model="formItem.rsrcName"
                type="text"
                :placeholder="$t('ec.resource.name')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.table.code')"
              prop="code"
              :rules="[
                {required: true, message: $t('ec.table.code') + $t('ec.table.emptyError'), trigger:'blur'},
                { validator: validateCode, trigger: 'blur'}
              ]"
            >
              <el-input
                v-model="formItem.code"
                type="text"
                :placeholder="$t('ec.table.code')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item
              v-if="superAdmin && enableTenant===true"
              :label="$t('ec.user.tenant')"
              prop="tenantId"
            >
              <ec-tenant v-model="formItem.tenantId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="superAdmin"
              :label="$t('ec.app.app')"
              prop="appId"
            >
              <ec-register-app
                v-model="formItem.appId"
                :disabled="method !== 'add'"
                :tenantId="formItem.tenantId"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">

          <el-col :span="12">
            <el-form-item
              label="首页图标"
              prop="portalImg"
              :rules="[
              ]"
            >
              <el-input v-model="formItem.portalImg" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.resource.permission')"
              prop="permission"
              :rules="[
              ]"
            >
              <el-input
                v-model="formItem.permission"
                type="text"
                :placeholder="$t('ec.resource.permission')"
              />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.tree.parent')"
              prop="pid"
            >
              <ec-select-tree
                ref="parentTree"
                v-model="formItem.pid"
                :title="$t('ec.tree.chooseParent')"
                check-strictly
                url="api/v1/resource/sysrResource/data"
                :data="reqData"
                :params="reqParams"
                attr-name="rsrcName"
                @change="parentChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.route.icons')"
              prop="rsrcIcon"
              :rules="[
              ]"
            >
              <ec-icon v-model="formItem.rsrcIcon" />
              <!--              <el-input v-model="formItem.rsrcIcon" type="text" placeholder="资源样式" />-->
            </el-form-item>
          </el-col></el-row>

        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item
              :label="$t('ec.resource.requestUrl')"
              prop="url"
              :rules="[
              ]"
            >
              <el-input
                v-model="formItem.url"
                type="text"
                :placeholder="$t('ec.resource.requestUrl')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <ec-line :title="'设置类'"></ec-line>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item
                :label="$t('ec.resource.type')"
                prop="typeSrc"
                :rules="[
                  {required: true, message: $t('ec.resource.type') + $t('ec.table.emptyError'), trigger:'blur'}
                ]"
              >
                <ec-radio-group
                  v-model="formItem.typeSrc"
                  dict-type="typeSrc"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="$t('ec.resource.nodeType')"
                prop="typeNode"
                :rules="[
                  {required: true, message: $t('ec.resource.nodeType') + $t('ec.table.emptyError'), trigger:'blur'}
                ]"
              >
                <ec-radio-group
                  v-model="formItem.typeNode"
                  dict-type="typeNode"
                />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.app.target')"
              prop="urlTarget"
              :rules="[
              ]"
            >
              <ec-radio-group
                v-model="formItem.urlTarget"
                dict-type="urlTarget"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.table.sort')"
              prop="sortNm"
              :rules="[
              ]"
            >
              <el-input-number v-model="formItem.sortNm" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.table.enableStatus')"
              prop="rsrcStatus"
              :rules="[
                {required: true, message: $t('ec.table.enableStatus') + $t('ec.table.emptyError'), trigger:'blur'}
              ]"
            >
              <ec-radio-group
                v-model="formItem.rsrcStatus"
                dict-type="enableState"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('ec.resource.defaultPermission')"
              :rules="[
                {required: true, message: $t('ec.resource.defaultPermission') + $t('ec.table.status') + $t('ec.table.emptyError'), trigger:'blur'}
              ]"
            >
              <ec-radio-group
                v-model="defaultpermission"
                :ec-data="statusOptions"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-collapse v-if="formItem.typeSrc == '1' && formItem.typeNode == '1'">
          <el-collapse-item
            :title="$t('ec.resource.vueRoute')"
            name="1"
          >
            <el-row
              v-if="designPage===true"
              :gutter="15"
            >
              <el-col :span="12">
                <el-form-item
                  label="引入页面定制"
                  prop=""
                  :rules="[]"
                >
                  <ec-radio-group
                    v-model="defaultpermissionCustom"
                    :ec-data="customOptions"
                    @change="defaultpermissionCustomChange"
                  />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.component')"
                  prop="component"
                  :rules="[
                  ]"
                >
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="tips.componentTip"
                    placement="bottom"
                  >
                    <el-input
                      v-model="formItem.component"
                      :disabled="defaultpermissionCustom"
                      type="text"
                      :placeholder="$t('ec.resource.component')"
                    />
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.component') + $t('ec.table.name')"
                  prop="componentName"
                >
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="tips.componentNameTip"
                    placement="bottom"
                  >
                    <el-input
                      v-model="formItem.componentName"
                      type="text"
                      :placeholder="$t('ec.resource.component') + $t('ec.table.name')"
                    />
                  </el-tooltip>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.breadcrumb')"
                  prop="flagBreadcrumb"
                  :rules="[
                    {required: true, message: $t('ec.resource.breadcrumb') + $t('ec.table.status') + $t('ec.table.emptyError'), trigger:'blur'}
                  ]"
                >
                  <ec-radio-group
                    v-model="formItem.flagBreadcrumb"
                    :ec-data="statusOptions"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.menuGroup')"
                  prop="flagMenuGroup"
                  :rules="[
                    {required: true, message: $t('ec.resource.menuGroup') + $t('ec.table.status') + $t('ec.table.emptyError'), trigger:'blur'}
                  ]"
                >
                  <ec-radio-group
                    v-model="formItem.flagMenuGroup"
                    :ec-data="statusOptions"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.hidden')"
                  prop="hidden"
                  :rules="[
                    {required: true, message: $t('ec.resource.hidden') + $t('ec.table.status') + $t('ec.table.emptyError'), trigger:'blur'}
                  ]"
                >
                  <ec-radio-group
                    v-model="formItem.hidden"
                    :ec-data="statusOptions"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.cache')"
                  prop="noCache"
                  :rules="[
                    {required: true, message: $t('ec.resource.cache') + $t('ec.table.status') + $t('ec.table.emptyError'), trigger:'blur'}
                  ]"
                >
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="tips.componentNameTip"
                    placement="bottom"
                  >
                    <ec-radio-group
                      v-model="formItem.noCache"
                      :ec-data="[{value: false, label: $t('ec.table.yes')}, {value: true, label: $t('ec.table.no')}]"
                    />
                  </el-tooltip>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.showRoot')"
                  prop="alwaysShow"
                  :rules="[
                    {required: true, message: $t('ec.resource.showRoot') + $t('ec.table.status') + $t('ec.table.emptyError'), trigger:'blur'}
                  ]"
                >
                  <ec-radio-group
                    v-model="formItem.alwaysShow"
                    :ec-data="statusOptions"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.affix')"
                  prop="affix"
                  :rules="[
                    {required: true, message: $t('ec.resource.affix') + $t('ec.table.status') + $t('ec.table.emptyError'), trigger:'blur'}
                  ]"
                >
                  <ec-radio-group
                    v-model="formItem.affix"
                    :ec-data="statusOptions"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.activeMenu')"
                  prop="activeMenu"
                  :rules="[
                  ]"
                >
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="tips.activeMenuTip"
                    placement="bottom"
                  >
                    <el-input
                      v-model="formItem.activeMenu"
                      type="text"
                      :placeholder="$t('ec.resource.activeMenu')"
                    />
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.redirect')"
                  prop="redirect"
                  :rules="[
                  ]"
                >
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="tips.redirectTip"
                    placement="bottom"
                  >
                    <el-input
                      v-model="formItem.redirect"
                      type="text"
                      :placeholder="$t('ec.resource.redirect')"
                    />
                  </el-tooltip>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.routeMenu')"
                  prop="route"
                  :rules="[
                    {required: true, message: $t('ec.resource.routeMenu') + $t('ec.table.status') + $t('ec.table.emptyError'), trigger:'blur'}
                  ]"
                >
                  <ec-radio-group
                    v-model="formItem.route"
                    :ec-data="statusOptions"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="$t('ec.resource.modulePath')"
                  prop="modulePath"
                  :rules="[
                  ]"
                >
                  <el-input
                    v-model="formItem.modulePath"
                    type="textarea"
                    :autosize="{minRows: 3, maxRows: 5}"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="visible = false">{{ $t('ec.table.close') }}</el-button>
        <el-button
          v-if="method !== 'view'"
          type="primary"
          :loading="confirmLoading"
          @click="save"
        >{{ $t('ec.table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import mixin from 'ecip-web/utils/common-mixin'
import {
  getById,
  save,
  update,
  addPermission,
  checkCode,
  getStatusByCode
} from 'ecip-web/api/vue/resource/sysrResourceApi'
const enableTenant =
  window._CONFIG['enableTenant'] === undefined
    ? true
    : window._CONFIG['enableTenant']
const designPage =
  window._CONFIG['designPage'] === undefined
    ? true
    : window._CONFIG['designPage']
export default {
  name: 'VueResourceSysrResourceForm',
  components: {},
  mixins: [...mixin],
  data() {
    return {
      enableTenant,
      designPage,
      visible: false,
      loading: false,
      confirmLoading: false,
      resource: { id: '' },
      method: '',
      title: '',
      statusOptions: [
        { value: true, label: '是' },
        { value: false, label: '否' }
      ],
      customOptions: [
        { value: true, label: '是' },
        { value: false, label: '否' }
      ],
      formItem: {
        appId: '',
        pid: '',
        rsrcName: '',
        tenantId: '',
        code: '',
        url: '',
        urlTarget: '_self',
        typeNode: '1',
        typeSrc: '1',
        modulePath: '',
        permission: '',
        rsrcIcon: '',
        portalImg: '',
        rsrcStatus: '1',
        typeShow: '',
        sortNm: '',
        flagBreadcrumb: false,
        flagMenuGroup: true,
        hidden: false,
        alwaysShow: false,
        noCache: false,
        affix: false,
        route: true,
        activeMenu: null,
        component: null,
        redirect: null,
        componentName: ''
      },
      defaultpermission: false,
      defaultpermissionCustom: false,
      tips: {
        componentTip:
          '有子菜单的一级菜单的需填@ecip/ecip-web/layout；中间的菜单需填：@ecip/ecip-web/layout/components/AppMain；其他节点填对应的路径，如：views/modules/system/sysrUserAlone/view',
        activeMenuTip:
          '一般没有菜单的页面才需配置，如新增，编辑页面配置查询列表的路径',
        redirectTip: '如需禁用，请填: noRedirect',
        componentNameTip:
          '如需缓存路由生效，需填写vue文件name保持一致(vue文件中name尽量不要重复)'
      }
    }
  },
  computed: {
    reqParams() {
      return { excludeId: this.resource && this.resource.id }
    },
    reqData() {
      return { appId: this.formItem.appId, tenantId: this.formItem.tenantId }
    }
  },
  methods: {
    async codeBlur(code) {
      if (code === '') return

      const s = await getStatusByCode(code)

      switch (s.data) {
        case '-1':
        case '0':
        case '1':
          {
            this.$notify.error('编码未发布，不可用！')
            this.formItem.code = ''
          }

          break
        case '2':
          {
            this.$notify.success('编码已发布，可用！')
          }

          break

        default:
          break
      }
    },
    defaultpermissionCustomChange() {
      this.formItem.code = ''
      this.formItem.component = this.defaultpermissionCustom
        ? '@ecip/ecip-design-page/views/modules/docking/comDesign.vue'
        : ''
    },
    init(method, tenantId, appId, row, parent) {
      this.visible = true
      this.loading = false
      this.method = method
      this.resource = row
      if (method === 'add') {
        this.title = `新增资源`
      } else if (method === 'edit') {
        this.title = `编辑-${row.rsrcName}`
      } else if (method === 'view') {
        this.title = `查看-${row.rsrcName}`
      }

      this.$nextTick(async () => {
        // 清空初始化
        this.$refs.form.clearValidate()
        Object.assign(this.$data.formItem, this.$options.data().formItem)
        if (parent && parent.id) {
          this.formItem.pid = parent.id
          this.formItem.tenantId = parent.tenantId
        }
        this.formItem.tenantId = tenantId
        this.formItem.appId = appId
        if (method === 'edit' || method === 'view') {
          // 修改或者查看
          try {
            this.loading = true
            const { data } = await getById(row.id)
            this.formItem = Object.assign({}, this.formItem, data)
          } finally {
            this.loading = false
          }
        }
      })
    },
    async validateCode(rule, value, callback) {
      const { data } = await checkCode(
        (this.resource && this.resource.id) || '',
        value,
        this.formItem.appId,
        this.formItem.tenantId
      )

      // 过了校验【验证：编码是否全局唯一性】
      if (data.valid) {
        // 且 系统有配置 【designPage】为true
        // 且 用户有选择 【页面定制】
        if (designPage && this.defaultpermissionCustom) {
          this.codeBlur(value)
        }

        callback()
      } else {
        callback(new Error('编码已存在'))
      }
    },
    parentChange(parentId, parent) {
      this.formItem.tenantId = parent.tenantId
    },
    async save() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.confirmLoading = true
            let res = {}
            if (this.method === 'edit') {
              res = await update(this.resource.id, this.formItem)
            } else {
              res = await save(this.formItem)
            }
            if (this.defaultpermission) {
              // 新增默认权限
              await addPermission(res.data)
            }

            this.$notify.success('保存成功')
            this.$emit('refreshData')
            this.visible = false
          } finally {
            this.confirmLoading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
