<script setup lang="ts">
import { ref, computed, onBeforeMount } from 'vue';
import { VxeUI } from 'vxe-pc-ui';
import { notification } from 'ant-design-vue';
import { getDictionaryMethod } from '@/request/api/dictionary.api';
import { confirmShipmentMethod } from '@/request/api/order.api';
import type { ShipmentModel } from '@/model/order.model';
import { useRequest } from 'alova/client';
type FollowModel = Partial<ShipmentModel>;
interface ShipmentForm {
  receiptType: string; // 发货形式 0-配送 1-线下取货
  expressType?: string; // 快递类型 0-邮政速递 1-顺丰速运 2-京东快递 3-中通快递 4-圆通速递 5-申通快递 6-韵达快递 7-极兔速递
  expressNo?: string; // 快递单号
}

const props = defineProps<{ data: FollowModel }>();

const emits = defineEmits<{
  submit: [data?: ShipmentModel];
}>();

// 提交状态
const { loading: submitting, send: submit } = useRequest(confirmShipmentMethod, { immediate: false }).onSuccess(() => {

})
// 快递类型选项列表
const expressTypeOptions = ref<{ label: string; value: string }[]>([]);

const formData = ref<ShipmentForm>({
  receiptType: '1', // 默认选择线下取货
  expressType: '',
  expressNo: '',
});

// 快递类型选项
const expressTypeOptionsList = [
  { label: '邮政速递', value: '0' },
  { label: '顺丰速运', value: '1' },
  { label: '京东快递', value: '2' },
  { label: '中通快递', value: '3' },
  { label: '圆通速递', value: '4' },
  { label: '申通快递', value: '5' },
  { label: '韵达快递', value: '6' },
  { label: '极兔速递', value: '7' },
];

onBeforeMount(async () => {
  try {
    const res = await getDictionaryMethod('logistics_company').catch(() => null);
    if (res && Array.isArray(res) && res.length > 0) {
      expressTypeOptions.value = res;
    } else {
      // 如果没有字典数据，使用默认选项
      expressTypeOptions.value = expressTypeOptionsList;
    }
  } catch (error) {
    // 使用默认数据
    expressTypeOptions.value = expressTypeOptionsList;
  }

  if (props.data) {
    formData.value.receiptType = props.data.receiptType || '1';
    formData.value.expressType = props.data.expressType || '';
    formData.value.expressNo = props.data.expressNo || '';
  }
});


const showDeliveryFields = computed(() => formData.value.receiptType === '0');


const handleReceiptTypeChange = (e: any) => {
  formData.value.receiptType = e.target.value;
  if (formData.value.receiptType === '1') {
    formData.value.expressType = '';
    formData.value.expressNo = '';
  }
};

// 提交表单
const handleSubmit = async () => {
  if (submitting.value) return;

  if (formData.value.receiptType === '0') {
    if (!formData.value.expressType) {
      notification.warning({
        message: '提示',
        description: '请选择快递类型',
      });
      return;
    }
    if (!formData.value.expressNo?.trim()) {
      notification.warning({
        message: '提示',
        description: '请输入快递单号',
      });
      return;
    }
  }


  const receiptType = formData.value.receiptType;
  const expressType = formData.value.receiptType === '0' ? formData.value.expressType : '';
  const expressNo = formData.value.receiptType === '0' ? formData.value.expressNo : '';

  const id = props.data?.id;
  if (!id) {
    notification.error({
      message: '缺少患者调理方案ID',
    });
    return;
  }
  const submitData = {
    id,
    conditioningProgramSupplierId: props.data?.conditioningProgramSupplierId,
    receiptType,
    expressType : expressType || '',
    expressNo : expressNo || '',
  } as any;
  try {
    await submit(submitData);
    notification.success({
      message: '操作成功',
      description: '发货成功',
    });
    emits('submit');
  } catch (error) {
    console.error('发货失败:', error);
  }
}
// 取消操作
const handleCancel = () => {
  VxeUI.modal.close('shipment-modal');
};

</script>

<template>
  <div class="shipment-form">
    <!-- 标题 -->
    <div class="form-title">发货</div>
    <!-- 发货类型选择 -->
    <div class="form-section">
      <a-radio-group v-model:value="formData.receiptType" @change="handleReceiptTypeChange" class="delivery-type-group">
        <a-radio value="1">线下取货</a-radio>
        <a-radio value="0">配送</a-radio>
      </a-radio-group>
    </div>

    <!-- 配送相关字段（仅在选择配送时显示） -->
    <div v-if="showDeliveryFields" class="form-section delivery-fields-container">
      <!-- 快递类型 -->
      <div class="form-item">
        <label class="form-label">快递类型</label>
        <a-select v-model:value="formData.expressType" placeholder="请选择" class="form-select"
          :options="expressTypeOptions" show-search :filter-option="(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())" />
      </div>

      <!-- 快递单号 -->
      <div class="form-item">
        <label class="form-label">快递单号</label>
        <a-input v-model:value="formData.expressNo" placeholder="请输入" class="form-input" />
      </div>

      <!-- 提示信息 -->
      <div class="form-tip">
        请检查物流信息是否正确，每条商品仅支持一次修改
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <vxe-button @click="handleCancel" content="取消" class="cancel-btn" :disabled="submitting">取消</vxe-button>
      <vxe-button type="submit" @click="handleSubmit" status="primary" class="confirm-btn"
        :loading="submitting">确定</vxe-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.shipment-form {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 400px;
  padding: 24px 24px 100px 24px;
  background: #fff;
}

.form-title {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 24px;
  color: #000;
}

.form-section {
  margin-bottom: 20px;
}

.delivery-type-group {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-bottom: 20px;

  :deep(.ant-radio-wrapper) {
    font-size: 14px;
  }
}

.delivery-fields-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  width: 100%;
  justify-content: center;

  .form-label {
    min-width: 80px;
    font-size: 14px;
    color: #000;
    margin-right: 12px;
    text-align: left;
  }

  .form-select,
  .form-input {
    flex: 1;
    max-width: 300px;
  }
}

.form-tip {
  font-size: 14px;
  color: #000;
  margin-bottom: 0;
  line-height: 1.5;
  text-align: center;
  width: 100%;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: auto;
  padding-top: 24px;

  .cancel-btn {
    min-width: 80px;
    border: 1px solid #1890ff;
    background: #fff;
    color: #1890ff;

    &:hover {
      border-color: #40a9ff;
      color: #40a9ff;
    }
  }

  .confirm-btn {
    min-width: 80px;
    background: #1890ff;
    border-color: #1890ff;
    color: #fff;

    &:hover {
      background: #40a9ff;
      border-color: #40a9ff;
    }
  }
}
</style>
