<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
	<view class="health-form">
    <Navbar title="健康信息" :showRightText="true" :isBack="false" />
	<scroll-view style="width: 100%;height: 85vh;" scroll-y="true">
		<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" style="margin-left: 20rpx;">
		  <u-form-item label="身高(cm)" prop="height" borderBottom required labelWidth="200rpx">
			<u--input
			  v-model.number="form.height"
			  border="none"
			  placeholder="请输入身高cm"
			  type="number"
			></u--input>
		  </u-form-item>

		  <u-form-item label="体重(kg)" prop="weight" borderBottom required labelWidth="200rpx">
			<u--input
			  v-model.number="form.weight"
			  border="none"
			  placeholder="请输入体重kg"
			  type="number"
			></u--input>
		  </u-form-item>

		  <u-form-item label="体重控制" prop="weightControl" borderBottom labelWidth="200rpx" @click="showSelector('weightControl')">
			<u--input
			  v-model="weightControlName"
			  disabled
			  disabledColor="#ffffff"
			  placeholder="请选择"
			  border="none"
			></u--input>
			<u-icon slot="right" name="arrow-right"></u-icon>
		  </u-form-item>

		  <u-form-item label="BMI" prop="bmi" borderBottom labelWidth="200rpx">
			<u--input
			  v-model="form.bmi"
			  disabled
			  border="none"
			  disabledColor="#ffffff"
			  placeholder="请输入身高、体重"
			></u--input>
		  </u-form-item>

		  <u-form-item label="劳动强度" prop="labourIntensity" borderBottom labelWidth="200rpx" @click="showSelector('labourIntensity')">
			<u--input
			  v-model="labourIntensityName"
			  disabled
			  border="none"
			  disabledColor="#ffffff"
			  placeholder="请选择"
			></u--input>
			<u-icon slot="right" name="arrow-right"></u-icon>
		  </u-form-item>

		  <u-form-item label="是否住院" prop="ifHospitalized" borderBottom labelWidth="200rpx" @click="showSelector('ifHospitalized')">
			<u--input
			  v-model="ifHospitalizedName"
			  disabled
			  border="none"
			  disabledColor="#ffffff"
			  placeholder="请选择"
			></u--input>
			<u-icon slot="right" name="arrow-right"></u-icon>
		  </u-form-item>

		  <u-form-item label="医嘱" borderBottom labelWidth="200rpx">
			<text class="u-content-color">暂无医嘱信息</text>
		  </u-form-item>
		  
		  <u-form-item label="孕否" prop="pregnantStatus" borderBottom labelWidth="200rpx" @click="showSelector('pregnantStatus')">
		  			<u--input
		  			  v-model="pregnantStatusName"
		  			  disabled
		  			  border="none"
		  			  disabledColor="#ffffff"
		  			  placeholder="请选择"
		  			></u--input>
		  			<u-icon slot="right" name="arrow-right"></u-icon>
		  </u-form-item>
		  

		  <u-form-item label="过敏源" prop="allergen" borderBottom labelWidth="200rpx">
			<u--input
			  v-model="form.allergen"
			  border="none"
			  placeholder="请输入过敏源"
			></u--input>
		  </u-form-item>
		</u--form>
		<view class="chronic-diseases">
			<view style="display: flex;justify-content: space-between;">
				<text class="chronic-diseases__label">慢性病</text>
				<text style="color: #ccc;">请从下方选择慢性病</text>
			</view> 
			<u-checkbox-group v-model="form.chronicDiseases" borderBottom placement="column" iconSize="16">
				<u-checkbox
				  v-for="(item, index) in chronicList"
				  :key="index"
				  :name="item.chronicId"
				  :label="item.chronicName"
				  style="display: flex;justify-content: space-between;width: 100%;padding: 10rpx 20rpx;"
				  shape="squrd"
				></u-checkbox>
			</u-checkbox-group>
		</view>
	</scroll-view>
    <view class="submit-btn">
      <u-button type="warning" text="保存" @click="handleSubmit"></u-button>
    </view>

    <u-action-sheet
      v-if="currentSelector"
      :show="selectorVisible"
      :actions="getSelectorOptions(currentSelector)"
      :title="getSelectorTitle(currentSelector)"
      @close="hideSelector"
      @select="handleSelectorSelect"
    >
    </u-action-sheet>
  </view>
</template>

<script>
	import { dictHealthChronicApi,healthDetailApi, editHealthInfoApi } from '@/api/mine/health.js'
