<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="160rpx"
          :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="shortName" required >
              <u--input v-model="form.shortName"  placeholder="请填写药品简称"
                inputAlign="left" :customStyle="getInputStyle('shortName')"></u--input>
            </u-form-item>
            <u-form-item label="品牌" prop="brand" required >
              <u--input v-model="form.brand"  placeholder="请填写品牌"
                inputAlign="left" :customStyle="getInputStyle('brand')"></u--input>
            </u-form-item>
            <u-form-item label="药品包装" prop="packaging" required >
              <u--input v-model="form.packaging"  placeholder="请填写药品包装"
                inputAlign="left" :customStyle="getInputStyle('packaging')"></u--input>
            </u-form-item>
            <u-form-item label="生产厂家" prop="manufacturers"  >
              <u--input v-model="form.manufacturers"  placeholder="请填写生产厂家"
                inputAlign="left" :customStyle="getInputStyle('manufacturers')"></u--input>
            </u-form-item>
        
            <u-form-item label="药品编码" prop="code"  >
              <u--input v-model="form.code"  placeholder="请填写药品编码"
                inputAlign="left" :customStyle="getInputStyle('code')"></u--input>
            </u-form-item>

          <u-form-item label="药品剂型" prop="dosageFormName"  @click="handleDosageForm">
              <view class="input-with-arrow">
                <u--input v-model="form.dosageFormName" readonly disabledColor="#ffffff" placeholder="请选择药品剂型"
                  inputAlign="left" :customStyle="getInputStyle('dosageFormName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="治疗类型" prop="treatmentTypeName"  @click="handleTreatmentType">
              <view class="input-with-arrow">
                <u--input v-model="form.treatmentTypeName" readonly disabledColor="#ffffff" placeholder="请选择治疗类型"
                  inputAlign="left" :customStyle="getInputStyle('treatmentTypeName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="药品分类"  prop="classificationName"  @click="handleClassification">
              <view class="input-with-arrow">
                <u--input v-model="form.classificationName" readonly disabledColor="#ffffff" placeholder="请选择药品分类"
                  inputAlign="left" :customStyle="getInputStyle('classificationName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>

            <u-form-item label="类别" prop="categoryName"  @click="handleCategory">
              <view class="input-with-arrow">
                <u--input v-model="form.categoryName" readonly disabledColor="#ffffff" placeholder="请选择类别"
                  inputAlign="left" :customStyle="getInputStyle('categoryName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="包装单位" prop="packageUnitName"  @click="handlePackageUnit">
              <view class="input-with-arrow">
                <u--input v-model="form.packageUnitName" readonly disabledColor="#ffffff" placeholder="请选择包装单位"
                  inputAlign="left" :customStyle="getInputStyle('packageUnitName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
        
            <u-form-item label="是否进口" prop="isImportName"  @click="handleIsImport">
              <view class="input-with-arrow">
                <u--input v-model="form.isImportName" readonly disabledColor="#ffffff" placeholder="请选择是否进口"
                  inputAlign="left" :customStyle="getInputStyle('isImportName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="规格" prop="specifications" >
              <u--input v-model="form.specifications"  placeholder="请填写规格"
                inputAlign="left" :customStyle="getInputStyle('specifications')"></u--input>
            </u-form-item>
            <u-form-item label="规格单位" prop="unitName"  @click="handleUnit">
              <view class="input-with-arrow">
                <u--input v-model="form.unitName" readonly disabledColor="#ffffff" placeholder="请选择规格单位"
                  inputAlign="left" :customStyle="getInputStyle('unitName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="单个含量" prop="content"  >
              <u--input v-model="form.content"  placeholder="请填写单个含量"
                inputAlign="left" :customStyle="getInputStyle('content')"></u--input>
            </u-form-item>
            <u-form-item label="含量单位" prop="contentUnitName"  @click="handleContentUnit">
              <view class="input-with-arrow">
                <u--input v-model="form.contentUnitName" readonly disabledColor="#ffffff" placeholder="请选择含量单位"
                  inputAlign="left" :customStyle="getInputStyle('contentUnitName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="生产地址" prop="address"  >
              <u--input v-model="form.address"  placeholder="请填写生产地址"
                inputAlign="left" :customStyle="getInputStyle('address')"></u--input>
            </u-form-item>
            <u-form-item label="功能主治" prop="indications"  labelPosition="top">
            <u--textarea v-model="form.indications" placeholder="请填写功能主治" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="贮藏" prop="storage"  labelPosition="top">
            <u--textarea v-model="form.storage" placeholder="请填写贮藏" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="药品成分" prop="ingredients"  labelPosition="top">
            <u--textarea v-model="form.ingredients" placeholder="请填写药品成分" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="用法用量" prop="usage"  labelPosition="top">
            <u--textarea v-model="form.usage" placeholder="请填写用法用量" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="性状" prop="character"  labelPosition="top">
            <u--textarea v-model="form.character" placeholder="请填写性状" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
          <u-form-item label="不良反应" prop="adverseReaction"  labelPosition="top">
            <u--textarea v-model="form.adverseReaction" 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" 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="showPerson" :columns="personList" keyName="name" @cancel="handlePersonCancel"
      @confirm="handlePersonConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showDosageForm" :columns="dosageFormList" keyName="dictLabel" @cancel="handleDosageFormCancel"
        @confirm="handleDosageFormConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showTreatmentType" :columns="treatmentTypeList" keyName="dictLabel" @cancel="handleTreatmentTypeCancel"
        @confirm="handleTreatmentTypeConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showClassification" :columns="classificationList" keyName="dictLabel" @cancel="handleClassificationCancel"
        @confirm="handleClassificationConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showCategory" :columns="categoryList" keyName="dictLabel" @cancel="handleCategoryCancel"
      @confirm="handleCategoryConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showPackageUnit" :columns="packageUnitList" keyName="dictLabel" @cancel="handlePackageUnitCancel"
      @confirm="handlePackageUnitConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showIsImport" :columns="isImportList" keyName="dictLabel" @cancel="handleIsImportCancel"
      @confirm="handleIsImportConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showUnit" :columns="unitList" keyName="dictLabel" @cancel="handleUnitCancel"
      @confirm="handleUnitConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showContentUnit" :columns="contentUnitList" keyName="dictLabel" @cancel="handleContentUnitCancel"
      @confirm="handleContentUnitConfirm"></u-picker>
  </view>
