<template>
  <div class="staff page_container">
    <table-list v-bind="tableOptions" ref="tabList" @selection-change="handleSelectionChange">
      <template #header-aside>
        <el-button type="primary" size="mini" @click="handleCreate" v-if="hasCreate">新建员工</el-button>
      </template>
      <!-- 筛选-搜索用户 -->
      <template v-slot:filter-user="option">
        <div style="display:flex;">
          <span>
            {{ option.real_name || option.nickname }}
            <template v-if="option.mobile">(手机号：{{option.mobile}})</template>
          </span>
          <span style="color: #8492a6; font-size: 13px; margin:0 20px 0 10px;" v-if="option.email">邮箱：{{ option.email }}</span>
          <span style="color: #8492a6; font-size: 13px; margin:0 20px 0 10px;" v-else>ID：{{ option.id }}</span>
        </div>
      </template>
      <!-- 姓名 -->
      <template v-slot:table-name="{ row }">
        <p class="details-handle" @click="handleDetails(row)">{{row.sso_user.real_name || row.sso_user.nickname}}</p>
      </template>
      <!-- 角色 -->
      <template v-slot:table-role="{ row }">
        <span v-for="(item, index) in row.roles" :key="index">{{index > 0 ? '、' : ''}}{{item.name}}</span>
      </template>
      <!-- 项目 -->
      <template v-slot:table-project="{ row }">
        <p class="details-handle">
          <span v-for="(item, index) in row.projects" :key="index">{{index > 0 ? '、' : ''}}{{item.name}}</span>
        </p>
      </template>
      <!-- 创建人 -->
      <template v-slot:table-creator="{ row }">
        <p>{{row.create_user.realname || row.create_user.nickname}}</p>
      </template>
      <!-- 发布状态 -->
      <template v-slot:status="{ row }">
        <el-switch v-model="row.status" :active-value="0" :inactive-value="1" active-text="启用" inactive-text="停用" @change="statusChange(row)" :disabled="!hasCreate"></el-switch>
      </template>
      <!-- 操作 -->
      <!-- <template v-slot:tools="{ row }">
        <el-button type="text" @click="changePassword(row)">重置密码</el-button>
        <el-button type="text" @click="changePhone(row)">更换手机号</el-button>
      </template> -->
      <template #footer>
        <el-button size="mini" :disabled="!multipleSelection.length" @click="handleRemove" v-if="hasDelete"
          >删除</el-button
        >
      </template>
    </table-list>
    <el-drawer :title="drawerTitle" :visible.sync="drawerVisible" size="440px" @close="handleDrawerClose">
      <div class="drawer__content">
        <el-form :model="form" ref="drawerForm" :rules="rules" label-width="70px" class="drawer-form">
          <el-form-item label="账户" prop="userid" v-if="dialogType === 'edit'">
            <el-input v-model="form.userid" size="small" disabled></el-input>
          </el-form-item>
          <el-form-item label="账户" prop="sso_id" v-else style="position:relative;">
            <el-select v-model="form.sso_id" placeholder="输入邮箱/手机号码搜索" size="small" filterable remote :remote-method="fetchUserList" :loading="searchUsersloading" style="width:100%;">
              <el-option :label="user.realname || user.nickname " :value="user.id" v-for="user in userList" :key="user.id" >
                <div style="display:flex;">
                  <span>
                    {{ user.realname || user.nickname }}
                    <template v-if="user.mobile">(手机号：{{user.mobile}})</template>
                  </span>
                  <span style="color: #8492a6; font-size: 13px; margin:0 20px 0 10px;" v-if="user.email">邮箱：{{ user.email }}</span>
                  <span style="color: #8492a6; font-size: 13px; margin:0 20px 0 10px;" v-else>ID：{{ user.id }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" size="small"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" size="small"></el-input>
          </el-form-item> -->
          <!-- <el-form-item label="姓名" prop="username">
            <el-input v-model="form.username" size="small"></el-input>
          </el-form-item> -->
          <el-form-item label="角色" prop="role_id">
            <el-select v-model="form.role_id" placeholder="请选择角色" size="small" style="width:100%;">
              <el-option :label="role.name" :value="role.id" v-for="role in roleList" :key="role.id" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目" prop="project_ids">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 8px 0;"></div>
            <el-checkbox-group v-model="form.project_ids" @change="handleCheckedProjectChange">
              <el-checkbox v-for="pr in projectList" :label="pr.id" :key="pr.id">{{pr.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div class="drawer__footer">
          <el-button @click="handleDrawerClose" size="mini">取 消</el-button>
          <el-button type="primary" @click="handleDrawerSubmit" size="mini">提 交</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="440px" :destroy-on-close="true">
      <el-form :model="dialogForm" ref="dialogForm" label-width="80px" class="dialog-form">
          <template v-if="dialogType === 'pwd'">
            <el-form-item label="新密码" prop="password" :rules="{ required: true, message: '请输入新密码', trigger: 'blur' }">
              <el-input v-model="dialogForm.password" size="small"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="ensurePassword" :rules="[{ required: true, message: '请输入确认密码', trigger: 'blur' }, { validator: (rule, value, callback) => checkedDialogForm(dialogForm.password, value, callback, '密码'), trigger: 'blur' }]">
              <el-input v-model="dialogForm.ensurePassword" size="small"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone" :rules="{ validator: checkedMobile, trigger: 'blur' }">
              <el-input v-model="dialogForm.phone" size="small"></el-input>
            </el-form-item>
            <el-form-item label="验证码">
              <el-col :span="16">
                <el-form-item prop="code" :rules="{ required: true, message: '请输入验证码', trigger: 'blur' }">
                  <el-input v-model="dialogForm.code" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="7" style="float:right">
                <el-button type="primary" @click="sendCode" size="small" style="width:100%;" id="checkedCode" :disabled="isBtnDisabled">
                  获取验证码
                </el-button>
              </el-col>
            </el-form-item>
          </template>
          <template  v-if="dialogType === 'phone'">
            <el-form-item label="新手机号" prop="phone" :rules="[{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkedMobile, trigger: 'blur' }]">
              <el-input v-model="dialogForm.phone" size="small"></el-input>
            </el-form-item>
            <el-form-item label="确认号码" prop="ensurePhone" :rules="[{ required: true, message: '请输入确认密码', trigger: 'blur' }, { validator: (rule, value, callback) => checkedDialogForm(dialogForm.phone, value, callback, '手机号'), trigger: 'blur' }]">
              <el-input v-model="dialogForm.ensurePhone" size="small"></el-input>
            </el-form-item>
          </template>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="handleDialogSubmit" size="mini">提 交</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
import TableList from '@/components/TableList'
import { getStaffList, getProjectList, getRoleList, createStaff, updateStaff, batchDeleteStaff } from '@/api/settings'
import { sendCode, updatePassword, updateUserInfo } from '@/api/account'
import { searchUserList } from '@/api/system'
import { mapGetters } from 'vuex'
const MOBILE_REG = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{4,8}$/
const EMAIL_REG = /^[A-Za-z0-9]+([_.][A-Za-z0-9]+)*@[A-Za-z0-9-.]+$/
const drawerForm = {
  sso_id: '',
  role_id: '',
  project_ids: []
}
const dialogForm = {
  password: '',
  ensurePassword: '',
  code: '',
  phone: '',
  ensurePhone: ''
}
export default {
  components: { TableList },
  data() {
    const mobileReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{4,8}$/
    const checkMobile = (rule, value, callback) => {
      if (value) {
        if (!mobileReg.test(value)) {
          callback(new Error('手机号格式错误'));
        } else {
          callback()
        }
      }
    }
    return {
      activeName: '0',
      projectList: [],
      roleList: [],
      drawerVisible: false,
      drawerType: '',
      checkAll: false,
      isIndeterminate: false,
      form: Object.assign({}, drawerForm),
      rules: {
        sso_id: [{ required: true, message: '请选择账户', trigger: 'change' }],
        role_id: [{ required: true, message: '请选择角色', trigger: 'change' }],
        project_ids: { required: true, message: '请选择项目', trigger: 'change' }
      },
      userList: [],
      searchUsersloading: false,
      dialogVisible: false,
      dialogType: '',
      operateItem: '',
      dialogForm: Object.assign({}, dialogForm),
      checkedMobile: checkMobile,
      isBtnDisabled: false,
      multipleSelection: []
    }
  },
  computed: {
    ...mapGetters(['user']),
    // 权限列表
    permissions() {
      return this.$store.state.user.permissions || []
    },
    // 创建权限
    hasCreate() {
      return this.permissions.includes('setting-function-user-create')
    },
    // 删除权限
    hasDelete() {
      return this.permissions.includes('setting-function-user-delete')
    },
    drawerTitle() {
      return this.drawerType === 'create' ? '新建员工' : '编辑员工'
    },
    dialogTitle() {
      const text = this.dialogType === 'pwd' ? '修改密码' : '修改手机'
      const user = this.operateItem.sso_user
      let username = ''
      if (user) {
        username = user.real_name || user.nickname
      }
      return text + '（' + username + '）'
    },
    tableOptions() {
      return {
        remote: {
          httpRequest: getStaffList,
          params: {}
        },
        filters: [
          {
            type: 'select',
            placeholder: '项目',
            prop: 'project_id',
            options: this.projectList,
            labelKey: 'name',
            valueKey: 'id'
          },
          // { type: 'input', placeholder: '手机号/邮箱', prop: 'id' },
          {
            type: 'select',
            placeholder: '输入邮箱/手机号搜索',
            options: this.userList,
            prop: 'sso_id',
            labelKey: 'realname',
            alternateLabelKey: 'nickname',
            valueKey: 'id',
            filterable: true,
            remote: true,
            'remote-method': this.fetchUserList,
            slots: 'filter-user'
          },
          {
            type: 'select',
            placeholder: '角色',
            prop: 'role_id',
            options: this.roleList,
            labelKey: 'name',
            valueKey: 'id'
          }
        ],
        columns: [
          { type: 'selection', minWidth: '50px', fixed: 'left', visible: this.hasDelete },
          { prop: 'sso_user.real_name', label: '姓名', slots: 'table-name', minWidth: '80px', fixed: 'left' },
          { prop: 'roles', label: '角色', slots: 'table-role', minWidth: '100px' },
          { prop: 'sso_user.mobile', label: '手机号', minWidth: '110px' },
          { prop: 'sso_user.email', label: '邮箱', minWidth: '160px' },
          { prop: 'projects', label: '项目', minWidth: '130px', slots: 'table-project' },
          { prop: 'create_user', label: '创建人', minWidth: '80px', slots: 'table-creator' },
          { prop: 'created_at', label: '创建时间', minWidth: '150px' },
          { prop: 'status', label: '状态', slots: 'status', minWidth: '140px', fixed: 'right' }
          // { prop: 'x', label: '操作', slots: 'tools', minWidth: '200px', fixed: 'right', visible: this.hasCreate }
        ]
      }
    }
  },
  created() {
    // console.log(this.hasCreate)
    this.fetchProjectList()
    this.fetchRoleList()
  },
  methods: {
    // 选择
    handleSelectionChange(value) {
      this.multipleSelection = value
    },
    // 删除
    handleRemove() {
      const selection = this.multipleSelection
      const ids = selection.map(item => item.sso_id)
      let isWarn = false
      for (const i in selection) {
        if (selection[i].status === 0) {
          isWarn = true
        }
      }
      if (isWarn) {
        this.$confirm('选中的项中有已启用的账户, 是否继续执行删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.fetchDeleteStaff(ids)
        }).catch(() => {});
      } else {
        this.fetchDeleteStaff(ids)
      }
    },
    handleCreate() {
      this.drawerVisible = true
      this.drawerType = 'create'
    },
    handleDrawerClose() {
      this.$refs.drawerForm.resetFields();
      this.drawerVisible = false
      this.form = Object.assign({}, drawerForm)
      this.checkAll = false
      this.isIndeterminate = false
    },
    handleDialogClose() {
      this.drawerVisible = false
      this.dialogForm = Object.assign({}, dialogForm)
    },
    handleCheckAllChange(val) {
      this.form.project_ids = val ? this.projectList.map(item => item.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedProjectChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.projectList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.projectList.length;
    },
    checkedDialogForm(val, value, callback, word) {
      if (value && value !== val) {
        callback(new Error(word + '两次输入不一致'));
      } else callback()
    },
    // 重置密码
    changePassword(data) {
      this.operateItem = data
      this.dialogVisible = true
      this.dialogType = 'pwd'
    },
    sendCode() {
      if (!this.dialogForm.phone) {
        this.$message('请填写手机号')
      } else if (!MOBILE_REG.test(this.dialogForm.phone)) {
        this.$message('手机号格式错误')
      } else {
        this.fetchSendCode()
        this.isBtnDisabled = true
        this.btnDisabledTimer()
      }
    },
    // 发送验证码按钮计时器
    btnDisabledTimer() {
      let count = 3
      const btnEl = document.querySelector('#checkedCode')
      btnEl.innerHTML = count + '秒后重发'
      const timer = setInterval(() => {
        count--
        if (count < 1) {
          clearInterval(timer)
          this.isBtnDisabled = false
          btnEl.innerHTML = '获取验证码'
        } else {
          btnEl.innerHTML = count + '秒后重发'
        }
      }, 1000)
    },
    // 更换手机号
    changePhone(data) {
      this.operateItem = data
      this.dialogVisible = true
      this.dialogType = 'phone'
    },
    handleDetails(val) {
      if (this.hasCreate) {
        this.drawerVisible = true
        this.drawerType = 'details'
        const form = this.form
        form.sso_id = val.sso_id
        form.role_id = val.roles[0] ? val.roles[0].id : ''
        form.project_ids = val.projects.map(item => item.id) || []
        this.handleCheckedProjectChange(form.project_ids)
        this.operateItem = val
        this.userList = [val.sso_user]
      }
    },
    statusChange(val) {
      this.fetchUpdateStaff({
        sso_id: val.sso_id,
        status: val.status
      }, 'status')
    },
    handleDrawerSubmit() {
      this.$refs.drawerForm.validate(valid => {
        if (valid) {
          if (this.drawerType === 'create') {
            this.fetchCreateStaff()
          } else {
            this.fetchUpdateStaff(this.form)
          }
          return false
        }
      })
    },
    handleDialogSubmit() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          if (this.dialogType === 'pwd') {
            this.fetchChangePwd()
          } else {
            this.fetchChangePhone()
          }
        } else {
          return false
        }
      })
    },
    fetchSendCode() {
      const params = {
        account: this.dialogForm.phone,
        service: 'ezijing.com'
      }
      sendCode(params).then(res => {
        if (res && res.code === 0) {
          this.$message.success('验证码发送成功')
        } else {
          this.$message.error(res.msg || '发送验证码失败')
        }
      })
    },
    fetchChangePwd() {
      const params = {
        account: this.dialogForm.phone,
        code: this.dialogForm.code,
        password: this.dialogForm.password,
        passwordR: this.dialogForm.ensurePassword
      }
      updatePassword(params).then(res => {
        if (res.code === 0 && res.msg === 'OK') {
          this.$message.success('更改密码成功')
          this.dialogVisible = false
          this.fetchClearUserCached()
        } else {
          this.$message.error('更改密码失败')
        }
      })
    },
    fetchChangePhone() {
      const params = {
        mobile: this.dialogForm.phone || ''
      }
      updateUserInfo(params).then(res => {
        if (res.code === 0 && res.data && res.data.mobile) {
          this.$message.success('更改手机号成功')
          this.dialogVisible = false
          this.fetchClearUserCached()
        } else {
          this.$message.error('更改手机号失败')
        }
      })
    },
    fetchCreateStaff() {
      createStaff(this.form).then((res) => {
        if (res.code === 0 && res.data && res.data.id) {
          this.$message.success('新建员工成功')
          this.$refs.tabList.refetch()
          this.handleDrawerClose()
        } else {
          this.$message.error(res.message || '新建项目失败')
        }
      })
    },
    fetchUpdateStaff(data, type) {
      const msg = type === 'status' ? '更改状态' : '更改员工信息'
      updateStaff(data).then((res) => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success(msg + '成功')
          this.$refs.tabList.refetch()
          this.handleDrawerClose()
          // 刷新用户user_detail
          if (this.user.id === data.sso_id) {
            this.$store.dispatch('checkRolesPermissions')
          }
        } else {
          this.$message.error(res.message || msg + '失败')
        }
      })
    },
    fetchUserList(val) {
      let searchType = 'username'
      if (EMAIL_REG.test(val)) {
        searchType = 'email'
      } else if (MOBILE_REG.test(val)) {
        searchType = 'mobile'
      }
      if (!val) return false
      else {
        const params = {
          [searchType]: val
        }
        this.searchUsersloading = true
        searchUserList(params)
          .then(res => {
            this.searchUsersloading = false
            if (res.data && Array.isArray(res.data.items)) {
              this.userList = res.data.items
            }
          })
          .catch(() => {})
      }
    },
    fetchRoleList() {
      getRoleList({ limit: 100 }).then((res) => {
        if (res.code === 0 && res.data && Array.isArray(res.data.data)) {
          this.roleList = res.data.data
        }
      })
    },
    fetchProjectList() {
      getProjectList({ type: 0, status: 1, limit: 100 }).then((res) => {
        if (res.code === 0 && res.data && Array.isArray(res.data.data)) {
          this.projectList = res.data.data
        }
      })
    },
    fetchDeleteStaff(ids) {
      if (ids.includes(this.user.id)) {
        this.$message.error('您所删除的账户包含你的账户，删除后将导致您没法使用此系统')
      }
      batchDeleteStaff({ sso_ids: ids }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.$refs.tabList.refetch(true)
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style scoped>
.drawer__content{
  height:100%;
}
.drawer-form{
  width:400px;
  margin:0 20px;
  padding-top:20px;
  min-height: calc(100% - 70px);
}
.drawer__footer{
  text-align:center;
  padding-bottom:15px;
}
</style>
