<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="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="deadline">
              <el-date-picker clearable v-model="queryParams.gmtCreate" type="date" value-format="YYYY-MM-DD" 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="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasRoles="['superadmin']" 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-hasRoles="['superadmin']"
              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-hasRoles="['superadmin']"
              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>-->
          <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-card shadow="never">
              <el-table :data="props.row.sendOrders">
                <!--        <el-table-column type="selection" width="55" align="center" />-->
                <el-table-column label="采购单号" align="center" prop="orderSn" />
                <el-table-column label="发货单号" align="center" prop="id" />
                <el-table-column label="创建日期" align="center" prop="createTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="发货日期" align="center" prop="sendDate" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.sendDate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="采购店铺" align="center" prop="storeName" />
                <el-table-column label="供应商名称" align="center" prop="sendName" />
                <el-table-column label="物流商名称" align="center" prop="logisticsProviderName">
                  <!--                  <template #default="{ row }">-->
                  <!--                    <el-popover placement="top" title="物流商地址" :width="200" trigger="click">-->
                  <!--                      <template #reference>-->
                  <!--                        <el-button v-if="row.logisticsProviderName !== null" text size="small" type="primary">-->
                  <!--                          {{ row.logisticsProviderName }}-->
                  <!--                        </el-button>-->
                  <!--                      </template>-->
                  <!--                      <div>{{ row.address || '暂无地址' }}</div>-->
                  <!--                    </el-popover>-->
                  <!--                  </template>-->
                </el-table-column>
                <el-table-column label="产品名称" align="center" prop="productName" />
                <el-table-column label="发货数量" align="center" prop="quantitySend" />
                <!--        <el-table-column label="单箱产品数量" align="center" prop="quantityPerBox" />-->
                <el-table-column label="箱数" align="center" prop="boxCount">
                  <template #default="{ row }">
                    <el-popover placement="top" title="装箱明细" :width="500" trigger="click">
                      <template #reference>
                        <el-button text size="small" type="primary"> {{ row.boxCount }}箱</el-button>
                      </template>
                      <div v-if="row.sendDetail !== null" v-html="formatText(row.sendDetail)"></div>
                      <div v-else>暂无数据</div>
                    </el-popover>
                  </template>
                </el-table-column>
                <!--        <el-table-column label="箱子尺寸" align="center" prop="boxDimensions" />-->
                <el-table-column label="总重量" align="center" prop="weightPerBox" />
                <el-table-column label="实际发货店铺" align="center" prop="realStoreName" />
                <!--                <el-table-column label="发货状态" align="center" prop="sendStatus">-->
                <!--                  <template #default="scope">-->
                <!--                    <dict-tag :options="send_status" :value="scope.row.sendStatus" />-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
                <!--                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
                <!--                  <template #default="scope">-->
                <!--                    &lt;!&ndash;            <el-tooltip content="修改" placement="top" v-if="scope.row.sendStatus === 'pending'">&ndash;&gt;-->
                <!--                    &lt;!&ndash;              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['amz:sendOrder:edit']"></el-button>&ndash;&gt;-->
                <!--                    &lt;!&ndash;            </el-tooltip>&ndash;&gt;-->
                <!--                    <el-tooltip content="删除" placement="top">-->
                <!--                      <el-button-->
                <!--                        link-->
                <!--                        type="primary"-->
                <!--                        icon="Delete"-->
                <!--                        @click="handleDeleteRelation(props.row.id, scope.row.id)"-->
                <!--                        v-hasRoles="['superadmin', 'yunying']"-->
                <!--                      ></el-button>-->
                <!--                    </el-tooltip>-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
              </el-table>
            </el-card>
          </template>
        </el-table-column>

        <el-table-column label="创建日期" align="center" prop="gmtCreate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" align="center" prop="sellerName" />
        <el-table-column label="货件编号" align="center" prop="shipmentId" />
        <el-table-column label="商品详情" align="center">
          <template #default="scope">
            <el-popover placement="top" :width="950" trigger="hover" @show="showPop(scope.row)">
              <template #reference>
                <el-button size="small" plain 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="150" property="sku" label="sku" />
                <el-table-column width="150" property="asin" label="asin" />
                <el-table-column width="80" property="quantityShipped" label="申报量" />
                <el-table-column width="150" property="fnsku" label="fnsku" />
                <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="boxQuantity" />-->
        <!--        <el-table-column label="箱子尺寸" align="center" prop="boxSize" />-->
        <!--        <el-table-column label="供应商称重-总重量" align="center" prop="vendorWeight" />-->
        <!--        <el-table-column label="套数" align="center" prop="setTotal" />-->
        <!--        <el-table-column label="渠道ID" align="center" prop="channelId" />-->

        <el-table-column label="关联采购单" align="center" prop="sendOrderId">
          <template #default="scope">
            <el-popover v-if="scope.row.sendOrderId" placement="top" :width="800" trigger="click">
              <template #reference>
                <!--                <el-button style="margin-right: 16px">Click to activate</el-button>-->
                <el-button size="small" plain v-if="scope.row.sendOrderId" type="success"> 已关联</el-button>
              </template>
              <el-descriptions v-if="scope.row.sendOrderId" title="供应商发货单" border :column="2" label-class-name="desc-label">
                <!-- 订单信息 -->
                <el-descriptions-item label="订单编号" min-width="120px">
                  {{ scope.row.sendOrder.orderSn }}
                </el-descriptions-item>

                <el-descriptions-item label="产品名称">
                  {{ scope.row.sendOrder.productName }}
                </el-descriptions-item>

                <el-descriptions-item label="总箱数"> {{ scope.row.sendOrder.boxCount }} 箱</el-descriptions-item>
                <el-descriptions-item label="总重量"> {{ scope.row.sendOrder.weightPerBox }} kg</el-descriptions-item>

                <el-descriptions-item label="箱体规格">
                  <div v-html="formatText(scope.row.sendOrder.sendDetail)"></div>
                </el-descriptions-item>

                <!--                <el-descriptions-item label="每箱数量"> {{ scope.row.sendOrder.quantityPerBox }} 件/箱 </el-descriptions-item>-->
              </el-descriptions>
            </el-popover>
            <!--            <el-tooltip class="box-item" effect="dark" content="点击关联采购单" placement="top">-->
            <!--              <el-button size="small" plain v-if="!scope.row.sendOrderId" type="info" @click="handleLink(scope.row)"> 未关联 </el-button>-->
            <!--            </el-tooltip>-->
          </template>
        </el-table-column>

        <!--        <el-table-column label="渠道ID" align="center" prop="channelId" />-->

        <el-table-column width="150" label="仓库配送地址" align="center" prop="shipToAddress">
          <template #default="{ row }">
            <!--            <el-button @click="openAddressDialog(row.shipToAddress)"> 查看详情</el-button>-->
            <el-popover placement="left" :width="800" trigger="click">
              <template #reference>
                <!--                <el-button style="margin-right: 16px">Click to activate</el-button>-->
                <el-button plain size="small" type="success"> 点击查看详情</el-button>
              </template>
              <el-descriptions title="收货地址信息" :column="3" border>
                <el-descriptions-item v-for="item in descriptItems" :key="item.prop" :label="item.label">
                  {{ row.shipToAddress[item.prop] || 'N/A' }}
                </el-descriptions-item>
              </el-descriptions>
            </el-popover>
          </template>
        </el-table-column>
        <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="channelName" />-->
        <el-table-column label="物流状态" align="center">
          <template #default="scope">
            <el-tag>未确认</el-tag>
          </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-hasRoles="['superadmin']"
                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-button link type="primary" size="small" @click="handleSend(scope.row)" v-hasPermi="['amz:shipmentPlan:remove']">查询报价 </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="shipmentPlanFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="货件编号" prop="shipmentId">
          <el-input v-model="form.shipmentId" placeholder="请输入货件编号" disabled />
        </el-form-item>
        <el-form-item label="货件名称" prop="shipmentName">
          <el-input v-model="form.shipmentName" placeholder="请输入货件名称" disabled />
        </el-form-item>
        <el-form-item label="物流中心编码" prop="destination">
          <el-input v-model="form.destination" placeholder="请输入物流中心编码" disabled />
        </el-form-item>
        <el-form-item label="物流渠道">
          <el-cascader
            ref="channelCascaderRef"
            v-model="selectedChannel"
            :props="{ emitPath: false }"
            placeholder="请选择渠道"
            :options="groupedChannels"
            @change="cascaderChange"
            :show-all-levels="false"
            filterable
          />
        </el-form-item>
        <el-form-item label="总箱子数量" prop="boxQuantity">
          <el-input v-model="form.boxQuantity" placeholder="请输入总箱子数量" />
        </el-form-item>
        <el-form-item label="箱子尺寸" prop="boxSize">
          <el-input v-model="form.boxSize" placeholder="请输入箱子尺寸" />
        </el-form-item>
        <el-form-item label="供应商称重-总重量" prop="vendorWeight">
          <el-input v-model="form.vendorWeight" placeholder="请输入供应商称重-总重量" />
        </el-form-item>
        <el-form-item label="套数" prop="setTotal">
          <el-input v-model="form.setTotal" placeholder="请输入套数" />
        </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="'default'" />
        </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="80%" 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="物流商名称" align="center" prop="logisticsName" />
          <el-table-column label="目的地" align="center" prop="destination" />
          <el-table-column label="渠道名称" align="center" prop="channelName" />
          <!--          <el-table-column label="询价类型" align="center" prop="type">-->
          <!--            <template #default="scope">-->
          <!--              <dict-tag :options="request_type" :value="scope.row.type" />-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="报价类型" align="center" prop="remark">
            <template #default="scope">
              <dict-tag :options="biz_quote_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="基础价格" align="center" prop="price">
            <template #default="scope">
              <!--              <el-tag type="warning" v-if="scope.row.type === 'weight'">重量询价参考总价</el-tag>-->
              <span>{{ scope.row.price + scope.row.unit }}</span>
            </template>
          </el-table-column>
          <el-table-column label="体积比" align="center" prop="volumeRatio">
            <template #default="scope">
              <span>{{ scope.row.volumeRatio }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column label="总价" align="center" prop="totalPrice">-->
          <!--            <template #default="scope">-->
          <!--              <span v-if="scope.row.type === 'weight'">{{ scope.row.totalPrice }}</span>-->
          <!--              <el-tag type="warning" v-else>普通询价参考单价</el-tag>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="最短时效" align="center" prop="minLeadTime" />
          <el-table-column label="时效" align="center" prop="leadTime" />
          <el-table-column label="附加费" align="center" prop="surcharge" />
          <el-table-column label="报关费" align="center" prop="customsDeclarationFee" />
          <el-table-column label="报价生效日期" align="center" prop="quoteDate" width="120">
            <template #default="scope">
              <span>{{ parseTime(scope.row.quoteDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column label="提交状态" align="center" prop="isSubmitted">-->
          <!--            <template #default="scope">-->
          <!--              <dict-tag :options="sys_yes_no" :value="scope.row.isSubmitted" />-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <!--          <el-table-column label="渠道类型" align="center" prop="channelType" />-->
          <el-table-column label="是否双清包税" align="center" prop="isDdp">
            <template #default="scope">
              <dict-tag :options="sys_yes_no" :value="scope.row.isDdp" />
            </template>
          </el-table-column>
          <!--          <el-table-column label="单位" align="center" prop="unit" />-->
          <el-table-column label="报价备注" align="center" prop="remark" />
          <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:shipmentPlan: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>
</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 { DrawerProps, ElNotification } from 'element-plus';
import { createWithDesAndChannel, queryWithDesAndChannel } from '@/api/amz/inquiryRequest';

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

import { ShipmentPlanVO, ShipmentPlanQuery, ShipmentPlanForm, DescriptItem } 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_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));
const { biz_quote_type } = toRefs<any>(proxy?.useDict('biz_quote_type'));

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

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

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 descriptItems: DescriptItem[] = [
  { label: '姓名', prop: 'name' },
  { label: '国家', prop: 'countryCode' },
  { label: '州/省代码', prop: 'stateOrProvinceCode' },
  { label: '城市', prop: 'city' },
  { label: '州/省', prop: 'region' },
  { label: '地址行1', prop: 'addressLine1' },
  { label: '地址行2', prop: 'addressLine2' },
  { label: '邮政编码', prop: 'postalCode' },
  { label: '电话', prop: 'phone' },
  { label: '门牌号', prop: 'doorplate' }
];

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,
  vendorWeight: 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,
    fbaStatus: 'send',
    boxQuantity: undefined,
    boxSize: undefined,
    vendorWeight: 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('创建成功');
    const updateForm = ref({
      id: currentFBAData.value.id,
      fbaStatus: 'query'
    });
    await updateShipmentPlan(updateForm.value).finally(() => (buttonLoading.value = false));
  } 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 channelCascaderRef = ref(null);
const cascaderChange = (value) => {
  console.log(value);
  console.log('selectedChannel', selectedChannel);
  console.log('groupedChannels', groupedChannels);

  // console.log('channelCascaderRef', channelCascaderRef);
  console.log('label====', channelCascaderRef.value.getCheckedNodes()[0].label);
};

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 formatText = (text) => {
  // 1. 转义HTML特殊字符
  const escaped = String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');

  // 2. 替换换行符
  return escaped.replace(/\n/g, '<br>');
};
/** 表单重置 */
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 () => {
  // form.value.fbaStatus = 'send';
  //
  // const updateForm = ref({
  //   id: currentFBAData.value.id,
  //   fbaStatus: 'send'
  // });
  // await updateShipmentPlan(updateForm.value).finally(() => (buttonLoading.value = false));

  console.log('checkPrice', currentDes.value, selectedChannel.value);
  //查询报价单
  console.log('sshipDate.value', shipDate.value);
  // if (currentFBAData.value.channelId == null) {
  //   ElMessage({
  //     type: 'warning',
  //     message: '请先设置渠道！'
  //   });
  //   return;
  // }

  const res = await queryLogisticsQuoteWithDes(currentDes.value, shipDate.value, currentFBAData.value.shipmentId);
  console.log('查询报价单', res);
  if (res.total == 0) {
    ElNotification({
      title: '警告',
      message: '暂时没有物流商报价',
      type: 'warning',
      duration: 3000
    });
  } else {
    //显示报价单
    // ElMessage.success('已经有人报价了');

    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;
  checkPrice();
};

const showPop = async (row: any) => {
  console.log('row', row);
};

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

/** 提交按钮 */
const submitForm = () => {
  console.log('selectedChannel', selectedChannel);
  console.log('groupedChannels', groupedChannels);

  // console.log('channelCascaderRef', channelCascaderRef);
  console.log('label====', channelCascaderRef.value.getCheckedNodes()[0].label);
  form.value.channelName = channelCascaderRef.value.getCheckedNodes()[0].label;
  form.value.channelId = selectedChannel;
  const updateForm = ref({
    id: form.value.id,
    boxQuantity: form.value.boxQuantity,
    boxSize: form.value.boxSize,
    vendorWeight: form.value.vendorWeight,
    setTotal: form.value.setTotal,
    channelId: selectedChannel,
    channelName: channelCascaderRef.value.getCheckedNodes()[0].label
  });
  shipmentPlanFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (updateForm.value.id) {
        await updateShipmentPlan(updateForm.value).finally(() => (buttonLoading.value = false));
      } else {
        await addShipmentPlan(updateForm.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
    },
    `shipmentPlan_${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>
