<template>
  <a-card>
    <a-spin v-if="modifyAuth" :spinning="isSubmitting">
      <h2 :class="$style.title">用户密码批量修改工具</h2>
      <div :class="$style.tips">提示：如修改密码的用户较多，可能耗时较长</div>
      <a-form-model
        ref="form"
        :model="formData"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        @submit.prevent="handleSubmit"
      >
        <a-form-model-item label="修改范围" prop="scope">
          <a-radio-group v-model="formData.scope">
            <a-radio value="all">
              全部用户
              <a-tooltip title="修改的人员范围为：当前用户管理的分级机构下的人员（不包含下级）">
                <a-icon type="question-circle-o" />
              </a-tooltip>
            </a-radio>
            <a-radio value="dept">
              按部门
            </a-radio>
            <a-radio value="person">
              按人员
            </a-radio>
            <a-radio value="role">
              按角色
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          v-if="formData.scope === 'dept'"
          key="dept"
          :label="'部\u2003\u2003门'"
          prop="dept"
        >
          <div :class="$style.deptcontent">
            <sd-group-picker v-model="formData.dept" :root-node="rootNode" :hierarchical="false" />
            <a-checkbox :checked="formData.authSubIncluded === '1'" @change="setAuthSub"
              >含下级</a-checkbox
            >
          </div>
        </a-form-model-item>
        <a-form-model-item
          v-if="formData.scope === 'person'"
          key="person"
          :label="'人\u2003\u2003员'"
          prop="person"
        >
          <sd-user-picker v-model="formData.person" :root-node="rootNode" :hierarchical="false" />
        </a-form-model-item>
        <a-form-model-item
          v-if="formData.scope === 'role'"
          key="role"
          :label="'角\u2003\u2003色'"
          prop="role"
        >
          <sd-role-picker v-model="formData.role" />
        </a-form-model-item>
        <!-- 添加一个无用的text和password属性的input，避免chrome等浏览器自动填充用户名和密码 -->
        <div :class="$style.disabledDiv">
          <a-input />
          <a-input-password />
        </div>
        <a-form-model-item :label="'新\u2002密\u2002码'" has-feedback prop="newPwd">
          <a-input-password v-model="formData.newPwd" />
        </a-form-model-item>
        <a-form-model-item label="确认新密码" has-feedback prop="confirmNewPwd">
          <a-input-password v-model="formData.confirmNewPwd" />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 12, offset: 12 }">
          <a-button
            :class="$style.buttonclass"
            type="primary"
            :loading="isSubmitting"
            html-type="submit"
          >
            确定
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-card>
</template>

<script>
import { message } from '@/common/one-ui'
import axios from '@/common/services/axios-instance'
// eslint-disable-next-line no-restricted-imports
import orginAxios from 'axios'
import loginService from '@/login/login-service'
import components from './_import-components/sd-password-batch-modify-import'

export default {
  name: 'SdPasswordBatchModify',
  metaInfo: {
    title: '用户密码批量修改工具',
  },
  components,
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      formData: {
        scope: 'all',
        dept: [],
        authSubIncluded: '0',
        person: [],
        role: [],
        newPwd: '',
        confirmNewPwd: '',
      },
      rules: {
        dept: [{ required: true }],
        person: [{ required: true }],
        role: [{ required: true }],
        newPwd: [{ required: true }],
        confirmNewPwd: [{ required: true }, { validator: this.validateConfirmPwd }],
      },
      isSubmitting: false,
      rootNode: undefined,
      modifyAuth: false,
    }
  },
  created() {
    axios.post('api/framework/v1/user-manager/check-manage-auth').then((res) => {
      this.modifyAuth = res.data
      if (this.modifyAuth) {
        // 获取当前用户可选择的部门(分级)根节点
        axios
          .get(`api/framework/v1/group-manager/group/root-node`, { hierarchical: '1' })
          .then((res) => {
            const root = res.data
            if (root) {
              this.rootNode = { code: root.id, name: root.text }
            }
          })
      } else message.error('您没有权限访问此页面')
    })
  },
  methods: {
    validateConfirmPwd(rule, value, callback) {
      if (value === '') {
        callback(new Error('不能为空'))
      } else {
        if (value !== this.formData.newPwd) {
          callback(new Error('两次密码输入不一致！'))
        }
        callback()
      }
    },
    setAuthSub() {
      this.formData.authSubIncluded = this.formData.authSubIncluded === '1' ? '0' : '1'
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let ids = ''
          switch (this.formData.scope) {
            case 'all':
              ids = 'ALL'
              break
            case 'dept': {
              // 部门：G+机构id
              const deptIds = this.formData.dept.map((item) => `G${item.code}`)
              // 含子部门：包含下级首个值后+“_SUB”
              if (this.formData.authSubIncluded === '1') {
                deptIds[0] = `${deptIds[0]}_SUB`
              }
              ids = deptIds.join(',')
              break
            }
            case 'person': {
              // 用户：用户id
              ids = this.formData.person.map((item) => `${item.id}`).join(',')
              break
            }
            case 'role': {
              // 角色：R+角色code
              ids = this.formData.role.map((item) => `R${item.code}`).join(',')
              break
            }
            default:
              break
          }
          this.isSubmitting = true
          orginAxios.get('api/ott').then((res) => {
            const ott = res.data
            axios
              .post('api/framework/v1/user-manager/users/reset-pwd', {
                ids,
                pwd: loginService.encryptBySm4(ott.id, ott.token, this.formData.newPwd),
              })
              .then((res) => {
                // 重置密码请求发送完成，查询重置结果
                this.getResult(res.data)
              })
              .catch(() => {
                message.error('重置密码出错')
                this.isSubmitting = false
              })
          })
        }
      })
    },
    getResult(id) {
      // 根据id查询重置密码结果
      axios
        .post('api/framework/v1/user-manager/users/change-pwd-task', { id })
        .then((res) => {
          const status = res.data?.status
          // EXECUTING表示进行中（密码还没有修改完成），COMPLETED表示已完成
          if (status === 'EXECUTING') {
            // 尚未完成重置，2s后再请求
            setTimeout(() => {
              this.getResult(id)
            }, 2000)
          } else if (status === 'COMPLETED') {
            // 执行完成，判断是否成功，返回值中error=1表示成功
            if (res.data?.error === 1) {
              message.success('重置完成')
            } else {
              message.error(`重置失败，原因：${res.data.remark || '未知'}`)
            }
            this.isSubmitting = false
          } else {
            message.warning('重置结果未知')
            this.isSubmitting = false
          }
        })
        .catch(() => {
          message.error('重置结果未知')
          this.isSubmitting = false
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.title {
  text-align: center;
}
.tips {
  color: $red-6;
  text-align: center;
}
.deptcontent {
  display: flex;
  justify-content: space-between;
  :global(.ant-checkbox-wrapper) {
    width: 21%;
    min-width: 86px;
    text-align: right;
  }
}
.disabled-div {
  position: absolute;
  width: 0;
  opacity: 0;
}
</style>
