<template>
  <div class="org-info">
    <div style="margin-bottom: 30px;">
      <span style="font-size: 23px; margin-right: 20px; vertical-align: middle;">{{ info.name ? info.name.split('（')[0] : '' }}</span>
      <el-button v-if="info.name && !info.name.includes('长安银科资产管理有限公司')" v-power="'updateOrg'" type="normal" @click="ruleForm.name = info.name.split('（')[0], canDelete = true, $refs.addOrg.show = true">编辑部门</el-button>
    </div>
    <div style="margin-bottom: 30px;">
      <div style="font-size: 18px; margin-bottom: 10px;">下级部门</div>
      <div style="width: 100%; background-color: #F5F6F6; height: 50px; line-height: 50px; padding-left: 20px;">
        <el-button v-power="'addOrg'" type="primary" @click="ruleForm.name = '', $refs.addOrg.show = true">添加子部门</el-button>
      </div>
      <template v-if="nextOrg && nextOrg.length > 0">
        <div v-for="(item, index) in nextOrg" :key="item.id + '_' + index" class="org-item" @click="toOrg(item)">
          <span>{{ item.name }}</span>
          <i class="el-icon-arrow-right"></i>
        </div>
      </template>
      <template v-else>
        <div style="height: 100px; width: 100%; line-height: 70px; font-size: 14px; color: #96999f; text-align: center;">
          该部门无下级部门
        </div>
      </template>
    </div>
    <div>
      <div style="font-size: 18px; margin-bottom: 10px;">部门成员</div>
      <div style="width: 100%; background-color: #F5F6F6; height: 50px; line-height: 50px; padding-left: 20px;">
        <el-button v-power="'addUser'" type="primary" @click="$emit('addPerson')">添加成员</el-button>
        <el-button v-power="'batchUserDisabled'" type="primary" @click="updateStatus(1)">批量禁用</el-button>
        <el-button v-power="'batchUserEnabled'" type="primary" @click="updateStatus(2)">批量启用</el-button>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="setCheckStatus"></el-table-column>
        <el-table-column prop="name" label="姓名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="position" label="职位" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="jobNumber" label="工号" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="mobile" label="手机号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="name" label="操作" width="200">
          <template slot-scope="{ row }">
            <el-button v-power="'resetUserPassword'" type="text" @click="pwdForm.id = row.id, $refs.changePwd.show = true">重置密码</el-button>
            <el-button v-power="'switchOrg'" type="text" @click="updateOrg(row)">调整部门</el-button>
            <el-button v-power="'addRole'" type="text" @click="setPersonInfo(row)">修改</el-button>
            <el-button type="text" @click="watchPersonInfo(row)">查看</el-button>
            <!-- <el-button type="text" @click="updateStatus(3, row)">{{ row.enabled ? '禁用' : '启用' }}</el-button> -->
            <el-button v-if="row.enabled" v-power="'userDisabled'" type="text" @click="updateStatus(3, row)">禁用</el-button>
            <el-button v-if="!row.enabled" v-power="'userEnabled'" type="text" @click="updateStatus(3, row)">启用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <cy-dialog ref="addOrg" :title="canDelete ? '编辑子部门' : '添加子部门'" @close="$refs.ruleForm.resetFields(), canDelete = false">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" label-position="left">
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入部门名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button v-if="canDelete" type="normal" @click="deleteOrg">删除</el-button>
        <el-button type="normal" @click="$refs.ruleForm.resetFields(), $refs.addOrg.show = false, canDelete = false">取消</el-button>
      </template>
    </cy-dialog>
    <cy-dialog ref="changePwd" title="重置密码" @close="$refs.pwdForm.resetFields()">
      <el-form ref="pwdForm" :model="pwdForm" :rules="pwdRules" label-width="150px" label-position="left">
        <el-form-item label="新密码：" prop="pwd">
          <el-input
            v-model="pwdForm.pwd"
            :type="passwordType"
            placeholder="请输入新密码"
          ></el-input>
          <span class="show-pwd" @click="showPwdNewPassword">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="submitPwd">保存</el-button>
        <el-button type="normal" @click="$refs.pwdForm.resetFields(), $refs.changePwd.show = false">取消</el-button>
      </template>
    </cy-dialog>
    <cy-dialog ref="changeOrg" title="选择部门" @close="$refs.orgForm.resetFields(), orgForm.orgIds = []">
      <el-form ref="orgForm" :model="orgForm" :rules="orgRules" label-width="150px" label-position="left">
        <el-form-item label="部门" prop="orgIds" style="width: 100%;">
          <el-cascader
            ref="cascader"
            v-model="orgForm.orgIds"
            style="width: 100%;"
            :options="orgListInfo"
            :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
            :show-all-levels="false"
            placeholder="请选择"
            clearable
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="submitOrg">保存</el-button>
        <el-button type="normal" @click="$refs.orgForm.resetFields(), orgForm.orgIds = [], $refs.changeOrg.show = false">取消</el-button>
      </template>
    </cy-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import md5 from 'js-md5'
