<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="orderStatus">
              <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 200px">
                <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="paymentStatus">
              <el-select v-model="queryParams.paymentStatus" placeholder="请选择支付状态" clearable style="width: 200px">
                <el-option v-for="dict in payment_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </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="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['order:zhongcheorder:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['order:zhongcheorder:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['order:zhongcheorder:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['order:zhongcheorder:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="zhongcheorderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="订单编号" align="center" prop="orderNo" width="150" />
        <el-table-column label="订单类型" align="center" prop="preOrder" width="100">
          <template #default="scope">
            <dict-tag :options="order_type" :value="scope.row.preOrder" />
          </template>
        </el-table-column>
        <el-table-column label="下单人" align="center" prop="buyerName" />
        <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="确认时间" align="center" prop="confirmTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.confirmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" align="center" prop="totalAmount" />
        <el-table-column label="支付状态" align="center" prop="paymentStatus">
          <template #default="scope">
            <dict-tag :options="payment_status" :value="scope.row.paymentStatus" />
          </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" prop="reconciliationStatus">
          <template #default="scope">
            <dict-tag :options="reconciliation_status" :value="scope.row.reconciliationStatus" />
          </template>
        </el-table-column>
        <el-table-column label="是否妥投" align="center" prop="isProperDelivery">
          <template #default="scope">
            <dict-tag :options="is_proper_delivery" :value="scope.row.isProperDelivery" />
          </template>
        </el-table-column>
        <el-table-column label="开票状态" align="center" prop="invoiceStatus">
          <template #default="scope">
            <dict-tag :options="invoice_issuance_status" :value="scope.row.invoiceStatus" />
          </template>
        </el-table-column>
        <el-table-column label="包裹数量" align="center" prop="packageCount" />
        <el-table-column label="结算状态" align="center" prop="settlementStatus" width="160">
          <template #default="scope">
            <dict-tag :options="settlement_status" :value="scope.row.settlementStatus" />
            <el-button
              v-if="String(scope.row.settlementStatus) !== '1'"
              link
              type="primary"
              @click="handleSettlement(scope.row)"
            >
              结算
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="截止还款时间" align="center" prop="repaymentDeadline" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.repaymentDeadline, '{y}-{m}-{d}') }}</span>
            <el-button link type="primary" @click="handleOpenDeadline(scope.row)">录入</el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300" fixed="right">
          <template #default="scope">
            <el-button
              v-if="String(scope.row.orderStatus) === '1'"
              link
              type="primary"
              @click="handleAccept(scope.row)"
            >
              接单
            </el-button>
            <el-button
              v-if="String(scope.row.orderStatus) === '1'"
              link
              type="danger"
              @click="handleReject(scope.row)"
            >
              拒单
            </el-button>
            <el-button v-if="String(scope.row.orderStatus) !== '1'" link type="primary" @click="handleViewLogistics(scope.row)">查看物流</el-button>
            <el-button link type="primary" @click="handleViewOrder(scope.row)">查看订单</el-button>
            <el-button v-if="String(scope.row.orderStatus) !== '1'" link type="primary" @click="handleOpenInvoice(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>
    <!-- 添加或修改订单列表对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="zhongcheorderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父订单id" prop="parentOrderId">
          <el-input v-model="form.parentOrderId" placeholder="请输入父订单id" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="发货单号" prop="shipmentNo">
          <el-input v-model="form.shipmentNo" placeholder="请输入发货单号" />
        </el-form-item>
        <el-form-item label="子订单编号" prop="subOrderNo">
          <el-input v-model="form.subOrderNo" placeholder="请输入子订单编号" />
        </el-form-item>
        <el-form-item label="所属公司" prop="companyId">
          <el-input v-model="form.companyId" placeholder="请输入所属公司" />
        </el-form-item>
        <el-form-item label="客户编号" prop="customerCode">
          <el-input v-model="form.customerCode" placeholder="请输入客户编号" />
        </el-form-item>
        <el-form-item label="客户ID" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户ID" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="收货地址ID" prop="shippingAddressId">
          <el-input v-model="form.shippingAddressId" placeholder="请输入收货地址ID" />
        </el-form-item>
        <el-form-item label="采购事由" prop="purchaseReason">
          <el-input v-model="form.purchaseReason" placeholder="请输入采购事由" />
        </el-form-item>
        <el-form-item label="发货仓库" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入发货仓库" />
        </el-form-item>
        <el-form-item label="信用额度" prop="creditLimit">
          <el-input v-model="form.creditLimit" placeholder="请输入信用额度" />
        </el-form-item>
        <el-form-item label="预计送达时间" prop="expectedDeliveryTime">
          <el-date-picker clearable
            v-model="form.expectedDeliveryTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择预计送达时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="业务员姓名/工号" prop="businessStaff">
          <el-input v-model="form.businessStaff" placeholder="请输入业务员姓名/工号" />
        </el-form-item>
        <el-form-item label="客服人员" prop="customerService">
          <el-input v-model="form.customerService" placeholder="请输入客服人员" />
        </el-form-item>
        <el-form-item label="业务部门" prop="businessDept">
          <el-input v-model="form.businessDept" placeholder="请输入业务部门" />
        </el-form-item>
        <el-form-item label="用户所属部门" prop="userDept">
          <el-input v-model="form.userDept" placeholder="请输入用户所属部门" />
        </el-form-item>
        <el-form-item label="商品总数量" prop="productQuantity">
          <el-input v-model="form.productQuantity" placeholder="请输入商品总数量" />
        </el-form-item>
        <el-form-item label="运费" prop="shippingFee">
          <el-input v-model="form.shippingFee" placeholder="请输入运费" />
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单总金额" />
        </el-form-item>
        <el-form-item label="应付金额" prop="payableAmount">
          <el-input v-model="form.payableAmount" placeholder="请输入应付金额" />
        </el-form-item>
        <el-form-item label="订单来源" prop="orderSource">
          <el-input v-model="form.orderSource" placeholder="请输入订单来源" />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="确认时间" prop="confirmTime">
          <el-date-picker clearable
            v-model="form.confirmTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择确认时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发货时间" prop="shippingTime">
          <el-date-picker clearable
            v-model="form.shippingTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收货时间" prop="receivingTime">
          <el-date-picker clearable
            v-model="form.receivingTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择收货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否为拆分子单：0=是 (子订单), 1=否 (父订单)" prop="isSplitChild">
          <el-input v-model="form.isSplitChild" placeholder="请输入是否为拆分子单：0=是 (子订单), 1=否 (父订单)" />
        </el-form-item>
        <el-form-item label="包裹数量" prop="packageCount">
          <el-input v-model="form.packageCount" placeholder="请输入包裹数量" />
        </el-form-item>
        <el-form-item label="签收数量" prop="signedQuantity">
          <el-input v-model="form.signedQuantity" placeholder="请输入签收数量" />
        </el-form-item>
        <el-form-item label="已完成售后数量" prop="afterSaleCompleted">
          <el-input v-model="form.afterSaleCompleted" placeholder="请输入已完成售后数量" />
        </el-form-item>
        <el-form-item label="申请售后数量" prop="afterSalePending">
          <el-input v-model="form.afterSalePending" placeholder="请输入申请售后数量" />
        </el-form-item>
        <el-form-item label="配送时效描述" prop="deliveryDesc">
          <el-input v-model="form.deliveryDesc" placeholder="请输入配送时效描述" />
        </el-form-item>
        <el-form-item label="订单附件文件路径" prop="attachmentPath">
          <el-input v-model="form.attachmentPath" placeholder="请输入订单附件文件路径" />
        </el-form-item>
        <el-form-item label="创建类别" prop="orderCategory">
          <el-input v-model="form.orderCategory" placeholder="请输入创建类别" />
        </el-form-item>
        <el-form-item label="取消或异常原因" prop="cancelReason">
          <el-input v-model="form.cancelReason" placeholder="请输入取消或异常原因" />
        </el-form-item>
        <el-form-item label="用户编号" prop="userNo">
          <el-input v-model="form.userNo" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="数据来源" prop="dataSource">
          <el-input v-model="form.dataSource" placeholder="请输入数据来源" />
        </el-form-item>
        <el-form-item label="分配对象ID" prop="assigneeId">
          <el-input v-model="form.assigneeId" placeholder="请输入分配对象ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="查看物流信息" v-model="logisticsDialog.visible" width="900px" append-to-body>
      <el-form :inline="true" label-width="80px" class="mb-[10px]">
        <el-form-item label="快递单号">
          <el-select v-model="logisticsDialog.selectedId" placeholder="请选择" style="width: 260px" @change="handleLogisticNoChange">
            <el-option v-for="item in logisticsDialog.options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司">
          <el-input v-model="logisticsDialog.companyName" disabled style="width: 260px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="logisticsDialog.trackLoading" :disabled="!logisticsDialog.selectedId" @click="handleQueryLogisticsTrack">查询</el-button>
        </el-form-item>
      </el-form>

      <div v-loading="logisticsDialog.trackLoading">
        <el-timeline v-if="logisticsDialog.traces && logisticsDialog.traces.length">
          <el-timeline-item v-for="(item, idx) in logisticsDialog.traces" :key="idx" :timestamp="item.ftime && item.time ? `${item.ftime}||${item.time}` : (item.ftime || item.time || '')" placement="top">
            <div>{{ item.context }}</div>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂无物流信息" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="logisticsDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="录入截止还款时间" v-model="deadlineDialog.visible" width="460px" append-to-body>
      <el-form label-width="110px">
        <el-form-item label="截止还款时间">
          <el-date-picker
            v-model="deadlineDialog.repaymentDeadline"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择截止还款时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="deadlineDialog.loading" type="primary" @click="handleSubmitDeadline">确 定</el-button>
          <el-button :disabled="deadlineDialog.loading" @click="deadlineDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="上传发票" v-model="invoiceDialog.visible" width="500px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="发票文件" required>
          <fileUpload v-model="invoiceDialog.invoice" :fileType="['doc', 'docx', 'pdf']" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="invoiceDialog.loading" type="primary" @click="handleSubmitInvoice">确 定</el-button>
          <el-button :disabled="invoiceDialog.loading" @click="invoiceDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="订单商品明细" v-model="orderProductDialog.visible" width="1050px" append-to-body>
      <el-table v-loading="orderProductDialog.loading" :data="orderProductDialog.list" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="产品编号" align="center" prop="productNo" width="120" />
        <el-table-column label="产品名称" align="center" prop="productName" min-width="150" show-overflow-tooltip />
        <el-table-column label="品牌" align="center" prop="brandName" width="110" />
        <el-table-column label="单价" align="center" prop="orderPrice" width="110" />
        <el-table-column label="数量" align="center" prop="orderQuantity" width="90" />
        <el-table-column label="金额" align="center" prop="subtotal" width="110" />
        
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="orderProductDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Zhongcheorder" lang="ts">
import { listZhongcheorder, getZhongcheorder, delZhongcheorder, addZhongcheorder, updateZhongcheorder, acceptZhongcheorder, rejectZhongcheorder, getZhongcheorderLogistics, getZhongcheorderLogisticsTrack, settlementZhongcheorder, setZhongcheorderDeadline, uploadZhongcheorderInvoice } from '@/api/order/zhongcheorder/index';
import { ZhongcheorderVO, ZhongcheorderQuery, ZhongcheorderForm } from '@/api/order/zhongcheorder/types';
import { ElMessageBox } from 'element-plus';
import { listByIds } from '@/api/system/oss';
import { getZhongCheOrderProducts } from '@/api/order/orderProduct/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status } = toRefs<any>(proxy?.useDict('order_status'));
const { payment_status } = toRefs<any>(proxy?.useDict('payment_status'));
const { order_type } = toRefs<any>(proxy?.useDict('order_type'));
const { reconciliation_status } = toRefs<any>(proxy?.useDict('reconciliation_status'));
const { is_proper_delivery } = toRefs<any>(proxy?.useDict('is_proper_delivery'));
const { invoice_issuance_status } = toRefs<any>(proxy?.useDict('invoice_issuance_status'));
const { settlement_status } = toRefs<any>(proxy?.useDict('settlement_status'));

