<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户编号" prop="customerCode">
              <el-input v-model="queryParams.customerCode" placeholder="请输入客户编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单来源" prop="orderSource">
              <el-select v-model="queryParams.orderSource" placeholder="请选择订单来源" clearable>
                <el-option v-for="dict in order_source" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
                <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="业务员" prop="">
              <el-select v-model="queryParams.orderStatus" placeholder="请选择业务员" clearable> </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="">
              <el-select v-model="queryParams.orderStatus" placeholder="请选择部门" clearable> </el-select>
            </el-form-item> -->
            <el-form-item label="提交时间" prop="createTime">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery()">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8" type="flex" justify="space-between" align="middle">
          <!-- 左侧标题 -->
          <span style="font-size: 16px; font-weight: 500">发货单信息列表</span>
          <div style="display: flex; flex-wrap: nowrap; gap: 10px">
            <el-button type="primary" @click="handleCloseOrder()" :disabled="!ids.length" plain>关闭订单</el-button>
            <el-button type="primary" @click="handleDelete()" :disabled="!ids.length" plain>删除订单</el-button>
            <el-button type="primary" :disabled="!ids.length" plain>导出订单</el-button>
          </div>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="orderMainList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="发货单编号" align="center" prop="shipmentNo" />
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="关联单号" align="center" prop="parentOrderNo" />
        <el-table-column label="平台\项目订单号" align="center" prop="projectOrderNo">
          <template #default="scope">
            <span>{{ scope.row._crrcOrderNo || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="customerName">
          <template #default="scope">
            <span>{{ scope.row.customerName || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="orderStatus">
          <template #default="scope">
            <dict-tag :options="order_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" v-if="scope.row.orderStatus != '4'" @click="handleDeliver(scope.row)">发货</el-button>
            <el-button link type="primary" v-if="scope.row.orderStatus > '2'" @click="handleReview(scope.row)">查看发货信息</el-button>
            <el-button link type="primary" v-else @click="handleReview(scope.row)">查看订单信息</el-button>
            <!-- <el-button link type="primary" @click="handleCancel(scope.row)">取消订单</el-button> -->
            <el-button
              link
              type="primary"
              v-if="scope.row.orderStatus == '3' || scope.row.orderStatus == '4' || scope.row.orderStatus == '5'"
              @click="handleViewLogistics(scope.row)"
              >查看物流</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 发货对话框 -->
    <DeliverDialog v-model="showDeliverDialog" :order-id="currentOrderId" :order-no="currentOrderNo" @success="handleDeliverSuccess" />

    <LogisticsDetail v-model="showLogisticsDialog" :order-id="logisticsOrderId" />
  </div>
</template>

<script setup name="OrderMain" lang="ts">
import {
  listOrderMain,
  getOrderMain,
  delOrderMain,
  addOrderMain,
  updateOrderMain,
  queryOrderStatusStats,
  closeOrderMain,
  changeStatus
} from '@/api/order/orderMain';
import { OrderMainVO, OrderMainQuery, OrderMainForm } from '@/api/order/orderMain/types';
import DeliverDialog from '../saleOrder/deliverDialog.vue';
import LogisticsDetail from '../saleOrder/logisticsDetail.vue';
import { getOrderMainCrrcExt } from '@/api/order/orderMainCrrcExt';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status, fee_type, pay_method, order_source, deliver_method } = toRefs<any>(
  proxy?.useDict('order_status', 'fee_type', 'pay_method', 'order_source', 'deliver_method')
);

const orderMainList = ref<OrderMainVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const router = useRouter();
const queryFormRef = ref<ElFormInstance>();
const orderMainFormRef = ref<ElFormInstance>();
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

// 发货对话框
const showDeliverDialog = ref(false);
const currentOrderId = ref<string | number>();
const currentOrderNo = ref<string>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const showLogisticsDialog = ref(false);
const logisticsOrderId = ref<string | number>();

const orderStatusStats = ref({
  pendingPaymentCount: 0, // 待支付
  pendingShipmentCount: 0, // 待发货
  shippedCount: 0, // 已发货（发货完成）
  completedCount: 0, // 已完成
  closedCount: 0, // 已关闭
  totalCount: 0 // 全部订单
});

const initFormData: OrderMainForm = {
  id: undefined,
  orderNo: undefined,
  isSplitChild: undefined,
  shipmentNo: undefined,
  subOrderNo: undefined,
  companyId: undefined,
  customerId: undefined,
  customerCode: undefined,
  userId: undefined,
  shippingAddressId: undefined,
  purchaseReason: undefined,
  invoiceType: undefined,
  payType: undefined,
  warehouseId: undefined,
  creditLimit: undefined,
  expectedDeliveryTime: undefined,
  businessStaff: undefined,
  customerService: undefined,
  businessDept: undefined,
  userDept: undefined,
  productQuantity: undefined,
  shippingFee: undefined,
  totalAmount: undefined,
  payableAmount: undefined,
  paymentStatus: undefined,
  orderSource: undefined,
  orderStatus: undefined,
  orderTime: undefined,
  confirmTime: undefined,
  shippingTime: undefined,
  receivingTime: undefined,
  shippedQuantity: undefined,
  unshippedQuantity: undefined,
  packageCount: undefined,
  signedQuantity: undefined,
  afterSaleCompleted: undefined,
  afterSalePending: undefined,
  deliveryDesc: undefined,
  pushStatus: undefined,
  attachmentPath: undefined,
  deliveryType: undefined,
  orderCategory: undefined,
  productCode: undefined,
  cancelReason: undefined,
  expenseType: undefined,
  userNo: undefined,
  status: undefined,
  remark: undefined,
  orderProductBos: [],
  customerSalesInfoVo: {}
};
const data = reactive<PageData<OrderMainForm, OrderMainQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    shipmentNo: undefined,
    subOrderNo: undefined,
    companyId: undefined,
    customerCode: undefined,
    customerId: undefined,
    userId: undefined,
    purchaseReason: undefined,
    invoiceType: undefined,
    payType: undefined,
    warehouseId: undefined,
    creditLimit: undefined,
    expectedDeliveryTime: undefined,
    businessStaff: undefined,
    customerService: undefined,
    businessDept: undefined,
    userDept: undefined,
    paymentStatus: undefined,
    orderSource: undefined,
    orderStatus: undefined,
    orderStatuses: '1,2,3,4',
    orderTime: undefined,
    confirmTime: undefined,
    shippingTime: undefined,
    receivingTime: undefined,
    deliveryType: undefined,
    orderCategory: undefined,
    productCode: undefined,
    expenseType: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    customerId: [{ required: true, message: '客户ID不能为空', trigger: 'blur' }],
    payType: [{ required: true, message: '支付方式不能为空', trigger: 'change' }],
    warehouseId: [{ required: true, message: '发货仓库不能为空', trigger: 'change' }],
    expectedDeliveryTime: [{ required: true, message: '预计送达时间不能为空', trigger: 'blur' }],
    shippingFee: [{ required: true, message: '运费不能为空', trigger: 'blur' }],
    confirmTime: [{ required: true, message: '确认时间不能为空', trigger: 'blur' }],
    shippingTime: [{ required: true, message: '发货时间不能为空', trigger: 'blur' }],
    receivingTime: [{ required: true, message: '收货时间不能为空', trigger: 'blur' }],
    cancelReason: [{ required: true, message: '取消或异常原因不能为空', trigger: 'blur' }],
    expenseType: [{ required: true, message: '费用类型不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单主信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrderMain(proxy?.addDateRange(queryParams.value, dateRange.value));
  const rows = res.rows;
  await fetchCrrcOrderNos(rows);
  orderMainList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  queryOrderStatusStatsMethod();
};

/** 取消订单按钮操作 */
const handleCancel = async (row?: OrderMainVO) => {
  try {
    await proxy?.$modal.confirm('是否确认取消该订单？');
    await changeStatus(row.id, '7');
    getList();
    proxy?.$modal.msgSuccess('操作成功');
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      proxy?.$modal.msgError('操作失败，请重试');
    }
  }
};

// 批量获取平台订单号
const fetchCrrcOrderNos = async (rows: OrderMainVO[]) => {
  const results = await Promise.allSettled(
    rows.map((row) => {
      const id = row.parentOrderId || row.id;
      if (!id) return Promise.resolve(null);
      return getOrderMainCrrcExt(id);
    })
  );
  rows.forEach((row, i) => {
    const result = results[i];
    if (result.status === 'fulfilled') {
      (row as any)._crrcOrderNo = result.value?.data?.crrcOrderNo || '';
    } else {
      (row as any)._crrcOrderNo = '';
    }
  });
};

/** 查看物流按钮操作 */
const handleViewLogistics = (row?: OrderMainVO) => {
  if (!row?.id) {
    proxy?.$modal.msgWarning('订单ID不能为空');
    return;
  }
  logisticsOrderId.value = row.id;

  showLogisticsDialog.value = true;
};

const queryOrderStatusStatsMethod = async () => {
  const res = await queryOrderStatusStats();
  orderStatusStats.value = res as any;
};

/** 关闭订单操作 */
const handleCloseOrder = async (row?: OrderMainVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认关闭订单主信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await closeOrderMain(_ids);
  proxy?.$modal.msgSuccess('关闭成功');
  await getList();
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  orderMainFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = (orderStatus?: string) => {
  if (orderStatus) {
    queryParams.value.orderStatus = orderStatus;
  } else {
    queryParams.value.orderStatus = undefined;
  }
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderMainVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleReview = (row?: OrderMainVO) => {
  router.push({
    path: '/order-manage/order-sendDetail',
    query: { id: row.id }
  });
};

/** 发货按钮操作 */
const handleDeliver = (row?: OrderMainVO) => {
  if (!row?.id) {
    proxy?.$modal.msgWarning('订单ID不能为空');
    return;
  }
  currentOrderId.value = row.id;
  currentOrderNo.value = row.orderNo;
  showDeliverDialog.value = true;
};

/** 发货成功回调 */
const handleDeliverSuccess = () => {
  getList();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderMainVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getOrderMain(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改订单主信息';
};

/** 提交按钮 */
const submitForm = () => {
  orderMainFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateOrderMain(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addOrderMain(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrderMainVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除订单主信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delOrderMain(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'order/orderMain/export',
    {
      ...queryParams.value
    },
    `orderMain_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});

onActivated(() => {
  getList();
});
</script>
