<template>
  <div class="fullheight">
    <el-tabs
      type="card"
      v-model="orgResume"
      @tab-click="tabClick"
      class="org-manager__tabs"
    >
      <el-tab-pane
        label="组织简介"
        name="orgInfo"
        class="fullheight set-content-height"
      >
        <el-form
          data-vv-scope="form1"
          v-form="{formItemAlign: 'left'}"
          class="fullheight"
          :label-width="labelWidth"
        >
          <div class="plane">
            <h1 class="title">组织信息</h1>
            <el-row :gutter="20">
              <el-col :span="8">
                <ht-form-item label="上级组织名称">
                  <ht-input
                    v-model="org.parentOrgName"
                    permission="r"
                    placeholder="请输入上级组织名称"
                    style="width: 100%"
                    class="parent-org-name"
                    type="button"
                    :clearable="false"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8">
                <ht-form-item label="组织名称">
                  <ht-input
                    v-model="org.name"
                    :permission="type == 'showInfo' ? 'r' : 'b'"
                    placeholder="请输入组织名称"
                    style="width: 100%"
                    :maxlength="50"
                    show-word-limit
                    :disabled="type == 'showInfo'"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8">
                <ht-form-item label="组织现编用户数量">
                  <ht-input
                    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="排序号">
                  <ht-input
                    v-model="org.orderNo"
                    :permission="type == 'showInfo' ? 'r' : 'b'"
                    placeholder="请输入排序号"
                    style="width: 100%"
                    :maxlength="9"
                    show-word-limit
                    :validate="{regex: {exp: '^[0-9]*$', message: ''}}"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8">
                <ht-form-item label="级别">
                  <ht-input
                    v-model="org.grade"
                    :permission="type == 'showInfo' ? 'r' : 'w'"
                    placeholder="请输入级别"
                    :maxlength="30"
                    :showWordLimit="true"
                    style="width: 100%"
                  />
                </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="组织限编用户数量">
                  <ht-input
                    v-model="org.limitNum"
                    :permission="type == 'showInfo' ? 'r' : 'w'"
                    placeholder="组织限编用户数量"
                    style="width: 100%"
                    :maxlength="9"
                    show-word-limit
                    :validate="{regex: {exp: '^[0-9]*$', message: ''}}"
                  />
                </ht-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <ht-form-item label="组织编码">
                  <ht-input
                    v-model="org.code"
                    :permission="type != 'addOrg' ? 'r' : 'b'"
                    placeholder="请输入组织编码"
                    v-pinyin="type == 'addOrg' ? org.name : null"
                    :maxlength="50"
                    show-word-limit
                    style="width: 100%"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="8">
                <ht-form-item label="是否允许超过限编" label-width="140px">
                   <span v-if="type == 'showInfo'">{{
                    org.exceedLimitNum == 0 ? '允许' : '不允许'
                  }}</span>
                  <ht-radio
                   v-else
                    v-model="org.exceedLimitNum"
                    :permission="type == 'showInfo' ? 'r' : 'b'"
                    :options="[
                      {key: 0, value: '允许'},
                      {key: 1, value: '不允许'}
                    ]"
                  />
                </ht-form-item>
              </el-col>
            </el-row>
          </div>
          <el-form v-model="orgParam" v-form="{formItemAlign: 'left'}">
            <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"
                  >
                    <ht-date
                      v-model="orgParam[param.code]"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期时间"
                      :permission="type == 'showInfo' ? 'r' : 'w'"
                      class="width-wrap"
                      v-if="param.ctlType === 'date'"
                    ></ht-date>
                    <ht-input
                      v-model="orgParam[param.code]"
                      :permission="type == 'showInfo' ? 'r' : 'w'"
                      v-if="param.ctlType === 'input'"
                    />
                    <ht-input
                      type="number"
                      v-model="orgParam[param.code]"
                      :permission="type == 'showInfo' ? 'r' : 'w'"
                      v-if="param.ctlType === 'number'"
                      class="input-number_wrap"
                      width="220px"
                    />
                    <ht-select
                      v-model="orgParam[param.code]"
                      :permission="type == '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="type == 'showInfo' ? 'r' : 'w'"
                      v-if="param.ctlType === 'radio' && param.json"
                      :options="JSON.parse(param.json)"
                    />
                    <ht-checkbox
                      v-model="orgParam[param.code]"
                      :permission="type == '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="type != 'showInfo'">
            <el-button type="primary" @click="submit">保存</el-button>
          </el-footer>
        </el-form>
      </el-tab-pane>
      <el-tab-pane
        label="组织人员"
        name="orgUser"
        :disabled="type === 'addOrg'"
        class="fullheight set-content-height"
      >
        <ht-table
          @load="loadData"
          :data="orgUser"
          :pageResult="pageResult"
          :selection="true"
          :quick-search-props="[{prop: 'u.fullname_', label: '姓名'}]"
          :default-querys="defaultQuerys"
          ref="htTable"
          v-if="orgResume == 'orgUser'"
          @select-all="selectUser"
          @select="selectUser"
          @row-click="rowClick"
          :show-export="false"
          :show-custom-column="false"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange"
        >
          <template v-slot:toolbar>
            <!-- <el-button-group> -->
            <el-button
              size="small"
              @click="addNewUser"
              icon="el-icon-plus"
              type="primary"
              v-if="
                orgManagerNow.userPerms &&
                  orgManagerNow.userPerms.indexOf('add') >= 0
              "
              >新增用户</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="showAddOrgUser()"
              icon="el-icon-plus"
              v-if="
                orgManagerNow.userPerms &&
                  orgManagerNow.userPerms.indexOf('add') >= 0
              "
              >加入用户</el-button
            >
            <!--<el-button v-if="orgManagerNow.userPerms && orgManagerNow.userPerms.indexOf('setMaster')>=0" @click="setUserMaster()">设置主组织</el-button>-->
            <el-button
              v-if="
                orgManagerNow.userPerms &&
                  orgManagerNow.userPerms.indexOf('setPos') >= 0
              "
              @click="setUserPost()"
              >设置岗位</el-button
            >
            <ht-delete-button
              :disabled="isDisabled"
              :url="orgUserDeleteUrl"
              :htTable="$refs.htTable"
              pk="orgUserId"
              v-if="
                orgManagerNow.userPerms &&
                  orgManagerNow.userPerms.indexOf('delete') >= 0
              "
              @after-delete="afterDelete"
              >删除</ht-delete-button
            >
            <!-- </el-button-group> -->
          </template>
          <template>
            <ht-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            />
            <ht-table-column
              prop="fullName"
              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="账号"
              :show-overflow-tooltip="true"
            />
            <ht-table-column
              prop="relName"
              label="岗位名称"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <template v-for="(item, i) in scope.row.relName">
                  <el-tag type="info">{{ item }}</el-tag
                  >&nbsp;
                </template>
              </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_"
              label="是否主要组织"
              width="150"
              :render-header="renderHeaderMethod"
              :filters="[{text: '否', value: '0'}, {text: '是', value: '1'}]"
            >
              <template v-slot="{row}">
                <el-tag type="danger" v-if="row.isMaster == '0'">否</el-tag>
                <el-tag type="success" v-if="row.isMaster == '1'">是</el-tag>
              </template>
            </ht-table-column>
            <ht-table-column
              prop="orguser.is_charge_"
              label="负责人"
              width="100"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '否', value: '0'},
                {text: '是', value: '1'},
                {text: '主', value: '2'}
              ]"
            >
              <template v-slot="{row}">
                <el-tag type="danger" v-if="row.isCharge == '0'">否</el-tag>
                <el-tag v-if="row.isCharge == '1'">是</el-tag>
                <el-tag type="success" v-if="row.isCharge == '2'">主</el-tag>
              </template>
            </ht-table-column>
            <ht-table-column
              prop="u.STATUS_"
              label="状态"
              width="100"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '禁用', value: '0'},
                {text: '正常', value: '1'},
                {text: '离职', value: '-2'}
              ]"
            >
              <template v-slot="{row}">
                <el-tag type="danger" v-if="row.status == '0'">禁用</el-tag>
                <el-tag type="success" v-if="row.status == '1'">正常</el-tag>
                <el-tag type="warning" v-if="row.status == '-2'">离职</el-tag>
              </template>
            </ht-table-column>
            <ht-table-column label="操作" width="300">
              <template v-slot="{row}">
                <!-- <el-dropdown
                  size="mini"
                  split-button
                  @command="orgUserHandleCommand"
                  @click="
                    orgManagerNow.userPerms &&
                    orgManagerNow.userPerms.indexOf('setMaster') >= 0
                      ? orgUserHandleCommand({row: row, command: 'setIsMaster'})
                      : orgUserHandleCommand({
                          row: row,
                          command: 'setOrgCharge',
                        })
                  "
                  v-if="
                    orgManagerNow.userPerms &&
                    (orgManagerNow.userPerms.indexOf('edit') >= 0 ||
                      orgManagerNow.userPerms.indexOf('setMaster') >= 0)
                  "
                >
                  <span
                    v-if="
                      orgManagerNow.userPerms &&
                      orgManagerNow.userPerms.indexOf('setMaster') >= 0
                    "
                  >
                    <i class="el-icon-user"></i
                    >{{ row.isMaster == '0' ? '设置主组织' : '取消主组织' }}
                  </span>
                  <span v-else>
                    <i class="el-icon-user"></i
                    >{{ row.isCharge == '0' ? '设置负责人' : '取消负责人' }}
                  </span>
                             
                  <el-dropdown-menu
                    slot="dropdown"
                    v-if="
                      orgManagerNow.userPerms &&
                        orgManagerNow.userPerms.indexOf('edit') >= 0
                    "
                  >
                    <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
                  v-if="
                    orgManagerNow.userPerms &&
                      (orgManagerNow.userPerms.indexOf('edit') >= 0 ||
                        orgManagerNow.userPerms.indexOf('setMaster') >= 0)
                  "
                >
                  <el-button
                    type="text"
                    v-if="
                      orgManagerNow.userPerms &&
                        orgManagerNow.userPerms.indexOf('setMaster') >= 0
                    "
                    @click="
                      orgManagerNow.userPerms &&
                      orgManagerNow.userPerms.indexOf('setMaster') >= 0
                        ? orgUserHandleCommand({
                            row: row,
                            command: 'setIsMaster'
                          })
                        : orgUserHandleCommand({
                            row: row,
                            command: 'setOrgCharge'
                          })
                    "
                    >{{
                      row.isMaster == '0' ? '设置主组织' : '取消主组织'
                    }}</el-button
                  >
                  <!-- <el-button
                    v-else
                    type="text"
                    @click="
                      orgManagerNow.userPerms &&
                      orgManagerNow.userPerms.indexOf('setMaster') >= 0
                        ? orgUserHandleCommand({
                            row: row,
                            command: 'setIsMaster'
                          })
                        : orgUserHandleCommand({
                            row: row,
                            command: 'setOrgCharge'
                          })
                    "
                  
                    >{{
                      row.isCharge == '0' ? '设置负责人' : '取消负责人'
                    }}</el-button
                  > -->

                  <template
                    v-if="
                      orgManagerNow.userPerms &&
                        orgManagerNow.userPerms.indexOf('edit') >= 0
                    "
                  >
                    <el-button
                      type="text"
                      v-if="row.isCharge != '2'"
                      @click="
                        orgUserHandleCommand({
                          row: row,
                          command: 'setIsMainChange'
                        })
                      "
                      >设置主负责人</el-button
                    >
                    <el-button
                      type="text"
                      v-if="row.isCharge == '2'"
                      @click="
                        orgUserHandleCommand({
                          row: row,
                          command: 'setOrgCharge'
                        })
                      "
                      >取消主负责人</el-button
                    >
                    <el-button
                      type="text"
                      v-if="row.isCharge == '0'"
                      @click="
                        orgUserHandleCommand({
                          row: row,
                          command: 'setOrgCharge'
                        })
                      "
                      >设置负责人</el-button
                    >
                    <el-button
                      type="text"
                      v-if="row.isCharge == '1'"
                      @click="
                        orgUserHandleCommand({
                          row: row,
                          command: 'setOrgCharge'
                        })
                      "
                      >取消负责人</el-button
                    >
                  </template>
                </template>
                <span
                  v-if="
                    !(
                      orgManagerNow.userPerms &&
                      (orgManagerNow.userPerms.indexOf('edit') >= 0 ||
                        orgManagerNow.userPerms.indexOf('setMaster') >= 0)
                    )
                  "
                  >无权限</span
                >
              </template>
            </ht-table-column>
          </template>
        </ht-table>

        <el-dialog
          title="组织岗位信息"
          :visible.sync="dialogVisible"
          @close="otherPostClose"
          width="55%"
        >
          <el-table border style="width: 100%" :data="otherPostData">
            <el-table-column
              prop="userName"
              label="姓名"
              width="120"
              align="center"
            />
            <el-table-column prop="orgName" label="组织名称" align="center" />
            <el-table-column prop="posName" label="岗位名称" align="center" />
            <el-table-column label="是否主要组织" width="100" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isMaster" type="success">是</el-tag>
                <el-tag v-else type="danger">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="负责人" width="80" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isCharge == '0'" type="danger"
                  >否</el-tag
                >
                <el-tag v-if="scope.row.isCharge == '1'" type="primary"
                  >是</el-tag
                >
                <el-tag v-if="scope.row.isCharge == '2'" type="success"
                  >主</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="状态" width="80" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status == '0'" type="danger"
                  >禁用</el-tag
                >
                <el-tag v-if="scope.row.status == '1'" type="primary"
                  >正常</el-tag
                >
                <el-tag v-if="scope.row.status == '-2'" type="success"
                  >离职</el-tag
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @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"
          >
          </el-pagination>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">关 闭</el-button>
          </div>
        </el-dialog>

        <post-dialog
          ref="postDialog"
          @onConfirm="postDialogOnConfirm"
          :orgId="org.id"
          append-to-body
        />
        <el-dialog
          width="70%"
          :title="clickUserAccount ? '编辑用户' : '新增用户'"
          :visible="isUserManagerShow"
          v-if="isUserManagerShow"
          :before-close="handleCloseUserManager"
          ref="userManagerref"
          :close-on-click-modal="false"
          @close="clickUserAccount = ''"
        >
          <!--编辑用户面板-->
          <user-manager
            :org-code="orgCode"
            ref="userManager"
            :user-account="clickUserAccount"
            v-if="isUserManagerShow"
            @handleCloseUserManager="handleCloseUserManager"
            @closeUserManeger="handleCloseUserManager"
            :role-perms="orgManagerNow.rolePerms"
            :roles="
              orgManagerNow.roleConfig
                ? JSON.parse(orgManagerNow.roleConfig)
                : []
            "
          ></user-manager>
        </el-dialog>
        <ht-sidebar-dialog
          width="28%"
          title="查看用户"
          :visible="isUserInfo"
          :before-close="handleCloseUserManager"
        >
          <user-detail :user="user" />
        </ht-sidebar-dialog>
        <!-- <ht-user-dialog     
          ref="eipUserDialog"  
          v-show="orgResume=='orgUser'"    
          :current-uo-path="currentUoPath"
          @on-confirm="userDialogOnConfirm"
          append-to-body
        />   -->
      </el-tab-pane>
      <el-tab-pane
        label="组织岗位"
        name="orgPost"
        :disabled="type === 'addOrg'"
        class="fullheight set-content-height"
      >
        <org-post
          :org-id="org.id"
          :org-code="org.groupCode"
          v-if="orgResume == 'orgPost'"
          class="fullheight set-content-height"
          :orgManagerNow="orgManagerNow"
        ></org-post>
      </el-tab-pane>
      <!-- <el-tab-pane label="组织参数" name="orgParam" :disabled ="type==='addOrg'"  class="fullheight set-content-height">
        <el-form v-model="orgParam"  >
          <template v-for="param in orgParams">
            <ht-form-item :label="param.name" prop="name" label-width="200px" >
              <el-date-picker
                  v-model="orgParam[param.code]"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 86%"
                  v-if="param.ctlType === 'date'">
              </el-date-picker>
              <ht-input
                  v-model="orgParam[param.code]"
                  style="width: 86%"
                  v-if="param.ctlType === 'input'"/>
              <ht-input
                  type="number"
                  v-model="orgParam[param.code]"
                  v-if="param.ctlType === 'number'"/>
              <ht-select
                  v-model="orgParam[param.code]"
                  v-if="param.ctlType === 'select'"
                  :options="JSON.parse(param.json)"/>
              <ht-radio
                  v-model="orgParam[param.code]"
                  v-if="param.ctlType === 'radio'"
                  :options="JSON.parse(param.json)"/>
              <ht-checkbox
                  v-model="orgParam[param.code]"
                  v-if="param.ctlType === 'checkbox'"
                  :options="JSON.parse(param.json)"/>
            </ht-form-item>
          </template>
        </el-form>
        <div style="text-align:center; margin-top:24px">
            <el-button type="primary" @click="orgParamSubmit" v-if="orgParams.length>0">保存</el-button>
        </div>
      </el-tab-pane> -->
      <el-tab-pane
        label="分级组织管理设置"
        name="orgManageSetting"
        :disabled="type === 'addOrg'"
        class="fullheight"
        v-if="isOrgSetShow"
      >
        <org-auth-page
          :org-code="orgCode"
          v-if="orgResume == 'orgManageSetting'"
          :dem-code="org.demCode"
          @orgAuthData="getOrgAuthData"
          :orgManagerNow="orgManagerNow"
        ></org-auth-page>
      </el-tab-pane>
    </el-tabs>
    <!-- 直接下属管理组件   -->
    <under-user-table
      :org-id="org.id"
      :user-id="selectOrgUserAccount"
      :dim-id="demId"
      ref="underUserTable"
    />
    <!-- :current-org-obj="currentOrgObj" -->
    <ht-user-dialog
      v-if="orgResume == 'orgUser'"
      ref="eipUserDialog"
      :queryLoadContactUser="true"
  
      @on-confirm="userDialogOnConfirm"
      append-to-body
    />
  </div>
