<template>
  <div class="fullheight">
    <el-tabs
      type="card"
      v-model="orgResume"
      @tab-click="tabClick"
      class="fullheight org-manage-tabs"
    >
      <el-tab-pane label="组织简介" name="orgInfo">
        <el-form
          class="brief"
          data-vv-scope="form1"
          v-form="{formItemAlign: 'left'}"
          :label-width="labelWidth"
        >
          <div class="plane">
            <h1 class="title">组织信息</h1>
            <el-row :gutter="20">
              <el-col :span="8">
                <ht-form-item label="上级组织名称">
                  <span v-if="OrgManagerFormType == 'showInfo'">{{
                    org.parentOrgName || '-'
                  }}</span>
                  <!-- <ht-input
                    v-else
                    v-model="org.parentOrgName"
                    permission="b"
                    placeholder="请输入上级组织名称"
                    style="width: 100%"
                    class="parent-org-name"
                    type="button"
                    :clearable="false"
                    @focus="showOrgTreeDialog"
                  /> -->
                  <tree-Select
                    v-else
                    v-model="org.parentId"
                    :normalizer="normalizer"
                    :multiple="false"
                    :options="treeData"
                    noOptionsText=" "
                    noChildrenText=" "
                    class="pre-menu"
                    placeholder="请选择父节点"
                    @select="treeSelect"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8">
                <ht-form-item label="组织名称">
                  <span v-if="OrgManagerFormType == 'showInfo'">{{
                    org.name || '-'
                  }}</span>
                  <ht-input
                    v-else
                    v-model="org.name"
                    permission="b"
                    placeholder="请输入组织名称"
                    style="width: 100%"
                    :maxlength="50"
                    show-word-limit
                    :disabled="OrgManagerFormType == 'showInfo'"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8">
                <ht-form-item label="组织现编用户数量">
                  <span v-if="OrgManagerFormType == 'showInfo'">{{
                    org.nowNum || '-'
                  }}</span>
                  <ht-input
                    v-else
                    v-model="org.nowNum"
                    permission="r"
                    placeholder="组织现编用户数量"
                    style="width: 100%"
                  />
                </ht-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <ht-form-item label="排序号">
                  <span v-if="OrgManagerFormType == 'showInfo'">{{
                    org.orderNo
                  }}</span>
                  <ht-input
                    v-else
                    v-model="org.orderNo"
                    permission="b"
                    placeholder="请输入排序号"
                    style="width: 100%"
                    :maxlength="9"
                    show-word-limit
                    :validate="{regex: {exp: '^[0-9]*$', message: ''}}"
                    :disabled="OrgManagerFormType == 'showInfo'"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8">
                <ht-form-item label="级别">
                  <span v-if="OrgManagerFormType == 'showInfo'">{{
                    org.grade || '-'
                  }}</span>
                  <ht-input
                    v-else
                    v-model="org.grade"
                    permission="w"
                    placeholder="请输入级别"
                    :maxlength="30"
                    :showWordLimit="true"
                    style="width: 100%"
                    :disabled="OrgManagerFormType == 'showInfo'"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8" style="position: relative;">
                <el-tooltip
                  class="tooltip-item"
                  effect="dark"
                  content="0表示不受限制"
                  placement="top"
                >
                  <span class="el-icon-question"></span>
                </el-tooltip>
                <ht-form-item label="组织限编用户数量">
                  <span v-if="OrgManagerFormType == 'showInfo'">{{
                    org.limitNum || '-'
                  }}</span>
                  <ht-input
                    v-else
                    v-model="org.limitNum"
                    permission="w"
                    placeholder="组织限编用户数量"
                    style="width: 100%"
                    :maxlength="9"
                    show-word-limit
                    :validate="{regex: {exp: '^[0-9]*$', message: ''}}"
                    :disabled="OrgManagerFormType == 'showInfo'"
                  />
                </ht-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <ht-form-item label="组织编码">
                  <span v-if="OrgManagerFormType != 'addOrg'">{{
                    org.code || '-'
                  }}</span>
                  <ht-input
                    v-else
                    v-model="org.code"
                    permission="b"
                    placeholder="请输入组织编码"
                    v-pinyin="org.name"
                    :maxlength="50"
                    show-word-limit
                    style="width: 100%"
                    :disabled="OrgManagerFormType != 'addOrg'"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8">
                <ht-form-item label="是否允许超过限编">
                  <span v-if="OrgManagerFormType == 'showInfo'">{{
                    org.exceedLimitNum == 0 ? '允许' : '不允许'
                  }}</span>
                  <ht-radio
                    v-else
                    v-model="org.exceedLimitNum"
                    :disabled="OrgManagerFormType == 'showInfo'"
                    :options="[
                      {key: 0, value: '允许'},
                      {key: 1, value: '不允许'}
                    ]"
                  />
                </ht-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <el-form v-model="orgParam" v-form="{formItemAlign: 'left'}" data-vv-scope="orgForm">
          <div class="plane">
            <h1 class="title">组织参数</h1>
            <el-row :gutter="20" class="row-wrap">
              <el-col
                :span="8"
                v-for="(param, num) in orgParams"
                :key="param.name"
              >
                <ht-form-item
                  :title="param.name"
                  :label="param.name"
                  prop="name"
                  label-width="130px"
                >
                  <el-date-picker
                    v-model="orgParam[param.code]"
                    type="datetime"
                    placeholder="选择日期时间"
                    :disabled="OrgManagerFormType == 'showInfo' ? true : false"
                    class="width-wrap"
                    v-if="param.ctlType === 'date'"
                  ></el-date-picker>
                  <ht-input
                    v-model="orgParam[param.code]"
                    type="text"
                    :maxlength="64"
                    show-word-limit
                    :permission="OrgManagerFormType == 'showInfo' ? 'r' : 'w'"
                    v-if="param.ctlType === 'input'"
                  />
                  <ht-input
                    type="number"
                    v-model="orgParam[param.code]"
                    :permission="OrgManagerFormType == 'showInfo' ? 'r' : 'w'"
                    v-if="param.ctlType === 'number'"
                    class="input-number_wrap"
                    width="220px"
                  />
                  <ht-select
                    v-model="orgParam[param.code]"
                    :permission="OrgManagerFormType == 'showInfo' ? 'r' : 'w'"
                    v-if="param.ctlType === 'select' && param.json"
                    :options="JSON.parse(param.json)"
                    class="width-wrap"
                  />
                  <ht-radio
                    v-model="orgParam[param.code]"
                    :permission="OrgManagerFormType == 'showInfo' ? 'r' : 'w'"
                    v-if="param.ctlType === 'radio' && param.json"
                    :options="JSON.parse(param.json)"
                  />
                  <ht-checkbox
                    v-model="orgParam[param.code]"
                    :permission="OrgManagerFormType == 'showInfo' ? 'r' : 'w'"
                    v-if="param.ctlType === 'checkbox' && param.json"
                    :options="JSON.parse(param.json)"
                  />
                </ht-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <el-footer
          class="parameters-footer"
          v-if="OrgManagerFormType != 'showInfo'"
        >
          <el-button type="primary" @click="submit">保存</el-button>
        </el-footer>
      </el-tab-pane>
      <el-tab-pane
        label="组织人员"
        name="orgUser"
        :disabled="OrgManagerFormType === 'addOrg'"
        class="fullheight"
      >
        <ht-table
          @load="loadData"
          :data="orgUser"
          :pageResult="pageResult"
          :selection="true"
          :quick-search-props="[{prop: 'u.fullname_', label: '姓名'}]"
          :default-querys="defaultQuerys"
          @select-all="selectUser"
          @select="selectUser"
          ref="htTable"
          v-if="orgUserShow"
          class="fullheight"
          :show-custom-column="false"
          :show-export="false"
          @row-click="rowClick"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange"
        >
          <template v-slot:toolbar>
            <el-button-group>
              <el-button
                size="small"
                @click="showAddOrgUser()"
                icon="el-icon-plus"
                type="primary"
                >添加</el-button
              >
              <el-button @click="setUserMaster()">设置主组织</el-button>
              <el-button
                size="small"
                style="margin-left:10px"
                @click="setUserPost()"
                >设置岗位</el-button
              >
              <ht-delete-button
                :url="orgUserDeleteUrl"
                :htTable="$refs.htTable"
                pk="orgUserId"
                @after-delete="afterDelete"
                :disabled="isDisabled"
                >删除</ht-delete-button
              >
            </el-button-group>
          </template>
          <template>
            <ht-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            />
            <ht-table-column
              prop="u.FULLNAME_"
              align="center"
              label="名称"
              width="150"
              :sortable="true"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <el-link type="primary" @click="editUser(scope.row.account)">{{
                  scope.row.fullName
                }}</el-link>
              </template>
            </ht-table-column>
            <ht-table-column
              prop="account"
              label="账号"
              :sortable="true"
              :show-overflow-tooltip="true"
            />
            <ht-table-column prop="relName" label="岗位名称" :sortable="false">
              <template slot-scope="scope">
                <div
                  v-if="scope.row.relName"
                  :title="scope.row.relName ? scope.row.relName.join(',') : ''"
                  class="text-hidden"
                >
                  {{ scope.row.relName ? scope.row.relName.join(',') : '' }}
                </div>
              </template>
            </ht-table-column>
            <ht-table-column width="120" label="全部组织岗位">
              <template slot-scope="scope">
                <!--<el-tag type="danger" v-if="scope.row.otherPost == 1">无</el-tag>-->
                <!--<el-link type="primary" @click="getOtherPost(scope.row)"><el-tag v-if="scope.row.otherPost == 2">有</el-tag></el-link>-->
                <!--<el-link type="primary" @click="getOtherPost(scope.row)"><el-tag v-if="scope.row.otherPost == 3"  type="success">有（主）</el-tag></el-link>-->
                <el-link type="primary" @click="getOtherPost(scope.row)"
                  ><el-tag type="success">查看</el-tag></el-link
                >
              </template>
            </ht-table-column>
            <ht-table-column
              prop="orguser.IS_MASTER_"
              align="center"
              label="是否主要组织"
              width="150"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '否', value: 0},
                {text: '是', value: 1}
              ]"
            >
              <template v-slot="{row}">
                <span type="danger" v-if="row.isMaster == 0">否</span>
                <span type="success" v-if="row.isMaster == 1">是</span>
              </template>
            </ht-table-column>
            <ht-table-column
              prop="orguser.IS_CHARGE_"
              align="center"
              label="负责人"
              width="100"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '否', value: 0},
                {text: '是', value: 1},
                {text: '主', value: 2}
              ]"
            >
              <template v-slot="{row}">
                <span type="danger" v-if="row.isCharge == 0">否</span>
                <span v-if="row.isCharge == 1">是</span>
                <span type="success" v-if="row.isCharge == 2">主</span>
              </template>
            </ht-table-column>
            <ht-table-column
              prop="u.STATUS_"
              align="center"
              label="状态"
              width="100"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '禁用', value: 0},
                {text: '正常', value: 1},
                {text: '离职', value: -2}
              ]"
            >
              <template v-slot="{row}">
                <span
                  :class="{success: row.status == 1, danger: row.status == 0}"
                >
                  {{
                    row.status == 0
                      ? '禁用'
                      : row.status == 1
                      ? '正常'
                      : row.status == -2
                      ? '离职'
                      : ''
                  }}
                </span>
              </template>
            </ht-table-column>
            <ht-table-column width="300" align="left">
              <template v-slot:header>
                <span>操作</span>
              </template>
              <template v-slot="{row}">
                <el-button
                  type="text"
                  @click="
                    orgUserHandleCommand({row: row, command: 'setIsMaster'})
                  "
                >
                  {{ row.isMaster == '0' ? '设置主组织' : '取消主组织' }}
                </el-button>
                <el-button
                  type="text"
                  @click="
                    orgUserHandleCommand({row: row, command: 'setIsMainChange'})
                  "
                  v-if="row.isCharge != '2'"
                >
                  设置主负责人
                </el-button>
                <el-button
                  type="text"
                  @click="
                    orgUserHandleCommand({row: row, command: 'setOrgCharge'})
                  "
                  v-if="row.isCharge == '2'"
                >
                  取消主负责人
                </el-button>
                <el-button
                  type="text"
                  @click="
                    orgUserHandleCommand({row: row, command: 'setOrgCharge'})
                  "
                  v-if="row.isCharge == '0'"
                >
                  设置负责人
                </el-button>
                <el-button
                  type="text"
                  @click="
                    orgUserHandleCommand({row: row, command: 'setOrgCharge'})
                  "
                  v-if="row.isCharge == '1'"
                >
                  取消负责人
                </el-button>
                <!-- <el-dropdown
                  size="mini"
                  split-button
                  @command="orgUserHandleCommand"
                  @click="
                    orgUserHandleCommand({
                      row: row,
                      command: 'setIsMaster',
                    })
                  "
                > -->
                <!-- <span>
                    <i class="el-icon-user"></i
                    >{{ row.isMaster == '0' ? '设置主组织' : '取消主组织' }}
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      icon="el-icon-s-home"
                      :command="{row: row, command: 'setIsMainChange'}"
                      v-if="row.isCharge != '2'"
                      >设置主负责人</el-dropdown-item
                    >
                    <el-dropdown-item
                      icon="el-icon-s-home"
                      :command="{row: row, command: 'setOrgCharge'}"
                      v-if="row.isCharge == '2'"
                      >取消主负责人</el-dropdown-item
                    >
                    <el-dropdown-item
                      icon="el-icon-s-home"
                      :command="{row: row, command: 'setOrgCharge'}"
                      v-if="row.isCharge == '0'"
                      >设置负责人</el-dropdown-item
                    >
                    <el-dropdown-item
                      icon="el-icon-s-home"
                      :command="{row: row, command: 'setOrgCharge'}"
                      v-if="row.isCharge == '1'"
                      >取消负责人</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown> -->
              </template>
            </ht-table-column>
          </template>
        </ht-table>
        <el-dialog
          title="其他组织岗位信息"
          :visible.sync="dialogVisible"
          @close="otherPostClose"
          width="55%"
          :append-to-body="true"
        >
          <el-table
            border
            style="width: 100%"
            :data="otherPostData"
            height="360"
          >
            <el-table-column
              prop="userName"
              label="姓名"
              width="120"
              align="left"
            />
            <el-table-column prop="orgName" label="组织名称" align="left" />
            <el-table-column prop="posName" label="岗位名称" align="left" />
            <el-table-column label="是否主要组织" width="120" align="left">
              <template slot-scope="scope">
                <span type="success" v-if="scope.row.isMaster">是</span>
                <span v-else type="danger">否</span>
              </template>
            </el-table-column>
            <el-table-column label="负责人" width="80" align="left">
              <template slot-scope="scope">
                <span v-if="scope.row.isCharge == '0'" type="danger">否</span>
                <span v-if="scope.row.isCharge == '1'" type="primary">是</span>
                <span v-if="scope.row.isCharge == '2'" type="success">主</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="80" align="left">
              <template slot-scope="scope">
                <span
                  :class="{
                    success: scope.row.status == 1,
                    danger: scope.row.status == 0
                  }"
                >
                  {{
                    scope.row.status == 0
                      ? '禁用'
                      : scope.row.status == 1
                      ? '正常'
                      : scope.row.status == -2
                      ? '离职'
                      : ''
                  }}
                </span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="text-right mrt24"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="otherPostPageResult.page"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="otherPostPageResult.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="otherPostPageResult.total"
            background
          >
          </el-pagination>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogVisible = false"
              >关 闭</el-button
            >
          </div>
        </el-dialog>
        <ht-user-dialog
          ref="eipUserDialog"
          @on-confirm="userDialogOnConfirm"
          append-to-body
        />
        <post-dialog
          ref="postDialog"
          @onConfirm="postDialogOnConfirm"
          :orgId="org.id"
          append-to-body
        />
      </el-tab-pane>
      <el-tab-pane
        label="组织岗位"
        name="orgPost"
        :disabled="OrgManagerFormType === 'addOrg'"
        class="fullheight"
      >
        <org-post
          :org-id="org.id"
          :org-code="org.groupCode"
          v-if="orgPostShow"
          class="fullheight"
        ></org-post>
      </el-tab-pane>
      <el-tab-pane
        label="分级组织管理设置"
        name="orgManageSetting"
        :disabled="OrgManagerFormType === 'addOrg'"
        class="fullheight"
      >
        <org-auth-page
          :org-code="org.code"
          v-if="orgAuthPageShow"
          :dem-code="org.demCode"
          @orgAuthData="getOrgAuthData"
          class="fullheight"
        ></org-auth-page>
      </el-tab-pane>
      <ht-sidebar-dialog
        width="36%"
        title="查看用户"
        :visible="isUserInfo"
        :before-close="handleCloseUserManager"
        :append-to-body="true"
      >
        <user-detail :user="user" />
      </ht-sidebar-dialog>
      <el-dialog
        width="70%"
        title="编辑用户"
        :visible="isUserManagerShow"
        :before-close="handleCloseUserManager"
        ref="userManagerref"
        :close-on-click-modal="false"
        :append-to-body="true"
      >
        <!--编辑用户面板-->
        <user-manager
          ref="userManager"
          :user-account="clickUserAccount"
          v-if="isUserManagerShow"
          @handleCloseUserManager="handleCloseUserManager"
          @closeUserManeger="handleCloseUserManager"
        ></user-manager>
      </el-dialog>
    </el-tabs>
    <!-- 直接下属管理组件   -->
    <under-user-table
      :org-id="org.id"
      :user-id="selectOrgUserAccount"
      :dim-id="demId"
      ref="underUserTable"
    ></under-user-table>
    <org-tree-dialog
      :def-id="demId"
      ref="orgTreeDialog"
      :support-filter="true"
      :default-expand-all="true"
      :show-checkbox="false"
      :expand-on-click-node="false"
      :highlight-current="true"
      :orgTreeDialogVisible.sync="orgTreeDialogVisible"
      @org-tree-dialog-confirm="orgTreeDialogConfirm"
    />
  </div>
