<template>
  <view class="container" style="paddingBottom:1rpx;">
    <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="140rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
          <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">
            <view class="input-with-arrow">
              <u--input v-model="form.typeName" readonly disabledColor="#ffffff" placeholder="请选择类型"
                inputAlign="left" :customStyle="getInputStyle('typeName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </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()">
            <view class="input-with-arrow">
              <u--input v-model="form.startTime" readonly disabledColor="#ffffff" placeholder="请选择开始时间"
                inputAlign="left" :customStyle="getInputStyle('startTime')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="结束时间" prop="endTime"  @click="selectEndTime()">
            <view class="input-with-arrow">
              <u--input v-model="form.endTime" readonly disabledColor="#ffffff" placeholder="请选择结束时间"
                inputAlign="left" :customStyle="getInputStyle('endTime')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <!-- <u-form-item label="活动时长" prop="exerciseTime" >
            <u--input v-model="form.exerciseTime" placeholder="请填写活动时长"
              inputAlign="left" :customStyle="getInputStyle('exerciseTime')"></u--input>
          </u-form-item> -->
          <u-form-item label="活动量" prop="activityVolumeName" required @click="handleActivityVolume">
            <view class="input-with-arrow">
              <u--input v-model="form.activityVolumeName" readonly disabledColor="#ffffff" placeholder="请选择活动量"
                inputAlign="left" :customStyle="getInputStyle('activityVolumeName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="总费用" prop="totalCost" >
            <u--input v-model="form.totalCost" type="digit"  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" height="80rpx" placeholder="请填写费用明细" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="饮食" prop="foods"  labelPosition="top">
            <u--textarea v-model="form.foods"  height="80rpx" placeholder="请填写饮食" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="收获" prop="harvest"  labelPosition="top">
            <u--textarea v-model="form.harvest"  height="80rpx" placeholder="请填写收获" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="备注" prop="remark"  labelPosition="top">
            <u--textarea v-model="form.remark"  height="80rpx" placeholder="请填写备注" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="附件图片" prop="attachment" labelPosition="top">
            <view class="upload-wrap">
              <view class="img-list">
                <view class="img-item" v-for="(img, index) in attachmentList" :key="index">
                  <image :src="img" class="img-preview" mode="aspectFill" @click="previewImage(index)"></image>
                  <view class="img-del" @click="deleteImage(index)">
                    <uni-icons type="clear" size="20" color="#f5576c"></uni-icons>
                  </view>
                </view>
                <view class="img-add" v-if="attachmentList.length < 9" @click="chooseImage">
                  <uni-icons type="plusempty" size="28" color="#667eea"></uni-icons>
                  <text class="img-add-text">上传图片</text>
                </view>
              </view>
              <view class="upload-tip">最多上传9张图片，支持 jpg/png/jpeg 等格式</view>
            </view>
          </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, uploadFile } from '@/api/health/activity'
import config from '@/config'
import { compressImage } from '@/utils/imageCompress'
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 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
}

function normalizeAttachmentUrl(url) {
  if (!url) return ''
  if (url.startsWith('http')) return url
  // 附件是后端静态资源直链（如 /fileUrl/...、/profile/upload/...）
  // 需要用域名拼接，不能带网关前缀 prod-api（否则会 404）
  const origin = config.baseUrl.replace(/^(https?:\/\/[^/]+).*$/, '$1')
  return origin + url
}

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 attachmentList = ref([])
const uploading = ref(false)

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,
    attachment: 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'] }],
  // endTime: [{ 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   
            if (form.value.attachment) {
              attachmentList.value = form.value.attachment.split(',').filter(url => url).map(normalizeAttachmentUrl)
            }
            // 类型
           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 = []
  form.value.attachment = attachmentList.value.join(',')
  
  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 && errors.length > 0) {
      errorFields.value = errors.map(err => err.field)
    }
    proxy.$modal.msgError('请填写完整信息')
  })
}

