<template>
  <el-row :gutter="10" type="flex" justify="center">
    <el-col
      :xs="24"
      :sm="24"
      :md="24"
      :lg="16"
      :style="{ marginBottom: '10px' }"
    >
      <el-card class="add-container">
        <el-form
          :model="userForm"
          :rules="rules"
          ref="userRef"
          :label-width="100"
          class="userForm"
        >
          <el-form-item required label="登陆账户" prop="LoginName">
            <el-input
              v-model="userForm.LoginName"
              placeholder="请输入登陆账户"
            ></el-input>
          </el-form-item>
          <el-form-item required label="手机号码" prop="PhoneNo">
            <el-input
              v-model="userForm.PhoneNo"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="UserName">
            <el-input
              v-model="userForm.UserName"
              placeholder="请输入真实姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户头像">
            <el-upload
              action="/"
              :http-request="uploadImage"
              class="avatar-uploader"
              :show-file-list="false"
            >
              <img
              style="width:100px;"
                v-if="userForm.ProfilePhotoPath"
                :src="userForm.ProfilePhotoPath"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item required label="授权角色">
            <span
              v-for="role in roles"
              :key="role.Name"
              style="margin-right: 20px"
            >
              <el-checkbox
                v-model="role.Checked"
                :label="role.Name"
                size="large"
              />
            </span>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="btnLoading"
              @click="onSubmit()"
              >{{ Id != -1 ? '立即修改' : '立即创建' }}</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
import { reactive, ref, toRefs, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { editUser, getUserDetail } from '@/api/user'
import { getRoleList } from '@/api/role'
import { checkphone } from '@/hooks/useValidateForm'
import config from '@/utils/config'
import { useStore } from 'vuex'
import { uploadFile } from '@/api/upload'

export default {
  name: 'UserEdit',
  setup() {
    const store = useStore()
    const myheader = {
      AccessToken: store.getters.token
    }
    const userRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const { Id } = route.params
    const state = reactive({
      btnLoading: false,
      //接口返回的角色列表
      roles: [],
      roleIds: null,
      Id: Id,
      imageUrl: null,
      userForm: {
        LoginName: '',
        UserName: '',
        PhoneNo: '',
        UserRoles: [],
        ProfilePhotoPath: ''
      },
      rules: {
        LoginName: [
          { required: 'true', message: '请输入登陆账户', trigger: ['change'] }
        ],
        UserName: [
          { required: 'true', message: '请输入用户姓名', trigger: ['change'] }
        ],
        PhoneNo: [{ required: true, validator: checkphone, trigger: 'change' }]
      }
    })

    const uploadUrl = computed(() => {
      return `${config.apiUrl}/upload/uploadFile`
    })

    const uploadImage = async (param) => {
      const formData = new FormData()
      formData.append('file', param.file)
      formData.append('FileName', new Date().getTime() + '.jpg')
      const res = await uploadFile(formData)
      state.userForm.ProfilePhotoPath = res.BussinessData.FileUrl
    }

    const handleAvatarSuccess = (res) => {
      console.log('handleAvatarSuccess => ' + res)
    }

    const loadAllRoles = async () => {
      const response = await getRoleList(1, 10000)
      if (response.BussinessCode === 0) {
        const roleList = response.BussinessData
        roleList.forEach((r) => {
          r.Checked = false
        })
        state.roles = roleList
        //标记是否选中角色
        state.userForm.UserRoles.forEach((ur) => {
          state.roles.forEach((r) => {
            if (r.Id === ur.Id) {
              r.Checked = true
            }
          })
        })
      } else {
        ElMessage.error(response.BussinessMsg)
      }
    }

    onMounted(async () => {
      const Id = state.Id
      if (Id === null || Id === '-1') {
        await loadAllRoles()
      } else {
        await loadUserInfo(Id)
      }
    })

    const loadUserInfo = async (Id) => {
      const response = await getUserDetail({ Id })
      if (response.BussinessCode !== 0) {
        ElMessage.error(response.BussinessMsg)
        return
      }
      const data = response.BussinessData
      state.userForm.UserName = data.UserName
      state.userForm.LoginName = data.LoginName
      state.userForm.PhoneNo = data.PhoneNo
      state.userForm.UserRoles = data.RoleList
      state.userForm.ProfilePhotoPath = data.ProfilePhotoPath
      loadAllRoles()
    }

    const onSubmit = () => {
      state.btnLoading = true
      userRef.value.validate(async (vaild) => {
        if (vaild) {
          const Id = state.Id === '-1' ? '' : state.Id
          let roleIds = ''
          state.roles.forEach((r) => {
            if (r.Checked) {
              roleIds += r.Id + ','
            }
          })
          roleIds = roleIds.substring(0, roleIds.lastIndexOf(','))
          //必须选择角色才能提交
          if (!roleIds) {
            state.buttonLoading = false
            ElMessage.error('请选择角色')
            state.btnLoading = false
            return
          }

          // 默认新增用 post 方法
          const params = {
            Id: Id,
            UserName: state.userForm.UserName,
            LoginName: state.userForm.LoginName,
            PhoneNo: state.userForm.PhoneNo,
            RoleIds: roleIds,
            ProfilePhotoPath: state.userForm.ProfilePhotoPath
          }
          await editUser(params)
          ElMessage.success(Id ? '修改成功' : '添加成功')
          state.btnLoading = false
          router.push({ path: '/right/user_list' })
        } else {
          state.btnLoading = false
        }
      })
    }

    return {
      ...toRefs(state),
      userRef,
      onSubmit,
      uploadUrl,
      myheader,
      handleAvatarSuccess,
      uploadImage
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #ddd;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: rgb(42, 132, 206);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
