<template>
  <div class="layout-no-cols right-detail-tabs">
    <!--基本信息编辑-->
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" v-loading="confirmLoading" @click="confirm" priv="Platform.Branch.Add||Platform.Branch.Edit"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel">
        <div class="panel-header">
          <div class="title">{{branchId === 'new' ? '添加组织机构' : '修改组织机构'}}</div>
        </div>
        <el-form :model="tmpBranch" :rules="branchRules" ref="branchForm" label-suffix="：" class="system-branch-form" label-width="120px" v-loading="dialogLoading">
          <el-form-item label="名称" prop="name">
            <el-input v-model="tmpBranch.name"></el-input>
            <i class="fa fa-language" @click="langBtnClickHandler('name',tmpBranch.name,tmpBranch.name_I18N)"></i>
          </el-form-item>
          <el-form-item label="编号" prop="branchCode">
            <el-input v-model="tmpBranch.branchCode"></el-input>
          </el-form-item>
          <el-form-item label="上级机构" prop="parentInnerCode">
            <tree-select :value.sync="tmpBranch.parentInnerCode" :items="branch" :itemsOptions="treeItemsOptions" :disabled="branchId !== 'new'" :style="{width:'auto','display':'inline-block'}" placeholder="请选择">
            </tree-select>
          </el-form-item>
          <el-form-item label="机构主管">
            <el-select v-model="tmpBranch.managerselected" filterable :filter-method="managerFilter" :multiple="true" placeholder="请机构主管" class="manager-select">
              <el-option v-for="item in filterUsers" :key="item.userName" :label="item.realName" :value="item.userName">
                <span class="manager-select-item-left">{{ item.userName }}</span>
                <span class="manager-select-item-right">{{ item.realName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="电话" prop="phone" :verify="['Length<20']">
            <el-input v-model="tmpBranch.phone" ></el-input>
          </el-form-item>
          <el-form-item label="传真" prop="fax" :verify="['Length<20']">
            <el-input v-model="tmpBranch.fax"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 多语言编辑器 -->
    <lang-edit-dlg
      :show.sync="langDialog.isShowModal"
      :ID="langDialog.ID"
      :target-value="langDialog.targetValue"
      :languages="langDialog.languages"
      @callback="getI18nBack">
    </lang-edit-dlg>
    <!--基本信息编辑结束-->

    <el-tabs v-model="currentTab" class="tabs-wrap" value="menuPermission" v-if="this.branchId!='new'">
      <el-tab-pane :label="type.name" :name="type.code" v-for="(type,index) in branchPermissionTypes" :key="type.code">
        <component  :is="type.code" v-if="index==0||currentTab==type.code" :id="branchId" :type="privType"></component>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>

import util from '@src/common/util.js'
import TreeSelect from '@src/components/TreeSelect.vue'
import LangEditDialog from '@src/pages/platform/components/LangEditDialog.vue'
import MenuPermission from './MenuPermission.vue'
import SitePermission from './SitePermission.vue'
import APIPermission from './APIPermission.vue'
import CatalogPermission from './CatalogPermission.vue'
import DocPermission from './DocPermission.vue'
import ModulesPermission from './ModulesPermission.vue'
import BlockPermission from './BlockPermission.vue'
export default {
  components: {
    menuPermission: MenuPermission,
    sitePermission: SitePermission,
    apiPermission: APIPermission,
    catalogPermission: CatalogPermission,
    modulesPermission: ModulesPermission,
    docPermission: DocPermission,
    blockPermission: BlockPermission,
    'tree-select': TreeSelect,
    'lang-edit-dlg': LangEditDialog
  },
  props: {
    branchId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      dialogLoading: false,
      confirmLoading: false,
      parentId: '0',
      branch: [],
      treeItemsOptions: {
        children: 'children',
        label: 'name',
        key: 'branchInnerCode'
      },
      tmpBranch: {},
      branchRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        branchCode: [{ required: false, message: '请输入编号', trigger: 'blur' }],
        parentInnerCode: [
          {
            required: true,
            message: '请选择上级机构',
            trigger: 'change'
          }
        ]
      },
      filterUsers: [],
      users: [],
      langDialog: {
        isShowModal: false,
        branchId: '',
        languages: '',
        targetValue: ''
      },

      branchPermissionTypes: [],
      privType: 'B',
      currentTab: 'menuPermission'
    }
  },

  watch: {
    branchId() {
      this.loadBranchPermissionTypes()
    }
  },

  mounted() {
    this.parentId = this.$route.query.parentId ? this.$route.query.parentId : '0'
    this.beforeTurnToPage()
    if (this.branchId !== 'new') {
      this.loadBranchPermissionTypes()
    }
  },
  methods: {
    async beforeTurnToPage() {
      this.dialogLoading = true
      await this.loadBranchTree()
      this.tmpBranch = {
        name: '',
        branchCode: '',
        managers: [],
        managerselected: [],
        phone: '',
        fax: '',
        parentInnerCode: ''
      }
      if (this.branchId !== 'new') {
        await this.getSingleBranch()
      }
      await this.fetchUsers()
      this.dialogLoading = false
      Vue.set(this.tmpBranch, 'parentInnerCode', String(this.parentId) === '0' ? '' : this.parentId)
    },
    async getSingleBranch() {
      let res
      try {
        res = await axios.get(`/ui/branches/${this.branchId}`)
      } catch (e) {
        this.dialogLoading = false
        return
      }
      this.tmpBranch = Object.assign({}, res.data.data, {
        managerselected: []
      })
      this.tmpBranch.managers.forEach(val => {
        this.tmpBranch.managerselected.push(val.userName)
      })
      this.tmpBranch.addTime = util.formatDate(this.tmpBranch.addTime, 'yyyy-MM-dd HH:mm:ss')
    },
    async loadBranchTree() {
      let res
      try {
        res = await axios.get('/ui/branches', {params: {parentID: this.parentId}})
      } catch (e) {
        this.dialogLoading = false
        return
      }
      this.branch = res.data.data
    },
    // 机构主管筛选
    managerFilter(name) {
      let arr = this.users.filter(val => window.util.getSpell(val.userName.toLowerCase(), false).indexOf(window.util.getSpell(name.toLowerCase(), false)) !== -1 || window.util.getSpell(val.realName.toLowerCase(), false).indexOf(window.util.getSpell(name.toLowerCase(), false)) !== -1 || window.util.getSpell(val.realName.toLowerCase(), true).indexOf(window.util.getSpell(name.toLowerCase(), true)) !== -1 || window.util.getSpell(val.userName.toLowerCase(), true).indexOf(window.util.getSpell(name.toLowerCase(), true)) !== -1)
      this.filterUsers = arr.concat()
    },
    async fetchUsers() {
      if (!this.users || !this.users.length) {
        let res = ''
        try {
          res = await axios.get(`/ui/users`)
        } catch (e) {
          this.dialogLoading = false
          return
        }
        this.users = res.data.data
        this.filterUsers = res.data.data.concat()
      }
    },
    getI18nBack(data) {
      this.tmpBranch.name = data.val
      this.tmpBranch.name_I18N = data.data
    },
    // 打开多语言编辑框
    langBtnClickHandler(ID, value, languages) {
      this.langDialog.isShowModal = true
      this.langDialog.ID = ID
      this.langDialog.languages = languages
      this.langDialog.targetValue = value
    },
    async confirm() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['branchForm'])
        this.tmpBranch.manager = this.tmpBranch.managerselected.join(',')
        let res
        if (this.branchId === 'new') {
          res = await axios.post('/ui/branches', this.tmpBranch)
        } else {
          res = await axios.put(`/ui/branches/${this.branchId}`, this.tmpBranch)
        }
        this.confirmLoading = false
        if (res.data.status === 1 && this.branchId === 'new' && res.data.branchInnerCode) {
          this.$router.replace({path: `/platform/branch/${res.data.branchInnerCode}?parentId=${this.tmpBranch.parentInnerCode}`})
        }
        util.showResponseMessage(res.data)
      } catch (e) {
        this.confirmLoading = false
        util.showErrorMessageBox(e)
      }
    },

    async loadBranchPermissionTypes() {
      let res = await axios.get('/ui/permissions/id/none/type/none/types')
      this.branchPermissionTypes = res.data.data
    }
  }
}
</script>
<style scoped>
.pane-wrap {
  max-height: 420px;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
<style>
.system-branch-form {
  margin-top: 20px;
}
.system-branch-form .el-form-item .el-input {
  width: 450px;
  margin-right: 5px;
}
.system-branch-form .manager-select {
  width: 100%;
}
.system-branch-form .manager-select-item-left {
  float: left;
}
.system-branch-form .manager-select-item-right {
  float: right;
  color: #8492a6;
  font-size: 13px;
  margin-right: 32px;
}
.system-branch-form .el-form-item .select-wrap .el-input {
  width: auto;
}
</style>