export default {
  name: 'OrgInfo',
  props: ['info', 'orgList'],
  data() {
    const validatePwd = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'))
      } else {
        if (value.length < 6 || value.length > 16) {
          callback(new Error('密码长度在6-16个字符内'))
        } else {
          callback()
        }
      }
    }
    return {
      nextOrg: [],
      tableData: [],
      ruleForm: {
        name: ''
      },
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
      },
      canDelete: false,
      selectedIds: [],
      pwdForm: {
        pwd: '',
        id: ''
      },
      pwdRules: {
        pwd: [{ required: true, trigger: 'blur', validator: validatePwd }]
      },
      orgForm: {
        orgIds: [],
        orgInfo: {}
      },
      orgRules: {
        orgIds: [{ required: true, trigger: 'blur', message: '请选择部门' }]
      },
      orgListInfo: [],
      passwordType: 'password'
    }
  },
  watch: {
    info: {
      handler: function(val) {
        if (val.id) {
          this.getOrgList(val.id)
          this.getOrgPerson(val.id)
        }
      },
      immediate: true,
      deep: true
    },
    orgList: {
      handler: function(val) {
        if (val) {
          this.orgListInfo = JSON.parse(JSON.stringify(val))
          this.setOrgName(this.orgListInfo)
        }
      }
    }
  },
  mounted() {},
  methods: {
    showPwdNewPassword() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    getOrgList(id) {
      request({
        url: '/org/findNodeByParentIdNumber',
        method: 'get',
        params: {
          parentId: id
        }
      }).then(({ data }) => {
        this.nextOrg = data || []
      })
    },
    getOrgPerson(id) {
      request({
        url: '/user/do_list',
        method: 'get',
        params: {
          orgId: id,
          page: 1,
          rows: 100
        }
      }).then(({ rows }) => {
        this.tableData = rows || []
      })
    },
    setCheckStatus(row) {
      return !'admin, businessAdmin'.includes(row.loginName)
    },
    toOrg(info) {
      this.$emit('toOrg', info)
    },
    addOrg() {
      const data = new FormData()
      data.append('parent.id', this.info.id)
      data.append('name', this.ruleForm.name)
      request({
        url: '/org/do_add',
        method: 'post',
        data
      }).then(({ data }) => {
        this.$message.success('新增成功')
        this.$refs.addOrg.show = false
        this.$refs.ruleForm.resetFields()
        this.ruleForm.name = ''
        this.$emit('addOrg', data)
      })
    },
    submit() {
      this.$refs.ruleForm.validate(flag => {
        if (flag) {
          this.addOrg()
        } else {
          this.$message.error('必填项不能为空')
        }
      })
    },
    deleteOrg() {
      if (this.tableData.length > 0) {
        this.$message.error('该部门下有成员，不能删除')
        return
      }
      const data = new FormData()
      data.append('id', this.info.id)
      request({
        url: '/org/do_delete',
        method: 'post',
        data
      }).then(() => {
        this.$message.success('删除成功')
        this.$refs.addOrg.show = false
        this.$refs.ruleForm.resetFields()
        this.ruleForm.name = ''
        this.$emit('addOrg')
      })
    },
    handleSelectionChange(val) {
      this.selectedIds = val.map(item => {
        return item.id
      })
    },
    updateStatus(val, info) {
      if (this.selectedIds.length === 0 && val != 3) {
        this.$message.error(`请选择要${val == 1 ? '禁用' : '启用'}的成员`)
        return
      }
      const data = new FormData()
      data.append('enabled', val == 3 ? !info.enabled : val != 1)
      data.append('ids', val == 3 ? info.id : this.selectedIds.join(','))
      request({
        url: '/user/do_modifyEnabled',
        method: 'post',
        data
      }).then(({ data }) => {
        this.$message.success(`${val == 3 ? (info.enabled ? '禁用' : '启用') : val == 1 ? '禁用' : '启用'}成功`)
        this.getOrgPerson(this.info.id)
      })
    },
    submitPwd() {
      this.$refs.pwdForm.validate(flag => {
        if (flag) {
          const data = new FormData()
          data.append('id', this.pwdForm.id)
          data.append('password', md5(this.pwdForm.pwd))
          request({
            url: '/user/do_resetpassword',
            method: 'post',
            data
          }).then(() => {
            this.$message.success('修改成功')
            this.$refs.pwdForm.resetFields()
            this.$refs.changePwd.show = false
          })
        } else {
          this.$message.error('必填项不能为空')
        }
      })
    },
    setOrgName(orgList) {
      if (!orgList || orgList.length === 0) return
      orgList.forEach(item => {
        if (item.children && item.children.length > 0) {
          item.name = item.name.split('（')[0]
          item.userIdentity = false
          this.setOrgName(item.children)
        } else {
          item.userIdentity = false
          item.name = item.name.split('（')[0]
        }
      })
    },
    updateOrg(info) {
      this.orgForm.orgInfo = info
      this.$refs.changeOrg.show = true
      this.orgForm.orgIds.push(this.info.id)
      this.$nextTick(() => {
        if (this.$refs.cascader) {
          this.$refs.cascader.presentTags.push({ text: this.info.name.split('（')[0], closable: true })
        }
      })
    },
    submitOrg() {
      this.$refs.orgForm.validate(flag => {
        if (flag) {
          const data = new FormData()
          data.append('id', this.orgForm.orgInfo.id)
          this.orgForm.orgIds.forEach((item, index) => {
            data.append(`orgIdList[${index}]`, item)
          })
          request({
            url: '/user/do_adjustDepartment',
            method: 'post',
            data
          }).then(({ data }) => {
            this.$message.success('提交成功')
            this.$refs.orgForm.resetFields()
            this.orgForm.orgids = []
            this.$refs.changeOrg.show = false
            const info = { ...this.info, tempTime: Math.random() }
            this.$emit('addOrg', info)
          })
        } else {
          this.$message.error('必填项不能为空')
        }
      })
    },
    setPersonInfo(row) {
      this.$emit('addPerson', row)
    },
    watchPersonInfo(row) {
      this.$emit('watchPerson', row)
    }
  }
}
</script>

<style lang="scss">
.org-info {
  padding: 20px;
  width: 100%;
  .org-item {
    width: 100%;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #ccc;
    display: flex;
    justify-content: space-between;
    padding-left: 30px;
    cursor: pointer;
    i {
      line-height: 40px;
      color: #353535;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 2px;
    font-size: 16px;
    color: #889aa4;
    cursor: pointer;
    user-select: none;
  }
}
</style>