const zhongcheorderList = ref<ZhongcheorderVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const zhongcheorderFormRef = ref<ElFormInstance>();

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

const logisticsDialog = reactive<{
  visible: boolean;
  loading: boolean;
  trackLoading: boolean;
  packages: any[];
  options: Array<{ label: string; value: string }>;
  selectedId: string;
  companyName: string;
  traces: Array<{ time?: string; ftime?: string; context?: string }>;
}>({
  visible: false,
  loading: false,
  trackLoading: false,
  packages: [],
  options: [],
  selectedId: '',
  companyName: '',
  traces: []
});

const deadlineDialog = reactive<{ visible: boolean; loading: boolean; id: string | number | undefined; repaymentDeadline: string }>({
  visible: false,
  loading: false,
  id: undefined,
  repaymentDeadline: ''
});

const invoiceDialog = reactive<{ visible: boolean; loading: boolean; id: string | number | undefined; invoice: string }>({
  visible: false,
  loading: false,
  id: undefined,
  invoice: ''
});

const orderProductDialog = reactive<{
  visible: boolean;
  loading: boolean;
  list: any[];
}>({
  visible: false,
  loading: false,
  list: []
});

const initFormData: ZhongcheorderForm = {
  id: undefined,
  parentOrderId: undefined,
  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,
  splitStatus: undefined,
  isSplitChild: undefined,
  packageCount: undefined,
  signedQuantity: undefined,
  afterSaleCompleted: undefined,
  afterSalePending: undefined,
  deliveryDesc: undefined,
  pushStatus: undefined,
  attachmentPath: undefined,
  deliveryType: undefined,
  orderCategory: undefined,
  cancelReason: undefined,
  expenseType: undefined,
  userNo: undefined,
  remark: undefined,
  dataSource: undefined,
  checkStatus: undefined,
  assignmentStatus: undefined,
  assigneeId: undefined,
  assigneeType: undefined
}
const data = reactive<PageData<ZhongcheorderForm, ZhongcheorderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    paymentStatus: undefined,
    orderStatus: undefined,
    reconciliationStatus: undefined,
    isProperDelivery: undefined,
    settlementStatus: undefined,
    params: {
    }
  },
  rules: {
  }
});

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

