<template>
  <div>
    <el-dialog
      title="临时人员信息"
      :visible.sync="dialogVisible"
      :before-close="closeUserManager"
      append-to-body
      width="1000px"
    >
      <el-tabs type="card" @tab-click="tabClick" v-model="currentTabName">
        <el-tab-pane label="基本信息" name="basic">
          <form data-vv-scope="editUserForm">
            <table
              class="form-table"
              cellspacing="0"
              cellpadding="0"
              border="0"
            >
              <tbody>
                <tr>
                  <td class="is-required">姓名:</td>
                  <td>
                    <ht-input
                      v-model="user.fullname"
                      autocomplete="off"
                      :validate="{
                        required: true,
                        regex: {
                          exp: '^[\\s\\S]{1,20}$',
                          message: '内容超出输入限制',
                        },
                      }"
                    ></ht-input>
                  </td>
                  <td class="is-required">账号:</td>
                  <td>
                    <ht-input
                      v-model="user.account"
                      autocomplete="off"
                      :disabled="account != ''"
                      v-pinyin="user.fullname"
                      :validate="{
                        required: true,
                        regex: {
                          exp: '^[a-zA-Z0-9_-]{2,20}$',
                          message: '账号输入有误，请重新输入',
                        },
                      }"
                    ></ht-input>
                  </td>
                </tr>
                <tr>
                  <td class="is-required">密码:</td>
                  <td>
                    <ht-input
                      v-model="user.password"
                      show-password
                      :validate="pwdValidate"
                    />
                  </td>
                  <td>邮箱:</td>
                  <td>
                    <ht-input
                      v-model="user.email"
                      autocomplete="off"
                    ></ht-input>
                  </td>
                </tr>
                <tr>
                  <td>性别:</td>
                  <td>
                    <ht-select
                      v-model="user.sex"
                      :options="[
                        {key: '男', value: '男'},
                        {key: '女', value: '女'},
                      ]"
                    />
                  </td>
                  <td>地址:</td>
                  <td>
                    <ht-input
                      v-model="user.address"
                      autocomplete="off"
                      :validate="{
                        regex: {
                          exp: '^[\\s\\S]{0,100}$',
                          message: '内容超出输入限制',
                        },
                      }"
                    ></ht-input>
                  </td>
                </tr>
                <tr>
                  <td>状态:</td>
                  <td>
                    <ht-select
                      v-model="user.status"
                      :validate="{required: true}"
                      :options="[
                        {key: 0, value: '禁用'},
                        {key: 1, value: '正常'},
                        {key: -2, value: '离职'},
                      ]"
                    />
                  </td>
                  <td>手机:</td>
                  <td>
                    <ht-input
                      v-model="user.mobile"
                      autocomplete="off"
                      validate="mobile"
                    ></ht-input>
                  </td>
                </tr>
                <tr>
                  <td colspan="5" align="center">
                    <ht-submit-button
                      :url="saveUserUrl"
                      :model="user"
                      scope-name="editUserForm"
                      @before-save-data="beforeSaveData"
                      @after-save-data="afterSaveData"
                      >保存</ht-submit-button
                    >
                    <el-button @click="closeUserManager"> 取消 </el-button>
                  </td>
                </tr>
              </tbody>
            </table>
          </form>
        </el-tab-pane>
        <el-tab-pane
          label="所属组织岗位"
          name="orgPost"
          :disabled="account == ''"
        >
          <ht-table
            @load="orgPostData"
            v-if="userOrgPostLoaded"
            :data="orgPostList"
            :pageResult="orgPageResult"
            :selection="true"
            :show-export="false"
            :show-custom-column="false"
            :default-querys="[{property: 'account', value: account}]"
            ref="orgPostTables"
            style="height: 500px"
          >
            <template v-slot:toolbar>
              <el-button
                size="small"
                @click="showEipOrgDialog"
                icon="el-icon-plus"
                type="primary"
                >添加组织</el-button
              >
              <el-button
                size="small"
                @click="showEipPostDialog"
                icon="el-icon-plus"
                type="primary"
                >添加岗位</el-button
              >
              <ht-delete-button
                :url="delOrgUser"
                :htTable="$refs.orgPostTables"
                @after-delete="afterDelOrgUser"
                pk="orgUserId"
                >删除</ht-delete-button
              >
            </template>
            <template>
              <ht-table-column
                type="index"
                width="50"
                align="center"
                label="序号"
              />
              <ht-table-column prop="demName" label="组织维度" width="160" />
              <ht-table-column prop="orgName" label="组织名称" />
              <ht-table-column prop="posName" label="岗位名称" />
              <ht-table-column
                prop="isMaster"
                label="主组织/主岗位"
                width="120"
              >
                <template v-slot="{row}">
                  <el-tag type="danger" v-if="row.isMaster == '0'">否</el-tag>
                  <el-tag v-if="row.isMaster == '1'">是</el-tag>
                </template>
              </ht-table-column>
              <ht-table-column label="操作" width="200">
                <template v-slot="{row}">
                  <el-button
                    type="primary"
                    icon="el-icon-edit-outline"
                    v-if="row.isMaster == 0 && row.posName"
                    @click="setMaster(row)"
                    >设置主岗位</el-button
                  >
                  <el-button
                    type="primary"
                    icon="el-icon-edit-outline"
                    v-if="row.isMaster == 1 && row.posName"
                    @click="setMaster(row)"
                    >取消主岗位</el-button
                  >
                  <el-button
                    type="primary"
                    icon="el-icon-edit-outline"
                    v-if="row.isMaster == 0 && !row.posName"
                    @click="setMaster(row)"
                    >设置主组织</el-button
                  >
                  <el-button
                    type="primary"
                    icon="el-icon-edit-outline"
                    v-if="row.isMaster == 1 && !row.posName"
                    @click="setMaster(row)"
                    >取消主组织</el-button
                  >
                </template>
              </ht-table-column>
            </template>
          </ht-table>
        </el-tab-pane>
        <el-tab-pane label="所属角色" name="role" :disabled="account == ''">
          <ht-table
            @load="userRoleLoad"
            :data="userRoleList"
            :pageResult="rolePageResult"
            v-if="userRoleLoaded"
            :selection="true"
            :show-export="false"
            :show-custom-column="false"
            :default-querys="[{property: 'u.account_', value: account}]"
            ref="userRoleTable"
            style="height: 500px"
          >
            <template v-slot:toolbar>
              <el-button-group>
                <el-button
                  size="small"
                  @click="showEipRoleDialog"
                  icon="el-icon-plus"
                  >添加角色</el-button
                >
              </el-button-group>
            </template>
            <template>
              <ht-table-column
                type="index"
                width="50"
                align="center"
                label="序号"
              />
              <ht-table-column prop="roleName" label="名称" />
              <ht-table-column prop="alias" label="编码" width="300" />
              <ht-table-column width="154" label="操作">
                <template v-slot="{row}">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteUserRole(row.alias)"
                    >删除</el-button
                  >
                </template>
              </ht-table-column>
            </template>
          </ht-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 组织选择对话框  -->
    <eip-org-dialog
      ref="eipOrgDialog"
      @onConfirm="addUserOrg"
      :appendToBody="true"
    />
    <!-- 岗位选择对话框  -->
    <eip-post-dialog
      ref="eipPostDialog"
      @onConfirm="addUserPost"
      append-to-body
    />
    <!-- 角色选择对话框  -->
    <eip-role-dialog
      ref="eipRoleDialog"
      @onConfirm="addUserRole"
      append-to-body
    />
  </div>
