<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="dateRange">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
            </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="18"> 项目订单列表 </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="primary" :disabled="!ids.length" plain @click="handleAssignment(null)">批量整单分配</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="primary" :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-row>
      </template>

      <el-table v-loading="loading" border :data="orderMainList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :resizable="false" />
        <el-table-column label="订单时间" align="center" prop="orderTime" :resizable="false" />
        <el-table-column label="订单编号" align="center" prop="orderNo" :resizable="false" />
        <el-table-column label="关联单号" align="center" prop="parentOrderNo" :resizable="false" />
        <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="customerCode" :resizable="false" /> -->
        <el-table-column label="订单总金额" align="center" prop="totalAmount" :resizable="false" />
        <!-- <el-table-column label="支付方式" align="center" prop="payType" :resizable="false">
          <template #default="scope">
            <dict-tag :options="pay_method" :value="scope.row.payType" />
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="业务员" align="center" prop="businessStaff" :resizable="false" />
        <el-table-column label="客服" align="center" prop="customerService" :resizable="false" /> -->
        <!-- <el-table-column label="归属部门" align="center" prop="businessDept" :resizable="false" /> -->
        <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="dataSourceStr"> </el-table-column>
        <el-table-column label="分配状态" align="center" prop="assignmentStatus" :resizable="false">
          <template #default="scope">
            <dict-tag :options="order_assignment_status" :value="scope.row.assignmentStatus" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="当前平台" align="center" prop="platformCode">
          <template #default="scope">
            <dict-tag :options="sys_platform_code" :value="scope.row.platformCode" />
          </template>
        </el-table-column> -->

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180" :resizable="false">
          <template #default="scope">
            <el-button link type="primary" @click="handleReview(scope.row)">详情</el-button>
            <el-button link type="primary" v-if="scope.row.assignmentStatus != '1'" @click="handleAssignment(scope.row)">分配</el-button>
            <el-button link type="primary" v-if="scope.row.assignmentStatus == '1'" @click="handleAssignment(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>

    <!-- 订单分配对话框 -->
    <assignment-dialog ref="assignmentDialogRef" @success="getList" />
    <!-- 拆单分配对话框 -->
    <split-assign-dialog ref="splitAssignDialogRef" @success="getList" />
  </div>
</template>

<script setup name="OrderAssignment" lang="ts">
import { listOrderAssignment, getOrderMain, delOrderMain } from '@/api/order/orderMain';
import { OrderMainVO, OrderMainQuery, OrderMainForm } from '@/api/order/orderMain/types';
import AssignmentDialog from './assignmentDialog.vue';
import SplitAssignDialog from './splitAssignDialog.vue';
import { getOrderMainCrrcExt } from '@/api/order/orderMainCrrcExt';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_assignment_status, order_check_status, pay_method, order_source, sys_platform_code } = toRefs<any>(
  proxy?.useDict('order_assignment_status', 'order_check_status', 'pay_method', 'order_source', 'sys_platform_code')
);

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 assignmentDialogRef = ref<InstanceType<typeof AssignmentDialog>>();
const splitAssignDialogRef = ref<InstanceType<typeof SplitAssignDialog>>();

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderMainForm = {
  id: undefined,
  orderNo: 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,
  isSplitChild: 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,
    payType: undefined,
    warehouseId: undefined,
    expectedDeliveryTime: undefined,
    businessStaff: undefined,
    customerService: undefined,
    businessDept: undefined,
    productQuantity: undefined,
    totalAmount: undefined,
    payableAmount: undefined,
    paymentStatus: undefined,
    orderSource: undefined,
    // orderStatus: '2',
    orderStatuses: '2,3,4,5',
    orderTime: undefined,
    confirmTime: undefined,
    status: undefined,
    // isSplitChild: '1',
    currentLevelStr: '2',
    assigneeType: 'mkt',
    params: {}
  },
  rules: {}
});

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

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

// 批量获取平台订单号
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 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 handleAssignment = async (row?: OrderMainVO | null) => {
  let orderIds: Array<string | number>;

  if (row) {
    // 单个订单分配 - 直接打开统一的分配抽屉
    splitAssignDialogRef.value?.open(row.id, row.assignmentStatus);
  } else {
    // 批量分配 - 只支持整单分配
    if (!ids.value || ids.value.length === 0) {
      proxy?.$modal.msgWarning('请选择要分配的订单');
      return;
    }
    orderIds = ids.value;
    assignmentDialogRef.value?.open(orderIds, undefined, undefined);
  }
};

/** 删除按钮操作 */
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>
