<template>
  <view class="container">
    <uv-form labelPosition="top" labelWidth="100" :model="formModel" :rules="deliveryRules" ref="deliveryFormRef">
      <view class="formContent">
        <view class="title">配送信息</view>
        <uv-line color="#a8a8a8"></uv-line>
        <uv-form-item label="发货地" prop="originName">
          <uv-input placeholder="请输入内容" v-model="formModel.originName" clearable />
        </uv-form-item>
        <uv-form-item label="目的地" prop="destName">
          <uv-input placeholder="请输入内容" v-model="formModel.destName" clearable />
        </uv-form-item>
        <uv-form-item label="配送日期" prop="deliveryDate">
          <view class="carPickerText" :style="formModel.deliveryDate ? 'color: #303133;' : ''" @tap="openCalendar">{{ formModel.deliveryDate || '请选择配送日期'}}</view>
        </uv-form-item>
        <uv-form-item label="发货人" prop="shipperName">
          <uv-input placeholder="请输入内容" v-model="formModel.shipperName" clearable />
        </uv-form-item>
        <uv-form-item label="发货人电话" prop="shipperPhone">
          <uv-input placeholder="请输入内容" maxlength="11" type="number" v-model="formModel.shipperPhone" clearable />
        </uv-form-item>
        <uv-form-item label="接收人" prop="receiverName">
          <uv-input placeholder="请输入内容" v-model="formModel.receiverName" clearable />
        </uv-form-item>
        <uv-form-item label="接收人电话" prop="receiverPhone">
          <uv-input placeholder="请输入内容" maxlength="11" type="number" v-model="formModel.receiverPhone" clearable />
        </uv-form-item>
        <uv-form-item label="接收单位" prop="receiverOrgName">
          <uv-input placeholder="请输入内容" v-model="formModel.receiverOrgName" clearable />
        </uv-form-item>
      </view>
      <view class="formContent" style="margin-top: 20rpx;">
        <view class="title">货物信息</view>
        <uv-line color="#a8a8a8"></uv-line>
        <view style="display: flex;align-items: center;">
          <!-- <uv-form-item label="配送吨位" prop="deliveryTon">
            <uv-input placeholder="请输入内容" v-model="formModel.deliveryTon"clearable />
          </uv-form-item> -->
          <view style="flex: 1;">
            <!-- <uv-form-item label="高速费用" prop="tollFee">
              <uv-input placeholder="请输入内容" type="digit" v-model="formModel.tollFee" clearable />
            </uv-form-item> -->
            <uv-form-item label="总公里数" prop="totalKm">
              <uv-input placeholder="请输入内容" type="digit" v-model="formModel.totalKm" clearable />
            </uv-form-item>
          </view>
          <view class="matchCar" @tap="autoComputed(true)">
            <view>匹配</view>
            <view>车型</view>
          </view>
        </view>
      </view>
      <view class="formContent" style="margin-top: 20rpx;">
        <view class="title">配送车辆</view>
        <uv-line color="#a8a8a8"></uv-line>
        <uv-form-item label="车型" prop="vehicleTypeName">
          <view class="carPickerText" :style="formModel.vehicleTypeName ? 'color: #303133;' : ''" @tap="openCarPicker">{{ formModel.vehicleTypeName || '请选择配送车型'}}</view>
        </uv-form-item>
      </view>
    </uv-form>

    <uv-picker ref="carPicker" :columns="carColumns" keyName="name" @confirm="carConfirm"></uv-picker>

    <uv-calendar ref="calendar" @confirm="confirm"></uv-calendar>

    
    <view class="priceBtn">
      <view>预估价格：<text style="color: #D55A66;">￥</text><text class="price">{{ formModel.suggestFee || "0.00" }}</text></view>
      <uv-button type="primary" size="large" class="mainBtn" @click="submitForm">发布配送</uv-button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { autoCarAndPrice, sendOrder, getCarList } from "@/api/index"

const deliveryFormRef = ref()
const formModel = ref({
  originName: '',
  destName: '',
  deliveryDate: '',
  shipperName: '',
  shipperPhone: '',
  receiverName: '',
  receiverPhone: '',
  receiverOrgName: '',
  tollFee: '',
  totalKm: '',
  vehicleTypeName: '',
  // originName: '贾庵子',
  // destName: '路北供电室',
  // deliveryDate: '2025-10-28',
  // shipperName: '林总',
  // shipperPhone: '13000000000',
  // receiverName: '王总',
  // receiverPhone: '13100000000',
  // receiverOrgName: '供电所',
  // tollFee: '',
  // totalKm: '10',
  // vehicleTypeName: '',
})
const deliveryRules = ref({
  'originName': {
    type: 'string',
    required: true,
    message: '请输入起点位置',
    trigger: ['blur', 'change']
  },
  'destName': {
    type: 'string',
    required: true,
    message: '请输入终点位置',
    trigger: ['blur', 'change']
  },
  'deliveryDate': {
    type: 'string',
    required: true,
    message: '请选择配送日期',
    trigger: ['blur', 'change']
  },
  'shipperName': {
    type: 'string',
    required: true,
    message: '请输入发货人',
    trigger: ['blur', 'change']
  },
  'shipperPhone': [
    {
      type: 'string',
      required: true,
      message: '请输入发货人电话',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        // 自定义校验逻辑
        return uni.$uv.test.mobile(value)
      },
      message: '请输入正确的手机号',
      trigger: ['blur', 'change']
    }
  ],
  'receiverName': {
    type: 'string',
    required: true,
    message: '请输入接收人',
    trigger: ['blur', 'change']
  },
  'receiverPhone': [
    {
      type: 'string',
      required: true,
      message: '请输入接收人电话',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        // 自定义校验逻辑
        return uni.$uv.test.mobile(value)
      },
      message: '请输入正确的手机号',
      trigger: ['blur', 'change']
    }
  ],
  'receiverOrgName': {
    type: 'string',
    required: true,
    message: '请输入接收单位',
    trigger: ['blur', 'change']
  },
  'tollFee': {
    type: 'float',
    required: true,
    message: '请输入高速费用',
    trigger: ['blur', 'change']
  },
  'totalKm': {
    type: 'float',
    required: true,
    message: '请输入总公里数',
    trigger: ['blur', 'change']
  },
  'vehicleTypeName': {
    type: 'string',
    required: true,
    message: '请选择配送车型',
    trigger: ['blur', 'change']
  },
})

