<template>
  <div class="express-order-page">
    <!-- 寄件人和收件人在同一行 -->
    <div class="form-row">

      <!-- 寄件人 -->
      <div class="form-card">
        <div class="card-header send">
          <span class="header-title"><img src="../../../assets/images/icon-send.png"/>寄件人</span>
          <div class="header-actions">
            <el-button
                type="primary"
                link
                @click="openAddressBook('sender')"
                class="action-btn"
            >
              <img src="../../../assets/images/create-order-address.png"/>地址簿
            </el-button>
          </div>
        </div>
        <div class="form-content">
          <!-- 智能识别区域（寄件人） -->
          <div class="recognition-area">
            <div class="recognition-tip">识别后，请检查拆分地址信息是否准确，如有遗漏请及时补充</div>
            <el-input
                type="textarea"
                v-model="senderRecognitionText"
                placeholder="请输入文本，自动识别姓名、电话和地址"
                :rows="3"
                maxlength="250"
                show-word-limit
                class="recognition-textarea"
            />
            <div class="recognition-actions">
              <el-button
                  type="primary"
                  @click="handleRecognition('sender', 1)"
                  v-if="!senderRecognitionText"
                  class="recognition-btn"
              >粘贴并识别</el-button>
              <el-button
                  type="primary"
                  @click="handleRecognition('sender', 2)"
                  v-else
                  class="recognition-btn"
              >识别</el-button>
            </div>
          </div>

          <el-form
              label-position="left"
              :model="sender"
              :rules="senderRules"
              ref="senderForm"
              label-width="120px"
              class="sender-form"
          >
            <el-form-item label="姓名：" prop="contactName" required>
              <el-input
                  v-model="sender.contactName"
                  placeholder="请输入真实姓名"
                  size="large"
                  clearable
                  class="fixed-input"
                  maxlength="20"
                  show-word-limit
                  @input="handleSenderChange"
              />
            </el-form-item>

            <el-form-item label="电话：" prop="contactPhone" required>
              <el-input
                  v-model="sender.contactPhone"
                  placeholder="请输入电话号码"
                  size="large"
                  clearable
                  class="fixed-input"
                  maxlength="11"
                  @input="handleSenderChange"
              />
            </el-form-item>

            <el-form-item label="省市区：" prop="region" required>
              <RegionCascader
                  v-model="sender.region"
                  placeholder="请选择省市区"
                  size="large"
                  :clearable="true"
                  class="fixed-input"
                  @change="handleSenderRegionChange"
              />
            </el-form-item>

            <el-form-item label="详细地址：" prop="detailedAddress" required>
              <el-input
                  v-model="sender.detailedAddress"
                  placeholder="请输入详细地址"
                  size="large"
                  clearable
                  class="fixed-input"
                  maxlength="100"
                  show-word-limit
                  @input="handleSenderChange"
              />
            </el-form-item>

            <div class="default-address-footer">
              <!-- 默认地址相关已注释，保留原样 -->
            </div>
          </el-form>
        </div>
      </div>

      <!-- 收件人 -->
      <div class="form-card">
        <div class="card-header receive">
          <span class="header-title"><img src="../../../assets/images/icon-receive.png"/>收件人</span>
          <div class="header-actions">
            <el-button
                type="primary"
                link
                @click="openAddressBook('receiver')"
                class="action-btn"
            >
              <img src="../../../assets/images/create-order-address.png"/>地址簿
            </el-button>
          </div>
        </div>
        <div class="form-content">
          <!-- 智能识别区域（收件人） -->
          <div class="recognition-area">
            <div class="recognition-tip">识别后，请检查拆分地址信息是否准确，如有遗漏请及时补充</div>
            <el-input
                type="textarea"
                v-model="receiverRecognitionText"
                placeholder="请输入文本，自动识别姓名、电话和地址"
                :rows="3"
                maxlength="250"
                show-word-limit
                class="recognition-textarea"
            />
            <div class="recognition-actions">
              <el-button
                  type="primary"
                  @click="handleRecognition('receiver', 1)"
                  v-if="!receiverRecognitionText"
                  class="recognition-btn"
              >粘贴并识别</el-button>
              <el-button
                  type="primary"
                  @click="handleRecognition('receiver', 2)"
                  v-else
                  class="recognition-btn"
              >识别</el-button>
            </div>
          </div>

          <el-form
              label-position="left"
              :model="receiver"
              :rules="receiverRules"
              ref="receiverForm"
              label-width="120px"
              class="receiver-form"
          >
            <el-form-item label="姓名：" prop="contactName" required>
              <el-input
                  v-model="receiver.contactName"
                  placeholder="请输入真实姓名"
                  size="large"
                  clearable
                  class="fixed-input"
                  maxlength="20"
                  show-word-limit
                  @input="handleReceiverChange"
              />
            </el-form-item>

            <el-form-item label="电话：" prop="contactPhone" required>
              <el-input
                  v-model="receiver.contactPhone"
                  placeholder="请输入电话号码"
                  size="large"
                  clearable
                  class="fixed-input"
                  maxlength="11"
                  @input="handleReceiverChange"
              />
            </el-form-item>

            <el-form-item label="省市区：" prop="region" required>
              <RegionCascader
                  v-model="receiver.region"
                  placeholder="请选择省市区"
                  size="large"
                  :clearable="true"
                  class="fixed-input"
                  @change="handleReceiverRegionChange"
              />
            </el-form-item>

            <el-form-item label="详细地址：" prop="detailedAddress" required>
              <el-input
                  v-model="receiver.detailedAddress"
                  placeholder="请输入详细地址"
                  size="large"
                  clearable
                  class="fixed-input"
                  maxlength="100"
                  show-word-limit
                  @input="handleReceiverChange"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

    </div>

    <!-- 寄件方式 -->
    <div class="form-card full-width">
      <div class="card-header with-blue-line">
        <div class="blue-line"></div>
        <span class="header-title">寄件方式</span>
      </div>
      <div class="form-content">
        <div class="delivery-option">
          <div class="option-item">
            <div class="btn-radio">
              <el-radio v-model="deliveryMethod" label="pickup" size="large">
                上门取件
              </el-radio>
            </div>

            <el-form
                label-position="left"
                :model="deliveryForm"
                :rules="deliveryRules"
                ref="deliveryFormRef"
                label-width="120px"
                class="delivery-form"
            >
              <div class="item-info-grid-2">
                <el-form-item label="上门时间：" prop="pickupTime" required>
                  <PickupTimeCascader
                      v-model="deliveryForm.pickupTime"
                      placeholder="请选择上门时间"
                      :clearable="true"
                      class="fixed-input pickup-time-select"
                      @change="handlePickupTimeChange"
                  />
                </el-form-item>

                <el-form-item label="快递类型：" prop="expressType" required class="fixed-input">

                  <el-select
                      v-model="deliveryForm.expressType"
                      placeholder="请选择快递类型"
                      size="large"
                      class="fixed-input"
                  >
                    <el-option
                        v-if="productType == '1'"
                        v-for="dict in jd_logistics_product_code"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                    <el-option
                        v-if="productType == '2'"
                        v-for="dict in sf_logistics_product_code"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>

                  </el-select>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <!-- 物品信息（修改后） -->
    <div class="form-card full-width">
      <div class="card-header with-blue-line">
        <div class="blue-line"></div>
        <span class="header-title">物品信息</span>
      </div>
      <div class="form-content">
        <el-form
            label-position="left"
            :model="itemInfo"
            :rules="itemInfoRules"
            ref="itemInfoForm"
            label-width="120px"
            class="item-info-form"
        >
          <div class="item-info-grid-2">
            <!-- 物品类型改为下拉选择框，使用数据字典 jd_goods_type -->
            <el-form-item label="物品类型：" prop="type" required class="fixed-input">
              <el-select
                  v-model="itemInfo.type"
                  placeholder="请选择物品类型"
                  size="large"
                  clearable
                  class="fixed-input"
              >
                <el-option
                    v-for="dict in jd_goods_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="总重量 (kg)：" prop="weight" required>
              <el-input-number
                  v-model="itemInfo.weight"
                  :min="0.1"
                  :step="0.1"
                  size="large"
                  controls-position="right"
                  class="fixed-input"
              />
            </el-form-item>
          </div>
          <div class="item-info-grid-2">
            <el-form-item label="总体积 (m³)：" prop="volume" required>
              <el-input-number
                  v-model="itemInfo.volume"
                  :min="0.001"
                  :step="0.001"
                  size="large"
                  controls-position="right"
                  class="fixed-input"
              />
            </el-form-item>

            <el-form-item label="总件数 (件)：" prop="quantity" required>
              <el-input-number
                  v-model="itemInfo.quantity"
                  :min="1"
                  :step="1"
                  size="large"
                  controls-position="right"
                  class="fixed-input"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 增值服务 -->
    <div class="form-card full-width">
      <div class="card-header with-blue-line">
        <div class="blue-line"></div>
        <span class="header-title">增值服务</span>
      </div>
      <div class="form-content">
        <div class="value-services-grid">
          <div class="service-item" v-if="productType == '1'">
            <span class="service-label">包装服务</span>
            <el-switch
                v-model="valueServices.packaging"
                size="large"
                active-color="#1890ff"
            />
          </div>

          <div class="service-item" v-if="productType == '1' || productType == '2'">
            <span class="service-label">保价</span>
            <div class="insurance-wrapper">
              <el-switch
                  v-model="valueServices.insurance"
                  size="large"
                  active-color="#1890ff"
                  @change="handleInsuranceChange"
              />
              <div class="insurance-input-wrapper" v-if="valueServices.insurance">
                <el-input
                    v-model="insuranceAmount"
                    placeholder="请输入保价金额"
                    size="large"
                    class="insurance-input fixed-input"
                    @input="validateInsuranceAmount"
                    maxlength="10"
                >
                  <template #append>元</template>
                </el-input>
                <div v-if="insuranceAmountError" class="error-message">
                  {{ insuranceAmountError }}
                </div>
              </div>
            </div>
          </div>

          <div class="service-item" v-if="productType == '1'">
            <span class="service-label">签单返还</span>
            <div class="sign-return-wrapper">
              <el-switch
                  v-model="valueServices.signReturn"
                  size="large"
                  active-color="#1890ff"
                  @change="handleSignReturnChange"
              />
              <div class="sign-return-select-wrapper fixed-input" v-if="valueServices.signReturn && productType == '2'">
                <el-select
                    v-model="signReturnType"
                    placeholder="请选择凭证类型"
                    size="large"
                    class="fixed-input sign-return-select"
                >
                  <el-option
                      v-for="option in signReturnOptions"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                  />
                </el-select>

                <div v-if="signReturnTypeError" class="error-message">
                  {{ signReturnTypeError }}
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>

    <!-- 提交订单 -->
    <div class="form-card full-width">
      <div class="card-header with-blue-line">
        <div class="blue-line"></div>
        <span class="header-title">提交订单</span>
      </div>

      <div class="agreement">
        <div class="price-notice">
          实际费用以快递员核实为准
        </div>
      </div>
      <el-button
          type="primary"
          size="large"
          :disabled="!agreed"
          @click="submitOrder"
          class="submit-button"
      >
        提交订单
      </el-button>
    </div>

    <!-- 地址簿弹窗组件 -->
    <AddressBookDialog
        v-model:visible="addressBookVisible"
        :address-book-type="addressBookType"
        @confirm="applyAddress"
        @cancel="closeAddressBook"
        @close="closeAddressBook"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import RegionCascader from '@/components/RegionCascader.vue'