</template>

<script>
import orgrequest from '@/api/org.js'
import uc from '@/api/uc.js'
import EipUserDialog from '@/components/dialog/EipUserDialog.vue'
import underUserTable from '@/views/uc/org/UnderUserTable.vue'
import UserManager from '@/views/uc/heiorgmanager/UserManager'
import OrgPost from './OrgPost'
import OrgAuthPage from './OrgAuthPage'
import UserDetail from '@/views/uc/UserDetail.vue'
import PostDialog from '@/views/uc/org/PostDialog'
import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'
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
      },
      orgUserShow: false,
      underUserDialogShow: false,
      orgPostShow: false,
      orgAuthPageShow: false,
      selectOrgUserAccount: '',
      orgParams: [], // 组织参数
      orgParam: {},
      orgResume: 'orgInfo',
      saveRoleUrl: '/api/org/v1/org/addOrg',
      selectUsers: [],
      dialogVisible: false,
      otherPostData: [],
      otherPostPageResult: {
        page: 1,
        pageSize: 5,
        total: 0
      },
      clickUserAccount: '',
      isUserManagerShow: false,
      isUserInfo: false,
      user: {},
      orgAuthData: [],
      selectedList: [],
      isDisabled: true
    }
  },
  components: {
    EipUserDialog,
    underUserTable,
    OrgPost,
    OrgAuthPage,
    PostDialog,
    UserManager,
    UserDetail
  },
  props: {
    type: {
      type: String
    },
    orgCode: {
      type: String
    },
    parentName: {
      type: String
    },
    demId: {
      type: String
    },
    parentId: {
      type: String
    },
    orgManagerNow: {
      type: Object
    },
    isOrgSetShow: {
      type: Boolean
    },
    currentOrgObj: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    },
  
  },
  mounted() {
    this.org.parentId = this.parentId
    this.org.parentOrgName = this.parentName
    this.org.demId = this.demId
    if (this.type === 'showInfo' || this.type === 'editOrg') {
      orgrequest.getOrg(this.orgCode).then(resp => {
        this.org = resp
      })
    }
    if (this.type === 'addOrg') {
      var num = ''
      for (var i = 0; i < 3; i++) {
        num += Math.floor(Math.random() * 10)
      }
      this.org.orderNo = num
    }
    orgrequest.getOrgParams().then(resp => {
      console.log('resp', resp)
      this.orgParams = resp
      //当 新建维度下面的组织时清空
      if (this.type != 'addOrg') {
        this.getOrgParamsByCode()
      }
    })
  },
  computed: {
    orgUserDeleteUrl: function() {
      return window.context.uc + '/api/org/v1/orgUser/delOrgUserByUserIds'
    },
    defaultQuerys: function() {
      return [{property: 'org.ID_', value: this.org.id}]
    }
  },
  methods: {
    rowClick(row, column, event) {
      this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
    },
    loadData(param, cb) {
      this.selectUsers = []
      orgrequest
        .getOrgUserPage(param)
        .then(response => {
          let resp = response.rows
          let result = []
          let user = []
          let filterData = []
          let othPost = []
          resp.forEach(item => {
            if (item.isMaster) {
              user.push(item.account)
              result.push(item)
            } else {
              filterData.push(item)
            }
          })
          filterData.forEach(val => {
            if (user.indexOf(val.account) < 0) {
              user.push(val.account)
              result.push(val)
            } else {
              othPost.push(val)
            }
          })
          this.orgUser = result
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total - othPost.length
          }
        })
        .finally(() => cb())
    },
    tabClick() {
      //点击tab卡片
      // this.orgUserShow = false
      // this.orgPostShow = false
      // this.orgAuthPageShow = false
      // this.$nextTick(() => {
      //   this.orgUserShow = true
      //   this.orgPostShow = true
      //   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.tabClick()
            this.$message.warning(
              '当前用户有在该组织存在多个岗位，需要在组织岗位设值主组织'
            )
            break
          }
          orgrequest.setMasterById(params.row.orgUserId).then(() => {
            this.tabClick()
          })
          break
        case 'setOrgCharge':
          //设置是否为主要负责人
          this.setOrgCharge(params.row)
          break
        case 'setIsMainChange':
          //设置是否为主要负责人
          params.row.isMainChange = true
          this.setOrgCharge(params.row)
          break
        default:
          break
      }
      //操作后刷新
      this.$refs.htTable.load()
    },
    showAddOrgUser() {
      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.exceedLimitNum === 1
      ) {
        this.$message.error('设置用户数超过上限')
        return
      }
      let accounts = []
      for (let user of selection) {
        accounts.push(user.account)
      }
      let params = {}
      params.orgCode = this.org.groupCode
      params.accounts = accounts.join(',')
      orgrequest
        .addUsersForOrg(params)
        .then(data => {
          if (data.state) {
            this.$message({
              message: data.message,
              type: 'success',
              showClose: true
            })
            this.$refs.htTable.load()
            return
          }
          this.$message.error(data.message || '操作失败')
        })
        .then(() => {
          orgrequest.getOrg(this.orgCode).then(resp => {
            this.org = resp
          })
        })
    },
    underUserDialogClose() {
      this.underUserDialogShow = false
    },
    afterDelete() {
       orgrequest.getOrg(this.orgCode).then(resp => {
        this.org = resp
      })
      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(() => {
        this.tabClick()
        this.$refs.htTable.load()
      })
    },
    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 => {
        this.$message({
          message: resp.message,
          type: 'success',
          showClose: true
        })
      })
    },
    submit() {
      let patt = new RegExp('^[0-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 (
        (this.org.name && this.org.name.length > 30) ||
        (this.org.code && this.org.code.length > 30) ||
        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
      }
      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.type === '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.$emit('change-type', 'showInfo')
                this.orgParamSubmit()
              })
            }
          })
      } else if (this.type === 'editOrg') {
        orgrequest.updateOrg(orgParamData).then(resp => {
          this.type = '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.orgParam[respKey.alias]=respKey.value;
            this.$set(this.orgParam, respKey.alias, respKey.value)
          }
        })
      }
    },
    selectUser(selection) {
      this.selectUsers = selection
    },
    setUserMaster() {
      if (this.selectUsers.length < 1) {
        this.$message({message: '请选择人员', type: 'warning'})
        return
      }
      let ids = []
      this.selectUsers.forEach(item => {
        ids.push(item.orgUserId)
      })
      orgrequest.setMasterByIds(ids).then(resp => {
        if (resp.state) {
          this.$message({message: resp.message, type: 'success'})
          this.selectUsers = []
          this.tabClick()
        }
      })
    },
    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 || "分配用户失败");
      })
    },
    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())
    },
    otherPostClose() {
      this.otherPostPageResult = {
        page: 1,
        pageSize: 5,
        total: 0
      }
    },
    handleSizeChange(val) {
      this.otherPostPageResult.page = 1
      this.otherPostPageResult.pageSize = val
      this.loadOtherPost(this.clickOtherPost)
    },
    handleCurrentChange(val) {
      this.otherPostPageResult.page = val
      this.loadOtherPost(this.clickOtherPost)
    },
    editUser(userAccount) {
      if (
        this.orgManagerNow &&
        this.orgManagerNow.userPerms &&
        this.orgManagerNow.userPerms.indexOf('edit') != -1
      ) {
        this.clickUserAccount = userAccount
        this.isUserManagerShow = true
      } else {
        this.selectUserInfo(userAccount)
      }
    },
    handleCloseUserManager() {
      this.isUserInfo = false
      this.isUserManagerShow = false
      this.$refs.htTable.load()
    },
    selectUserInfo(account) {
      //查询用户的详细信息
      uc.getUser(account)
        .then(resp => {
          resp.photo = `${window.context.portal}` + resp.photo
          this.user = {...resp.user}
        })
        .then(() => {
          // 查询所属组织岗位，所属角色信息
          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
          })
        })
    },
    getOrgAuthData(data) {
      this.orgAuthData = data
    },
    addNewUser() {
      this.clickUserAccount = ''
      this.isUserManagerShow = true
    },
    handleSelectionChange(selection) {
      this.selectedList = selection
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep {
  .cell > .el-table__column-filter-trigger {
    display: none;
  }
}
.org-manager__main {
  .org-manager__tabs {
    padding: 0;
    height: 100%;
    ::v-deep {
      .el-tabs__content {
        height: calc(100% - 56px);
        .set-content-height {
          overflow-y: auto;
        }
      }
    }
  }
}

.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;
}
</style>
