<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="orderTime">
              <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">
          <el-col :span="13"> 销售订单信息列表 </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleCloseOrder()" :disabled="!ids.length" plain>关闭订单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleDelete()" :disabled="!ids.length" plain>删除订单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" :disabled="!ids.length" plain>导出订单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              :type="queryParams.orderStatus === undefined ? 'primary' : ''"
              :plain="queryParams.orderStatus !== undefined"
              @click="handleQuery()"
              >全部订单{{ orderStatusStats.totalCount }}</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button :type="queryParams.orderStatus === '0' ? 'primary' : ''" :plain="queryParams.orderStatus !== '0'" @click="handleQuery('0')"
              >待付款{{ orderStatusStats.pendingPaymentCount }}</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button :type="queryParams.orderStatus === '2' ? 'primary' : ''" :plain="queryParams.orderStatus !== '2'" @click="handleQuery('2')"
              >待发货{{ orderStatusStats.pendingShipmentCount }}</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button :type="queryParams.orderStatus === '4' ? 'primary' : ''" :plain="queryParams.orderStatus !== '4'" @click="handleQuery('4')"
              >已发货{{ orderStatusStats.shippedCount }}</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button :type="queryParams.orderStatus === '5' ? 'primary' : ''" :plain="queryParams.orderStatus !== '5'" @click="handleQuery('5')"
              >已完成{{ orderStatusStats.completedCount }}</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button :type="queryParams.orderStatus === '6' ? 'primary' : ''" :plain="queryParams.orderStatus !== '6'" @click="handleQuery('6')"
              >已关闭{{ orderStatusStats.closedCount }}</el-button
            >
          </el-col>
        </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="orderTime" />
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="客户编号" align="center" prop="customerCode" />
        <el-table-column label="订单总金额" align="center" prop="totalAmount" />
        <el-table-column label="支付方式" align="center" prop="payType">
          <template #default="scope">
            <dict-tag :options="pay_method" :value="scope.row.payType" />
          </template>
        </el-table-column>
        <el-table-column label="业务员" align="center" prop="businessStaff" />
        <el-table-column label="客服" align="center" prop="customerService" />
        <el-table-column label="归属部门" align="center" prop="businessDept" />
        <el-table-column label="订单来源" align="center" prop="orderSource">
          <template #default="scope">
            <dict-tag :options="order_source" :value="scope.row.orderSource" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="审核状态" align="center" prop="checkStatus">
          <template #default="scope">
            <dict-tag :options="order_check_status" :value="scope.row.checkStatus" />
          </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">
            <template v-for="btn in getActionButtons(scope.row)" :key="btn.label">
              <el-button link type="primary" @click="btn.handler(scope.row)">{{ btn.label }}</el-button>
            </template>
          </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,
  closeOrderMain,
  queryOrderStatusStats,
  changeStatus,
  changeCheckStatus
} from '@/api/order/orderMain';
import { OrderMainVO, OrderMainQuery, OrderMainForm } from '@/api/order/orderMain/types';
import DeliverDialog from './deliverDialog.vue';
import LogisticsDetail from './logisticsDetail.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status, order_check_status, pay_method, order_source } = toRefs<any>(
  proxy?.useDict('order_status', 'order_check_status', 'pay_method', 'order_source')
);

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 checkStatusValue = ref('1'); // 审核状态选择值

// 发货对话框
const showDeliverDialog = ref(false);
const currentOrderId = ref<string | number>();
const currentOrderNo = ref<string>();
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

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

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

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

const initFormData: OrderMainForm = {
  id: undefined,
  orderNo: undefined,
  shipmentNo: undefined,
  subOrderNo: undefined,
  companyId: undefined,
  customerId: undefined,
  customerCode: undefined,
  isSplitChild: 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,
    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,
    checkStatus: '1', // 默认已审核
    attachmentPath: undefined,
    deliveryType: undefined,
    orderCategory: undefined,
    productCode: undefined,
    cancelReason: 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));
  orderMainList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  queryOrderStatusStatsMethod();
};

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

/** 取消按钮 */
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 handleViewLogistics = (row?: OrderMainVO) => {
  if (!row?.id) {
    proxy?.$modal.msgWarning('订单ID不能为空');
    return;
  }
  logisticsOrderId.value = row.id;

  showLogisticsDialog.value = true;
};

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

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