import AddressBookDialog from './components/AddressBookDialog.vue'
import PickupTimeCascader from './components/PickupTimeCascader.vue'

import { areaData, getCodesByNames } from '@/utils/area-data.js'
import { addBook } from "@/api/logistics/book"
import { addOrder } from "@/api/logistics/order"

const { proxy } = getCurrentInstance()
const { jd_logistics_product_code, sf_logistics_product_code, jd_goods_type } =
    proxy.useDict("jd_logistics_product_code", "sf_logistics_product_code","jd_goods_type")

import { useRoute } from 'vue-router';
import { updateBook, getDefaultAddress, getAddressInfo } from "../../../api/logistics/book.js";

const route = useRoute();

const productType = ref('1') //1表示京东  2表示顺丰

// 寄件人信息
const sender = reactive({
  addressId:'',
  contactName: '',
  contactPhone: '',
  provinceName: '',
  cityName: '',
  countyName: '',
  detailedAddress: '',
  region: [],
  defaultFlag: '0'
})

// 收件人信息
const receiver = reactive({
  addressId:'',
  contactName: '',
  contactPhone: '',
  provinceName: '',
  cityName: '',
  countyName: '',
  detailedAddress: '',
  region: [],
  defaultFlag: '0'
})

// 寄件方式
const deliveryMethod = ref('pickup')

