<template>
  <el-watermark :content="['Element+', 'Element Plus']">
    <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="关联系统ID" prop="sid">
                <el-input v-model="queryParams.sid" placeholder="请输入关联系统ID" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="货件编号" prop="shipmentId">
                <el-input v-model="queryParams.shipmentId" placeholder="请输入货件编号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="货件名称" prop="shipmentName">
                <el-input v-model="queryParams.shipmentName" placeholder="请输入货件名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="物流中心编码" prop="destination">
                <el-input v-model="queryParams.destination" placeholder="请输入物流中心编码" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="运输模式" prop="shippingMode">
                <el-input v-model="queryParams.shippingMode" placeholder="请输入运输模式" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="运输方案" prop="shippingSolution">
                <el-input v-model="queryParams.shippingSolution" placeholder="请输入运输方案" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="最后更新时间" prop="gmtModified">
                <el-date-picker clearable v-model="queryParams.gmtModified" type="date" value-format="YYYY-MM-DD" placeholder="请选择最后更新时间" />
              </el-form-item>
              <el-form-item label="创建时间" prop="gmtCreate">
                <el-date-picker clearable v-model="queryParams.gmtCreate" type="date" value-format="YYYY-MM-DD" placeholder="请选择创建时间" />
              </el-form-item>
              <!--              <el-form-item label="同步时间" prop="syncTime">-->
              <!--                <el-date-picker clearable v-model="queryParams.syncTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择同步时间" />-->
              <!--              </el-form-item>-->
              <el-form-item label="计划发货日期" prop="staShipmentDate">
                <el-date-picker
                  clearable
                  v-model="queryParams.staShipmentDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择计划发货日期"
                />
              </el-form-item>
              <el-form-item label="预计到货开始日" prop="staDeliveryStartDate">
                <el-date-picker
                  clearable
                  v-model="queryParams.staDeliveryStartDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择预计到货开始日"
                />
              </el-form-item>
              <el-form-item label="预计到货截止日" prop="staDeliveryEndDate">
                <el-date-picker
                  clearable
                  v-model="queryParams.staDeliveryEndDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择预计到货截止日"
                />
              </el-form-item>
              <el-form-item label="参考编号" prop="referenceId">
                <el-input v-model="queryParams.referenceId" placeholder="请输入参考编号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="入库计划ID" prop="staInboundPlanId">
                <el-input v-model="queryParams.staInboundPlanId" placeholder="请输入入库计划ID" clearable @keyup.enter="handleQuery" />
              </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="['amz:shipmentPlan:add']"> 新增 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['amz:shipmentPlan:edit']"
                >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['amz:shipmentPlan:remove']"
                >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['amz:shipmentPlan:export']">导出 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="snycTodayPlan" v-hasPermi="['amz:shipmentPlan:export']"
                >同步今天的货件
              </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>

        <el-table v-loading="loading" :data="shipmentPlanList" @current-change="handleCurrentChange" highlight-current-row ref="singleTableRef">
          <el-table-column type="expand">
            <template #default="props">
              <el-descriptions size="small" border title="货件详情">
                <el-descriptions-item label="货件名称">{{ props.row.shipmentName }}</el-descriptions-item>
                <el-descriptions-item label="是否关闭">
                  <dict-tag :options="sys_zero_one" :value="props.row.isClosed" />
                </el-descriptions-item>
                <!--              <el-descriptions-item label="货件状态">{{ props.row.shipmentStatus }}</el-descriptions-item>-->
                <!--              <el-descriptions-item label="运输模式">{{ props.row.shippingMode }}</el-descriptions-item>-->
                <!--              <el-descriptions-item label="运输方案">{{ props.row.shippingSolution }}</el-descriptions-item>-->
                <!--                <el-descriptions-item label="入库计划ID">{{ props.row.staInboundPlanId }}</el-descriptions-item>-->

                <el-descriptions-item label="创建时间">{{ parseTime(props.row.gmtCreate, '{y}-{m}-{d}') }} </el-descriptions-item>
                <!--              <el-descriptions-item label="计划发货日期">{{ parseTime(props.row.staShipmentDate, '{y}-{m}-{d}') }} </el-descriptions-item>-->
                <!--              <el-descriptions-item label="预计到货开始日">{{ parseTime(props.row.staDeliveryStartDate, '{y}-{m}-{d}') }} </el-descriptions-item>-->
                <!--              <el-descriptions-item label="预计到货截止日">{{ parseTime(props.row.staDeliveryEndDate, '{y}-{m}-{d}') }} </el-descriptions-item>-->
              </el-descriptions>
            </template>
          </el-table-column>
          <el-table-column label="领星ID" align="center" prop="sid" />
          <el-table-column label="货件编号" align="center" prop="shipmentId" />
          <el-table-column label="商品详情" align="center">
            <template #default="scope">
              <el-popover placement="top" :width="600" trigger="hover" @show="showPop(scope.row)">
                <template #reference>
                  <el-button style="margin-right: 16px">查看</el-button>
                </template>
                <el-table :data="scope.row.itemVoList">
                  <el-table-column width="200" property="productName" label="品名" />
                  <el-table-column width="200" property="msku" label="msku" />
                </el-table>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="物流中心编码" align="center" prop="destination" />
          <el-table-column label="箱子数量" align="center" prop="boxNum" />
          <el-table-column label="货件状态" align="center" prop="gmtCreate" width="180">
            <template #default="scope">
              <el-tag>{{ scope.row.shipmentStatus }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="发货日期" align="center" prop="gmtCreate" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.staShipmentDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column width="150" label="发货地址" align="center" prop="shipFromAddress">
            <template #default="{ row }">
              <el-button @click="openAddressDialog(row.shipFromAddress)"> 查看详情</el-button>
            </template>
          </el-table-column>
          <el-table-column width="150" label="收货地址" align="center" prop="shipToAddress">
            <template #default="{ row }">
              <el-button @click="openAddressDialog(row.shipToAddress)"> 查看详情</el-button>
            </template>
          </el-table-column>
          <el-table-column label="是否STA计划" align="center" prop="isSta">
            <template #default="scope">
              <dict-tag :options="sys_zero_one" :value="scope.row.isSta" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['amz:shipmentPlan:edit']"></el-button>
              </el-tooltip>
              <!--            <el-tooltip content="删除" placement="top">-->
              <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['amz:shipmentPlan:remove']"></el-button>-->
              <!--            </el-tooltip>-->
              <el-tooltip content="发货" placement="top">
                <el-button link type="primary" icon="Promotion" @click="handleSend(scope.row)" v-hasPermi="['amz:shipmentPlan:remove']"></el-button>
              </el-tooltip>
            </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="shipmentPlanFormRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="关联系统ID" prop="sid">
            <el-input v-model="form.sid" placeholder="请输入关联系统ID" />
          </el-form-item>
          <el-form-item label="货件编号" prop="shipmentId">
            <el-input v-model="form.shipmentId" placeholder="请输入货件编号" />
          </el-form-item>
          <el-form-item label="货件名称" prop="shipmentName">
            <el-input v-model="form.shipmentName" placeholder="请输入货件名称" />
          </el-form-item>
          <el-form-item label="物流中心编码" prop="destination">
            <el-input v-model="form.destination" placeholder="请输入物流中心编码" />
          </el-form-item>
          <el-form-item label="运输模式" prop="shippingMode">
            <el-input v-model="form.shippingMode" placeholder="请输入运输模式" />
          </el-form-item>
          <el-form-item label="运输方案" prop="shippingSolution">
            <el-input v-model="form.shippingSolution" placeholder="请输入运输方案" />
          </el-form-item>
          <el-form-item label="最后更新时间" prop="gmtModified">
            <el-date-picker clearable v-model="form.gmtModified" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择最后更新时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="创建时间" prop="gmtCreate">
            <el-date-picker clearable v-model="form.gmtCreate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择创建时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="同步时间" prop="syncTime">
            <el-date-picker clearable v-model="form.syncTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择同步时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="计划发货日期" prop="staShipmentDate">
            <el-date-picker
              clearable
              v-model="form.staShipmentDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择计划发货日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="预计到货开始日" prop="staDeliveryStartDate">
            <el-date-picker
              clearable
              v-model="form.staDeliveryStartDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择预计到货开始日"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="预计到货截止日" prop="staDeliveryEndDate">
            <el-date-picker
              clearable
              v-model="form.staDeliveryEndDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择预计到货截止日"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="参考编号" prop="referenceId">
            <el-input v-model="form.referenceId" placeholder="请输入参考编号" />
          </el-form-item>
          <el-form-item label="入库计划ID" prop="staInboundPlanId">
            <el-input v-model="form.staInboundPlanId" 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 v-model="dialogVisible" title="地址详细信息" width="60%">
        <el-table :data="addressTableData">
          <el-table-column prop="key" label="字段" width="180" />
          <el-table-column prop="value" label="值" />
        </el-table>
      </el-dialog>

      <el-dialog v-model="channelDialogVisible" title="查询报价" width="60%">
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="目的地仓库">
            <el-input v-model="currentDes" disabled />
          </el-form-item>
          <el-form-item label="渠道选择">
            <el-cascader
              v-model="selectedChannel"
              placeholder="请选择渠道"
              :props="{ emitPath: false }"
              :options="groupedChannels"
              @change="cascaderChange"
              :show-all-levels="false"
              filterable
            />
          </el-form-item>
          <el-form-item label="日期选择">
            <el-date-picker v-model="shipDate" type="date" placeholder="Pick a day" value-format="YYYY-MM-DD" :size="size" />
          </el-form-item>
          <el-button :loading="buttonLoading" type="primary" @click="checkPrice()">查询报价</el-button>
        </el-form>
      </el-dialog>

      <el-dialog v-model="dialogTableVisible" title="已经存在的询价单" width="1800">
        <el-table :data="tableData" style="width: 100%" border stripe>
          <!-- 基础文本列 -->
          <el-table-column prop="inquiryNo" label="询价编号" width="180" />
          <el-table-column prop="channelName" label="渠道名称" width="200" />
          <el-table-column prop="transportChannel" label="运输方式" width="120" />
          <el-table-column prop="quoteDate" label="询价日期" width="200" />
          <!-- 时间格式化列 -->
          <el-table-column prop="deadline" label="截止时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.deadline) }}
            </template>
          </el-table-column>

          <el-table-column prop="effectiveStartTime" label="生效开始时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.effectiveStartTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="effectiveEndTime" label="生效结束时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.effectiveEndTime) }}
            </template>
          </el-table-column>

          <!-- 状态标签列 -->
          <el-table-column prop="inquiryStatus" label="询价状态" width="120">
            <template #default="{ row }">
              <el-tag :type="statusTagType(row.inquiryStatus)" effect="light">
                {{ row.inquiryStatus }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 其他信息列 -->
          <el-table-column prop="destination" label="目的地" width="120" />

          <el-table-column prop="requesterId" label="请求方ID" width="120" />

          <!-- 空值处理 -->
          <el-table-column prop="targetProviders" label="目标供应商">
            <template #default="{ row }">
              {{ row.targetProviders || '-' }}
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <el-drawer size="60%" v-model="drawer" :direction="direction">
        <template #header>
          <h4>物流商报价</h4>
        </template>
        <template #default>
          <el-table v-loading="loading" :data="logisticsQuoteList" @selection-change="handleSelectionChange">
            <el-table-column label="物流商用户ID" align="center" prop="userId" />
            <el-table-column label="目的地" align="center" prop="destination" />
            <el-table-column label="渠道名称" align="center" prop="channelName" />
            <el-table-column label="基础价格" align="center" prop="price" />
            <el-table-column label="时效" align="center" prop="leadTime" />
            <el-table-column label="附加费" align="center" prop="surcharge" />
            <el-table-column label="报价生效日期" align="center" prop="quoteDate" width="80">
              <template #default="scope">
                <span>{{ parseTime(scope.row.quoteDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="提交状态" align="center" prop="isSubmitted" />
            <el-table-column label="报价备注" align="center" prop="remark" />
            <el-table-column label="渠道类型" align="center" prop="channelType" />
            <el-table-column label="是否双清包税" align="center" prop="isDdp" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button text size="small" type="primary" @click="createOrder(scope.row)" v-hasPermi="['amz:logisticsQuote:edit']">
                  创建货运订单
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #footer>
          <div style="flex: auto">
            <el-button @click="cancelClick">取消</el-button>
            <el-button type="primary" @click="confirmClick">确认</el-button>
          </div>
        </template>
      </el-drawer>
    </div>
  </el-watermark>
</template>

<script setup name="ShipmentPlan" lang="ts">
import {
  listShipmentPlan,
  getShipmentPlan,
  delShipmentPlan,
  addShipmentPlan,
  updateShipmentPlan,
  takeTodayAmzPlanData
} from '@/api/amz/shipmentPlan';
import { listAllLogisticsChannel } from '@/api/amz/logisticsChannel';
import type { DrawerProps } from 'element-plus';
import { createWithDesAndChannel, queryWithDesAndChannel } from '@/api/amz/inquiryRequest';

import { queryLogisticsQuote } from '@/api/amz/logisticsQuote';

import { ShipmentPlanVO, ShipmentPlanQuery, ShipmentPlanForm } from '@/api/amz/shipmentPlan/types';
import { ElTable } from 'element-plus';
import { LogisticsQuoteVO } from '@/api/amz/logisticsQuote/types';
import { createOrderForm } from '@/api/amz/logisticsOrder/types';
import { createLogisticsOrder } from '@/api/amz/logisticsOrder';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { biz_transport_channel } = toRefs<any>(proxy?.useDict('biz_transport_channel'));

const { sys_zero_one } = toRefs<any>(proxy?.useDict('sys_zero_one'));

const shipmentPlanList = ref<ShipmentPlanVO[]>([]);
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 shipmentPlanFormRef = ref<ElFormInstance>();

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

const initFormData: ShipmentPlanForm = {
  id: undefined,
  sid: undefined,
  shipmentId: undefined,
  shipmentName: undefined,
  isClosed: undefined,
  shipmentStatus: undefined,
  destination: undefined,
  shippingMode: undefined,
  shippingSolution: undefined,
  gmtModified: undefined,
  gmtCreate: undefined,
  syncTime: undefined,
  staShipmentDate: undefined,
  staDeliveryStartDate: undefined,
  staDeliveryEndDate: undefined,
  shipFromAddress: undefined,
  shipToAddress: undefined,
  referenceId: undefined,
  staInboundPlanId: undefined,
  isSta: undefined,
  boxQuantity: undefined,
  boxSize: undefined,
  logisticsWeight: undefined,
  setTotal: undefined,
  channelId: undefined,
  channelName: undefined
};
const data = reactive<PageData<ShipmentPlanForm, ShipmentPlanQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sid: undefined,
    shipmentId: undefined,
    shipmentName: undefined,
    isClosed: undefined,
    shipmentStatus: undefined,
    destination: undefined,
    shippingMode: undefined,
    shippingSolution: undefined,
    gmtModified: undefined,
    gmtCreate: undefined,
    syncTime: undefined,
    staShipmentDate: undefined,
    staDeliveryStartDate: undefined,
    staDeliveryEndDate: undefined,
    shipFromAddress: undefined,
    shipToAddress: undefined,
    referenceId: undefined,
    staInboundPlanId: undefined,
    isSta: undefined,
    boxQuantity: undefined,
    boxSize: undefined,
    logisticsWeight: undefined,
    setTotal: undefined,
    channelId: undefined,
    channelName: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    sid: [{ required: true, message: '关联系统ID不能为空', trigger: 'blur' }],
    shipmentId: [{ required: true, message: '货件编号不能为空', trigger: 'blur' }],
    shipmentName: [{ required: true, message: '货件名称不能为空', trigger: 'blur' }],
    isClosed: [{ required: true, message: '是否关闭不能为空', trigger: 'blur' }],
    shipmentStatus: [{ required: true, message: '货件状态不能为空', trigger: 'change' }],
    destination: [{ required: true, message: '物流中心编码不能为空', trigger: 'blur' }],
    shippingMode: [{ required: true, message: '运输模式不能为空', trigger: 'blur' }],
    shippingSolution: [{ required: true, message: '运输方案不能为空', trigger: 'blur' }],
    gmtModified: [{ required: true, message: '最后更新时间不能为空', trigger: 'blur' }],
    gmtCreate: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
    syncTime: [{ required: true, message: '同步时间不能为空', trigger: 'blur' }],
    staShipmentDate: [{ required: true, message: '计划发货日期不能为空', trigger: 'blur' }],
    staDeliveryStartDate: [{ required: true, message: '预计到货开始日不能为空', trigger: 'blur' }],
    staDeliveryEndDate: [{ required: true, message: '预计到货截止日不能为空', trigger: 'blur' }],
    shipFromAddress: [{ required: true, message: '发货地址不能为空', trigger: 'blur' }],
    shipToAddress: [{ required: true, message: '收货地址不能为空', trigger: 'blur' }],
    referenceId: [{ required: true, message: '参考编号不能为空', trigger: 'blur' }],
    staInboundPlanId: [{ required: true, message: '入库计划ID不能为空', trigger: 'blur' }],
    isSta: [{ required: true, message: '是否STA计划不能为空', trigger: 'blur' }]
  }
});

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

const createOrderData = ref<createOrderForm>({
  fbaShipmentId: undefined,
  logicQuoteId: undefined
});

const createOrder = async (row: ShipmentPlanVO) => {
  // 创建货运订单
  console.log('row', row);
  console.log('currentFBAData', currentFBAData.value);
  createOrderData.value.fbaShipmentId = currentFBAData.value.shipmentId;
  createOrderData.value.logicQuoteId = row.id;
  const res = await createLogisticsOrder(createOrderData.value);
  console.log('res', res);
  if (res.code === 200) {
    ElMessage.success('创建成功');
  } else {
    ElMessage.error('创建失败');
  }
  drawer.value = false;
};

const dialogTableVisible = ref(false);

const logisticsQuoteList = ref<LogisticsQuoteVO[]>([]);

const tableData = ref([
  {
    channelId: '1902912289404719106',
    channelName: '美国-海运-美森正班船',
    deadline: '2025-03-22 11:00:00',
    destination: 'LGB8',
    effectiveEndTime: '2025-03-30 15:30:19',
    effectiveStartTime: '2025-03-23 15:30:19',
    id: '1903348528587018242',
    inquiryNo: 'INQ20250322000004',
    inquiryStatus: 'OPEN',
    quoteDate: '2025-03-22 00:00:00',
    requesterId: 1,
    targetProviders: null,
    transportChannel: 'sea'
  }
]);

// 时间格式化方法
const formatTime = (timeString) => {
  return timeString.replace(' ', '\n'); // 换行显示日期时间
};

// 状态标签样式
const statusTagType = (status) => {
  switch (status) {
    case 'OPEN':
      return 'success';
    case 'CLOSED':
      return 'info';
    case 'EXPIRED':
      return 'warning';
    default:
      return '';
  }
};

const drawer = ref(false);
const direction = ref<DrawerProps['direction']>('ltr');
const radio1 = ref('Option 1');
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure you want to close this?')
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};