</template>
<script>
import utils from '@/hotent-ui-util.js'
import uc from '@/api/uc.js'
import org from '@/api/org.js'
import sys from '@/api/portal.js'
import req from '@/request.js'
import eipOrgDialog from '@/components/dialog/EipOrgDialog.vue'
import eipPostDialog from '@/components/dialog/EipPostDialog.vue'
const eipRoleDialog = () => import('@/components/dialog/EipRoleDialog.vue')
export default {
  name: 'userInfo',
  components: {
    eipOrgDialog,
    eipPostDialog,
    eipRoleDialog,
  },
  props: ['userAccount', 'orgCode'],

  data() {
    return {
      dialogVisible: false,
      user: {}, //用户信息
      account: '', //当前用户账号
      currentTabName: 'basic',
      orgPageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      rolePageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      orgPostList: [], //组织岗位
      userRoleList: [], //用户角色,
      currentTabName: 'basic',
      userOrgPostLoaded: false,
      userRoleLoaded: false,
      pwdValidate: {
        required: true,
        min: 6,
        max: 30,
      },
    }
  },
  computed: {
    //保存用户
    saveUserUrl() {
      let preUrl = window.context.uc + '/api/user/v1/user'
      if (this.account == this.user.account) {
        preUrl += '/updateUser'
      } else {
        preUrl += '/addUser'
      }
      return preUrl
    },
    // 删除岗位
    delOrgUser: function () {
      return window.context.uc + '/api/org/v1/orgUser/delOrgUser'
    },
  },
  mounted() {
    // this.account = this.userAccount
    // 是否显示用户所属组织岗位
    this.userOrgPostLoaded = false
    // 是否显示用户拥有的角色
    this.userRoleLoaded = false
    //默认密码策略
    uc.getDefaultPwdStrategy().then((data) => {
      if (data) {
        let form = data
        //默认初始化密码
        if (form.initPwd) {
          this.user.password = form.initPwd
        }
        if (form.enable == 1) {
          let pwdRule = form.pwdRule
          let pwdLength = form.pwdLength
          if (pwdRule == 1) {
            this.pwdValidate = {
              required: true,
              min: pwdLength,
            }
          } else {
            let regex = {}
            if (pwdRule == 2) {
              regex = {
                exp: '^(?=.*[0-9])(?=.*[a-zA-Z]).{' + pwdLength + ',30}$',
                message: '密码必须包含字母、数字,至少' + pwdLength + '位',
              }
            } else if (pwdRule == 3) {
              regex = {
                exp:
                  '^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{' +
                  pwdLength +
                  ',30}$',
                message:
                  '密码必须包含数字、字母、特殊字符,至少' + pwdLength + '位',
              }
            } else if (pwdRule == 4) {
              regex = {
                exp:
                  '^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{' +
                  pwdLength +
                  ',30}$',
                message:
                  '密码必须包含数字、大小写字母、特殊字符,至少' +
                  pwdLength +
                  '位',
              }
            }
            this.pwdValidate = {
              required: true,
              regex: regex,
            }
          }
        }
      }
    })
  },
  methods: {
    addUserRole(param) {
      param = param.map((param) => {
        return param.code
      })
      var params = {
        account: this.account,
        codes: param,
      }
      uc.saveUserRoles(params).then(() => {
        this.$refs.userRoleTable.load()
      })
    },
    //删除角色
    deleteUserRole(code) {
      var params = {
        account: this.account,
        codes: code,
      }
      uc.delUserRole(params).then(() => {
        this.$refs.userRoleTable.load()
      })
    },
    //
    showEipRoleDialog() {
      this.$refs.eipRoleDialog.showDialog()
    },
    //加载角色
    userRoleLoad(param, cb) {
      uc.userRolePage(param)
        .then((response) => {
          if (response) {
            this.userRoleList = response.rows
            this.rolePageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            }
          }
        })
        .finally(() => cb())
    },
    //打开岗位
    showEipPostDialog() {
      this.$refs.eipPostDialog.showDialog()
    },
    //打开添加组织进行选择
    showEipOrgDialog() {
      this.$refs.eipOrgDialog.showDialog()
    },
    //删除组织岗位之后做的事
    afterDelOrgUser() {
      this.$refs.orgPostTables.load()
    },
    //组织岗位
    orgPostData(param, cb) {
      uc.getUserOrgPage(param)
        .then((response) => {
          this.orgPostList = response.rows.map((item) => {
            if (item.isMaster == 0) {
              item.isMaster = 1
              return item
            } else {
              item.isMaster = 0
              return item
            }
          })
          this.orgPostPageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total,
          }
        })
        .finally(() => cb())
    },
    //所属组织岗位 -> 选择组织
    addUserOrg(param) {
      param = param.map((param) => {
        return param.code
      })
      let _this = this
      this.checkBeyondOrg(param, function (resp) {
        if (resp.beyond.length > 0) {
          let beyondOrgNames = resp.beyond.map((org) => {
            return org.name
          })
          _this.$message.error(
            '添加失败：组织【' + beyondOrgNames.join(',') + '】超出限编'
          )
          return
        }
        var params = {
          account: _this.account,
          orgCode: resp.normal,
        }
        uc.saveUserOrgs(params).then((resp) => {
          _this.$refs.orgPostTables.load()
        })
      })
    },
    open() {
      this.dialogVisible = true
      this.currentTabName = 'basic'
      this.userRoleList = []
      this.orgPostList = []
      this.account = ''
      //初始化加载用户表单
      this.user = {
        id: '',
        account: '',
        address: '',
        email: '',
        fullname: '',
        mobile: '',
        password: '',
        photo: '',
        sex: '',
        status: 1,
        userType: 2,
      }
    },
    closeUserManager() {
      this.dialogVisible = false
    },
    // 保存添加临时人员personnelId，同时父组件页面重新加载调用查询接口展示
    savePersonnel() {
      let param = {
        pageBean: {
          page: 1,
          pageSize: -1,
        },
      }
      uc.getUsersByOrgId(param).then((res) => {
        res.rows.forEach((item) => {
          if (item.account == this.user.account) {
            let param = {}
            param.projectId = this.$route.params.id
            param.personnelId = item.id
            this.$http
              .post(
                '${cqxy}/biz/projectManagement/projectPersonnel/v1/save',
                param
              )
              .then((res) => {
                if (res.data.state) {
                  this.$emit('loadPersonnel')
                }
              })
          }
        })
      })
    },
    beforeSaveData() {},
    afterSaveData() {
      //  如果初始化添加没有账号，需要走接口添加相应的所属岗位组织
      if (this.account !== this.user.account) {
        this.account = this.user.account
        let params = {
          account: this.account,
          orgCode: 'dsf',
        }
        //同时把账号存入第三方接口中
        this.$http
          .get('${cqxy}/api/org/v1/org/getOrgLimitByCodes?codes=dsf')
          .then((res) => {
            console.log(res)
          })
        uc.saveUserOrgs(params).then((resp) => {
          if (resp.state) {
            this.savePersonnel()
            this.$refs.orgPostTables.load()
            this.$refs.userRoleTable.load()
          }
        })
      
      }
    },
    // 点击某个tab页签时再加载该页签的数据
    tabClick() {
      switch (this.currentTabName) {
        case 'orgPost':
          this.userOrgPostLoaded = true
          break
        case 'role':
          this.userRoleLoaded = true
          break
      }
    },
    addUserPost(param) {
      param = param.map((param) => {
        return param.code
      })
      var params = {
        account: this.account,
        Code: param,
      }
      uc.saveUserPosts(params).then((resp) => {
        this.$refs.orgPostTables.load()
      })
    },
    checkBeyondOrg(orgCodes, callback) {
      org.getOrgLimitByCodes(orgCodes.join(',')).then((resp) => {
        let normalOrgCodes = []
        let beyondOrgs = []
        if (resp && resp.rows) {
          resp.rows.forEach((org) => {
            if (org.exceedLimitNum === 1 && org.limitNum != 0) {
              if (org.limitNum > org.nowNum + 1) {
                normalOrgCodes.push(org.code)
              } else {
                beyondOrgs.push(org)
              }
            } else {
              normalOrgCodes.push(org.code)
            }
          })
        }
        callback({normal: normalOrgCodes, beyond: beyondOrgs})
      })
    },
    setMaster(row) {
      uc.setMasterById(row.orgUserId).then((resp) => {
        if (resp.state) {
          this.$message.success(resp.message)
          this.$refs.orgPostTables.load()
        }
      })
      let flag = false
      let orgName = ''
      // this.orgPostList.forEach((item) => {
      //   if (item.isMaster === 1 && row.orgId !== item.orgId) {
      //     orgName = item.orgName
      //     flag = true
      //   }
      // })
      // if (flag) {
      //   this.$confirm(
      //     '该用户已设置主组织' + orgName + '，是否重新设置？',
      //     '提示',
      //     {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'success',
      //     }
      //   )
      //     .then(() => {
      //       uc.setMasterById(row.orgUserId).then((resp) => {
      //         this.$refs.orgPostTables.load()
      //       })
      //     })
      //     .catch(() => {})
      // } else {
      //   uc.setMasterById(row.orgUserId).then((resp) => {
      //     this.$refs.orgPostTables.load()
      //   })
      // }
    },
  },
}
</script>
<style scoped>
.user-param-form {
  min-height: 400px;
}

.electronic-style {
  margin-left: 100px;
}
</style>
