<template>
  <view class="container" style="paddingBottom:1rpx;">
    <u-navbar
    leftIconSize="40rpx"
    leftIconColor="#333333"
    title="活动记录"
  >
  </u-navbar>
    <view class="section">
      <view class="section-title">{{ title}}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="160rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
          <u-form-item label="活动名称" prop="name" required >
              <u--input v-model="form.name"  placeholder="请填写活动名称"
                inputAlign="left" :customStyle="getInputStyle('name')"></u--input>
            </u-form-item>
          <u-form-item label="类型" prop="typeName" required @click="handleType" class="with-arrow">
              <u--input v-model="form.typeName" disabled disabledColor="#ffffff" placeholder="请选择类型"
                inputAlign="left" :customStyle="getInputStyle('typeName')"></u--input>
            </u-form-item>
            <u-form-item label="活动地点" required prop="place" >
              <u--input v-model="form.place"  placeholder="请填写活动地点"
                inputAlign="left" :customStyle="getInputStyle('place')"></u--input>
            </u-form-item>
            <u-form-item label="成员" required prop="partner" >
              <u--input v-model="form.partner" placeholder="请填写成员"
                inputAlign="left" :customStyle="getInputStyle('partner')"></u--input>
            </u-form-item>
            <u-form-item label="开始时间" prop="startTime" required @click="selectStartTime()" class="with-arrow">
            <u--input v-model="form.startTime" disabled disabledColor="#ffffff" placeholder="请选择开始时间" inputAlign="left" :customStyle="getInputStyle('startTime')"></u--input>
          </u-form-item>
          <u-form-item label="结束时间" prop="endTime"  @click="selectEndTime()" class="with-arrow">
            <u--input v-model="form.endTime" disabled disabledColor="#ffffff" placeholder="请选择结束时间" inputAlign="left" :customStyle="getInputStyle('endTime')"></u--input>
          </u-form-item>
            <u-form-item label="活动量" prop="activityVolumeName" required @click="handleActivityVolume" class="with-arrow">
              <u--input v-model="form.activityVolumeName" disabled disabledColor="#ffffff" placeholder="请选择活动量"
                inputAlign="left" :customStyle="getInputStyle('activityVolumeName')"></u--input>
            </u-form-item>
            <u-form-item label="总费用" prop="totalCost" >
              <u--input v-model="form.totalCost" type="number"  placeholder="请填写总费用"
                inputAlign="left" :customStyle="getInputStyle('totalCost')">
                <template #suffix>
					<up-text
						text="元"
					></up-text>
				</template></u--input>
            </u-form-item>
            <u-form-item label="费用明细" prop="costDetail"  labelPosition="top">
            <u--textarea v-model="form.costDetail" placeholder="请填写费用明细" autoHeight inputAlign="right" count
              maxlength="2000" height="45" style="border: 2rpx solid #dcdfe6 !important; min-height: 45rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="饮食" prop="foods"  labelPosition="top">
            <u--textarea v-model="form.foods" placeholder="请填写饮食" autoHeight inputAlign="right" count
              maxlength="2000" height="45" style="border: 2rpx solid #dcdfe6 !important; min-height: 45rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="收获" prop="harvest"  labelPosition="top">
            <u--textarea v-model="form.harvest" placeholder="请填写收获" autoHeight inputAlign="right" count
              maxlength="2000" height="45" style="border: 2rpx solid #dcdfe6 !important; min-height: 45rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="备注" prop="remark"  labelPosition="top">
            <u--textarea v-model="form.remark" placeholder="请填写备注" autoHeight inputAlign="right" count
              maxlength="2000" height="45" style="border: 2rpx solid #dcdfe6 !important; min-height: 45rpx;"></u--textarea>
          </u-form-item>
        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
        <u-picker itemHeight="88" :show="showType" :columns="typeList" keyName="dictLabel" @cancel="handleTypeCancel"
        @confirm="handleTypeConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showActivityVolume" :columns="activityVolumeList" keyName="dictLabel" @cancel="handleActivityVolumeCancel"
        @confirm="handleActivityVolumeConfirm"></u-picker>
        <u-datetime-picker
			:show="startTimeShow"
			mode="datetime"
      ref="startTimeRef" 
			@cancel="startTimeShow=false"
			@confirm="startTimeConfirm"
			itemHeight="88"
		></u-datetime-picker>

    <u-datetime-picker
			:show="endTimeShow"
			mode="datetime"
      ref="endTimeRef" 
			@cancel="endTimeShow=false"
			@confirm="endTimeConfirm"
			itemHeight="88"
		></u-datetime-picker>
  </view>
</template>

<script setup>
import { getActivity, addActivity, updateActivity } from '@/api/health/activity'
const { proxy } = getCurrentInstance()
  import { getDicts } from '@/api/system/dict/data.js'
import dayjs from 'dayjs'
import {onLoad,onReady} from "@dcloudio/uni-app";
  // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed ,getCurrentInstance }from "vue";
