<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import { FormInstance, FormRules, UploadProps } from "element-plus";
import { getRoleManageList, getUserList } from "@/api/business";
import {
  getDeptManageList,
  saveUserInfo,
  updateUserInfo,
  downloadFile
} from "@/api/system";
import { message } from "@/utils/message";
import { Plus } from "@element-plus/icons-vue";
defineOptions({
  name: "CreateForm"
});

const props = defineProps({
  createFlag: {
    type: Boolean,
    default: false
  },
  updateFrom: {
    type: Object,
    default: () => {
      return {};
    }
  },
  accountFromType: {
    type: String,
    default: ""
  },
  closeDrawer: {
    type: Function
  }
});
const modalVisible = ref(false);
console.log(props.accountFromType);
// 监听 props.message 的变化，并更新 modalVisible
watch(
  () => props.createFlag,
  newValue => {
    modalVisible.value = newValue; // 更新 modalVisible
    if (newValue) {
      if (
        props.accountFromType === "edit" ||
        props.accountFromType === "view"
      ) {
        getFlowDetails(props.updateFrom);
      }
    }
  }
);
watch(
  () => props.accountFromType,
  newValue => {
    console.log(newValue, "newValue");
  }
);
const ruleAccountFormRef = ref<FormInstance>();
const accountForm = reactive({
  id: "",
  headPicId: "",
  account: "",
  username: "",
  deptId: "",
  roleIds: [],
  remark: ""
});
const deptList = ref([]);
const roleNameList = ref([]);
const userNameList = ref([]);
const rules = reactive<FormRules>({
  headPicId: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  account: [{ required: true, message: "请输入", trigger: "blur" }],
  username: [{ required: true, message: "请输入", trigger: "blur" }],
  deptId: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  roleIds: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  remark: [{ required: true, message: "请输入", trigger: "blur" }]
});

const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log(response, "response");
  accountForm.headPicId = response.data;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  console.log(rawFile);
  // if (rawFile.type !== "image/jpeg") {
  //   // ElMessage.error("Avatar picture must be JPG format!");
  //   return false;
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   // ElMessage.error("Avatar picture size can not exceed 2MB!");
  //   return false;
  // }
  return true;
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(accountForm);
      // // console.log("submit!");
      // const createForm = {
      //   id: "",
      //   flowName: accountForm.flowName,
      //   remark: accountForm.remark,
      //   flowType: accountForm.flowType,
      //   roleIds: accountForm.roleIds,
      // };
      if (props.accountFromType === "edit") {
        updateUserInfo(accountForm).then(res => {
          if (res.code === 200) {
            message("修改成功", { type: "success" });
            props.closeDrawer();
          }
        });
      } else {
        saveUserInfo(accountForm).then(res => {
          if (res.code === 200) {
            message("新建成功", { type: "success" });
            props.closeDrawer();
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // formEl.resetFields();
  accountForm.id = "";
  accountForm.headPicId = "";
  accountForm.account = "";
  accountForm.username = "";
  accountForm.deptId = "";
  accountForm.roleIds = [];
  accountForm.remark = "";
};
const handleDrawerClosed = () => {
  accountForm.id = "";
  accountForm.headPicId = "";
  accountForm.account = "";
  accountForm.username = "";
  accountForm.deptId = "";
  accountForm.roleIds = [];
  accountForm.remark = "";
  props.closeDrawer();
};

const getDeptManageLists = async () => {
  const res: any = await getDeptManageList({
    baseName: "",
    deptCode: "",
    pageNum: 1,
    pageSize: 20
  });
  console.log(res);
  if (res.code == 200) {
    deptList.value = res.data.records;
  }
};
const getRoleManageLists = async () => {
  const res: any = await getRoleManageList({
    roleName: "",
    pageNum: "1",
    pageSize: "10"
  });
  // console.log(res);
  if (res.code == 200) {
    roleNameList.value = res.data.records;
  }
};
const getUserLists = async () => {
  const res: any = await getUserList({
    userName: "",
    deptId: "",
    roleId: "",
    pageNum: "1",
    pageSize: "10"
  });
  // console.log(res);
  if (res.code == 200) {
    userNameList.value = res.data.records;
  }
};
const getFlowDetails = (value: any) => {
  accountForm.id = props.accountFromType === "edit" ? value.id : "";
  accountForm.headPicId = value.headPicId;
  accountForm.account = value.account;
  accountForm.username = value.username;
  accountForm.deptId = value.deptId;
  accountForm.roleIds = value.userRoleList?.map(item => {
    return item.roleId;
  });
  accountForm.remark = value.remark;
};
const drawerName = (type: any) => {
  if (type === "edit") {
    return "编辑账号";
  } else if (type === "view") {
    return "查看账号";
  } else {
    return "新建账号";
  }
};
onMounted(() => {
  getDeptManageLists();
  getRoleManageLists();
  getUserLists();
});
</script>

<template>
  <div>
    <el-drawer
      v-model="modalVisible"
      modal-class="drawer_content"
      :with-header="false"
      @closed="handleDrawerClosed"
    >
      <div class="drawer_header">
        <span>{{ drawerName(props.accountFromType) }}</span>
      </div>
      <div class="drawer_box">
        <el-form
          :model="accountForm"
          :rules="rules"
          ref="ruleAccountFormRef"
          label-width="auto"
        >
          <el-form-item label="头像" prop="headPicId">
            <el-upload
              class="avatar-uploader"
              action="/know-sub/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <!-- <img
                v-if="accountForm.headPicId"
                :src="imageUrl"
                class="avatar"
              /> -->
              <img
                v-if="accountForm.headPicId"
                :src="
                  props.accountFromType === 'edit'
                    ? downloadFile(accountForm.headPicId)
                    : imageUrl
                "
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名" prop="account">
            <el-input
              v-model="accountForm.account"
              autocomplete="off"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="username">
            <el-input
              v-model="accountForm.username"
              autocomplete="off"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="所属部门" prop="deptId">
            <el-select
              v-model="accountForm.deptId"
              clearable
              placeholder="请选择"
              class="w-full"
            >
              <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.deptName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="roleIds">
            <el-select
              v-model="accountForm.roleIds"
              multiple
              clearable
              collapse-tags
              placeholder="请选择"
              popper-class="custom-header"
              :max-collapse-tags="3"
              class="w-full"
            >
              <el-option
                v-for="item in roleNameList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="accountForm.remark"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
        <div class="drawer_footer" v-if="props.accountFromType !== 'view'">
          <el-button plain @click="resetForm(ruleAccountFormRef)"
            >重置</el-button
          >
          <el-button type="primary" @click="submitForm(ruleAccountFormRef)"
            >确定</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-drawer__body) {
  padding: 0 !important;
}

.drawer_content {
  .drawer_header {
    box-sizing: border-box;
    height: 96px;
    padding: 24px;
    line-height: 65px;
    border-bottom: 1px solid #e9e9e9;

    span {
      padding-left: 8px;
      font-size: 20px;
      border-left: 6px solid #0052d9;
    }
  }

  .drawer_box {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100vh - 96px);
    padding: 24px;

    .drawer_footer {
      display: flex;
      justify-content: flex-end;
    }
  }

  .avatar-uploader {
    display: block;
    width: 100px;
    height: 100px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
  }

  .avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    // display: block;
    // border: 1px solid #d9d9d9;
  }

  .avatar-uploader .el-upload {
    position: relative;
    overflow: hidden;
    cursor: pointer;
    border-radius: 6px;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

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