</template>

<script>
import moment from 'moment'
import orgrequest from '@/api/org.js'
import uc from '@/api/uc.js'
import UserDetail from '@/views/uc/UserDetail.vue'
import UserManager from '@/views/uc/UserManager'
import EipUserDialog from '@/components/dialog/EipUserDialog.vue'
import PostDialog from './PostDialog.vue'
import underUserTable from './UnderUserTable'
import OrgPost from './OrgPost'
import OrgAuthPage from './OrgAuthPage'
import OrgTreeDialog from '@/views/uc/org/OrgTreeDialog'
import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'
const treeSelect = () => import('@riophae/vue-treeselect')
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'org-manager',
  mixins: [tableHeaderFilter],
  data() {
    return {
      labelWidth: '130px',
      org: {
        id: '',
        name: '',
        parentOrgName: '',
        groupCode: '',
        orderNo: '',
        grade: '',
        demId: '',
        demCode: '',
        parentId: '',
        code: '',
        exceedLimitNum: 0,
        limitNum: 0,
        nowNum: 0
      },
      orgUser: [], //组织人员
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      otherPostPageResult: {
        page: 1,
        pageSize: 5,
        total: 0
      },
      orgUserShow: false,
      underUserDialogShow: false,
      orgPostShow: false,
      orgAuthPageShow: false,
      selectOrgUserAccount: '',
      orgParams: [], // 组织参数
      orgParam: {},
      userParam: {}, // 用户参数
      orgResume: 'orgInfo',
      saveRoleUrl: '/api/org/v1/org/addOrg',
      OrgManagerFormType: '',
      selectUsers: [],
      otherPostData: [],
      dialogVisible: false,
      orgAuthData: [],
      isUserInfo: false,
      user: {},
      isUserManagerShow: false,
      clickUserAccount: '',
      orgTreeDialogVisible: false,
      selectedList: [],
      isDisabled: true
    }
  },
  components: {
    OrgTreeDialog,
    EipUserDialog,
    underUserTable,
    OrgPost,
    OrgAuthPage,
    PostDialog,
    UserDetail,
    UserManager,
    treeSelect
  },
  props: ['type', 'orgCode', 'parentName', 'demId', 'parentId', 'treeData'],
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },
  mounted() {
    this.OrgManagerFormType = this.type
    this.org.parentId = this.parentId
    this.org.parentOrgName = this.parentName
    this.org.demId = this.demId
    if (
      this.OrgManagerFormType === 'showInfo' ||
      this.OrgManagerFormType === 'editOrg'
    ) {
      orgrequest.getOrg(this.orgCode).then(resp => {
        this.org = resp
      })
    }
    if (this.OrgManagerFormType === 'addOrg') {
      var num = ''
      for (var i = 0; i < 3; i++) {
        num += Math.floor(Math.random() * 10)
      }
      this.org.orderNo = num
    }
    orgrequest.getOrgParams().then(resp => {
      this.orgParams = resp
      //当 新建维度下面的组织时清空
      if (this.type != 'addOrg') {
        this.getOrgParamsByCode()
      }
    })
  },
  filters: {
    dateFormat(val) {
      return moment(val).format('YYYY-MM-DD') || '-'
    }
  },
  computed: {
    orgUserDeleteUrl: function() {
      return window.context.uc + '/api/org/v1/orgUser/delOrgUserByUserIds'
    },
    defaultQuerys: function() {
      return [{property: 'org.ID_', value: this.org.id}]
    },
    treeDisabled: function() {
      let check = false
      if (this.treeData.length) {
        let id = this.treeData[0].id
        check = id === '0' ? true : false
      }
      return check
    }
  },
  methods: {
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
        isDefaultExpanded: false
      }
    },
    treeSelect(node) {
      this.$set(this.org, 'parentOrgName', node.name)
      this.$set(this.org, 'parentId', node.id)
    },
    rowClick(row, column, event) {
      this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
    },
    loadData(param, cb) {
      if (param.sorter) {
        param.sorter.forEach(item => {
          if (item.property == 'account') {
            item.property = 'u.ACCOUNT_'
          } else if (item.property == 'relName') {
            item.property = 'rel.POS_NAME_'
          }
        })
      }
      this.selectUsers = []
      orgrequest
        .getOrgUserPage(param)
        .then(response => {
          this.org.nowNum = response.total
          this.orgUser = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => cb())
    },
    tabClick(tab) {
      //点击tab卡片
      this.orgUserShow = false
      this.orgPostShow = false
      this.orgAuthPageShow = false
      this.$nextTick(() => {
        if (tab.index === '1') {
          this.orgUserShow = true
        } else if (tab.index === '2') {
          this.orgPostShow = true
        } else if (tab.index === '3') {
          this.orgAuthPageShow = true
        }
      })
    },
    orgUserHandleCommand(params) {
      this.readOnly = false
      switch (params.command) {
        case 'toUnderUserPage':
          this.selectOrgUserAccount = params.row.account
          this.$refs.underUserTable.showDialog(params.row.userId)
          break
        case 'setIsMaster':
          //设置主组织
          if (
            params.row.relName != undefined &&
            params.row.relName.length > 1 &&
            params.row.isMaster == 0
          ) {
            //当前用户有多个岗位时跳转组织岗位修改
            this.orgResume = 'orgPost'
            this.orgPostShow = true
            this.$message.warning(
              '当前用户有在该组织存在多个岗位，需要在组织岗位设值主组织'
            )
            break
          }
          orgrequest.setMasterById(params.row.orgUserId).then(resp => {
            if (resp.state) {
              this.$message.success(resp.message)
              let tab = {index: '1'}
              this.tabClick(tab)
            } else {
              this.$message.error(resp.message)
            }
          })
          break
        case 'setOrgCharge':
          //设置是否为主要负责人
          this.setOrgCharge(params.row)
          break
        case 'setIsMainChange':
          //设置是否为主要负责人
          params.row.isMainChange = true
          this.setOrgCharge(params.row)
          break
        default:
          break
      }
    },
    showAddOrgUser() {
      if (
        1 + this.org.nowNum > this.org.limitNum &&
        this.org.limitNum != 0 &&
        this.org.exceedLimitNum === 1
      ) {
        this.$message.error('现编用户数量已达到组织用户限编数量')
        return
      }
      this.$refs.eipUserDialog.showDialog()
    },
    userDialogOnConfirm(selection) {
      if (!selection || selection.length == 0) {
        this.$message.error('请至少选择一个用户')
        return
      }
      // （拿出现有人员+选择人数）和限有人员进行比对
      if (
        selection.length + this.org.nowNum > this.org.limitNum &&
        this.org.limitNum != 0 &&
        this.org.exceedLimitNum === 1
      ) {
        this.$message.error('设置用户数超过上限')
        return
      }
      let accounts = []
      for (let user of selection) {
        accounts.push(user.account)
      }
      let params = {}
      params.orgCode = this.org.groupCode
      if (params.orgCode == '') {
        params.orgCode = this.org.code
      }
      params.accounts = accounts.join(',')
      orgrequest
        .addUsersForOrg(params)
        .then(data => {
          if (data.state) {
            this.$message({
              message: data.message,
              type: 'success',
              showClose: true
            })
            this.org.nowNum += selection.length
            return
          }
          // this.$message.error(data.message || "操作失败");
        })
        .then(() => {
          this.$refs.htTable.load()
        })
    },
    underUserDialogClose() {
      this.underUserDialogShow = false
    },
    afterDelete() {
      this.$refs.htTable.load()
    },
    setOrgCharge(row) {
      var param = {}
      param.account = row.account
      param.orgCode = this.org.groupCode
      if (row.isMainChange) {
        param.isCharge = true
      } else {
        param.isCharge = false
      }
      orgrequest.setOrgCharge(param).then(resp => {
        if (resp.state) {
          this.$message.success(resp.message)
          let tab = {index: '1'}
          this.tabClick(tab)
        } else {
          this.$message.error(resp.message)
        }
      })
    },
    // 用户参数保存
    orgParamSubmit() {
      var param = {
        orgCode: this.org.groupCode
      }
      var data = []
      for (var orgparam in this.orgParam) {
        data.push({alias: orgparam, value: this.orgParam[orgparam]})
      }
      orgrequest.saveOrgParams(data, param).then(resp => {
        if (resp.state) {
          this.$message({
            message: resp.message,
            type: 'success',
            showClose: true
          })
        }
      })
    },
    // 组件简介保存
    submit() {
      let patt = new RegExp('^[0-9]*$')
      let codePatt = new RegExp('^[a-zA-Z0-9][a-zA-Z0-9_]*$')
      if (!patt.test(this.org.limitNum)) {
        this.$message.error('组织现编用户数量不是自然数')
        return
      }
      if (!this.org.orderNo || !patt.test(this.org.orderNo)) {
        this.$message.error('排序号不是自然数')
        return
      }
      if (!codePatt.test(this.org.code)) {
        this.$message.error(
          '组织编码只能输入字母、数字、下划线，且以字母或数字开头'
        )
        return
      }
      if (
        (this.org.name && this.org.name.length > 50) ||
        (this.org.code && this.org.code.length > 50) ||
        Number(this.org.orderNo) > Number.MAX_VALUE ||
        (this.org.grade && this.org.grade.length > 30) ||
        Number(this.org.limitNum) > Number.MAX_VALUE
      ) {
        this.$message({type: 'warning', message: '内容超出输入限制'})
        return false
      }
      this.$root.$validator.validateAll('orgForm').then((r) => {
        if (!r) {
          let arr = this.$validator.errors.items
          this.$message.warning(
            `有${arr.length}个字段未通过校验，请正确填写表单内容`
          )
          return
        }
        let {name,code,parentId,grade,demId,orderNo,limitNum,nowNum,exceedLimitNum} = this.org
        let orgParamData ={name,code,parentId,grade,demId,orderNo,limitNum,nowNum,exceedLimitNum}
        if (this.OrgManagerFormType === 'addOrg') {
          orgrequest
            .addOrg(orgParamData)
            .then(resp => {
              if (!resp.state) {
                return
              }
              if (resp && resp.errorCode && resp.errorCode == '5035') {
                this.$confirm( resp.message,'提示',{
                      cancelButtonText: '取消',
                      confirmButtonText: '确定',
                      type: 'warning',
                      closeOnClickModal: false,
                    }
                  ).then( () => {
                    orgrequest.restoreOrgtByAlias(this.org.code).then((resp1)=>{
                      if (!resp1.data.state) {
                          return
                      }
                      this.$emit('reloadTree')
                      this.OrgManagerFormType = 'showInfo'
                      this.$message.success('恢复成功')
                      return resp1.data
                    })
                  })
              }else{
                this.$emit('reloadTree')
                this.OrgManagerFormType = 'showInfo'
                this.$message.success('创建成功')
                return resp
              }
            })
            .then(response => {
              if (response.state) {
                orgrequest.getOrg(this.org.code).then(resp => {
                  this.org = resp
                  this.orgParamSubmit()
                })
              }
            })
        } else if (this.OrgManagerFormType === 'editOrg') {
          orgrequest.updateOrg(orgParamData).then(resp => {
            this.OrgManagerFormType = 'showInfo'
            this.$emit('reloadTree')
            this.$message.success('修改成功')
            this.orgParamSubmit()
          })
        }
      })
    },
    getOrgParamsByCode() {
      if (this.orgCode) {
        orgrequest.getOrgParamsByCode(this.orgCode).then(resp => {
          for (var i = 0; i < resp.length; i++) {
            var respKey = resp[i]
            this.$set(this.orgParam, respKey.alias, respKey.value)
            // this.orgParam[respKey.alias] = respKey.value;
          }
        })
      }
    },
    getOtherPost(row) {
      this.dialogVisible = true
      this.loadOtherPost(row)
    },
    loadOtherPost(row, cb) {
      let param = {}
      this.clickOtherPost = row
      let query = {
        group: 'defaultQueryGroup',
        operation: 'EQUAL',
        relation: 'AND',
        property: 'account',
        value: row.account
      }
      // let query1 = {
      //   group: "defaultQueryGroup",
      //   operation: "NOT_EQUAL",
      //   relation: "AND",
      //   property: "uopId",
      //   value: row.relId?row.relId : "-1"
      // };
      param = {
        pageBean: this.otherPostPageResult,
        querys: []
      }
      param.querys.push(query)
      // param.querys.push(query1);
      uc.getUserOrgPage(param)
        .then(response => {
          this.otherPostData = response.rows
          this.otherPostPageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => cb())
    },
    setUserMaster() {
      if (this.$refs.htTable.$refs.htTable.selection.length < 1) {
        this.$message({message: '请选择人员', type: 'warning'})
        return
      }
      let ids = []
      this.$refs.htTable.$refs.htTable.selection.forEach(item => {
        ids.push(item.orgUserId)
      })
      orgrequest.setMasterByIds(ids).then(resp => {
        if (resp.state) {
          this.$message({message: resp.message, type: 'success'})
          this.selectUsers = []
          let tab = {index: '1'}
          this.tabClick(tab)
        }
      })
    },
    setUserPost() {
      if (this.selectUsers.length < 1) {
        this.$message({message: '请选择人员', type: 'warning'})
        return
      }
      this.$refs.postDialog.showDialog()
    },
    postDialogOnConfirm(selection) {
      if (!selection || selection.length == 0) {
        this.$message.error('请至少选择一个岗位')
        return
      }
      let postCodeArr = []
      selection.forEach(item => {
        postCodeArr.push(item.code)
      })
      let postCode = postCodeArr.join(',')
      postCode = postCode + ','
      let accountArr = []
      this.selectUsers.forEach(val => {
        accountArr.push(val.account)
      })
      let account = accountArr.join(',')
      let param = {}
      param.postCode = postCode
      param.accounts = account
      orgrequest.saveUserPost(param).then(data => {
        if (data.state) {
          this.$message({
            message: data.message,
            type: 'success',
            showClose: true
          })
          this.$refs.htTable.load()
        }
        // this.$message.error(data.message || "分配用户失败");
      })
    },
    handleSizeChange(val) {
      this.otherPostPageResult.page = 1
      this.otherPostPageResult.pageSize = val
      this.loadOtherPost(this.clickOtherPost)
    },
    handleCurrentChange(val) {
      this.otherPostPageResult.page = val
      this.loadOtherPost(this.clickOtherPost)
    },
    otherPostClose() {
      this.otherPostPageResult = {
        page: 1,
        pageSize: 5,
        total: 0
      }
    },
    selectUser(selection) {
      this.selectUsers = selection
    },
    editUser(userAccount) {
      let userAuthData = []
      userAuthData = this.orgAuthData.filter(filter => {
        return filter.userAccount == userAccount
      })
      if (
        userAuthData[0] &&
        userAuthData[0].userPerms &&
        userAuthData[0].userPerms.indexOf('edit')
      ) {
        this.clickUserAccount = userAccount
        this.isUserManagerShow = true
      } else {
        this.selectUserInfo(userAccount)
      }
    },
    selectUserInfo(account) {
      //查询用户的详细信息
      uc.getUser(account)
        .then(resp => {
          resp.photo = `${window.context.portal}` + resp.photo
          this.user = {...resp.user}
        })
        .then(() => {
          // 获取用户参数
          this.getUserParams(account)
          // 所属角色
          this.userRoleLoad({
            pageBean: {
              page: 1,
              pageSize: -1
            },
            querys: [{property: 'u.account_', value: account}]
          })
          // 获取签章
          this.getSealByUserId()
          // 查询所属组织岗位，所属角色信息
          uc.getUserByUserId(this.user.id).then(resp => {
            this.$set(
              this.user,
              'roleName',
              resp[resp.length - 1].roleName.roleName
            )
            let _orgPostList = []
            for (var i = 0; i < resp.length - 1; i++) {
              _orgPostList.push(resp[i])
            }
            this.$set(this.user, 'orgPostList', _orgPostList)
            this.isUserInfo = true
          })
        })
    },
    // 获取签章
    getSealByUserId() {
      uc.getSealByUserId(this.user.id).then(resp => {
        if (resp) {
          this.$store.dispatch('menu/downloadImg', resp.fileId).then(res => {
            if (res != '') {
              this.$set(this.user, 'electronicSealPic', res)
            }
          })
        }
      })
    },
    // 所属角色
    userRoleLoad(param, cb) {
      uc.userRolePage(param).then(response => {
        if (response) {
          this.$set(this.user, 'userRoleList', response.rows)
        }
      })
    },
    // 获取用户参数
    getUserParams(account) {
      uc.getUserParams()
        .then(resp => {
          return resp
        })
        .then(params => {
          if (!params || params.constructor != Array || params.length < 1) {
            return
          }
          uc.getUserParamsValue(account).then(response => {
            if (response && response.constructor == Array) {
              response.forEach(r => {
                this.userParam[r['alias']] = r['value']
              })
              this.$set(this.user, 'userParam', this.userParam)
              this.$set(this.user, 'userParams', params)
            }
          })
        })
    },
    handleCloseUserManager() {
      this.isUserInfo = false
      this.isUserManagerShow = false
      this.$refs.htTable.load()
    },
    getOrgAuthData(data) {
      this.orgAuthData = data
    },
    showOrgTreeDialog() {
      this.orgTreeDialogVisible = true
    },
    orgTreeDialogConfirm(org) {
      if (this.org.id === org.id) {
        this.$message.warning('组织本身不能作为自己的上级组织，请重新选择！')
        return
      }
      this.org.parentId = org.id
      this.org.parentOrgName = org.name
      // orgrequest.updateOrgPos({orgId: this.org.id, parentId: org.id}).then(resp => {
      //   this.OrgManagerFormType = "showInfo";
      //   this.$emit("reloadTree");
      //   this.$message.success("修改成功");
      // });
    },
    handleSelectionChange(selection) {
      this.selectedList = selection
    }
  }
}
</script>