</template>

<script setup>
import {getMedicineBasic, addMedicineBasic, updateMedicineBasic, uploadFile } from '@/api/health/medicineBasic'
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 datePickShow = ref(false)
const title = ref("药品基础信息")
const flag = ref('add')

// 附件图片列表（存储完整URL）
const attachmentList = ref([])
const uploading = ref(false)

const dosageFormList = ref([])
const showDosageForm = ref(false)

const treatmentTypeList = ref([])
const showTreatmentType = ref(false)

const classificationList = ref([])
const showClassification = ref(false)

const categoryList = ref([])
const showCategory = ref(false)

const packageUnitList = ref([])
const showPackageUnit = ref(false)

const isImportList = ref([])
const showIsImport = ref(false)

const unitList = ref([])
const showUnit = ref(false)

const contentUnitList = ref([])
const showContentUnit = ref(false)


const data = reactive({
form: {
  id: null,
    name: null,
    classification: null,
    category: null,
    brand: null,
    packaging: null,
    manufacturers: null,
    treatmentType: null,
    isImport: null,
    ingredients: null,
    usage: null,
    dosageForm: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    code: null,
    specifications: null,
    unit: null,
    address: null,
    adverseReaction: null,
    content: null,
    contentUnit: null,
    character: null,
    storage: null,
    indications: null,
    attachment: null
},
rules: {
  name: [{ required: true, message: '药品全称不能为空', trigger:['change', 'blur'] }],
  shortName: [{ required: true, message: '药品简称不能为空', trigger: ['change', 'blur'] }],
  // classificationName: [{ required: true, message: '药品分类不能为空', trigger: ['change', 'blur'] }],
  // categoryName: [{ required: true, message: '类别不能为空', trigger: ['change', 'blur'] }],
  brand: [{ required: true, message: '品牌不能为空', trigger: ['change', 'blur'] }],
  packaging: [{ required: true, message: '药品包装不能为空', trigger: ['change', 'blur'] }],
  // manufacturers: [{ required: true, message: '生产厂家不能为空', trigger: ['change', 'blur'] }],
  // code: [{ required: true, message: '药品编码不能为空', trigger: ['change', 'blur'] }],
  // dosageFormName: [{ 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.dosingTime = 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  getData() {
     // 类型
     getDicts('dosage_form').then(res => {
      dosageFormList.value =[res.data] 
      })
       // 类型
     getDicts('mar_type').then(res => {
      treatmentTypeList.value =[res.data] 
      })
       // 类型
     getDicts('medicine_classification').then(res => {
      classificationList.value =[res.data] 
      })
       // 类型
     getDicts('medicine_category').then(res => {
      categoryList.value =[res.data] 
      })
       // 类型
     getDicts('package_unit').then(res => {
      packageUnitList.value =[res.data] 
      })
       // 类型
     getDicts('is_import').then(res => {
      isImportList.value =[res.data] 
      })
       // 类型
     getDicts('medical_unit').then(res => {
      unitList.value =[res.data] 
      })
       // 类型
     getDicts('content_unit').then(res => {
      contentUnitList.value =[res.data] 
      })

    if(form.value.id!=null){
      getMedicineBasic(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('dosage_form').then(result => {
          form.value.dosageFormName=dictStr(form.value.dosageForm, result.data)
         })
         getDicts('mar_type').then(result => {
          form.value.treatmentTypeName=dictStr(form.value.treatmentType, result.data)
         })
         getDicts('medicine_classification').then(result => {
          form.value.classificationName=dictStr(form.value.classification, result.data)
         })
         getDicts('medicine_category').then(result => {
          form.value.categoryName=dictStr(form.value.category, result.data)
         })
         getDicts('package_unit').then(result => {
          form.value.packageUnitName=dictStr(form.value.packageUnit, result.data)
         })
         getDicts('is_import').then(result => {
          form.value.isImportName=dictStr(form.value.isImport, result.data)
         })
         getDicts('medical_unit').then(result => {
          form.value.unitName=dictStr(form.value.unit, result.data)
         })
         getDicts('content_unit').then(result => {
          form.value.contentUnitName=dictStr(form.value.contentUnit, result.data)
         })
      })
    }
}

function handleDosageForm() {
        if (dosageFormList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品剂型为空  ', type: 'warning'
          })
        } else {
          showDosageForm.value = true
        }
     }
  function   handleDosageFormConfirm(e) {
        form.value.dosageFormName = e.value[0].dictLabel
        form.value.dosageForm = e.value[0].dictValue
        showDosageForm.value = false
  }
 function handleDosageFormCancel() {
  showDosageForm.value = false
      }

      function handleTreatmentType() {
        if (treatmentTypeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showTreatmentType.value = true
        }
     }
  function   handleTreatmentTypeConfirm(e) {
        form.value.treatmentTypeName = e.value[0].dictLabel
        form.value.treatmentType = e.value[0].dictValue
        showTreatmentType.value = false
  }
 function handleTreatmentTypeCancel() {
  showTreatmentType.value = false
      }

      function handleClassification() {
        if (classificationList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showClassification.value = true
        }
     }
  function   handleClassificationConfirm(e) {
        form.value.classificationName = e.value[0].dictLabel
        form.value.classification = e.value[0].dictValue
        showClassification.value = false
  }
 function handleClassificationCancel() {
  showClassification.value = false
      }

      function handleCategory() {
        if (categoryList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showCategory.value = true
        }
     }
  function   handleCategoryConfirm(e) {
        form.value.categoryName = e.value[0].dictLabel
        form.value.category = e.value[0].dictValue
        showCategory.value = false
  }
 function handleCategoryCancel() {
  showCategory.value = false
      }

      function handlePackageUnit() {
        if (packageUnitList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showPackageUnit.value = true
        }
     }
  function   handlePackageUnitConfirm(e) {
        form.value.packageUnitName = e.value[0].dictLabel
        form.value.packageUnit = e.value[0].dictValue
        showPackageUnit.value = false
  }
 function handlePackageUnitCancel() {
  showPackageUnit.value = false
      }

      function handleIsImport() {
        if (isImportList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showIsImport.value = true
        }
     }
  function   handleIsImportConfirm(e) {
        form.value.isImportName = e.value[0].dictLabel
        form.value.isImport = e.value[0].dictValue
        showIsImport.value = false
  }
 function handleIsImportCancel() {
  showIsImport.value = false
      }

      function handleUnit() {
        if (unitList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showUnit.value = true
        }
     }
  function   handleUnitConfirm(e) {
        form.value.unitName = e.value[0].dictLabel
        form.value.unit = e.value[0].dictValue
        showUnit.value = false
  }
 function handleUnitCancel() {
  showUnit.value = false
      }

      function handleContentUnit() {
        if (contentUnitList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showContentUnit.value = true
        }
     }
  function   handleContentUnitConfirm(e) {
        form.value.contentUnitName = e.value[0].dictLabel
        form.value.contentUnit = e.value[0].dictValue
        showContentUnit.value = false
  }
 function handleContentUnitCancel() {
  showContentUnit.value = false
      }
