<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" label-width="80px">
            <el-form-item label="FBA货件" prop="fbaShipmentId">
              <el-input v-model="queryParams.fbaShipmentId" placeholder="请输入FBA货件编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单编号" prop="orderId">
              <el-input v-model="queryParams.orderId" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物流商名称" prop="logisticsProviderName">
              <el-input v-model="queryParams.logisticsProviderName" placeholder="请输入物流商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物流渠道" prop="logisticsChannel">
              <!--              <el-input v-model="queryParams.logisticsChannel" placeholder="请输入物流渠道" clearable @keyup.enter="handleQuery" />-->
              <channel-cascader v-model="selectedChannelId" @change="handleChannelChange" />
            </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>
              <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:logisticsOrder:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['amz:logisticsOrder:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['amz:logisticsOrder:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['amz:logisticsOrder:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="logisticsOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="FBA货件编号" align="center" prop="fbaShipmentId" />
        <el-table-column label="订单编号" align="center" prop="orderId" />
        <el-table-column label="店铺名称" align="center" prop="storeName" />
        <el-table-column label="商品详情" align="center">
          <template #default="scope">
            <el-popover placement="top" :width="950" trigger="hover">
              <template #reference>
                <el-button size="small" plain style="margin-right: 16px">查看</el-button>
              </template>
              <el-table :data="scope.row.shipmentItems">
                <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="logisticsWeight">
          <template #default="scope">
            <span>{{ scope.row.logisticsWeight + ' KG' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物流商体积" align="center" prop="logisticsWeight">
          <template #default="scope">
            <span>{{ scope.row.totalVolume + ' cm³' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" align="center" prop="createTime" />
        <el-table-column label="物流商名称" align="center" prop="logisticsProviderName" />
        <el-table-column label="物流渠道" align="center" prop="channelName" />
        <el-table-column label="目的地仓库名称或编码" align="center" prop="destination" />
        <el-table-column label="总箱子数量" align="center" prop="boxQuantity" />
        <el-table-column width="150" label="报价详情" align="center" prop="quote">
          <template #default="scope">
            <!--            <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>
              <div v-if="scope.row.quote">
                <el-descriptions title="基本信息" :column="2" border>
                  <el-descriptions-item label="报价类型">
                    <dict-tag :options="biz_quote_type" :value="scope.row.quote.type" />
                  </el-descriptions-item>
                  <el-descriptions-item label="渠道名称">{{ scope.row.quote.channelName }}</el-descriptions-item>
                  <el-descriptions-item label="目的地">{{ scope.row.quote.destination }}</el-descriptions-item>
                  <!--                  <el-descriptions-item label="ID">{{ scope.row.quote.id }}</el-descriptions-item>-->
                  <el-descriptions-item label="物流公司">{{ scope.row.quote.logisticsName }}</el-descriptions-item>
                  <el-descriptions-item label="货运ID">{{ scope.row.quote.shipmentId }}</el-descriptions-item>
                  <el-descriptions-item label="体积比">{{ scope.row.quote.volumeRatio }}</el-descriptions-item>
                </el-descriptions>

                <el-descriptions title="时间信息" :column="2" border class="mt-4">
                  <el-descriptions-item label="运输时间">{{ scope.row.quote.leadTime }} 天</el-descriptions-item>
                  <el-descriptions-item label="最小运输时间">{{ scope.row.quote.minLeadTime }} 天</el-descriptions-item>
                  <el-descriptions-item label="报价日期">{{ scope.row.quote.quoteDate }}</el-descriptions-item>
                </el-descriptions>

                <el-descriptions title="费用信息" :column="2" border class="mt-4">
                  <el-descriptions-item label="报关费">{{ scope.row.quote.customsDeclarationFee + ' 元' }} </el-descriptions-item>
                  <el-descriptions-item label="价格">{{ scope.row.quote.price }} {{ scope.row.quote.unit }} </el-descriptions-item>
                  <el-descriptions-item label="附加费">{{ scope.row.quote.surcharge + ' 元' }}</el-descriptions-item>
                  <el-descriptions-item label="物流商称重">{{ scope.row.logisticsWeight + ' KG' }} </el-descriptions-item>
                  <el-descriptions-item label="物流商体积">{{ scope.row.totalVolume + ' cm³' }}</el-descriptions-item>
                  <el-descriptions-item label="体积重">{{ scope.row.volumeWeight + ' KG' }}</el-descriptions-item>

                  <el-descriptions-item label-class-name="my-total" label="结算总价">{{ scope.row.settlementPrice + ' 元' }} </el-descriptions-item>
                </el-descriptions>
              </div>
              <div v-else>
                <p>暂无报价信息</p>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="总货件数量" align="center" prop="shipmentQuantity" />
        <el-table-column label="订单状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="logic_order_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="亚马逊仓库实际上架日期" align="center" prop="amazonShelfDate" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.amazonShelfDate, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="上架时效" align="center" prop="shelfTimeliness" />-->
        <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:logisticsOrder:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasRoles="['manager']"
                v-hasPermi="['amz:logisticsOrder:remove']"
              ></el-button>
            </el-tooltip>
            <el-popconfirm title="是否确认收货?" @confirm="handleConfirm(scope.row)">
              <template #reference>
                <el-button v-if="scope.row.status === 'unshipped'" link size="small" type="primary" v-hasRoles="['wuliu']"> 确认收货 </el-button>
              </template>
            </el-popconfirm>
            <el-button v-if="scope.row.status === 'received'" link size="small" type="primary" @click="openDetail(scope.row)" v-hasRoles="['wuliu']">
              编辑明细
            </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="logisticsOrderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="FBA货件编号" prop="fbaShipmentId">
          <el-input v-model="form.fbaShipmentId" placeholder="请输入FBA货件编号" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="物流商ID" prop="logisticsProviderId">
          <el-input v-model="form.logisticsProviderId" placeholder="请输入物流商ID" />
        </el-form-item>
        <el-form-item label="物流商名称" prop="logisticsProviderName">
          <el-input v-model="form.logisticsProviderName" placeholder="请输入物流商名称" />
        </el-form-item>
        <el-form-item label="物流渠道" prop="logisticsChannel">
          <el-input v-model="form.channelName" 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="boxQuantity">
          <el-input v-model="form.boxQuantity" placeholder="请输入总箱子数量" />
        </el-form-item>
        <el-form-item label="总货件数量" prop="shipmentQuantity">
          <el-input v-model="form.shipmentQuantity" placeholder="请输入总货件数量" />
        </el-form-item>
        <el-form-item label="亚马逊仓库实际上架日期" prop="amazonShelfDate">
          <el-date-picker
            clearable
            v-model="form.amazonShelfDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择亚马逊仓库实际上架日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上架时效" prop="shelfTimeliness">
          <el-input v-model="form.shelfTimeliness" 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-drawer size="80%" v-model="hotTableDrawer" :direction="'ttb'">
      <template #header>
        <h4>订单明细</h4>
      </template>
      <template #default>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Document" @click="handleExportDetail"> 导出模板文件</el-button>
          </el-col>
          <el-col :span="1.5">
            <OrderDetailFileUpload :file-type="['xlsx', 'xls']" :file-size="20" />
          </el-col>
          <el-col :span="1.5">
            <file-custom-upload
              :title-name="'上传IEN文件'"
              v-model="fileList"
              :limit="1"
              :file-size="1"
              :file-type="['pdf', 'png', 'jpg']"
              :is-show-tip="true"
              :file-data="orderData"
            />
          </el-col>
        </el-row>
        <HotTable class="hot-container" ref="hotTable" :settings="hotSettings" :data="processedData" :key="tableKey"></HotTable>
        <pagination
          v-show="detailTotal > 0"
          :total="detailTotal"
          v-model:page="queryDetailParams.pageNum"
          v-model:limit="queryDetailParams.pageSize"
          @pagination="getDetailList"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="hotTableDrawer = false">取消</el-button>
          <el-button type="primary" @click="updateCheckDatas">提交选中数据</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="LogisticsOrder" lang="ts">
import { listLogisticsOrder, getLogisticsOrder, delLogisticsOrder, addLogisticsOrder, updateLogisticsOrder } from '@/api/amz/logisticsOrder';
import { LogisticsOrderVO, LogisticsOrderQuery, LogisticsOrderForm } from '@/api/amz/logisticsOrder/types';
import { registerAllModules } from 'handsontable/registry';
import { computed, ref, watch } from 'vue';
import { HotTable } from '@handsontable/vue3';
import { checkPermi } from '@/utils/permission';
import { LogisticsOrderDetailVO } from '@/api/amz/logisticsOrderDetail/types';
import { listLogisticsOrderDetail, updateList } from '@/api/amz/logisticsOrderDetail';
import 'handsontable/dist/handsontable.full.min.css';
import { InfoFilled } from '@element-plus/icons-vue';
import { ElTable } from 'element-plus';
// import 'handsontable/styles/ht-theme-horizon.css';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

// 初始化注册所有模块
registerAllModules();

// 表格实例引用
const hotTable = ref<InstanceType<typeof HotTable>>();
const tableKey = ref(0);
const logisticsOrderDetailList = ref<LogisticsOrderDetailVO[]>([]);
const logisticsOrderDetailFormRef = ref<ElFormInstance>();

// 处理后的表格数据（包含派生字段）
const processedData = computed(() => {
  return logisticsOrderDetailList.value.map((item) => ({
    ...item,
    weightDiff: item.logisticsWeight - item.supplierWeight,
    estimatedDeliveryDateFormatted: proxy.parseTime(item.estimatedDeliveryDate, '{y}-{m}-{d}'),
    actualDeliveryDateFormatted: proxy.parseTime(item.actualDeliveryDate, '{y}-{m}-{d}')
  }));
});

const fileList = ref([]);

const hotTableDrawer = ref(false);

const statusOptions = computed(() => biz_logistics_status.value.map((item) => item.label));

// 创建标签到值的映射
const valueToLabelMap = computed(() => {
  return biz_logistics_status.value.reduce((map, item) => {
    map[item.value] = item.label;
    return map;
  }, {});
});

const labelTovalueMap = computed(() => {
  return biz_logistics_status.value.reduce((map, item) => {
    map[item.label] = item.value;
    return map;
  }, {});
});

const orderData = ref({
  order: ''
});

const selectedChannelId = ref('');
const handleChannelChange = ({ value, node }) => {
  console.log('选中渠道ID:', value);
  console.log('完整渠道信息:', node);
  // 可以访问 node.code 等附加信息
  queryParams.value.channelName = node;
};

// 表格配置-------
const hotSettings = ref({
  licenseKey: 'non-commercial-and-evaluation',
  // afterValidate: (isValid, value, row, prop, source) => {
  //   if (!isValid) {
  //     // 获取旧值并恢复
  //     console.log('isValid:', isValid, 'value:', value, 'row:', row, 'prop:', prop, 'source:', source);
  //     const oldValue = hotTable.value.hotInstance.getDataAtCell(row, prop);
  //     console.log('旧值:', oldValue);
  //     hotTable.value.hotInstance.setDataAtRowProp(row, prop, oldValue);
  //   }
  // },
  theme: 'ht-theme-horizon',
  manualColumnResize: true, // 手动调整列宽默认 false
  rowHeaders: true, // 关闭行号
  filters: true, // 启用筛选
  // dropdownMenu: true, // 启用菜单
  // contextMenu: true, // 启用右键菜单
  height: 'auto', // 初始高度
  manualRowResize: true, // 允许行高调整
  autoWrapRow: true, // 自动换行
  multiSelect: true, // 多选支持
  stretchH: 'all', // 列宽自适应
  afterGetColHeader: (col: number, th: HTMLElement) => {
    const columnDef = hotSettings.value.columns[col];
    const isEditable = !columnDef?.readOnly; // 判断是否可编辑

    // 添加可编辑标识
    if (isEditable) {
      th.style.backgroundColor = '#f0f9eb'; // Element Plus 成功色浅版
      th.style.borderLeft = '3px solid #67c23a';
      th.innerHTML = `
        ${th.innerText}
      `;
    }
  },
  afterChange: (changes) => {
    if (!changes) return;
    // console.log('changes:', changes);
    // changes.forEach(([row, prop, oldVal, newVal]) => {
    //   console.log('修改的行:', row);
    //   console.log('修改的列:', prop);
    //   console.log('旧值:', oldVal);
    //   console.log('新值:', newVal);
    // });
    changes.forEach(([row, prop, oldVal, newVal]) => {
      console.log('修改的行:', row);
      console.log('修改的列:', prop);
      console.log('旧值:', oldVal);
      console.log('新值:', newVal);

      logisticsOrderDetailList.value[row][prop] = newVal;
      if (prop === 'logisticsStatus') {
        logisticsOrderDetailList.value[row].logisticsStatus = labelTovalueMap.value[newVal];
      }

      // if (prop === 'logisticsWeight' || prop === 'pricePerKg' || prop === 'otherFee') {
      //   console.log('计算总价');
      //   logisticsOrderDetailList.value[row].totalFee =
      //     (parseFloat(logisticsOrderDetailList.value[row].logisticsWeight) ?? 0) * (parseFloat(logisticsOrderDetailList.value[row].pricePerKg) ?? 0) +
      //     (parseFloat(logisticsOrderDetailList.value[row].otherFee) ?? 0) +
      //     (parseFloat(logisticsOrderDetailList.value[row].totalPrice) ?? 0);
      // }
      if (prop === 'length' || prop === 'width' || prop === 'height') {
        console.log('计算体积');
        logisticsOrderDetailList.value[row].totalVolume =
          (parseFloat(logisticsOrderDetailList.value[row].length) ?? 0) *
          (parseFloat(logisticsOrderDetailList.value[row].width) ?? 0) *
          (parseFloat(logisticsOrderDetailList.value[row].height) ?? 0);
      }
    });
    console.log('logisticsOrderDetailList.value:', logisticsOrderDetailList.value);
  },
  colHeaders: [
    '选择',
    '订单号',
    'FBA货件编号',
    'FBA箱号',
    // '物流商名称',
    // '物流渠道',
    // '目的地仓库',
    '数量',
    // '实际数量',
    '物流追踪号',
    '物流商计重(KG)',
    '长(CM)',
    '宽(CM)',
    '高(CM)',
    '体积',
    // '称重差异',
    // '物流单价报价',
    // '物流总价报价',
    // '物流计价重量',
    // '其他物流费用',
    // '费用合计',
    '物流状态',
    '预计签收日期',
    '实际签收日期',
    '报价时效',
    '操作'
  ],
  columns: [
    {
      // 选择列
      type: 'checkbox',
      className: 'htCenter',
      data: 'checked',
      width: 55
    },
    { data: 'orderId', className: 'htCenter', readOnly: true },
    { data: 'fbaShipmentId', className: 'htCenter', readOnly: true },
    { data: 'fbaBoxNumber', className: 'htCenter', readOnly: true }, // FBA箱号
    // { data: 'logisticsProviderName', className: 'htCenter', readOnly: true }, // 物流商名称
    // { data: 'logisticsChannel', className: 'htCenter', readOnly: true }, // 物流渠道
    // { data: 'destinationWarehouse', className: 'htCenter', readOnly: true }, // 目的地仓库
    { data: 'plannedQuantity', className: 'htCenter', readOnly: true }, // 计划数量
    // { data: 'shipmentQuantity', className: 'htCenter', readOnly: false, type: 'numeric' }, // 实际数量
    { data: 'trackingNumber', className: 'htCenter', readOnly: false }, // 物流追踪号
    {
      data: 'logisticsWeight',
      className: 'htCenter',
      readOnly: false,
      type: 'numeric',
      renderer: function (instance, td, row, col, prop, value, cellProperties) {
        // 调用默认的数字渲染器以保持格式（如千分位）
        // 处理单位显示
        if (typeof value === 'number' && !isNaN(value)) {
          td.textContent = value.toLocaleString() + ' kg'; // 添加单位
        } else if (typeof value === 'string') {
          td.textContent = value + ' kg';
        }

        // 确保居中对齐（可选，若 className 已生效可省略）
        return td;
      }
    }, // 物流商计重
    {
      data: 'length',
      className: 'htCenter',
      readOnly: false,
      type: 'numeric',
      renderer: function (instance, td, row, col, prop, value, cellProperties) {
        // 调用默认的数字渲染器以保持格式（如千分位）
        // 处理单位显示
        if (typeof value === 'number' && !isNaN(value)) {
          td.textContent = value.toLocaleString() + ' cm'; // 添加单位
        } else if (typeof value === 'string') {
          td.textContent = value + ' cm';
        }

        // 确保居中对齐（可选，若 className 已生效可省略）
        return td;
      }
    }, // 长
    {
      data: 'width',
      className: 'htCenter',
      readOnly: false,
      type: 'numeric',
      renderer: function (instance, td, row, col, prop, value, cellProperties) {
        // 调用默认的数字渲染器以保持格式（如千分位）
        // 处理单位显示
        if (typeof value === 'number' && !isNaN(value)) {
          td.textContent = value.toLocaleString() + ' cm'; // 添加单位
        } else if (typeof value === 'string') {
          td.textContent = value + ' cm';
        }

        // 确保居中对齐（可选，若 className 已生效可省略）
        return td;
      }
    }, // 宽
    {
      data: 'height',
      className: 'htCenter',
      readOnly: false,
      type: 'numeric',
      renderer: function (instance, td, row, col, prop, value, cellProperties) {
        // 调用默认的数字渲染器以保持格式（如千分位）
        // 处理单位显示
        if (typeof value === 'number' && !isNaN(value)) {
          td.textContent = value.toLocaleString() + ' cm'; // 添加单位
        } else if (typeof value === 'string') {
          td.textContent = value + ' cm';
        }

        // 确保居中对齐（可选，若 className 已生效可省略）
        return td;
      }
    }, // 高
    {
      data: 'totalVolume',
      className: 'htCenter',
      readOnly: true,
      type: 'numeric',
      renderer: function (instance, td, row, col, prop, value, cellProperties) {
        // 调用默认的数字渲染器以保持格式（如千分位）
        // 处理单位显示
        if (typeof value === 'number' && !isNaN(value)) {
          td.textContent = value.toLocaleString() + ' cm³'; // 添加单位
        } else if (typeof value === 'string') {
          td.textContent = value + ' cm³';
        }

        // 确保居中对齐（可选，若 className 已生效可省略）
        return td;
      }
    }, // 体积
    // {
    //   data: 'weightDiff', // 称重差异
    //   className: 'htCenter',
    //   readOnly: true,
    //   type: 'numeric',
    //   renderer: (instance, td) => {
    //     // 添加差异颜色标识
    //     const value = instance.getDataAtCell(td.row, td.col);
    //     td.style.color = value > 0 ? '#67C23A' : '#F56C6C';
    //     td.innerText = value;
    //     return td;
    //   }
    // },
    // {
    //   data: 'pricePerKg',
    //   className: 'htCenter',
    //   type: 'numeric',
    //   readOnly: true,
    //   renderer: function (instance, td, row, col, prop, value, cellProperties) {
    //     // 调用默认的数字渲染器以保持格式（如千分位）
    //     // 处理单位显示
    //     if (typeof value === 'number' && !isNaN(value)) {
    //       td.textContent = value.toLocaleString() + ' 元/kg'; // 添加单位
    //     }
    //
    //     // 确保居中对齐（可选，若 className 已生效可省略）
    //     return td;
    //   }
    // }, // 物流单价
    // {
    //   data: 'totalPrice',
    //   className: 'htCenter',
    //   type: 'numeric',
    //   readOnly: true,
    //   renderer: function (instance, td, row, col, prop, value, cellProperties) {
    //     // 调用默认的数字渲染器以保持格式（如千分位）
    //     // 处理单位显示
    //     if (typeof value === 'number' && !isNaN(value)) {
    //       td.textContent = value.toLocaleString() + ' 元'; // 添加单位
    //     }
    //
    //     // 确保居中对齐（可选，若 className 已生效可省略）
    //     return td;
    //   }
    // }, // 物流总价报价
    // { data: 'logisticsBillingWeight', className: 'htCenter', type: 'numeric', readOnly: true }, // 物流计价重量
    // {
    //   data: 'otherFee',
    //   className: 'htCenter',
    //   type: 'numeric',
    //   readOnly: false,
    //   renderer: function (instance, td, row, col, prop, value, cellProperties) {
    //     // 调用默认的数字渲染器以保持格式（如千分位）
    //     // 处理单位显示
    //     if (typeof value === 'number' && !isNaN(value)) {
    //       td.textContent = value.toLocaleString() + ' 元'; // 添加单位
    //     }
    //
    //     // 确保居中对齐（可选，若 className 已生效可省略）
    //     return td;
    //   }
    // }, // 其他物流费用
    // { data: 'totalFee', className: 'htCenter', readOnly: true }, // 费用合计
    {
      data: 'logisticsStatus',
      className: 'htCenter',
      readOnly: false,
      type: 'select',
      selectOptions: statusOptions,
      strict: false, // 允许显示 label 但存储 value
      renderer: (instance, td, row, col, prop, value) => {
        // 显示 label（兼容初始化时可能直接拿到 value 的情况）
        td.textContent = valueToLabelMap.value[value] || value;
        return td;
      }
    }, // 物流状态
    {
      // 预计签收日期
      data: 'estimatedDeliveryDate',
      type: 'date', // 日期类型
      dateFormat: 'YYYY-MM-DD', // 日期格式
      correctFormat: true, // 自动纠正格式
      // locale: 'zh-CN', // 本地化（中文）
      // className: 'htCenter', // 单元格内容居中
      readOnly: true,
      validator: (value, callback) => {
        if (value === '') {
          callback(true); // 允许空值
          return;
        }

        // 校验日期格式和有效性（原生 JS）
        const regex = /^\d{4}-\d{2}-\d{2}$/;
        console.log('校验日期格式和有效性');
        if (!regex.test(value)) {
          callback(false);
          console.log('校验日期格式和有效性失败');
          return;
        }

        const [year, month, day] = value.split('-').map(Number);
        const date = new Date(year, month - 1, day);
        const isValid = date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
        console.log('校验日期格式和有效性', isValid);
        callback(isValid);
      }
    },
    {
      // 实际签收日期
      data: 'actualDeliveryDate',
      type: 'date', // 日期类型
      dateFormat: 'YYYY-MM-DD', // 日期格式
      correctFormat: true, // 自动纠正格式
      locale: 'zh-CN', // 本地化（中文）
      className: 'htCenter' // 单元格内容居中
    },
    {
      data: 'timeliness',
      readOnly: true,
      width: 150,
      type: 'numeric',
      renderer: function (instance, td, row, col, prop, value, cellProperties) {
        // 调用默认的数字渲染器以保持格式（如千分位）
        // 处理单位显示
        if (typeof value === 'number' && !isNaN(value)) {
          td.textContent = value.toLocaleString() + ' 天'; // 添加单位
        }

        // 确保居中对齐（可选，若 className 已生效可省略）
        return td;
      }
    }
  ],
  afterOnCellMouseDown: (event, coords) => {
    if (buttonLoading.value) return;

    if (coords.col === 21) {
      const rowData = logisticsOrderDetailList.value[coords.row];
      const target = event.target.closest('button');

      if (target?.classList.contains('edit-btn')) {
        buttonLoading.value = true;
        handleUpdate(rowData).finally(() => {
          buttonLoading.value = false;
        });
      } else if (target?.classList.contains('delete-btn')) {
        buttonLoading.value = true;
        handleDelete(rowData).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  },
  contextMenu: {
    items: {
      editRow: {
        name: '修改',
        disabled: () => !checkPermi(['amz:logisticsOrderDetail:edit']) || buttonLoading.value,
        callback: (_, selection) => {
          const rowData = logisticsOrderDetailList.value[selection[0].start.row];
          buttonLoading.value = true;
          handleUpdate(rowData).finally(() => {
            buttonLoading.value = false;
          });
        }
      }
    }
  }
});

// 监听数据变化
watch(
  logisticsOrderDetailList,
  () => {
    tableKey.value++;
  },
  { deep: true }
);

const logisticsOrderList = ref<LogisticsOrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const detailLoading = 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 detailTotal = ref(0);

const queryFormRef = ref<ElFormInstance>();
const logisticsOrderFormRef = ref<ElFormInstance>();

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

const initFormData: LogisticsOrderForm = {
  id: undefined,
  fbaShipmentId: undefined,
  orderId: undefined,
  logisticsProviderId: undefined,
  logisticsProviderName: undefined,
  channelName: undefined,
  destination: undefined,
  boxQuantity: undefined,
  shipmentQuantity: undefined,
  amazonShelfDate: undefined,
  shelfTimeliness: undefined
};
const data = reactive<PageData<LogisticsOrderForm, LogisticsOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fbaShipmentId: undefined,
    orderId: undefined,
    logisticsProviderId: undefined,
    logisticsProviderName: undefined,
    logisticsChannel: undefined,
    destination: undefined,
    boxQuantity: undefined,
    channelName: undefined,
    shipmentQuantity: undefined,
    amazonShelfDate: undefined,
    shelfTimeliness: undefined,
    channelId: undefined,
    params: {}
  },
  queryDetailParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: undefined
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    fbaShipmentId: [{ required: true, message: 'FBA货件编号不能为空', trigger: 'blur' }],
    orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
    logisticsProviderId: [{ required: true, message: '物流商ID不能为空', trigger: 'blur' }],
    logisticsProviderName: [{ required: true, message: '物流商名称不能为空', trigger: 'blur' }],
    logisticsChannel: [{ required: true, message: '物流渠道不能为空', trigger: 'blur' }],
    destination: [{ required: true, message: '目的地仓库名称或编码不能为空', trigger: 'blur' }],
    boxQuantity: [{ required: true, message: '总箱子数量不能为空', trigger: 'blur' }],
    shipmentQuantity: [{ required: true, message: '总货件数量不能为空', trigger: 'blur' }],
    amazonShelfDate: [{ required: true, message: '亚马逊仓库实际上架日期不能为空', trigger: 'blur' }],
    shelfTimeliness: [{ required: true, message: '上架时效不能为空', trigger: 'blur' }]
  }
});

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

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

const getDetailList = async () => {
  detailLoading.value = true;
  const res = await listLogisticsOrderDetail(queryDetailParams.value);

  logisticsOrderDetailList.value = res.rows.map((item) => ({
    ...item,
    checked: false // 初始化为未选中
  }));
  console.log('logisticsOrderDetailList', logisticsOrderDetailList);
  detailTotal.value = res.total;
  detailLoading.value = false;
};

const updateCheckDatas = async () => {
  // 获取选中的行数据
  const checkedRows = logisticsOrderDetailList.value.filter((row) => row.checked);
  console.log('checkedRows', checkedRows);
  if (checkedRows.length === 0) {
    ElMessage.warning('请选择要修改的行');
    return;
  }

  const res = await updateList(checkedRows);
  console.log('res', res);
  if (res.code === 200) {
    ElMessage.success('更新成功');
    getDetailList();
  } else {
    ElMessage.error('更新失败');
  }
  hotTableDrawer.value = false;
  getList();
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: LogisticsOrderVO[]) => {
  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?: LogisticsOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getLogisticsOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改物流订单';
};

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

const handleConfirm = async (row?: LogisticsOrderVO) => {
  console.log('row:', row);
  const updateData = {
    id: row?.id,
    status: 'received'
  };
  buttonLoading.value = true;
  if (updateData.id) {
    await updateLogisticsOrder(updateData).finally(() => (buttonLoading.value = false));
  }
  proxy?.$modal.msgSuccess('操作成功');
  // dialog.visible = false;
  await getList();
};

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

/** 查看详情按钮操作 */
const openDetail = async (row?: LogisticsOrderVO) => {
  hotTableDrawer.value = true;
  const _ids = row?.id || ids.value;
  console.log(_ids);
  detailLoading.value = true;
  queryDetailParams.value.orderId = row.orderId;
  // const res = await listLogisticsOrderDetail(queryDetailParams.value);
  // logisticsOrderDetailList.value = res.rows;
  // detailTotal.value = res.total;
  // detailLoading.value = false;
  orderData.value.order = queryDetailParams.value.orderId;
  getDetailList();
};

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

const handleExportDetail = () => {
  proxy?.download(
    'amz/logisticsOrderDetail/export',
    {
      ...queryDetailParams.value
    },
    `logisticsOrderDetail_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
onActivated(() => {
  getList();
});
</script>
<style scoped>
:deep(.my-total) {
  background: var(--el-color-success-light-9) !important;
}
</style>
