<template>
  <!-- 订单状态日志抽屉 -->
  <el-drawer v-model="drawerVisible" title="变更物流状态" size="38%" :destroy-on-close="true" :close-on-click-modal="true">
    <div class="status-log-container">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="物流单号" prop="logisticNos">
          <el-input v-model="form.logisticNos" disabled />
        </el-form-item>

        <el-form-item label="包裹单号" prop="packageNo">
          <el-input v-model="form.packageNo" disabled />
        </el-form-item>

        <el-form-item label="所在状态" prop="statusName">
          <el-select v-model="form.statusName" placeholder="请选择状态" style="width: 100%" @change="handleStatusChange">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="isStatusDisabled(item.value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="发货人" prop="shipper">
          <el-input v-model="form.shipper" disabled />
        </el-form-item>

        <el-form-item label="操作时间" prop="operateTime">
          <el-date-picker v-model="form.operateTime" type="date" placeholder="请选择操作时间" style="width: 100%" />
        </el-form-item>

        <el-form-item label="快递员手机号" prop="courierPhone">
          <el-input v-model="form.courierPhone" disabled />
        </el-form-item>

        <el-form-item label="上传图片" prop="images" v-if="form.statusName === '已签收'">
          <ImageUpload v-model="form.images" :limit="3" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="closeDrawer">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup name="AddOrderStatusLogDrawer" lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { addOrderStatusLog } from '@/api/order/orderStatusLog';
import ImageUpload from '@/components/ImageUpload/index.vue';

const drawerVisible = ref(false);
const submitLoading = ref(false);
const formRef = ref<any>(null);

// 表单数据
const form = reactive({
  orderNo: '',
  orderId: undefined as string | number | undefined,
  customerNo: '',
  customerId: undefined as string | number | undefined,
  deliverMethod: '0',
  statusName: '',
  logisticNos: '',
  packageNo: '',
  shipper: '',
  operateTime: '',
  courierPhone: '',
  images: '',
  status: '0'
});

// 状态顺序定义
const statusOrder = ['已下单', '已揽件', '运输中', '派件中', '已签收'];

// 当前订单状态
const currentStatus = ref('');

// 状态选项
const statusOptions = [
  { label: '已下单', value: '已下单' },
  { label: '已揽件', value: '已揽件' },
  { label: '运输中', value: '运输中' },
  { label: '派件中', value: '派件中' },
  { label: '已签收', value: '已签收' }
];
const rules = {
  statusName: [{ required: true, message: '请选择状态名称', trigger: 'change' }]
};

// 打开抽屉
const openDrawer = (orderData?: any, currentOrderStatus?: string) => {
  if (orderData) {
    form.orderNo = orderData.orderNo || '';
    form.orderId = orderData.orderId || '';
    form.shipper = orderData.deliverMan || '';
    form.courierPhone = orderData.phone || '';
    form.packageNo = orderData.deliverCode || '';
    form.logisticNos = orderData.deliverCode || '';
    form.customerNo = orderData.customerNo || '';
    form.customerId = orderData.customerId;
    form.operateTime = orderData.createTime || '';
    form.deliverMethod = orderData.deliverMethod || '0';
    form.statusName = currentOrderStatus || '';
    form.images = orderData.images || '';

    currentStatus.value = currentOrderStatus || '';
  }
  drawerVisible.value = true;
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false;
  resetForm();
};

// 判断是否禁用某个状态选项
const isStatusDisabled = (statusValue: string) => {
  if (!currentStatus.value) return false;
  const currentIndex = statusOrder.indexOf(currentStatus.value);
  const targetIndex = statusOrder.indexOf(statusValue);
  // 如果目标状态在当前状态之前(索引更小),则禁用
  return targetIndex < currentIndex;
};

// 重置表单
const resetForm = () => {
  form.statusName = '';
  form.logisticNos = '';
  form.packageNo = '';
  form.orderId = undefined;
  form.shipper = '';
  form.operateTime = '';
  form.courierPhone = '';
  form.images = '';
  currentStatus.value = '';
};

// 状态变化处理
const handleStatusChange = () => {
  // 当状态变化时,如果不是已签收,清空图片
  if (form.statusName !== '已签收') {
    form.images = '';
  }
};
const handleSubmit = async () => {
  await formRef.value?.validate();
  submitLoading.value = true;
  try {
    await addOrderStatusLog(form);
    ElMessage.success('保存成功');
    closeDrawer();
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  } finally {
    submitLoading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  openDrawer
});
</script>

<style scoped>
.status-log-container {
  padding: 20px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