/** 审核按钮操作 */
const handleCheck = async (row?: OrderMainVO) => {
  const oldValue = row.checkStatus; // 保存旧值

  // 弹出审核选择对话框
  try {
    await ElMessageBox({
      title: '审核',
      message: h('div', { style: 'padding: 10px 0' }, [
        h('p', { style: 'margin-bottom: 15px; font-size: 14px' }, '请选择审核结果：'),
        h('div', { style: 'display: flex; flex-direction: column; gap: 12px' }, [
          h(
            'label',
            {
              style: 'display: flex; align-items: center; cursor: pointer; font-size: 14px',
              onClick: () => {
                checkStatusValue.value = '1';
                const radio = document.querySelector('input[name="checkStatus"][value="1"]') as HTMLInputElement;
                if (radio) radio.checked = true;
              }
            },
            [
              h('input', {
                type: 'radio',
                name: 'checkStatus',
                value: '1',
                checked: true,
                style: 'margin-right: 8px; cursor: pointer',
                onChange: () => {
                  checkStatusValue.value = '1';
                }
              }),
              h('span', null, '审核通过')
            ]
          ),
          h(
            'label',
            {
              style: 'display: flex; align-items: center; cursor: pointer; font-size: 14px',
              onClick: () => {
                checkStatusValue.value = '2';
                const radio = document.querySelector('input[name="checkStatus"][value="2"]') as HTMLInputElement;
                if (radio) radio.checked = true;
              }
            },
            [
              h('input', {
                type: 'radio',
                name: 'checkStatus',
                value: '2',
                style: 'margin-right: 8px; cursor: pointer',
                onChange: () => {
                  checkStatusValue.value = '2';
                }
              }),
              h('span', null, '驳回')
            ]
          )
        ])
      ]),
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          done();
        } else {
          done();
        }
      }
    });

    // 调用接口，传入用户选择的值
    await changeCheckStatus(row.id, checkStatusValue.value);
    getList();
    proxy?.$modal.msgSuccess('操作成功');
  } catch (error) {
    // 用户取消或操作失败
    if (error !== 'cancel' && error !== 'close') {
      row.checkStatus = oldValue; // 失败回滚
      proxy?.$modal.msgError('操作失败，请重试');
    }
  }
};

/** 审核按钮操作 */
const handleCancel = async (row?: OrderMainVO) => {
  const oldValue = row.checkStatus; // 保存旧值

  // 弹出审核选择对话框
  try {
    // 调用接口，传入用户选择的值
    await changeStatus(row.id, '7');
    getList();
    proxy?.$modal.msgSuccess('操作成功');
  } catch (error) {
    // 用户取消或操作失败
    if (error !== 'cancel' && error !== 'close') {
      row.checkStatus = oldValue; // 失败回滚
      proxy?.$modal.msgError('操作失败，请重试');
    }
  }
};

/** 发货按钮操作 */
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 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();
};

// 订单状态枚举
enum OrderStatus {
  PENDING_PAYMENT = '0', // 待支付
  PENDING_CONFIRM = '1', // 待确认
  PENDING_SHIPMENT = '2', // 待发货
  PARTIAL_SHIPMENT = '3', // 部分发货
  SHIPMENT_COMPLETED = '4', // 发货完成
  COMPLETED = '5', // 已完成
  CLOSED = '6', // 已关闭
  CANCELLED = '7' // 已取消
}

// 审核状态枚举
enum CheckStatus {
  PENDING = '0', // 待审核
  APPROVED = '1', // 审核通过
  REJECTED = '2' // 已驳回
}

// 按钮配置类型
interface ActionButton {
  label: string;
  handler: (row: OrderMainVO) => void;
}

// 按钮配置映射：根据订单状态和审核状态返回可用按钮
const getButtonsByStatus = (orderStatus: string, checkStatus: string): ActionButton[] => {
  const buttons: ActionButton[] = [];

  // 待支付状态：显示查看按钮
  if (orderStatus === OrderStatus.PENDING_PAYMENT) {
    buttons.push({ label: '查看', handler: handleReview });
    buttons.push({ label: '确认订单', handler: handleAffirm });
  }
  // 待确认状态：显示确认订单按钮
  if (orderStatus === OrderStatus.PENDING_CONFIRM) {
    buttons.push({ label: '查看', handler: handleReview });
    buttons.push({ label: '确认订单', handler: handleAffirm });
  }

  // 待审核：显示审核按钮
  // if (checkStatus === CheckStatus.PENDING) {
  //   buttons.push({ label: '审核', handler: handleCheck });
  // }

  // 待发货或部分发货：显示发货按钮
  if (orderStatus === OrderStatus.PENDING_SHIPMENT || orderStatus === OrderStatus.PARTIAL_SHIPMENT) {
    buttons.push({ label: '发货', handler: handleDeliver });
  }

  // 待发货、部分发货、发货完成、已完成：显示查看订单信息按钮
  if (
    [OrderStatus.PENDING_SHIPMENT, OrderStatus.PARTIAL_SHIPMENT, OrderStatus.SHIPMENT_COMPLETED, OrderStatus.COMPLETED].includes(
      orderStatus as OrderStatus
    )
  ) {
    buttons.push({ label: '查看订单信息', handler: handleReview });
  }

  // 发货完成或已完成：显示查看物流按钮
  if (orderStatus === OrderStatus.PARTIAL_SHIPMENT || orderStatus === OrderStatus.SHIPMENT_COMPLETED || orderStatus === OrderStatus.COMPLETED) {
    buttons.push({ label: '查看物流', handler: handleViewLogistics });
  }

  // 非已取消和已关闭状态：显示取消订单按钮
  if (orderStatus !== OrderStatus.CANCELLED && orderStatus !== OrderStatus.CLOSED && orderStatus !== OrderStatus.SHIPMENT_COMPLETED) {
    buttons.push({ label: '取消订单', handler: handleCancel });
  }

  return buttons;
};

// 根据订单状态获取可用的操作按钮
const getActionButtons = (row: OrderMainVO): ActionButton[] => {
  return getButtonsByStatus(row.orderStatus, row.checkStatus);
};

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

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

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