<template>
  <view class="profile-page">
    <!-- 表单区域 -->
    <view class="form-section bg-white">
      <!-- 姓名 -->
      <form-input
        name="姓名"
        :required="true"
        :form="formData"
        title="anotherName"
        @change="handleFieldChange"
      />
      <!-- 头像 -->
      <common-cell name="头像">
        <view class="form-content__wrapper" @click="chooseAvatar">
          <view class="flex-main-content flex items-center">
            <image
              v-if="formData.avatar"
              class="avatar-preview"
              :src="formData.avatar"
              mode="aspectFill"
            />
          </view>
          <uni-icons class="form-arrow" type="arrowright"></uni-icons>
        </view>
      </common-cell>
      <!-- 性别 -->
      <form-select
        name="性别"
        :form="formData"
        title="gender"
        :range="genderOptions"
        @change="handleFieldChange"
      />
      <!-- 手机号（不可修改） -->
      <common-cell name="手机号 (不可修改)">
        <view class="form-content__wrapper">
          <view class="flex-main-content text-dark">{{ formData.mobile }}</view>
        </view>
      </common-cell>
      <!-- 岗位 -->
      <form-select
        name="岗位"
        :form="formData"
        title="position"
        :range="positionOptions"
        @change="handleFieldChange"
      />
      <!-- 职称 -->
      <form-select
        name="职称"
        :form="formData"
        title="title"
        :range="titleOptions"
        @change="handleFieldChange"
      />
      <!-- 科室 -->
      <common-cell name="科室">
        <view class="form-content__wrapper" @click="openDepartmentSelect">
          <view
            class="flex-main-content text-right"
            :class="{ 'text-placeholder': !formData.departmentName }"
          >
            {{ formData.departmentName || "请选择" }}
          </view>
          <uni-icons class="form-arrow" type="arrowright"></uni-icons>
        </view>
      </common-cell>

      <!-- 个人介绍 -->
      <form-textarea
        name="个人介绍"
        :form="formData"
        title="memberTroduce"
        :word-limit="500"
        @change="handleFieldChange"
      />
    </view>
    <!-- 底部按钮 -->
    <view class="button-footer">
      <view class="btn btn-cancel" @click="handleCancel">取消</view>
      <view class="btn btn-save" @click="handleSave">保存</view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";

import useGuard from "@/hooks/useGuard.js";
import { chooseAndUploadImage } from "@/utils/file.js";
import useAccountStore from "@/store/account.js";
import { storeToRefs } from "pinia";
import CommonCell from "@/components/form-template/common-cell.vue";
import FormInput from "@/components/form-template/form-cell/form-input.vue";
import FormSelect from "@/components/form-template/form-cell/form-select.vue";
import FormTextarea from "@/components/form-template/form-cell/form-textarea.vue";
import api from "@/utils/api.js";
const { account, doctorInfo } = storeToRefs(useAccountStore());
const { useLoad } = useGuard();
const { getDoctorInfo } = useAccountStore();
// 表单数据
const formData = ref({
  anotherName: "",
  avatar: "",
  gender: "",
  mobile: "",
  position: "",
  title: "",
  department: "",
  departmentName: "",
  departmentId: "",
  memberTroduce: "",
});

// 选项数据
const genderOptions = [
  { label: "男", value: "0" },
  { label: "女", value: "1" },
];
const positionOptions = ["医生", "护士", "药师", "技师", "其他"];
const titleOptions = ["主任医师", "副主任医师", "主治医师", "医师", "其他"];
// 字段变更处理
const handleFieldChange = (e) => {
  if (e.title === "gender") {
    formData.value[e.title] = e.value.value;
  } else {
    formData.value[e.title] = e.value;
  }
};

// 选择头像
const chooseAvatar = async () => {
  const url = await chooseAndUploadImage();
  if (url) {
    formData.value.avatar = url;
  }
};
const handleCancel = () => {
  uni.navigateBack();
};
// 保存
const handleSave = async () => {
  createDoctorInfo();
};
useLoad(() => {
  if (doctorInfo.value) {
    formData.value = { ...doctorInfo.value };
  } else {
    formData.value.mobile = account.value.mobile;
  }
});

// 创建医生信息
const createDoctorInfo = async () => {
  if (!formData.value.anotherName) {
    uni.showToast({
      title: "请输入姓名",
      icon: "none",
    });
    return;
  }
  let params = {
    anotherName: formData.value.anotherName,
    avatar: formData.value.avatar,
    gender: formData.value.gender,
    mobile: formData.value.mobile,
    weChatOpenId: account.value.openid,
    deptIds: [],
    loginTypes: ["wxApp"],
    corpId: account.value.corpId,
  };
  const res = await api("addCorpMember", {
    params,
  });
  if (res.success && res.data) {
    uni.showToast({
      title: "创建成功",
      icon: "success",
    });
    await getDoctorInfo();
    uni.navigateBack();
  } else {
    uni.showToast({
      title: "创建失败",
      icon: "none",
    });
    console.error("创建医生信息失败:", res);
  }
};

const updateDoctorInfo = async () => {
  let params = {
    anotherName: formData.value.anotherName,
    avatar: formData.value.avatar,
    gender: formData.value.gender,
  };
  const res = await api("updateCorpMember", {
    params,
  });
  if (res.success && res.data) {
    uni.showToast({
      title: "更新成功",
      icon: "success",
    });
  }
  await getDoctorInfo();
  uni.navigateBack();
};
// 打开科室选择
const openDepartmentSelect = () => {
  uni.navigateTo({
    url: "/pages/work/department-select",
    events: {
      deptSelected: ({ name, deptId }) => {
        formData.value.department = name || "";
        formData.value.departmentName = name || "";
        formData.value.departmentId = deptId || "";
      },
    },
  });
};
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.form-section {
  margin-top: 20rpx;
}

.form-content__wrapper {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  text-align: right;
  font-size: 30rpx;

  input {
    text-align: right;
  }
}

.text-placeholder {
  color: #999;
}

.avatar-preview {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #e5e5e5;
}

.avatar-placeholder {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: center;

  .avatar-icon {
    font-size: 50rpx;
    color: #999;
  }
}

.button-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 20rpx 30rpx;
  background: #fff;
  border-top: 1px solid #eee;
  gap: 20rpx;
  z-index: 100;

  .btn {
    flex: 1;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    border-radius: 8rpx;
    font-size: 34rpx;
  }

  .btn-cancel {
    background: #fff;
    border: 1px solid #007aff;
    color: #007aff;
  }

  .btn-save {
    background: #007aff;
    color: #fff;
  }
}
</style>