function chooseImage() {
  if (uploading.value) {
    proxy.$refs['uToast'].show({ message: '正在上传中，请稍候', type: 'warning' })
    return
  }
  // H5 端传 camera 会触发 getUserMedia，可能卡死；微信小程序/APP 需要相机选项
  let sourceType
  // #ifdef H5
  sourceType = ['album']
  // #endif
  // #ifndef H5
  sourceType = ['album', 'camera']
  // #endif
  uni.chooseImage({
    count: 9 - attachmentList.value.length,
    sizeType: ['compressed'],
    sourceType,
    success: (res) => {
      uploadImages(res.tempFilePaths, 0)
    },
    fail: (err) => {
      // 用户取消选择不走 success，也不会报错，但某些浏览器会触发 fail
      if (err && err.errMsg && err.errMsg.indexOf('cancel') === -1) {
        proxy.$refs['uToast'].show({ message: '选择图片失败', type: 'warning' })
      }
    }
  })
}

async function uploadImages(paths, index) {
  if (index >= paths.length) {
    uploading.value = false
    return
  }
  uploading.value = true
  uni.showLoading({ title: `处理中 ${index + 1}/${paths.length}`, mask: false })
  try {
    // 上传前先压缩（超过 500KB 才压，避免小图多走一道）
    const compressedPath = await compressImage(paths[index])
    uni.showLoading({ title: `上传中 ${index + 1}/${paths.length}`, mask: false })
    const res = await uploadFile({
      filePath: compressedPath,
      name: 'file'
    })
    const url = (res.data && res.data.url) || res.fileName || res.url
    if (url) {
      attachmentList.value.push(normalizeAttachmentUrl(url))
    }
    uni.hideLoading()
    uploadImages(paths, index + 1)
  } catch (e) {
    uni.hideLoading()
    uploading.value = false
    proxy.$refs['uToast'].show({ message: `第 ${index + 1} 张上传失败`, type: 'error' })
  }
}

function deleteImage(index) {
  uni.showModal({
    title: '提示',
    content: '确定删除这张图片吗？',
    confirmColor: '#f5576c',
    success: (modalRes) => {
      if (modalRes.confirm) {
        attachmentList.value.splice(index, 1)
      }
    }
  })
}

function previewImage(index) {
  uni.previewImage({
    urls: attachmentList.value,
    current: attachmentList.value[index]
  })
}
</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;
    }

    // 带箭头的输入框容器
    .input-with-arrow {
      position: relative;
      width: 100%;

      .arrow-icon {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        color: #c0c4cc;
        font-size: 20rpx;
        pointer-events: none;
        z-index: 10;
      }
    }

    .upload-wrap {
      width: 100%;

      .img-list {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
        margin-bottom: 12rpx;
      }

      .img-item {
        position: relative;
        width: 180rpx;
        height: 180rpx;
        border-radius: 12rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
      }

      .img-preview {
        width: 100%;
        height: 100%;
        display: block;
      }

      .img-del {
        position: absolute;
        top: 6rpx;
        right: 6rpx;
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.92);
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .img-add {
        width: 180rpx;
        height: 180rpx;
        border: 2rpx dashed rgba(102, 126, 234, 0.55);
        border-radius: 12rpx;
        background: rgba(102, 126, 234, 0.06);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 10rpx;
      }

      .img-add-text {
        color: #667eea;
        font-size: 24rpx;
      }

      .upload-tip {
        font-size: 22rpx;
        color: #909399;
        line-height: 1.4;
      }
    }
  }
}
</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;
}

/* 强制让错误状态的输入框边框变红 */
.u-form-item--error .u--input,
.u-form-item--error .u-input,
.u-form-item--error .u-input__content,
.u-form-item--error .u-input__content__field-wrapper {
  border: 2rpx solid #f56c6c !important;
  background: #fef0f0 !important;
}

.u-form-item--error .u--textarea,
.u-form-item--error .u-textarea {
  border: 2rpx solid #f56c6c !important;
  background: #fef0f0 !important;
}
</style>