/** 查询订单列表列表 */
const getList = async () => {
  loading.value = true;
  const res = await listZhongcheorder(queryParams.value);
  zhongcheorderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加订单列表";
}

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

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

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

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

const handleAccept = async (row: ZhongcheorderVO) => {
  await proxy?.$modal.confirm('是否确认接单？');
  const res = await acceptZhongcheorder(row.id);
  proxy?.$modal.msgSuccess(res as any);
  await getList();
}

const handleReject = async (row: ZhongcheorderVO) => {
  try {
    const resPrompt = await ElMessageBox.prompt('请输入拒单理由', '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
      inputValidator: (value) => {
        if (!String(value ?? '').trim()) {
          return '拒单理由不能为空';
        }
        return true;
      }
    });
    const reason = (resPrompt as any)?.value;
    const res = await rejectZhongcheorder(row.id, reason);
    proxy?.$modal.msgSuccess(res as any);
    await getList();
  } catch {
    // 用户取消
  }
}

const handleSettlement = async (row: ZhongcheorderVO) => {
  await proxy?.$modal.confirm('是否确认结算？');
  await settlementZhongcheorder(row.id);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
}

const handleOpenDeadline = (row: ZhongcheorderVO) => {
  deadlineDialog.visible = true;
  deadlineDialog.loading = false;
  deadlineDialog.id = row.id;
  deadlineDialog.repaymentDeadline = (row as any)?.repaymentDeadline ?? '';
}

