<!-- 订单发货弹窗 -->
<template>
  <a-modal
    :visible="visible"
    title="订单发送货"
    width="600px"
    :confirm-loading="loading"
    @update:visible="updateVisible"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <!-- 配送方式 -->
      <a-form-item label="配送方式" name="deliveryType">
        <a-radio-group v-model:value="form.deliveryType">
          <a-radio :value="0">
            <span style="color: #1890ff;">快递配送</span>
          </a-radio>
          <a-radio :value="1">无需发货</a-radio>
          <a-radio :value="2">商家送货</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 发货类型 -->
      <a-form-item label="发货类型" name="deliveryMethod">
        <a-radio-group v-model:value="form.deliveryMethod">
          <a-radio value="manual">
            <span style="color: #1890ff;">手动填写</span>
          </a-radio>
          <a-radio value="print">电子面单打印</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 快递公司 -->
      <a-form-item
        label="快递公司"
        name="expressId"
        v-if="form.deliveryType === 0"
      >
        <a-row :gutter="8">
          <a-col :span="18">
            <a-select
              v-model:value="form.expressId"
              placeholder="请选择"
              show-search
              :filter-option="filterExpressOption"
              @change="onExpressChange"
            >
              <a-select-option
                v-for="express in expressList"
                :key="express.expressId"
                :value="express.expressId"
              >
                {{ express.expressName }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="6">
            <a-button type="primary" @click="openExpressModal">
              设置物流公司
            </a-button>
          </a-col>
        </a-row>
      </a-form-item>

      <!-- 快递单号 -->
      <a-form-item
        label="快递单号"
        name="trackingNumber"
        v-if="form.deliveryType === 0"
      >
        <a-input
          v-model:value="form.trackingNumber"
          placeholder="请输入快递单号"
          :maxlength="50"
        />
      </a-form-item>

      <!-- 分单发货 -->
      <a-form-item label="分单发货" v-if="form.deliveryType === 0">
        <a-switch
          v-model:checked="form.partialDelivery"
          checked-children="支持"
          un-checked-children="不支持"
        />
      </a-form-item>

      <!-- 发货备注 -->
      <a-form-item label="发货备注" name="deliveryNote">
        <a-textarea
          v-model:value="form.deliveryNote"
          placeholder="请输入发货备注（可选）"
          :rows="3"
          :maxlength="200"
          show-count
        />
      </a-form-item>

      <!-- 发货时间 -->
      <a-form-item label="发货时间" name="deliveryTime">
        <a-date-picker
          v-model:value="form.deliveryTime"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择发货时间"
          style="width: 100%"
        />
      </a-form-item>
    </a-form>

    <!-- 快递公司设置弹窗 -->
    <express-setting-modal
      v-model:visible="expressModalVisible"
      @done="loadExpressList"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { Form, message } from 'ant-design-vue';
import { ShopOrder } from '@/api/shop/shopOrder/model';
import { updateShopOrder } from '@/api/shop/shopOrder';
import { listShopExpress } from '@/api/shop/shopExpress';
import { ShopExpress } from '@/api/shop/shopExpress/model';
import { toDateString } from 'ele-admin-pro';
import dayjs, { Dayjs } from 'dayjs';
import ExpressSettingModal from './expressSettingModal.vue';

const useForm = Form.useForm;

const props = defineProps<{
  visible: boolean;
  data?: ShopOrder | null;
}>();

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void;
  (e: 'done'): void;
}>();

// 表单数据
const form = reactive({
  deliveryType: 0, // 0快递配送 1无需发货 2商家送货
  deliveryMethod: 'manual', // manual手动填写 print电子面单打印
  expressId: undefined as number | undefined,
  expressName: '',
  trackingNumber: '',
  partialDelivery: false,
  deliveryNote: '',
  deliveryTime: dayjs() as Dayjs
});

// 表单验证规则
const rules = {
  deliveryType: [
    { required: true, message: '请选择配送方式' }
  ],
  deliveryMethod: [
    { required: true, message: '请选择发货类型' }
  ],
  expressId: [
    {
      required: true,
      message: '请选择快递公司',
      validator: (_: any, value: any) => {
        if (form.deliveryType === 0 && !value) {
          return Promise.reject('请选择快递公司');
        }
        return Promise.resolve();
      }
    }
  ],
  trackingNumber: [
    {
      required: true,
      message: '请输入快递单号',
      validator: (_: any, value: any) => {
        if (form.deliveryType === 0 && !value) {
          return Promise.reject('请输入快递单号');
        }
        return Promise.resolve();
      }
    }
  ],
  deliveryTime: [
    { required: true, message: '请选择发货时间' }
  ]
};

const formRef = ref();
const { resetFields, validate } = useForm(form, rules);

// 状态
const loading = ref(false);
const expressList = ref<ShopExpress[]>([]);
const expressModalVisible = ref(false);

// 加载快递公司列表
const loadExpressList = async () => {
  try {
    const data = await listShopExpress({});
    expressList.value = data || [];
  } catch (error) {
    console.error('加载快递公司失败:', error);
  }
};

// 快递公司筛选
const filterExpressOption = (input: string, option: any) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 快递公司选择变化
const onExpressChange = (value: number) => {
  const express = expressList.value.find(item => item.expressId === value);
  if (express) {
    form.expressName = express.expressName || '';
  }
};

// 打开快递公司设置
const openExpressModal = () => {
  expressModalVisible.value = true;
};

// 更新弹窗显示状态
const updateVisible = (visible: boolean) => {
  emit('update:visible', visible);
};

// 取消
const handleCancel = () => {
  updateVisible(false);
};

// 提交发货
const handleSubmit = async () => {
  try {
    await validate();
    loading.value = true;

    const deliveryTime = toDateString(form.deliveryTime.toDate(), 'yyyy-MM-dd HH:mm:ss');

    const updateData = {
      ...props.data,
      deliveryStatus: 20, // 已发货
      deliveryType: form.deliveryType,
      deliveryTime: deliveryTime,
      deliveryNote: form.deliveryNote
    };

    // 如果是快递配送，添加快递信息
    if (form.deliveryType === 0) {
      updateData.expressId = form.expressId;
      updateData.expressName = form.expressName;
      updateData.trackingNumber = form.trackingNumber;
    }

    // 分单发货
    if(form.partialDelivery){
      updateData.deliveryStatus = 30;
    }

    await updateShopOrder(updateData);

    message.success('发货成功');
    emit('done');
    updateVisible(false);
  } catch (error: any) {
    message.error(error.message || '发货失败');
  } finally {
    loading.value = false;
  }
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      // 重置表单
      form.deliveryType = 0;
      form.deliveryMethod = 'manual';
      form.expressId = undefined;
      form.expressName = '';
      form.trackingNumber = '';
      form.partialDelivery = false;
      form.deliveryNote = '';
      form.deliveryTime = dayjs();

      // 加载快递公司列表
      loadExpressList();
    } else {
      resetFields();
    }
  }
);
</script>

<style scoped>
.ant-radio-wrapper {
  margin-right: 16px;
}
</style>