<style scoped lang="scss">
.fullheight {
  overflow: hidden;
  .tab-container .el-tabs--card {
    padding: 0;
  }
  ::v-deep {
    .pre-menu {
      .vue-treeselect__control {
        border-color: #ececec;
        height: 30px;
      }
    }
    .pre-menu .vue-treeselect--disabled {
      cursor: not-allowed;
      .vue-treeselect__control {
        background: #ececec;
        border: none;
      }
    }
  }
}
/deep/.vue-treeselect__menu {
  z-index: 1000;
}
::v-deep {
  .cell > .el-table__column-filter-trigger {
    display: none;
  }
  .org-manage-tabs {
    .el-tabs__header .el-tabs__item {
      color: #666;
    }
  }
}

.form-table tr td:first-child {
  text-align: right;
}
>>> .el-tabs__content {
  overflow-y: auto;
  height: calc(100% - 68px);
  overflow-x: hidden;
}

>>> .parent-org-name input {
  text-align: left;
}
.brief {
  margin-top: 25px;
}
.plane {
  padding: 32px 40px;
  border: 1px solid #e8e8e8;
  margin-bottom: 40px;
  // overflow: hidden;
  h1 {
    color: #333333;
    margin: 0 0 18px 0;
    font-size: 16px;
    font-weight: bold;
  }
  .row-wrap {
    display: flex;
    flex-wrap: wrap;
    .el-col-8 {
      min-width: 360px;
    }
  }
  /deep/ .el-form-item__label {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  /deep/ .el-form-item__content {
    span {
      word-wrap: break-word;
      word-break: break-all;
    }
  }
}
.tooltip-item {
  position: absolute;
  top: 8px;
  left: -6px;
}
.parameters-footer {
  text-align: center;
}
.success {
  color: #51b43a;
}
.danger {
  color: #e55555;
}
.text-right {
  text-align: right;
}
.input-number_wrap {
  /deep/.el-input-number .el-input__inner {
    text-align: left;
  }
}
.mrt24 {
  margin-top: 24px;
}
.fullheight {
  .width-wrap {
    width: 220px;
  }
}
.text-hidden {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  background-color: #f4f4f5;
  border: 1px solid #e9e9eb;
  border-radius: 4px;
  color: #909399;
  padding: 0 10px;
  max-width: 100%;
  display: inline-block;
  vertical-align: middle;
}
</style>