const handleSubmitDeadline = async () => {
  const id = deadlineDialog.id;
  const repaymentDeadline = String(deadlineDialog.repaymentDeadline ?? '').trim();
  if (!id) return;
  if (!repaymentDeadline) {
    proxy?.$modal.msgError('请选择截止还款时间');
    return;
  }
  deadlineDialog.loading = true;
  try {
    await setZhongcheorderDeadline(id, repaymentDeadline);
    proxy?.$modal.msgSuccess('操作成功');
    deadlineDialog.visible = false;
    await getList();
  } finally {
    deadlineDialog.loading = false;
  }
}

const handleOpenInvoice = (row: ZhongcheorderVO) => {
  invoiceDialog.visible = true;
  invoiceDialog.loading = false;
  invoiceDialog.id = row.id;
  invoiceDialog.invoice = '';
}

const handleSubmitInvoice = async () => {
  const id = invoiceDialog.id;
  const invoiceId = String(invoiceDialog.invoice ?? '').trim();
  if (!id) return;
  if (!invoiceId) {
    proxy?.$modal.msgError('请先上传发票文件');
    return;
  }
  invoiceDialog.loading = true;
  try {
    const ossRes = await listByIds(invoiceId);
    let invoiceUrl = invoiceId;
    if (ossRes && (ossRes as any).data && (ossRes as any).data.length > 0) {
      invoiceUrl = (ossRes as any).data[0].url;
    }
    await uploadZhongcheorderInvoice(id, invoiceUrl);
    proxy?.$modal.msgSuccess('上传发票成功');
    invoiceDialog.visible = false;
    await getList();
  } finally {
    invoiceDialog.loading = false;
  }
}