// 寄件方式表单（用于验证）
const deliveryForm = reactive({
  pickupTime: [],
  expressType: '',
  pickupStartTime: '',
  pickupEndTime: ''
})

// 寄件方式验证规则
const deliveryRules = {
  pickupTime: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择上门时间'))
        } else {
          if (Array.isArray(value) && value.length >= 2) {
            callback()
          } else {
            callback(new Error('请选择完整的上门时间'))
          }
        }
      },
      trigger: 'change'
    }
  ],
  expressType: [
    { required: true, message: '请选择快递类型', trigger: 'change' }
  ]
}

const deliveryFormRef = ref(null)

// 物品信息
const itemInfo = reactive({
  type: '',
  weight: 1,
  volume: 0.001,
  quantity: 1
})

// 增值服务
const valueServices = reactive({
  packaging: false,
  insurance: false,
  overweight: false,
  signReturn: false,
  woodenFrame: false
})

const insuranceAmount = ref('')
const insuranceAmountError = ref('')

const signReturnType = ref('')
const signReturnTypeError = ref('')
const signReturnOptions = ref([
  { label: '电子凭证', value: 'electronic' },
  { label: '纸质凭证', value: 'paper' }
])

const agreed = ref(true)

const senderRules = {
  contactName: [
    { required: true, message: '请输入寄件人姓名', trigger: 'blur' },
    { min: 1, max: 20, message: '姓名长度在1-20个字符之间', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入寄件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择省市区'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 3, max: 100, message: '地址长度在3-100个字符之间', trigger: 'blur' }
  ]
}

const receiverRules = {
  contactName: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' },
    { min: 1, max: 20, message: '姓名长度在1-20个字符之间', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入收件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择省市区'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
  ]
}

const itemInfoRules = {
  type: [
    { required: true, message: '请选择物品类型', trigger: 'change' }, // 触发方式改为 change
  ],
  weight: [
    { required: true, message: '请输入总重量', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('重量必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  volume: [
    { required: true, message: '请输入总体积', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('体积必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  quantity: [
    { required: true, message: '请输入总件数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('件数必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const senderForm = ref(null)
const receiverForm = ref(null)
const itemInfoForm = ref(null)

const addressBookVisible = ref(false)
const addressBookType = ref('sender')

const senderOriginalAddress = ref(null)
const receiverOriginalAddress = ref(null)

watch(() => deliveryForm.expressType, (newVal) => {
  if (newVal && deliveryFormRef.value) {
    deliveryFormRef.value.clearValidate(['expressType'])
  }
})

watch(() => deliveryForm.pickupTime, (newVal) => {
  if (newVal && newVal.length > 0 && deliveryFormRef.value) {
    deliveryFormRef.value.clearValidate(['pickupTime'])
  }
})

watch(() => valueServices.signReturn, (newVal) => {
  if (!newVal) {
    signReturnType.value = ''
    signReturnTypeError.value = ''
  }
})

watch(insuranceAmount, () => {
  validateInsuranceAmount()
})

watch(signReturnType, (newVal) => {
  if (newVal) {
    signReturnTypeError.value = ''
  }
})

// ==================== 智能识别 ====================
const senderRecognitionText = ref('')
const receiverRecognitionText = ref('')
const recognitionLoading = ref(false)

const handleRecognition = async (type, actionType) => {
  let text = ''
  if (actionType === 1) {
    try {
      const clipboardText = await navigator.clipboard.readText()
      if (!clipboardText) {
        ElMessage.warning('剪贴板内容为空')
        return
      }
      if (type === 'sender') {
        senderRecognitionText.value = clipboardText
        text = clipboardText
      } else {
        receiverRecognitionText.value = clipboardText
        text = clipboardText
      }
    } catch (err) {
      ElMessage.error('读取剪贴板失败，请手动粘贴')
      return
    }
  } else {
    text = type === 'sender' ? senderRecognitionText.value : receiverRecognitionText.value
  }

  if (!text.trim()) {
    ElMessage.warning('请输入要识别的文本')
    return
  }

  recognitionLoading.value = true
  try {
    const params = { param: text }
    const res = await getAddressInfo(params)
    if (res.code === 200 && res.data?.result?.length > 0) {
      const result = res.data.result[0]
      const target = type === 'sender' ? sender : receiver

      target.addressId = ''
      target.contactName = result.name || ''
      if (result.mobile && result.mobile.length > 0) {
        target.contactPhone = result.mobile[0]
      }
      if (result.xzq) {
        let province = '', city = '', district = ''
        if (result.xzq.fullName) {
          const parts = result.xzq.fullName.split(',').map(s => s.trim())
          province = parts[0] || ''
          city = parts[1] || ''
          district = parts[2] || ''
        } else {
          province = result.xzq.province || ''
          city = result.xzq.city || ''
          district = result.xzq.district || ''
        }
        target.provinceName = province
        target.cityName = city
        target.countyName = district

        const codes = getCodesByNames(province, city, district)
        target.region = codes

        if (result.xzq.subArea) {
          target.detailedAddress = result.xzq.subArea
        } else if (result.address) {
          const fullAddr = result.address
          const prefix = province + city + district
          target.detailedAddress = fullAddr.startsWith(prefix) ? fullAddr.substring(prefix.length) : fullAddr
        }
      }

      if (type === 'sender') {
        senderRecognitionText.value = ''
      } else {
        receiverRecognitionText.value = ''
      }

      ElMessage.success('识别成功，请核对信息')
    } else {
      ElMessage.error(res.message || '识别失败')
    }
  } catch (error) {
    console.error('识别错误', error)
    ElMessage.error('识别失败，请重试')
  } finally {
    recognitionLoading.value = false
  }
}
// ================================================

const handleSenderRegionChange = (regionInfo) => {
  sender.provinceName = regionInfo.provinceName || ''
  sender.cityName = regionInfo.cityName || ''
  sender.countyName = regionInfo.districtName || ''
  sender.region = [regionInfo.provinceCode, regionInfo.cityCode, regionInfo.districtCode]
  if (sender.addressId) {
    sender.addressId = ''
  }
}

const handleReceiverRegionChange = (regionInfo) => {
  receiver.provinceName = regionInfo.provinceName || ''
  receiver.cityName = regionInfo.cityName || ''
  receiver.countyName = regionInfo.districtName || ''
  receiver.region = [regionInfo.provinceCode, regionInfo.cityCode, regionInfo.districtCode]
  if (receiver.addressId) {
    receiver.addressId = ''
  }
}

const handlePickupTimeChange = (value) => {
  if (value && deliveryFormRef.value) {
    deliveryFormRef.value.clearValidate(['pickupTime'])
  }
  // 解析逻辑保持不变（仅用于日志）
}

const handleSenderChange = () => {
  if (sender.addressId) {
    sender.addressId = ''
  }
}

const handleReceiverChange = () => {
  if (receiver.addressId) {
    receiver.addressId = ''
  }
}

const openAddressBook = (type) => {
  addressBookType.value = type
  addressBookVisible.value = true
}

const closeAddressBook = () => {
  addressBookVisible.value = false
}

const applyAddress = (address) => {
  if (address) {
    if (addressBookType.value === 'sender') {
      sender.addressId = address.addressId || ''
      sender.contactName = address.contactName || ''
      sender.contactPhone = address.contactPhone || ''
      sender.provinceName = address.provinceName
      sender.cityName = address.cityName
      sender.countyName = address.countyName
      sender.detailedAddress = address.detailedAddress || ''
      sender.defaultFlag = address.defaultFlag || '0'
      sender.region = getCodesByNames(sender.provinceName, sender.cityName, sender.countyName)

      senderOriginalAddress.value = {
        contactName: address.contactName || '',
        contactPhone: address.contactPhone || '',
        provinceName: address.provinceName || '',
        cityName: address.cityName || '',
        countyName: address.countyName || '',
        detailedAddress: address.detailedAddress || '',
        defaultFlag: address.defaultFlag || '0'
      }

      if (senderForm.value) {
        senderForm.value.clearValidate()
      }
    } else {
      receiver.addressId = address.addressId || ''
      receiver.contactName = address.contactName || ''
      receiver.contactPhone = address.contactPhone || ''
      receiver.provinceName = address.provinceName
      receiver.cityName = address.cityName
      receiver.countyName = address.countyName
      receiver.detailedAddress = address.detailedAddress || ''
      receiver.defaultFlag = address.defaultFlag || '0'
      receiver.region = getCodesByNames(receiver.provinceName, receiver.cityName, receiver.countyName)

      receiverOriginalAddress.value = {
        contactName: address.contactName || '',
        contactPhone: address.contactPhone || '',
        provinceName: address.provinceName || '',
        cityName: address.cityName || '',
        countyName: address.countyName || '',
        detailedAddress: address.detailedAddress || '',
        defaultFlag: address.defaultFlag || '0'
      }

      if (receiverForm.value) {
        receiverForm.value.clearValidate()
      }
    }
  }
}

const addToAddressBook = async (type) => {
  let formRef = null
  let formData = null

  if (type === 'sender') {
    formRef = senderForm.value
    formData = sender
  } else {
    formRef = receiverForm.value
    formData = receiver
  }

  if (!formRef) return

  const valid = await formRef.validate().catch(() => false)
  if (!valid) {
    ElMessage.warning('请先填写完整的地址信息')
    return
  }

  if (!formData.region || formData.region.length === 0) {
    ElMessage.warning('请选择省市区')
    return
  }

  const addressData = {
    addressId: formData.addressId || '',
    contactName: formData.contactName,
    contactPhone: formData.contactPhone,
    detailedAddress: formData.detailedAddress,
    provinceName: formData.provinceName || '',
    cityName: formData.cityName || '',
    countyName: formData.countyName || '',
    defaultFlag: type === 'sender' ? formData.defaultFlag : '0',
    tag: 'custom',
  }
  try {
    let response = {}
    if (formData.addressId) {
      response = await updateBook(addressData)
    } else {
      response = await addBook(addressData)
    }
    if (response.code === 200) {
      ElMessage.success('地址保存成功')
    } else {
      ElMessage.error(response.msg || '地址保存失败')
    }
  } catch (error) {
    console.error('保存地址失败:', error)
    ElMessage.error('地址保存失败')
  }
}

const handleInsuranceChange = (value) => {
  if (!value) {
    insuranceAmount.value = ''
    insuranceAmountError.value = ''
  }
}

const validateInsuranceAmount = () => {
  if (valueServices.insurance && insuranceAmount.value) {
    const amount = parseFloat(insuranceAmount.value)
    if (isNaN(amount) || amount <= 0) {
      insuranceAmountError.value = '保价金额必须大于0且为数字'
      return false
    }
    if (amount > 1000000) {
      insuranceAmountError.value = '保价金额不能超过100万'
      return false
    }
    const decimalPart = insuranceAmount.value.toString().split('.')[1]
    if (decimalPart && decimalPart.length > 2) {
      insuranceAmountError.value = '保价金额最多保留两位小数'
      return false
    }
    insuranceAmountError.value = ''
    return true
  } else if (valueServices.insurance && !insuranceAmount.value) {
    insuranceAmountError.value = '请填写保价金额'
    return false
  } else {
    insuranceAmountError.value = ''
    return true
  }
}

const handleSignReturnChange = (value) => {
  if (!value) {
    signReturnType.value = ''
    signReturnTypeError.value = ''
  } else {
    signReturnTypeError.value = ''
  }
}

const validateFormData = () => {
  let isValid = true
  if (valueServices.insurance) {
    if (!validateInsuranceAmount()) {
      isValid = false
    }
  }
  if (valueServices.signReturn && !signReturnType.value && productType == '2') {
    signReturnTypeError.value = '请选择签单返还凭证类型'
    isValid = false
  }
  return isValid
}

// 监听字典数据，当有值且当前未选择时，设置默认选中第一个
watch(jd_logistics_product_code, (val) => {
  if (productType.value === '1' && val && val.length > 0 && !deliveryForm.expressType) {
    deliveryForm.expressType = val[0].value;
  }
});
watch(sf_logistics_product_code, (val) => {
  if (productType.value === '2' && val && val.length > 0 && !deliveryForm.expressType) {
    deliveryForm.expressType = val[0].value;
  }
});
watch(jd_goods_type, (val) => {
  if (val && val.length > 0 && !itemInfo.type) {
    itemInfo.type = val[0].value;
  }
});

function close() {
  const obj = { path: "/waybill/order" }
  proxy.$tab.closeOpenPage(obj)
}

const isSubmit = ref(false)
const submitOrder = async () => {
  if (!agreed.value) {
    ElMessage.warning('请先同意服务协议')
    return
  }

  let senderValid = false
  try {
    await senderForm.value.validate()
    senderValid = true
  } catch (error) {
    senderValid = false
  }
  if (!senderValid) {
    ElMessage.warning('请填写完整的寄件人信息')
    return
  }

  let receiverValid = false
  try {
    await receiverForm.value.validate()
    receiverValid = true
  } catch (error) {
    receiverValid = false
  }
  if (!receiverValid) {
    ElMessage.warning('请填写完整的收件人信息')
    return
  }

  let deliveryValid = false
  try {
    await deliveryFormRef.value.validate()
    deliveryValid = true
  } catch (error) {
    deliveryValid = false
  }
  if (!deliveryValid) {
    ElMessage.warning('请填写完整的寄件方式信息')
    return
  }

  let itemInfoValid = false
  try {
    await itemInfoForm.value.validate()
    itemInfoValid = true
  } catch (error) {
    itemInfoValid = false
  }
  if (!itemInfoValid) {
    ElMessage.warning('请填写完整的物品信息')
    return
  }

  if (!validateFormData()) {
    return
  }
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true
  proxy.$modal.loading("正在创建订单，请稍候...")

  let formattedPickupStartTime = ''
  let formattedPickupEndTime = ''
  if (Array.isArray(deliveryForm.pickupTime) && deliveryForm.pickupTime.length > 0) {
    const timeArr = deliveryForm.pickupTime[1].split('-')
    formattedPickupStartTime = deliveryForm.pickupTime[0] + ' ' + timeArr[0] + ":00"
    formattedPickupEndTime = deliveryForm.pickupTime[0] + ' ' + timeArr[1] + ":00"
  }

  let services = {}
  if (productType.value == '1') {
    services = {
      isPack: valueServices.packaging ? true : null,
      guaranteeMoney: valueServices.insurance ? insuranceAmount.value : null,
      isReceiptCollect: valueServices.signReturn ? true : null
    }
  } else {
    services = {
      isPack: valueServices.packaging ? true : null,
      guaranteeMoney: valueServices.insurance ? insuranceAmount.value : null,
      isReceiptCollect: valueServices.signReturn ? signReturnType.value : null
    }
  }

  const orderData = {
    orderType: productType.value,
    senderName: sender.contactName,
    senderPhone: sender.contactPhone,
    senderProvince: sender.provinceName,
    senderCity: sender.cityName,
    senderCounty: sender.countyName,
    senderAddress: sender.detailedAddress,
    receiverName: receiver.contactName,
    receiverPhone: receiver.contactPhone,
    receiverProvince: receiver.provinceName,
    receiverCity: receiver.cityName,
    receiverCounty: receiver.countyName,
    receiverAddress: receiver.detailedAddress,
    goodsName: itemInfo.type, // 物品类型值
    goodsWeight: itemInfo.weight,
    goodsVolume: itemInfo.volume,
    goodsQty: itemInfo.quantity,
    sendStartTime: formattedPickupStartTime,
    sendEndTime: formattedPickupEndTime,
    productCode: deliveryForm.expressType,
    addedService: JSON.stringify(services),
  }

  try {
    const response = await addOrder(orderData)
    if (response.code == 200) {
      ElMessage.success('订单创建成功！')
      close()
    } else {
      isSubmit.value = false
    }
  } catch (error) {
    isSubmit.value = false
    console.error('订单提交失败:', error)
  } finally {
    proxy.$modal.closeLoading()
  }
}

const getDefaultAddressFun = async () => {
  try {
    const response = await getDefaultAddress()
    if (response.code == 200) {
      addressBookType.value = 'sender'
      applyAddress(response.data)
    }
  } catch (error) {
    console.error('获取默认地址失败:', error)
  }
}

// ========== 生成默认上门时间（今天一小时内，与组件算法一致） ==========
function getDefaultPickupTime() {
  const now = new Date();
  // 开始时间 = now + 30分钟
  let start = new Date(now.getTime() + 3 * 60000);
  // 分钟向上取整到10的倍数
  let minutes = start.getMinutes();
  let roundedMinutes = Math.ceil(minutes / 10) * 10;
  start.setMinutes(roundedMinutes, 0, 0);
  // 如果分钟进位导致小时增加，无需额外处理，setMinutes会自动处理

  // 合规性处理：开始时间不能早于9:00，不能晚于19:00（保证结束不超20:00）
  const startOfDay = new Date(now);
  startOfDay.setHours(9, 0, 0, 0);
  if (start < startOfDay) {
    start = startOfDay;
  }
  const maxStart = new Date(now);
  maxStart.setHours(19, 0, 0, 0);
  if (start > maxStart) {
    start = maxStart;
  }

  // 结束时间 = 开始 + 1小时
  let end = new Date(start.getTime() + 60 * 60000);
  const maxEnd = new Date(now);
  maxEnd.setHours(20, 0, 0, 0);
  if (end > maxEnd) {
    start = new Date(maxEnd.getTime() - 60 * 60000);
    end = maxEnd;
  }

  // 日期字符串 YYYY-MM-DD
  const year = start.getFullYear();
  const month = String(start.getMonth() + 1).padStart(2, '0');
  const day = String(start.getDate()).padStart(2, '0');
  const dateStr = `${year}-${month}-${day}`;

  // 时间范围 HH:MM-HH:MM
  const startHour = String(start.getHours()).padStart(2, '0');
  const startMin = String(start.getMinutes()).padStart(2, '0');
  const endHour = String(end.getHours()).padStart(2, '0');
  const endMin = String(end.getMinutes()).padStart(2, '0');
  const timeRange = `${startHour}:${startMin}-${endHour}:${endMin}`;

  return [dateStr, timeRange];
}
// =====================================================

onMounted(() => {
  productType.value = route.query.productType || '1';
  getDefaultAddressFun();

  // 设置默认上门时间
  deliveryForm.pickupTime = getDefaultPickupTime();
})
</script>

<style scoped>
/* 样式保持不变，与原来一致 */
.express-order-page {
  width: 100%;
  padding: 20px;
  background-color: #F5F7FA;
  min-height: 100vh;
  box-sizing: border-box;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-card {
  flex: 1;
  background: #ffffff;
  border-radius: 16px;
  overflow: hidden;
  position: relative;
}

.form-card.full-width {
  width: 100%;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  height: 50px;
  justify-content: space-between;
  padding: 16px 20px;
  background: #fff;
}

.card-header.send {
  border-radius: 16px 16px 0px 0px;
  background: linear-gradient(90deg, #EAF1FF 0%, #FFFFFF 100%);
}

.card-header.receive {
  border-radius: 16px 16px 0px 0px;
  background: linear-gradient(90deg, #FFF8E9 0%, #FFFFFF 100%);
}

.card-header.with-blue-line {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  background: #fff;
  border-radius: 16px 16px 0px 0px;
}

.blue-line {
  width: 4px;
  height: 16px;
  background: #2D71FF;
  border-radius: 2px;
}

.header-title {
  vertical-align: center;
  line-height: 30px;
  height: 30px;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  display: flex;
  align-content: center;
}

.header-title img {
  width: 30px;
  height: 30px;
  margin-right: 16px;
}

.address-book-btn {
  font-size: 14px;
}

.address-book-btn img {
  width: 20px;
  height: 20px;
  margin-right: 4px;
}

.form-content {
  padding: 20px;
  padding-bottom: 20px;
}

:deep(.fixed-input .el-input .el-input-group__append){
  box-shadow:none;
}


/* 输入框统一样式 */
:deep(.fixed-input .el-input__wrapper),
:deep(.fixed-input .el-cascader .el-input__wrapper),
:deep(.fixed-input .el-select .el-select__wrapper),
:deep(.fixed-input .el-input-number .el-input__wrapper) {
  width: 100%;
  box-sizing: border-box;
  background: #F5F7FA;
  border-radius: 4px;
  border: none;
  box-shadow: none !important;
}

:deep(.fixed-input .el-input__inner),
:deep(.fixed-input .el-cascader .el-input__inner),
:deep(.fixed-input .el-select .el-select__wrapper),
:deep(.fixed-input .el-input-number .el-input__inner) {
  background: #F5F7FA;
  width: 100%;
  box-sizing: border-box;
  text-align: left !important;
}

/* 统一筛选框样式 */
:deep(.fixed-input .el-select),
:deep(.fixed-input .el-cascader),
:deep(.fixed-input .el-input-number) {
  width: 100%;
  box-sizing: border-box;
}

:deep(.fixed-input .el-select .el-select__wrapper),
:deep(.fixed-input .el-cascader .el-input__wrapper),
:deep(.fixed-input .el-input-number .el-input__wrapper) {
  width: 100%;
  box-sizing: border-box;
  background: #F5F7FA;
  border-radius: 4px;
  border: none;
  box-shadow: none !important;
}

:deep(.fixed-input .el-select .el-select__wrapper),
:deep(.fixed-input .el-cascader .el-input__inner),
:deep(.fixed-input .el-input-number .el-input__inner) {
  background: #F5F7FA;
  width: 100%;
  box-sizing: border-box;
}

/* 下拉框选项样式 */
:deep(.el-select-dropdown) {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-select-dropdown__item) {
  padding: 8px 20px;
  font-size: 14px;
  color: #333;
}

:deep(.el-select-dropdown__item.selected) {
  color: #1890ff;
  background-color: #f0f7ff;
}

:deep(.el-select-dropdown__item:hover) {
  background-color: #f5f7fa;
}

/* 错误边框样式 */
.error-border :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #f56c6c !important;
}

/* Form 样式调整 */
:deep(.sender-form .el-form-item),
:deep(.receiver-form .el-form-item),
:deep(.item-info-form .el-form-item),
:deep(.delivery-form .el-form-item) {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

:deep(.sender-form .el-form-item__label),
:deep(.receiver-form .el-form-item__label),
:deep(.item-info-form .el-form-item__label),
:deep(.delivery-form .el-form-item__label) {
  text-align: left;
  font-size: 14px;
  color: #666666;
  font-weight: 500;
  padding-right: 12px;
  width: 120px;
  flex-shrink: 0;
  white-space: nowrap;
}

:deep(.sender-form .el-form-item.is-required .el-form-item__label::before),
:deep(.receiver-form .el-form-item.is-required .el-form-item__label::before),
:deep(.item-info-form .el-form-item.is-required .el-form-item__label::before),
:deep(.delivery-form .el-form-item.is-required .el-form-item__label::before) {
  color: #f56c6c;
  content: '*';
  margin-right: 4px;
}

:deep(.sender-form .el-form-item__content),
:deep(.receiver-form .el-form-item__content),
:deep(.item-info-form .el-form-item__content),
:deep(.delivery-form .el-form-item__content) {
  flex: 1;
  min-width: 0;
}

:deep(.sender-form .el-input-number),
:deep(.receiver-form .el-input-number),
:deep(.item-info-form .el-input-number) {
  width: 100%;
  flex: 1;
  min-width: 0;
}

/* 输入框样式修改 */
:deep(.fixed-input .el-input__wrapper:hover),
:deep(.fixed-input .el-cascader .el-input__wrapper:hover),
:deep(.fixed-input .el-select .el-input__wrapper:hover),
:deep(.fixed-input .el-input-number .el-input__wrapper:hover) {
  background: #F0F2F5;
}

:deep(.fixed-input .el-input__wrapper.is-focus),
:deep(.fixed-input .el-cascader .el-input__wrapper.is-focus),
:deep(.fixed-input .el-select .el-input__wrapper.is-focus),
:deep(.fixed-input .el-input-number .el-input__wrapper.is-focus) {
  background: #F5F7FA;
  box-shadow: 0 0 0 1px #409eff;
}

/* 调整el-input-number的特殊样式 */
:deep(.fixed-input .el-input-number) {
  //display: flex;
  //align-items: center;
}

:deep(.fixed-input .el-input-number .el-input-number__decrease),
:deep(.fixed-input .el-input-number .el-input-number__increase) {
  background-color: #F5F7FA;
  border: none;
  color: #666666;
}

:deep(.fixed-input .el-input-number .el-input-number__decrease:hover),
:deep(.fixed-input .el-input-number .el-input-number__increase:hover) {
  background-color: #E6E8EB;
}

:deep(.fixed-input .el-input-number .el-input-number__decrease.is-disabled),
:deep(.fixed-input .el-input-number .el-input-number__increase.is-disabled) {
  background-color: #F5F7FA;
  color: #C0C4CC;
}

:deep(.el-form-item__error) {
  padding-top: 4px;
  font-size: 12px;
}

/* 字数限制提示样式 */
:deep(.el-input__count) {
  color: #999;
  font-size: 12px;
}

:deep(.el-input__count .el-input__count-inner) {
  background: transparent;
}

/* 默认地址复选框 */
.default-address-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 10px;
}

.default-address-wrapper {
  display: flex;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.checkbox-text {
  font-size: 14px;
  color: #666;
  margin-left: 8px;
  font-weight: normal;
}

.default-address-radio :deep(.el-checkbox__label) {
  display: none;
}

.default-address-radio :deep(.el-checkbox__inner) {
  border-color: #409eff;
}

.add-address-btn {
  padding: 10px 24px;
  border-radius: 4px;
  background-color: #1890ff;
  border-color: #1890ff;
}

.add-address-btn:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 10px;
}

/* 寄件方式样式 */
.delivery-option {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.option-item {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.btn-radio {
  background: #EAF0FF;
  border-radius: 8px;
  border: 1px solid #2D71FF;
  padding: 10px 16px;
  display: inline-block;
  width: fit-content;
}

/* 寄件方式网格布局 */
.delivery-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

/* 物品信息网格布局 */
.item-info-grid-3 {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20px;
}

/* 物品信息网格布局 */
.item-info-grid-1 {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

/* 物品信息网格布局 */
.item-info-grid-2 {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

/* 增值服务样式调整 */
.value-services-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30px 50px;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.service-label {
  line-height: 40px;
  font-size: 14px;
  color: #333333;
  font-weight: 500;
  min-width: 80px;
  white-space: nowrap;
}

/* 保价样式 */
.insurance-wrapper {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.insurance-input-wrapper {
  flex: 1;
  min-width: 200px;

  :deep(.el-input-group__append){
    box-shadow: none;
  }
}

.insurance-input {
  width: 100%;
}

/* 签单返还样式 */
.sign-return-wrapper {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.sign-return-select-wrapper {
  flex: 1;
  min-width: 200px;
}

.sign-return-select {
  flex: 1;
  width: 100%;
  position: relative;
}

/* 错误信息样式 */
.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  position: absolute;
}

:deep(.el-switch) {
  --el-switch-on-color: #1890ff;
}

/* 提交订单区域 */
.agreement {
  display: flex;
  flex-direction: column;
  margin-left: 16px;
  gap: 12px;
  padding: 20px 0;
}

.price-notice {
  font-size: 14px;
  color: #ff7d00;
  font-weight: 500;
}

.submit-button {
  width: 120px;
  height: 48px;
  font-size: 16px;
  position: absolute;
  bottom: 27px;
  right: 16px;
}

.submit-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .value-services-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 25px;
  }

  .service-item {
    flex-wrap: wrap;
  }

  .insurance-wrapper,
  .sign-return-wrapper {
    flex-wrap: wrap;
  }
}

@media (max-width: 992px) {
  .item-info-grid-3 {
    grid-template-columns: 1fr 1fr;
  }

  .delivery-info-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .express-type-options {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
  }

  .item-info-grid-3 {
    grid-template-columns: 1fr;
  }

  .value-services-grid {
    grid-template-columns: 1fr;
  }

  .express-type-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .express-type-label {
    min-width: auto;
  }

  .insurance-wrapper,
  .sign-return-wrapper {
    flex-direction: column;
    gap: 10px;
  }

  .insurance-input-wrapper,
  .sign-return-select-wrapper {
    min-width: 100%;
  }

  .service-label {
    min-width: auto;
  }

  .service-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .agreement {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .submit-section {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }

  .submit-button {
    position: static;
    width: 100%;
    margin-top: 20px;
  }

  :deep(.sender-form .el-form-item__label),
  :deep(.receiver-form .el-form-item__label),
  :deep(.item-info-form .el-form-item__label),
  :deep(.delivery-form .el-form-item__label) {
    width: 80px !important;
  }

  .default-address-footer {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .form-footer {
    justify-content: flex-start;
  }
}


/* 添加识别区域样式 */
.recognition-area {
  background-color: #fff;
  //border-radius: 8px;
  //padding: 16px;
  margin-bottom: 20px;
  //border: 1px solid #e4e7ed;
}

.recognition-textarea :deep(.el-textarea__inner) {
  background-color: #F5F7FA;
  border: none;
  border-radius: 4px;
  font-size: 14px;
}

.recognition-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

.recognition-btn {
  width: 120px;
  height: 36px;
  background: #1B64F0;
  border-radius: 18px;
  font-size: 14px;
}

.recognition-tip {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
  line-height: 1.5;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>