export default {
  data() {
    return { 
	  fontValue:uni.getStorageSync('fontSize') || 8,
      form: {
        height: null,
        weight: null,
        weightControl: '',
        bmi: '',
        labourIntensity: '',
        ifHospitalized: '',
        allergen: '',
        chronicDiseases: []
      },
      selectorVisible: false,
      currentSelector: null,
      selectors: {
        weightControl: { options: [{ name: '减重', value: '1' }, { name: '增重', value: '2' }], title: '请选择体重控制' },
        labourIntensity: { options: [{ name: '轻劳力', value: '1' }, { name: '中等强度劳动', value: '2' }, { name: '重强度劳动', value: '3' }, { name: '孕妇(早期)', value: '4' }, { name: '孕妇(中期)', value: '5' }, { name: '孕妇(晚期)', value: '6' }, { name: '乳母', value: '7' }], title: '请选择劳动强度' },
        ifHospitalized: { options: [{ name: '是', value: '1' }, { name: '否', value: '2' }], title: '是否住院' },
		pregnantStatus: { options: [{ name: '保密', value: '0' },{ name: '是', value: '2' }, { name: '否', value: '1' }], title: '是否怀孕' }
      },
      chronicDiseaseOptions: [
        { label: '糖尿病', value: 'diabetes' },
        { label: '肾结石', value: 'kidney_stone' },
        { label: '心脏疾病', value: 'heart_disease' },
        { label: '痛风', value: 'gout' }
      ],
      rules: {
        height: { type: 'number', required: true, message: '请输入身高', trigger: ['blur', 'change'] },
        weight: { type: 'number', required: true, message: '请输入体重', trigger: ['blur', 'change'] },
        // labourIntensity: { type: 'string',required: true, message: '请选择劳动强度', trigger: ['change'] }
      },
      weightControlName: '',
      labourIntensityName: '',
      ifHospitalizedName: '',
	  pregnantStatusName: '',
	  chronicList:[]
    }
  },
  watch: {
    'form.height': 'calculateBMI',
    'form.weight': 'calculateBMI',
    'form.weightControl': 'updateDisplayBodyTypeName',
    'form.labourIntensity': 'updateDisplayLaborIntensityName',
    'form.ifHospitalized': 'updateDisplayHousingName',
    'form.pregnantStatus': 'updatePregnantStatusName',
	
  },
  onLoad() {
  	this.getHealthDetail()
	this.getHealthChronic()
  },
  methods: {
	  //获取慢性病字典
	  async getHealthChronic() {
	  	let param = {}
	  	const res = await dictHealthChronicApi(param)
		this.chronicList = res.data
	  	console.log(res, '慢性病')  
	  },
	  //获取健康信息
	  async getHealthDetail() {
	  	let param = {
			"custId": uni.getStorageSync('custId')
		}
	  	const res = await healthDetailApi(param)
		this.form = res.data;
		if(this.form.chronicIds){
			this.form.chronicDiseases = this.form.chronicIds.split(",")
		}
	  	console.log(res, '详情')  
	  }, 
	  
	  
    calculateBMI() {
      // if (this.form.height && this.form.weight) {
      //   const heightInMeters = this.form.height / 100
      //   const bmi = (this.form.weight / (heightInMeters * heightInMeters)).toFixed(1)
      //   this.form.bmi = bmi
      // }
    },
    showSelector(selector) {
      this.currentSelector = selector;
      this.selectorVisible = true;
    },
    hideSelector() {
      this.currentSelector = null;
      this.selectorVisible = false;
    },
    getSelectorOptions(selector) {
      return this.selectors[selector]?.options || [];
    },
    getSelectorTitle(selector) {
      return this.selectors[selector]?.title || '';
    },
    handleSelectorSelect(e) {
      this.form[this.currentSelector] = e.value;
	  
      this.hideSelector();
    },
    updateDisplayBodyTypeName() {
      this.weightControlName = this.getDisplayName('weightControl', this.form.weightControl);
    },
    updateDisplayLaborIntensityName() {
      this.labourIntensityName = this.getDisplayName('labourIntensity', this.form.labourIntensity);
    },
    updateDisplayHousingName() {
		this.ifHospitalizedName = this.getDisplayName('ifHospitalized', this.form.ifHospitalized);
    },
	updatePregnantStatusName() {
		this.pregnantStatusName = this.getDisplayName('pregnantStatus', this.form.pregnantStatus);
    },
    getDisplayName(selector, value) {
      const options = this.selectors[selector]?.options || [];
      const selectedOption = options.find(option => option.value == value);
      return selectedOption ? selectedOption.name : '';
    },
    handleSubmit() {
		console.log('Form submitted:', this.form);
      this.$refs.uForm.validate().then(valid => {
        if (valid) {
          console.log('Form submitted:', this.form);
		  if(this.form.chronicDiseases&&this.form.chronicDiseases.length>0){
			this.form.chronicIds = this.form.chronicDiseases.join(",")
		  }
		  editHealthInfoApi(this.form).then((res) => {
			uni.$u.toast('保存成功');
			this.getHealthDetail()
		  })
          
        } else {
          uni.$u.toast('请填写完整信息');
        }
      }).catch(errors => {
        console.error('Validation failed:', errors);
        uni.$u.toast('请检查并修正错误');
      });
    },
    hideKeyboard() {
      uni.hideKeyboard();
    }
  }
}
</script>

<style scoped lang="scss">
.health-form {
  padding: 20rpx;
  background-color: #ffffff;

  .chronic-diseases {
    margin-top: 20rpx;

    &__label {
      font-size: 28rpx;
      color: $u-main-color;
      margin-bottom: 20rpx;
      display: block;
    }
  }

  .submit-btn {
    margin-top: 40rpx;
  }
}

::v-deep .u-form-item {
  min-height: 100rpx;

  &__body__right__content__slot {
    text-align: right;
  }
}

::v-deep .u-checkbox {
  margin-bottom: 16rpx;
}
</style>
