<template>
  <view class="ciy-page">
    <view class="ciy-title mk bg2">
      <view class="title">新增实验室成员</view>
      <button class="btn def sm" @click="goBack">返回</button>
    </view>
    <view class="main bg4 flex1 overflow-auto px4 py3">
      <form class="ciy-form-group">
        <view class="ciy-form">
          <label class="imp char4">姓名</label>
          <input 
            type="text" 
            v-model="form.name" 
            placeholder="请输入成员姓名"
            class="ciy-edit px2 py1 bg1 rounded"
            required
          />
        </view>
        <view class="ciy-form">
          <label class="char4">头像</label>
          <view class="flex flex-center">
            <image 
              :src="form.icon || '/lab/lab.png'" 
              mode="aspectFill" 
              class="w-12 h-12 rounded-full mr3"
            ></image>
            <button class="btn def sm" @click="chooseAvatar">选择图片</button>
          </view>
        </view>
        <view class="ciy-form">
          <label class="char4">头衔</label>
          <picker 
            mode="selector" 
            :range="titleOptions"
            :range-key="'label'"
            class="px2 py1 bg1 rounded w-full"
			      @change="handlePickerChange($event, 'usertitle')"
          >
            <view class="txt-left px2 py1">{{getPickerCurrentLabel('usertitle')  }}</view>
          </picker>
        </view>
        <view class="ciy-form">
          <label class="imp char4">状态</label>
          <picker 
            mode="selector" 
            :range="statusOptions"
            :range-key="'label'"
            class="px2 py1 bg1 rounded w-full"
			      @change="handlePickerChange($event, 'role')"
            required
          >
            <view class="txt-left px2 py1">{{ getPickerCurrentLabel('role') }}</view>
          </picker>
        </view>
        <view class="ciy-form">
          <label class="char4">学历</label>
          <picker 
            mode="selector" 
            :range="educationOptions"
            :range-key="'label'"
            class="px2 py1 bg1 rounded w-full"
			      @change="handlePickerChange($event, 'education')"
          >
            <view class="txt-left px2 py1">{{ getPickerCurrentLabel('education') }}</view>
          </picker>
        </view>
        <view class="ciy-form">
          <label class="char4">编号</label>
          <input 
            type="text" 
            v-model="form.sn" 
            placeholder="如 LAB-2024-001"
            class="ciy-edit px2 py1 bg1 rounded"
          />
        </view>
        <view class="ciy-form">
          <label class="char4">性别</label>
          <picker 
            mode="selector" 
            :range="sexOptions"
            :range-key="'label'"
            class="px2 py1 bg1 rounded w-full"
			      @change="handlePickerChange($event, 'sex')"
          >
            <view class="txt-left px2 py1">{{ getPickerCurrentLabel('sex') }}</view>
          </picker>
        </view>
        <view class="ciy-form">
          <label class="char4">加入日期</label>
          <picker 
            mode="date" 
            v-model="form.addtimesText"
            start="2000-01-01"
            end="2100-12-31"
            class="px2 py1 bg1 rounded w-full"
			      @change="handleDateChange"
          >
            <view class="txt-left px2 py1">{{ form.addtimesText || '请选择日期' }}</view>
          </picker>
        </view>
        <view class="ciy-form">
          <label class="char4">手机号</label>
          <input 
            type="number" 
            v-model="form.mobile" 
            placeholder="请输入11位手机号"
            class="ciy-edit px2 py1 bg1 rounded"
            maxlength="11"
          />
        </view>
        <view class="ciy-form">
          <label class="char4">邮箱</label>
          <input 
            type="email" 
            v-model="form.email" 
            placeholder="请输入邮箱地址"
            class="ciy-edit px2 py1 bg1 rounded"
          />
        </view>
        <view class="ciy-form">
          <label class="char4">初始密码</label>
          <input 
            type="password" 
            v-model="form.password" 
            placeholder="默认：1"
            class="ciy-edit px2 py1 bg1 rounded"
            :value="form.password || '1'"
          />
        </view>
      </form>
      <view class="ciy-form-bottom mt4">
        <button 
          class="btn man lgg long" 
          @click="submitForm"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '提交成员信息' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isSubmitting: false, 
      form: {
		laborgid: 0,
		stpstatus: 10, 
		userlevel:10,
		dvotecnt:0,
        name: '',         
        icon: '',         
        usertitle: 0,      
        role: 30,         
        education: 50,   
        sn: '',          
        sex: 90,          
        addtimesText: '',  
        addtimes: 0,       
        mobile: '',        
        email: '',         
        password: '1' 
      },
      titleOptions: [
        { value: 0, label: '无头衔' },
        { value: 10, label: '主任' },
        { value: 20, label: '副主任' },
        { value: 30, label: '顾问' },
        { value: 40, label: '名誉主任' },
        { value: 50, label: '教授' },
        { value: 60, label: '副教授' },
        { value: 70, label: '讲师' },
        { value: 80, label: '研究员' }
      ],
      statusOptions: [
        { value: 10, label: '负责人' },
        { value: 20, label: '科研秘书' },
        { value: 30, label: '在册成员' },
        { value: 40, label: '历史成员' },
        { value: 50, label: '外部成员' }
      ],
      educationOptions: [
        { value: 50, label: '本科' },
        { value: 60, label: '硕士' },
        { value: 70, label: '博士' }
      ],
      sexOptions: [
        { value: 10, label: '男' },
        { value: 20, label: '女' },
        { value: 90, label: '其他' }
      ],
      statusMap: { 10: '负责人', 20: '科研秘书', 30: '在册成员', 40: '历史成员', 50: '外部成员' },
      educationMap: { 50: '本科', 60: '硕士', 70: '博士' },
      sexMap: { 10: '男', 20: '女', 90: '其他' },
      titleMap: { 0: '无头衔', 10: '主任', 20: '副主任', 30: '顾问', 40: '名誉主任', 50: '教授', 60: '副教授', 70: '讲师', 80: '研究员' }
    };
  },
  methods: {
    goBack() {
      uni.navigateBack({ delta: 1 });
    },
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.form.icon = tempFilePath;
        }
      });
    },
	  handlePickerChange(e, type) {
	    const selectedIndex = Number(e.detail.value);
	    const optionMap = {
	      usertitle: this.titleOptions,
	      role: this.statusOptions,
	      education: this.educationOptions,
	      sex: this.sexOptions
	    };
	    const optionList = optionMap[type];
	    if (!optionList || !optionList[selectedIndex]) return;
	    this.form[type] = optionList[selectedIndex].value;
	  },
	  getPickerCurrentLabel(type) {
	    const optionMap = {
	      usertitle: this.titleOptions,
	      role: this.statusOptions,
	      education: this.educationOptions,
	      sex: this.sexOptions
	    };
	    const optionList = optionMap[type];
	    const currentValue = this.form[type];
	    if (!optionList) return '请选择';
	    // 3. 查找匹配项
	    const currentOption = optionList.find(item => item.value === currentValue);
	    // 4. 返回显示文本
	    return currentOption ? currentOption.label : '请选择';
	  },
	    handleDateChange(e) {
	      const selectedDate = e.detail.value;
	      this.form.addtimesText = selectedDate;
	      this.form.addtimes = new Date(selectedDate).getTime();
	    },

    async submitForm() {
      if (!this.form.name) {
        return uni.showToast({ title: '请输入成员姓名', icon: 'none' });
      }
      if (!this.form.addtimes) {
        return uni.showToast({ title: '请选择加入日期', icon: 'none' });
      }
      if (this.form.mobile && !/^1[3-9]\d{9}$/.test(this.form.mobile)) {
        return uni.showToast({ title: '请输入有效的11位手机号', icon: 'none' });
      }
      if (this.form.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.form.email)) {
        return uni.showToast({ title: '请输入有效的邮箱地址', icon: 'none' });
      }
      const postData = this.form;

      try {
          var retjson = await this.callfunc({
          func: 'adduser.add',
          data: postData     
         });
        if (retjson.code !== 1) { 
          return uni.showToast({ title: retjson.msg || '新增成员失败', icon: 'none' });
        }
        uni.showToast({ title: '新增成员成功', icon: 'success' });
        setTimeout(() => {
          this.goBack();
        }, 1500);
        console.log('提交的成员信息：', this.form);
      } catch (err) {
        uni.showToast({ title: '提交失败，请重试', icon: 'none' });
        console.error('新增成员失败：', err);
      }
    }
  }
};
</script>

<style scoped>
/* 补充样式：适配表单布局 */
.ciy-edit {
  width: 100%;
  height: 2rem;
  border: 1px solid var(--bg6);
  border-radius: 0.3rem;
}
.w-12 { width: 3rem; }
.h-12 { height: 3rem; }
</style>