
<template>
  <div>
    <el-dialog
      :visible="visible"
      :title="'变更管理员'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="rnr-dialog"
      width="960px"
      destroy-on-close
      @close="$emit('update:visible', false)"
    >
      <el-radio-group v-model="type">
        <el-radio :label="0">用其他用户替换</el-radio>
        <el-radio :label="1">用新账户替换</el-radio>
      </el-radio-group>
      <el-form ref="formRef" :model="formData[type]" label-position="top" style="margin-top: 24px;">
        <!-- 当上面选择其他用户替换时出现 -->
        <el-form-item v-if="type == 0" :rules="IS_NOT_EMPTY('请选择其他用户账户')" prop="newAdminUserId" label="其他用户账户">
          <el-select v-model="formData[0].newAdminUserId" clearable placeholder="请选择其他用户账户">
            <el-option v-for="user in userList[organId]" :key="user.value" v-bind="user" />
          </el-select>
        </el-form-item>
        <!-- 当上面选择用新账户替换时出现 -->
        <template v-else>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item :rules="IS_NOT_EMPTY('请输入管理员姓名')" prop="createAdminUserName" label="管理员姓名">
                <el-input v-model="formData[1].createAdminUserName" placeholder="请输入管理员姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="IS_NOT_EMPTY('请输入管理员账号')" prop="createAdminAccount" label="管理员账号">
                <el-input v-model="formData[1].createAdminAccount" placeholder="请输入管理员账号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item :rules="[IS_NOT_EMPTY('请输入管理员密码'), IS_RIGHT_PASSWORD()]" prop="createAdminPassword" label="管理员密码">
                <el-input v-model="formData[1].createAdminPassword" type="password" placeholder="请输入管理员密码" />
                <div class="el-form-item__field-tip">密码长度必须为8～20位字符，由大写字母、小写字母、数字、特殊符号中的3种及以上类型组成</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="[IS_NOT_EMPTY('请输入确认密码'), CONFIRM_PASSWORD]" prop="confirmPassword" label="确认密码">
                <el-input v-model="formData[1].confirmPassword" type="password" placeholder="请确认密码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item :rules="[IS_NOT_EMPTY('请输入管理员手机号'), IS_PHONE()]" prop="createAdminPhone" label="管理员手机号">
                <el-input v-model="formData[1].createAdminPhone" placeholder="请输入管理员手机号" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button :loading="isLoading" type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { changeUserEnterpriseDistributor, queryUserEnterpriseAccount, queryUserAccount, changeOrganAdmin } from '@/api/management'
import { IS_NOT_EMPTY, IS_PHONE, CONFIRM_PASSWORD, IS_RIGHT_PASSWORD } from '../../rules'
import '../dialog.scss'

export default {
  name: 'ModifyAdministrator',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    },
    from: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      IS_NOT_EMPTY,
      IS_PHONE,
      IS_RIGHT_PASSWORD,
      isLoading: false,
      type: 0,
      userList: {},
      organId: '',
      formData: [
        { newAdminUserId: '' },
        {
          createAdminUserName: '',
          createAdminAccount: '',
          createAdminPassword: '',
          createAdminPhone: ''
        }
      ]
    }
  },
  computed: {
    /**
     * 确认密码
     */
    CONFIRM_PASSWORD() {
      return CONFIRM_PASSWORD(this.formData[this.type].createAdminPassword)
    }
  },
  watch: {
    /**
     * 如果当前是可见
     */
    visible() {
      // 如果当前不可见不调用接口
      if (!this.visible) {
        // 清空用户输入
        this.formData = [
          { newAdminUserId: '' },
          {
            createAdminUserName: '',
            createAdminAccount: '',
            createAdminPassword: '',
            createAdminPhone: ''
          }
        ]
        return
      }
      // 开始查询账户信息
      this.queryUserEnterpriseAccount()
    }
  },
  methods: {
    /**
     * 查询用户列表
     */
    async queryUserEnterpriseAccount() {
      // 取出id和租户号
      const { uuid, id, tenantNo } = this.data
      // 如果当前是组织
      const requestFn = this.from === 'organ' ? queryUserAccount : queryUserEnterpriseAccount
      // 组织id
      this.organId = this.from === 'organ' ? uuid : id
      // 如果当前组织之前请求过数据
      if (this.userList[this.organId] && this.userList[this.organId].length > 0) {
        return
      }
      // 开始请求接口数据
      const respData = await requestFn({
        organId: this.organId,
        tenantNo,
        currPage: 1,
        pageSize: 20
      })
      // 当前列表数据
      const list = this.from === 'organ' ? respData : respData.list
      // 开始绑定数据
      this.$set(this.userList, this.organId, list.map(item => ({
        label: this.from === 'organ' ? item.fullName : item.userName,
        value: item.id || item.uuid
      })))
    },

    /**
     * 关闭弹框
     */
    handleClose() {
      this.$emit('update:visible', false)
    },

    /**
     * 点击提交方法
     */
    handleSubmit() {
      // 校验表格数据
      this.$refs.formRef.validate(async valid => {
        // 校验失败
        if (!valid) {
          return
        }
        // 按钮出现loading状态
        this.isLoading = true
        try {
          // 其他参数
          const { id, uuid, distributorAdminUserId, bizType, organAdminUserId, tenantNo } = this.data
          // 接口请求数据
          const formData = { ...this.formData[this.type] }
          // 如果当前是组织，则请求组织接口
          if (this.from === 'organ') {
            await changeOrganAdmin({
              ...formData,
              uuid,
              bizType,
              tenantNo,
              currentAdminUserId: organAdminUserId
            })
          } else {
            // 更换管理员
            await changeUserEnterpriseDistributor({
              ...formData,
              id,
              currentAdminUserId: distributorAdminUserId
            })
          }
          // 关闭弹框
          this.handleClose()
          // 刷新数据
          this.$emit('refresh')
        } catch (error) {
          console.error(error)
        }
        // 关闭loading状态
        this.isLoading = false
      })
    }
  }
}
</script>