const handleViewOrder = async (row: ZhongcheorderVO) => {
  orderProductDialog.visible = true;
  orderProductDialog.loading = true;
  orderProductDialog.list = [];
  try {
    const res = await getZhongCheOrderProducts(row.id);
    orderProductDialog.list = (res as any)?.data || (res as any)?.rows || res || [];
  } finally {
    orderProductDialog.loading = false;
  }
}

const handleViewLogistics = async (row: ZhongcheorderVO) => {
  logisticsDialog.visible = true;
  logisticsDialog.loading = true;
  logisticsDialog.trackLoading = false;
  logisticsDialog.packages = [];
  logisticsDialog.options = [];
  logisticsDialog.selectedId = '';
  logisticsDialog.companyName = '';
  logisticsDialog.traces = [];
  try {
    const res = await getZhongcheorderLogistics(row.id);
    const data = (res as any)?.data ?? res;
    const packages = (data?.list ?? data?.rows ?? data?.data ?? data) as any;
    if (Array.isArray(packages)) {
      logisticsDialog.packages = packages;
      logisticsDialog.options = packages
        .filter((p: any) => p?.id != null && !!p?.logisticNo)
        .map((p: any) => ({ label: String(p.logisticNo), value: String(p.id) }));

      const firstNo = logisticsDialog.options[0]?.value;
      if (firstNo) {
        logisticsDialog.selectedId = firstNo;
        handleLogisticNoChange(firstNo);
      }
    }
  } finally {
    logisticsDialog.loading = false;
  }
}

const handleLogisticNoChange = (no: any) => {
  const val = String(no ?? '');
  const pkg = logisticsDialog.packages.find((p: any) => String(p?.id ?? '') === val);
  logisticsDialog.companyName = pkg?.logisticsCompanyName ?? '';
  logisticsDialog.traces = [];
}

const handleQueryLogisticsTrack = async () => {
  const id = String(logisticsDialog.selectedId ?? '').trim();
  if (!id) return;
  logisticsDialog.trackLoading = true;
  logisticsDialog.traces = [];
  try {
    const res = await getZhongcheorderLogisticsTrack(id);
    const data = (res as any)?.data ?? res;
    const list = (data?.list ?? data?.rows ?? data?.data ?? data) as any;
    if (Array.isArray(list)) {
      logisticsDialog.traces = list.map((item: any) => ({
        time: item.time,
        ftime: item.ftime,
        context: item.context
      }));
    }
  } finally {
    logisticsDialog.trackLoading = false;
  }
}

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