// 配送日期选择器
const openCalendar = () => {
  calendar.value.open()
}
const calendar = ref()
const confirm = (e) => {
  console.log(e)
  formModel.value.deliveryDate = e[0]
}



// 配送车辆选择器
const openCarPicker = () => {
  carPicker.value.open()
}
const carPicker = ref()
const carColumns = ref([])
const carConfirm = (e) => {
  console.log(e)
  // formModel.value.vehicleTypeId = e.indexs
  formModel.value.vehicleTypeName = e.value[0].name
  formModel.value.vehicleTypeId = e.value[0].id
  autoComputed(false)
}


const submitForm = () => {
  console.log(formModel.value)
  
  deliveryFormRef.value.validate().then(res => {
    let params = {
      ...formModel.value,
      items:selectedInfo.value.detailList
    }
    console.log(params)
    sendOrder(params).then(res => {
      console.log(res)
      uni.$uv.toast('发布成功')
      uni.reLaunch({ url: '/pages/index/index' })
    })
  }).catch(errors => {
  })
}

let selectedInfo = ref({})

const autoComputed = (status) => {
  if (!formModel.value.totalKm) {
    uni.$uv.toast('请输入总公里数')
    return
  }
  let selectedParams = ref({
    weightTon: 0,
    volumeM3: 0,
    distanceKm: 0,
  })
  selectedParams.value.weightTon = formModel.value.deliveryTon
  selectedParams.value.volumeM3 = formModel.value.goodsSize
  selectedParams.value.distanceKm = formModel.value.totalKm
  if (!status) {
    selectedParams.value.vehicleTypeId = formModel.value.vehicleTypeId
  }
  autoCarAndPrice(selectedParams.value).then(res => {
    console.log(res)
    if (res.data.errorMessage) {
      uni.$uv.toast(res.data.errorMessage)
      return
    }
    if (status) {
      console.log("变")
      carColumns.value[0] = res.data.candidates
      formModel.value.vehicleTypeName = res.data.vehicleTypeName
      formModel.value.vehicleTypeId = res.data.vehicleTypeId
    }
    formModel.value.suggestFee = res.data.suggestFee
  })
}

// const getCarDataList = () => {
//   let obj = {
//     page: 1,
//     pageSize: 100,
//   }
//   getCarList(obj).then(res => {
//     console.log(res)
//     // carColumns.value[0] = res.rows
//   })
// }

onLoad(() => {
  const instance = getCurrentInstance().proxy
  const eventChannel = instance.getOpenerEventChannel();
  eventChannel.on('acceptData', function(data) {
    console.log('acceptData',data)
    selectedInfo.value = data.data
    if (data.totalWeightKg) {
      formModel.value.deliveryTon = data.totalWeightKg / 1000
      formModel.value.goodsSize = data.goodsSize / 1000
    } else {
      formModel.value.deliveryTon = selectedInfo.value.detailList.reduce((pre, cur) => pre + cur.totalWeight * 100000, 0) / 100000000
      formModel.value.goodsSize = selectedInfo.value.detailList.reduce((pre, cur) => pre + cur.totalVolume * 100000, 0) / 100000000
    }
    console.log(formModel.value)
    // getCarDataList()
  })
})

onShow(() => {
})


</script>

<style scoped lang="scss">
.container {
  padding: 32rpx;
  background-color: #F6F8FA;
  padding-bottom: 160rpx;
  // ::v-deep .uv-input{
  //   border: unset;
  // }
  .title {
    // font-size: 28rpx;
    font-weight: bold;
    // display: flex;
    // align-items: center;
    // margin-left: 20rpx;
    // margin-bottom: 20rpx;
    color: #333333;
    padding: 20rpx 0;
  }
  .formContent {
    background-color: white;
    border-radius: 20rpx;
    padding: 0 20rpx;
  }
  .matchCar{
    width: 120rpx;
    height: 120rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    background-color: #3c9cff;
    border-radius: 10rpx;
    color: white;
    margin-left: 20rpx;
  }
  .carPickerText{
    padding: 16rpx 18rpx;
    padding-left: 20rpx;
    color: #c0c4cc;
    border: #dadbde 1px solid;
    border-radius: 8rpx;
    width: 100%;
  }
  .priceBtn{
    position: fixed;
    width: 100vw;
    padding: 16rpx 32rpx;
    bottom: 0;
    left: 0;
    z-index: 99;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: white;
    box-sizing: border-box;
    .price {
      font-size: 42rpx;
      color: #D55A66;
    }
    ::v-deep .uv-button--large{
      padding: 0 60rpx !important;
    }
  }
}

</style>