<script lang="ts" setup>
/**
 * 独立「物流动态」弹窗：只请求 express-detail，不展示整单其它信息。
 * 仓名为空时 Tab 仅显示「包裹N」，与后端诊所开关抹名约定一致。
 * 已发货包裹展示脱敏收件人/查件手机号，并支持修改手机号与快递单号。
 */
import { computed, reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import {
  Button,
  Descriptions,
  Form,
  FormItem,
  Input,
  Modal as AModal,
  Spin,
  Tabs,
  Tag,
  Timeline,
  message,
} from 'ant-design-vue';

import ExpressCompanySelect from '#/components/form/components/express-company-select.vue';
import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';

import { expressDetailByOrderId, updateExpressNosApi } from '../api';

defineOptions({
  name: 'ProductOrderLogisticsModal',
});

const loading = ref(false);
const expressDetail = ref<Record<string, any>>({});
const activePkg = ref('0');
const orderId = ref<number | null>(null);

/** 改运单弹窗 */
const editVisible = ref(false);
const editSubmitting = ref(false);
const editForm = reactive({
  express_no_id: 0,
  express_no: '',
  mobile: '',
  express_company_code: '' as string | undefined,
});

/**
 * 多包裹列表：以物流接口 packages 为准（门店角色已按开关抹仓名）
 */
const packageTabs = computed(() => {
  const pkgs = expressDetail.value?.packages;
  return Array.isArray(pkgs) ? pkgs : [];
});

/**
 * Tab 文案：有仓名才拼括号，空串不兜底「平台/仓」
 */
function packageTabLabel(pkg: Record<string, any>, idx: number): string {
  const no = pkg.package_no || idx + 1;
  const name = String(pkg.warehouse_name || '').trim();
  return name ? `包裹${no}（${name}）` : `包裹${no}`;
}

/**
 * 收件人姓名脱敏：保留首字，其余用 *
 */
function maskExpressName(name: unknown): string {
  const str = String(name || '').trim();
  if (!str) {
    return '-';
  }
  if (str.length === 1) {
    return `${str}*`;
  }
  return str.slice(0, 1) + '*'.repeat(str.length - 1);
}

/**
 * 解析运单 ID：优先 express_no_id，其次 express.id
 */
function resolveExpressNoId(
  express: Record<string, any> | null | undefined,
  fallbackId?: number,
): number {
  const fromExpress = Number(express?.id || 0);
  const fromFallback = Number(fallbackId || 0);
  return fromExpress > 0 ? fromExpress : fromFallback;
}

/**
 * 物流状态 Tag 颜色
 */
function getColor(status: any) {
  switch (status) {
    case '在途': {
      return '';
    }
    case '揽收': {
      return 'orange';
    }
    case '派件': {
      return 'blue';
    }
    case '签收': {
      return 'green';
    }
    default: {
      return '';
    }
  }
}

async function loadExpress(id: number, keepActive = false) {
  loading.value = true;
  try {
    expressDetail.value = (await expressDetailByOrderId({ order_id: id })) || {};
    if (!keepActive) {
      activePkg.value = '0';
    }
  } finally {
    loading.value = false;
  }
}

/**
 * 打开改运单表单（包裹或旧单运单共用）
 */
function openEditExpress(payload: {
  express_no_id: number;
  express_no?: string;
  mobile?: string;
  express_company_code?: string;
}) {
  const id = Number(payload.express_no_id || 0);
  if (id <= 0) {
    message.warning('缺少运单信息，无法修改');
    return;
  }
  editForm.express_no_id = id;
  editForm.express_no = String(payload.express_no || '');
  editForm.mobile = String(payload.mobile || '');
  editForm.express_company_code = payload.express_company_code || undefined;
  editVisible.value = true;
}

/**
 * 提交修改运单号 / 查件手机号 / 快递公司
 */
async function submitEditExpress() {
  if (!editForm.express_no?.trim()) {
    message.warning('请输入快递单号');
    return;
  }
  if (!editForm.express_company_code) {
    message.warning('请选择快递公司');
    return;
  }
  if (!editForm.mobile?.trim()) {
    message.warning('请输入手机号');
    return;
  }
  editSubmitting.value = true;
  try {
    await updateExpressNosApi({
      express_no_id: editForm.express_no_id,
      express_no: editForm.express_no.trim(),
      mobile: editForm.mobile.trim(),
      express_company_code: editForm.express_company_code,
    });
    message.success('修改成功');
    editVisible.value = false;
    if (orderId.value) {
      await loadExpress(orderId.value, true);
    }
  } finally {
    editSubmitting.value = false;
  }
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  showConfirmButton: false,
  cancelText: '关闭',
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const payload = modalApi.getData<Record<string, any>>() || {};
      const id = Number(payload.order_id || payload.id || 0);
      orderId.value = id || null;
      expressDetail.value = {};
      editVisible.value = false;
      if (id) {
        loadExpress(id);
      }
    } else {
      orderId.value = null;
      expressDetail.value = {};
      activePkg.value = '0';
      editVisible.value = false;
    }
  },
});
</script>