const birthdayShow = ref(false)
const title = ref("活动记录")
const startTimeShow = ref(false)
const endTimeShow = ref(false)

const typeList = ref([])
const showType = ref(false)
const flag = ref('add')
const activityVolumeList = ref([])
const showActivityVolume = ref(false)

// 表单验证错误字段
const errorFields = ref([])

// 输入框基础样式
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 输入框错误样式
const inputErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 根据字段名获取输入框样式
const getInputStyle = (field) => {
  return errorFields.value.includes(field) ? inputErrorStyle : inputBaseStyle
}

const data = reactive({
form: {
  id: null,
    name: null,
    type: null,
    place: null,
    activityVolume: null,
    exerciseTime: null,
    startTime: null,
    endTime: null,
    harvest: null,
    foods: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    totalCost: 0,
    partner: null,
    costDetail: null
},
rules: {
  name: [{ required: true, message: '活动名称不能为空', trigger:['change', 'blur'] }],
  place: [{ required: true, message: '活动地点不能为空', trigger: ['change', 'blur'] }],
  partner: [{ required: true, message: '成员不能为空', trigger: ['change', 'blur'] }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: ['change', 'blur'] }],
  activityVolumeName: [{ required: true, message: '活动量不能为空', trigger: ['change', 'blur'] }],
  typeName: [{ required: true, message: '类型不能为空', trigger: ['change', 'blur'] }],
}
})
const { form, rules} = toRefs(data)


onLoad((option) => {
  form.value.id = option.id
     flag.value = option.flag
     if(flag.value==null){
      if(form.value.id!=null){
      title.value="活动记录-修改"
     }else{
      title.value="活动记录-新增"
     }
     }else{
      title.value="活动记录-复制"
     }
    getData()
})
onReady(() => {
  form.value.startTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
})
function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
 }
 function  selectStartTime() {
      startTimeShow.value = true
      proxy.$refs['startTimeRef'].innerValue = new Date().getTime()
  }
function startTimeConfirm(e) {
      form.value.startTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      startTimeShow.value = false
  }

  function  selectEndTime() {
    endTimeShow.value = true
      proxy.$refs['endTimeRef'].innerValue = new Date().getTime()
  }
function endTimeConfirm(e) {
      form.value.endTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      endTimeShow.value = false
  }
function  getData() {
     // 类型
     getDicts('activity_type').then(res => {
        typeList.value =[res.data] 
      })
           // 类型
     getDicts('activity_exercise').then(res => {
      activityVolumeList.value =[res.data] 
      })
    if(form.value.id!=null){
      getActivity(form.value.id).then(res => {
        form.value = res.data   
            // 类型
           getDicts('activity_type').then(result => {
          form.value.typeName=dictStr(form.value.type, result.data)
         })
               // 类型
               getDicts('activity_exercise').then(result => {
          form.value.activityVolumeName=dictStr(form.value.activityVolume, result.data)
         })
      })
    }
}


  function handleType() {
        if (typeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '类型为空  ', type: 'warning'
          })
        } else {
          showType.value = true
        }
     }
  function   handleTypeConfirm(e) {
        form.value.typeName = e.value[0].dictLabel
        form.value.type = e.value[0].dictValue
        showType.value = false
  }
 function handleTypeCancel() {
       showType.value = false
      }

      function handleActivityVolume() {
        if (activityVolumeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '活动量为空  ', type: 'warning'
          })
        } else {
          showActivityVolume.value = true
        }
     }
  function   handleActivityVolumeConfirm(e) {
        form.value.activityVolumeName = e.value[0].dictLabel
        form.value.activityVolume = e.value[0].dictValue
        showActivityVolume.value = false
  }
 function handleActivityVolumeCancel() {
       showActivityVolume.value = false
      }


function submit() {
   errorFields.value = [] // 清空错误字段
      proxy.$refs['uForm'].validate().then(() => {
        if (form.value.id != null) {
        if(flag.value==null){
          updateActivity(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/health/activity/list` })
            }
          })
        })
          }else {
            form.value.id == null
            addActivity(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/activity/list` })
            }
          })
        })
          }
        }else {
          addActivity(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/activity/list` })
            }
          })
        })
        }
      }).catch((errors) => {
    // 记录验证失败的字段
    if (errors && Array.isArray(errors)) {
      errorFields.value = errors.map(err => err.field || err.prop)
    }
    proxy.$modal.msgError('请填写完整信息')
  })
    }
</script>

<style lang="scss" scoped>
.section {
  margin: 24rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    line-height: 1.2;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      width: 6rpx;
      height: 28rpx;
      background: #ffffff;
      border-radius: 3rpx;
      margin-right: 12rpx;
    }
  }

  .form-view {
    padding: 24rpx;

    .form-btn {
      padding-top: 16rpx;
    }
  }
}
</style>

<style lang="scss">
.form-btn .u-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 24rpx !important;
  height: 80rpx !important;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
}

.form-btn .u-button__text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  letter-spacing: 2rpx !important;
}
</style>