function submit() {
      // 清空错误字段
      errorFields.value = []
      // 提交前同步附件字段（逗号分隔的URL字符串）
      form.value.attachment = attachmentList.value.join(',')

      proxy.$refs['uForm'].validate().then(() => {
        if (form.value.id != null) {
        if(flag.value==null){
          updateMedicineBasic(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/health/medicineBasic/list` })
            }
          })
        })
          }else {
            form.value.id == null
            addMedicineBasic(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/medicineBasic/list` })
            }
          })
        })
          }

        }else {
          addMedicineBasic(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/medicineBasic/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'
    })
    // 打印返回数据，便于调试
    console.log('==== upload response ====', JSON.stringify(res))
    // 兼容多种返回格式
    const url = (res.data && (res.data.url || res.data.fileName || res.data.imgUrl))
      || res.url
      || res.fileName
      || res.imgUrl
      || res.fileUrl
    if (url) {
      const fullUrl = normalizeAttachmentUrl(url)
      console.log('==== push attachment url ====', fullUrl)
      // 使用重新赋值确保响应式更新
      attachmentList.value = [...attachmentList.value, fullUrl]
    } else {
      console.error('==== 上传成功但未找到URL字段，请查看上方返回数据 ====', res)
      proxy.$refs['uToast'].show({ message: '上传成功但未解析到图片地址', type: 'warning' })
    }
    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(102, 126, 234, 0.15);

        .img-preview {
          width: 100%;
          height: 100%;
          background: #f5f7fa;
        }

        .img-del {
          position: absolute;
          top: 4rpx;
          right: 4rpx;
          width: 36rpx;
          height: 36rpx;
          background: rgba(255, 255, 255, 0.9);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.15);

          &:active {
            transform: scale(0.9);
          }
        }
      }

      .img-add {
        width: 180rpx;
        height: 180rpx;
        border-radius: 12rpx;
        border: 2rpx dashed rgba(102, 126, 234, 0.4);
        background: rgba(102, 126, 234, 0.06);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 8rpx;
        transition: all 0.2s ease;

        &:active {
          transform: scale(0.96);
          background: rgba(102, 126, 234, 0.12);
        }

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

      .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>