function cancelClick() {
  drawer.value = false;
}

const cascaderChange = (value) => {
  console.log(value);
  console.log('selectedChannel', selectedChannel);
};

function confirmClick() {
  ElMessageBox.confirm(`你确定要关闭 ${radio1.value} ?`)
    .then(() => {
      drawer.value = false;
    })
    .catch(() => {
      // catch error
    });
}

const getLocalDate = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
const shipDate = ref(getLocalDate());
/** 查询货件计划列表 */
const getList = async () => {
  loading.value = true;
  const res = await listShipmentPlan(queryParams.value);
  shipmentPlanList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

let channelTableData = ref([]);

const getAllChannelData = async () => {
  const res = await listAllLogisticsChannel();
  console.log('getAllChannelData');
  console.log(res);
  channelTableData.value = res.rows;
  console.log('groupedChannels:', groupedChannels.value);
};

// 定义映射关系，将编码转换为中文标签
const countryMap = {
  us: '美国'
  // 可扩展其他国家的映射
};

const shippingMethodMap = {
  air: '空运',
  sea: '海运'
  // 可扩展其他运输方式
};

function transformChannels(channels) {
  const result = [];
  const countryGroups = {}; // 按国家缓存顶级节点

  channels.forEach((channel) => {
    const { country, shippingMethod, channelName, id } = channel;

    // 处理国家节点
    const countryValue = country;
    const countryLabel = countryMap[country] || country;
    if (!countryGroups[countryValue]) {
      countryGroups[countryValue] = {
        value: countryValue,
        label: countryLabel,
        children: []
      };
      result.push(countryGroups[countryValue]);
    }

    // 处理运输方式节点
    const methodValue = shippingMethod;
    const methodLabel = shippingMethodMap[shippingMethod] || shippingMethod;
    let methodNode = countryGroups[countryValue].children.find((m) => m.value === methodValue);
    if (!methodNode) {
      methodNode = {
        value: methodValue,
        label: methodLabel,
        children: []
      };
      countryGroups[countryValue].children.push(methodNode);
    }

    // 添加渠道节点
    methodNode.children.push({
      value: id,
      label: channelName
    });
  });

  return result;
}

const currentDes = ref<string | number>('');
const currentFBAData = ref<ShipmentPlanVO>();

// 分组后的渠道数据
const groupedChannels = computed(() => {
  // return channelTableData.value.reduce((acc, channel) => {
  //   const country = channel.country;
  //   const method = channel.shippingMethod;
  //
  //   if (!acc[country]) acc[country] = {};
  //   if (!acc[country][method]) acc[country][method] = [];
  //
  //   acc[country][method].push(channel);
  //   return acc;
  // }, {});
  return transformChannels(channelTableData.value);
});

// 从渠道名称中提取显示标签（移除国家+运输方式前缀）
const getChannelLabel = (name) => {
  return name.split('-').slice(2).join('-');
};

// 获取国家显示名称
const getCountryName = (code) => {
  return countryMap[code] || code.toUpperCase();
};

// 获取运输方式显示名称
const getShippingMethodName = (method) => {
  return shippingMethodMap[method] || method;
};

// 交互逻辑
const activeCollapse = ref(['us']); // 默认展开美国
const selectedChannel = ref(null);

const handleChannelSelect = (channelId) => {
  console.log('Selected channel ID:', channelId);
  // 这里可以触发自定义事件或调用API
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: ShipmentPlanVO[]) => {
  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 checkPrice = async () => {
  console.log('checkPrice', currentDes.value, selectedChannel.value);
  //查询报价单
  console.log('sshipDate.value', shipDate.value);
  const res = await queryLogisticsQuote(currentDes.value, selectedChannel.value, shipDate.value);
  console.log('查询报价单', res);
  if (res.total == 0) {
    //查询询价单
    const requestQuote = await queryWithDesAndChannel(currentDes.value, selectedChannel.value, shipDate.value);
    console.log('查询询价单', requestQuote);
    if (requestQuote.total == 0) {
      console.log('询价单也没数据');
      channelDialogVisible.value = false;
      ElMessageBox.confirm('未查询到价格信息,是否要向物流商发布询价？', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res2 = await createWithDesAndChannel(currentDes.value, selectedChannel.value, shipDate.value);
          console.log('checkPriceEnd2', res2);
          if (res2.code == 200) {
            ElMessage({
              type: 'success',
              message: '询价单创建成功'
            });
          }
        })
        .catch(() => {
          // ElMessage({
          //   type: 'info',
          //   message: 'Delete canceled'
          // });
        });
    } else {
      //显示询价单
      channelDialogVisible.value = false;
      dialogTableVisible.value = true;
      tableData.value = requestQuote.rows;
      console.log('requestQuote.rows', requestQuote.rows);
      console.log('tableData', tableData.value);
    }
  } else {
    //显示报价单
    channelDialogVisible.value = false;
    drawer.value = true;
    logisticsQuoteList.value = res.rows;
  }
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ShipmentPlanVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getShipmentPlan(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改货件计划';
};

const handleSend = async (row?: ShipmentPlanVO) => {
  reset();
  channelDialogVisible.value = true;
  console.log(row);
  currentFBAData.value = row;
  currentDes.value = row.destination;
};

const snycTodayPlan = async () => {
  const res = await takeTodayAmzPlanData();
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('同步成功');

    setTimeout(() => {
      await getList();
    }, 2000);
  }
};

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'amz/shipmentPlan/export',
    {
      ...queryParams.value
    },
    `FBA货件_${new Date().getTime()}.xlsx`
  );
};

const dialogVisible = ref(false);
const addressTableData = ref([]);

const channelDialogVisible = ref(false);

// 转换对象为表格需要的数组格式
const convertAddressToTableData = (address) => {
  return Object.entries(address).map(([key, value]) => ({
    key: key,
    value: value
  }));
};

// 打开对话框
const openAddressDialog = (address) => {
  addressTableData.value = convertAddressToTableData(address);
  dialogVisible.value = true;
};

const currentRow = ref();
const singleTableRef = ref<InstanceType<typeof ElTable>>();

const handleCurrentChange = (val: ShipmentPlanVO | undefined) => {
  currentRow.value = val;
};

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

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