<template>
  <div class="layout-no-cols">
    <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"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel">
        <h4>{{branchId === 'new' ? '添加会员机构' : '修改会员机构'}}</h4>
        <el-form label-position="right" :model="tmpBranch" ref="form"  label-suffix="：" class="branch-opt-form" label-width="120px" v-loading="dialogLoading">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称" prop="name" :verify="['NotNull']">
                <el-input v-model="tmpBranch.name" @change="setAlias()"></el-input>
                <i class="fa fa-language" @click="langBtnClickHandler('name',tmpBranch.name,tmpBranch.name_I18N)"></i>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编码" prop="branchCode" :verify="['NotNull']">
                <el-input v-model="tmpBranch.branchCode"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="上级机构">
                <tree-select  :disabled="branchId!='new'" :value.sync="tmpBranch.parentInnerCode" :items="branchTree" :itemsOptions="treeItemsOptions" :style="{width:'auto','display':'inline-block'}">
                </tree-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构主管" >
                <el-input v-model="tmpBranch.managerName" style="width:230px;" readonly>
                  <el-button slot="append" @click="addBranchManagerClickHandler" title="添加"><i class="fa fa-plus"></i></el-button>
                  <el-button slot="append" @click="clearBranchManagerClickHanlder" title="清空"><i class="fa fa-remove"></i></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="电话" prop="phone" :verify="['Length<13','CnTel']">
                <el-input v-model="tmpBranch.phone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真" prop="fax" :verify="['Length<13','CnTel']">
                <el-input v-model="tmpBranch.fax"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </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>
    <!-- 选择机构主管 -->
     <user-select-dlg
      ref="refUserSelectDlg"
      :userSelectShow.sync="memberSelect.isShowModal"
      :toUsers="memberSelect.selectedUser"
      :types="type"
      @callback="afterSelectMember">
    </user-select-dlg>
  </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 userSelectDlg from '../platform/components/UserSelectDialog.vue'
export default {
  components: {
    'tree-select': TreeSelect,
    'lang-edit-dlg': LangEditDialog,
    'user-select-dlg': userSelectDlg
  },
  props: {
    branchId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      parentId: '0',
      type: 'mem',
      tmpBranch: {parentInnerCode: ''},
      dialogLoading: false,
      confirmLoading: false,
      treeItemsOptions: {
        //  树形菜单选项
        children: 'children',
        label: 'name',
        key: 'branchInnerCode'
      },
      branchTree: [], // 机构树
      langDialog: {
        isShowModal: false,
        branchId: '',
        languages: '',
        targetValue: ''
      },
      memberSelect: {// 选中机构管理员
        isShowModal: false,
        selectedUser: ''
      }
    }
  },
  mounted() {
    this.parentId = this.$route.query.parentId ? this.$route.query.parentId : '0'
    this.beforeTurnToPage()
  },
  methods: {
    // 别名设置：取名称首字母
    setAlias() {
      if (this.tmpBranch.branchCode.trim()) {
        return
      }
      this.tmpBranch.branchCode = window.util.getSpell(
        this.tmpBranch.name,
        true
      )
    },
    async confirm() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['form'])
        let res = ''
        if (this.branchId !== 'new') {
          res = await axios.put(`/ui/memberbranch/${this.branchId}`, this.tmpBranch)
        } else {
          res = await axios.post('/ui/memberbranch', this.tmpBranch)
          if (res.data.status === 1 && res.data.branchInnerCode) {
            this.$router.replace({path: `/member/branch/${res.data.branchInnerCode}`, query: {parentId: this.tmpBranch.parentInnerCode || 0}})
          }
        }
        this.confirmLoading = false
        util.showMessage(res)
      } catch (e) {
        this.confirmLoading = false
        util.showErrorMessageBox(e)
      }
    },
    getI18nBack(data) {
      this.tmpBranch.name_I18N = data.data
      this.tmpBranch.name = data.val
    },
    // 打开多语言编辑框
    langBtnClickHandler(ID, value, languages) {
      this.langDialog.isShowModal = true
      this.langDialog.ID = ID
      this.langDialog.languages = languages
      this.langDialog.targetValue = value
    },
    // 清除机构管理员
    clearBranchManagerClickHanlder() {
      this.tmpBranch.managerName = ''
      this.tmpBranch.manager = ''
      this.memberSelect.selectedUser = ''
    },
    afterSelectMember(user) {
      this.tmpBranch.manager = user
      this.tmpBranch.managerName = user
    },
    // 添加机构管理员
    addBranchManagerClickHandler() {
      this.memberSelect.isShowModal = true
      this.memberSelect.selectedUser = this.tmpBranch.manager
      this.$refs.refUserSelectDlg.getBranchDatas(this.parentId)
    },
    // 加载组织机构树
    async loadBranchTree() {
      let res = await axios.get('/ui/memberbranch/memberbranchtable', {
        params: {
          parentID: this.parentId
        }
      })
      this.branchTree = res.data.data
    // console.log(this.branchTree)
    },
    async beforeTurnToPage() {
      this.dialogLoading = true
      await this.loadBranchTree()
      this.tmpBranch = {
        parentInnerCode: '0',
        name: '',
        branchCode: '',
        manager: '',
        managerName: '',
        phone: '',
        fax: ''
      }
      if (this.branchId !== 'new') {
        await this.initDialog()
      }
      this.dialogLoading = false
      Vue.set(this.tmpBranch, 'parentInnerCode', String(this.parentId) === '0' ? '' : this.parentId)
    },
    // 初始化编辑弹框
    async initDialog() {
      let res = await axios.get(`/ui/memberbranch/${this.branchId}`)
      this.tmpBranch = res.data.data
    }
  }
}
</script>
<style>
.branch-opt-form {
  margin-top: 20px;
}
.branch-opt-form .el-form-item .el-input {
  width: 230px;
  margin-right: 5px;
}
.branch-opt-form .el-form-item .el-textarea{
  width: 230px;
  margin-right: 5px;
}
.detail-panel h4 {font-weight: bold;}
</style>