<template>
  <Modal class="w-[640px]" title="物流动态">
    <Spin :spinning="loading">
      <div v-if="!orderId" class="text-gray-400 py-6 text-center">
        缺少订单信息
      </div>
      <template v-else>
        <Tabs
          v-if="packageTabs.length"
          v-model:active-key="activePkg"
          type="card"
        >
          <Tabs.TabPane
            v-for="(pkg, idx) in packageTabs"
            :key="String(idx)"
            :tab="packageTabLabel(pkg, idx)"
          >
            <template v-if="Number(pkg.is_send) === 1 && pkg.express">
              <Descriptions
                :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
                bordered
              >
                <Descriptions.Item label="收件人">
                  {{ maskExpressName(expressDetail.express_name) }}
                </Descriptions.Item>
                <Descriptions.Item label="手机号">
                  <span class="inline-flex items-center gap-2">
                    <SensitiveText :record="pkg.express" field="mobile" />
                    <Button
                      type="link"
                      size="small"
                      class="!px-0"
                      @click="
                        openEditExpress({
                          express_no_id: resolveExpressNoId(
                            pkg.express,
                            pkg.express_no_id,
                          ),
                          express_no: pkg.express.express_no,
                          mobile: pkg.express.mobile,
                          express_company_code: pkg.express.express_company_code,
                        })
                      "
                    >
                      修改
                    </Button>
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="物流公司">
                  {{ pkg.express.express_company_name || '-' }}
                </Descriptions.Item>
                <Descriptions.Item label="运单号">
                  <span class="inline-flex items-center gap-2">
                    <span>{{ pkg.express.express_no || '-' }}</span>
                    <Button
                      type="link"
                      size="small"
                      class="!px-0"
                      @click="
                        openEditExpress({
                          express_no_id: resolveExpressNoId(
                            pkg.express,
                            pkg.express_no_id,
                          ),
                          express_no: pkg.express.express_no,
                          mobile: pkg.express.mobile,
                          express_company_code: pkg.express.express_company_code,
                        })
                      "
                    >
                      修改
                    </Button>
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="最新状态">
                  {{ pkg.express.state_txt || '-' }}
                </Descriptions.Item>
              </Descriptions>
              <div class="mt-4">
                <h4 class="mb-2">物流追踪</h4>
                <Timeline
                  v-if="Array.isArray(pkg.express.detail) && pkg.express.detail.length"
                >
                  <Timeline.Item
                    v-for="(detail, dIdx) in pkg.express.detail"
                    :key="dIdx"
                  >
                    <Tag :color="getColor(detail.status)">{{ detail.status }}</Tag>
                    <p>{{ detail.detail_at }}</p>
                    <p>{{ detail.detail }}</p>
                  </Timeline.Item>
                </Timeline>
                <div v-else class="text-gray-400">暂无物流轨迹</div>
              </div>
            </template>
            <div v-else class="text-gray-400 py-2">本包裹尚未发货</div>
          </Tabs.TabPane>
        </Tabs>
        <template v-else>
          <Descriptions
            :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
            bordered
          >
            <Descriptions.Item label="收件人">
              {{ maskExpressName(expressDetail.express_name) }}
            </Descriptions.Item>
            <Descriptions.Item label="手机号">
              <span class="inline-flex items-center gap-2">
                <SensitiveText :record="expressDetail" field="mobile" />
                <Button
                  v-if="resolveExpressNoId(expressDetail, expressDetail.express_no_id)"
                  type="link"
                  size="small"
                  class="!px-0"
                  @click="
                    openEditExpress({
                      express_no_id: resolveExpressNoId(
                        expressDetail,
                        expressDetail.express_no_id,
                      ),
                      express_no: expressDetail.express_no,
                      mobile: expressDetail.mobile,
                      express_company_code: expressDetail.express_company_code,
                    })
                  "
                >
                  修改
                </Button>
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="物流公司">
              {{ expressDetail.express_company_name || '-' }}
            </Descriptions.Item>
            <Descriptions.Item label="运单号">
              <span class="inline-flex items-center gap-2">
                <span>{{ expressDetail.express_no || '-' }}</span>
                <Button
                  v-if="resolveExpressNoId(expressDetail, expressDetail.express_no_id)"
                  type="link"
                  size="small"
                  class="!px-0"
                  @click="
                    openEditExpress({
                      express_no_id: resolveExpressNoId(
                        expressDetail,
                        expressDetail.express_no_id,
                      ),
                      express_no: expressDetail.express_no,
                      mobile: expressDetail.mobile,
                      express_company_code: expressDetail.express_company_code,
                    })
                  "
                >
                  修改
                </Button>
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="最新状态">
              {{ expressDetail.state_txt || '-' }}
            </Descriptions.Item>
          </Descriptions>
          <div class="mt-4">
            <h4 class="mb-2">物流追踪</h4>
            <Timeline
              v-if="Array.isArray(expressDetail.detail) && expressDetail.detail.length"
            >
              <Timeline.Item
                v-for="(detail, index) in expressDetail.detail"
                :key="index"
              >
                <Tag :color="getColor(detail.status)">{{ detail.status }}</Tag>
                <p>{{ detail.detail_at }}</p>
                <p>{{ detail.detail }}</p>
              </Timeline.Item>
            </Timeline>
            <div v-else class="text-gray-400">暂无物流轨迹</div>
          </div>
        </template>
      </template>
    </Spin>
  </Modal>

  <!-- 修改运单号 / 查件手机号：与发货表单字段对齐，改单号时可重匹配公司 -->
  <AModal
    v-model:open="editVisible"
    title="修改运单信息"
    :confirm-loading="editSubmitting"
    destroy-on-close
    @ok="submitEditExpress"
  >
    <Form layout="vertical" class="mt-2">
      <FormItem label="快递单号" required>
        <Input
          v-model:value="editForm.express_no"
          placeholder="请输入快递单号"
          allow-clear
        />
      </FormItem>
      <FormItem label="快递公司" required>
        <ExpressCompanySelect
          v-model:value="editForm.express_company_code"
          placeholder="请选择快递公司"
          :tracking-no="editForm.express_no"
        />
      </FormItem>
      <FormItem label="手机号" required>
        <Input
          v-model:value="editForm.mobile"
          placeholder="请输入查件手机号"
          allow-clear
        />
      </FormItem>
    </Form>
  </AModal>
</template>

<style scoped>
.mt-4 {
  margin-top: 1rem;
}

.mb-2 {
  margin-bottom: 0.5rem;
}
</style>
