<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="120px">
            <el-form-item label="采购单号" prop="orderSn">
              <el-input v-model="queryParams.orderSn" placeholder="请输入采购单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发货日期" prop="sendDate">
              <el-date-picker clearable v-model="queryParams.sendDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择发货日期" />
            </el-form-item>
            <el-form-item label="采购店铺" prop="storeName">
              <el-input v-model="queryParams.storeName" placeholder="请输入采购店铺" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="实际采购店铺" prop="realStoreName">
              <el-input v-model="queryParams.realStoreName" placeholder="请输入实际采购店铺" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发货状态" prop="sendStatus">
              <el-select v-model="queryParams.sendStatus" placeholder="请选择发货状态" clearable>
                <el-option v-for="dict in send_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['amz:sendOrder:add']">新增 </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['amz:sendOrder:edit']"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['amz:sendOrder:remove']"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['amz:sendOrder:export']"> 导出 </el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="sendOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="props">
            <el-card shadow="never">
              <el-table v-loading="loading" :data="props.row.items" :border="true" size="small" :header-cell-style="{ fontSize: '10px' }">
                <el-table-column label="采购单号" align="center" prop="orderSn" />
                <el-table-column label="产品名称" align="center" prop="productName" />
                <el-table-column label="SKU" align="center" prop="sku" />
                <el-table-column label="采购数量" align="center" prop="quantitySend" />
              </el-table>
            </el-card>
          </template>
        </el-table-column>
        <el-table-column label="采购单号" align="center" prop="orderSn" />
        <el-table-column label="发货单号" align="center" prop="id" />
        <el-table-column label="订单类型" align="center" prop="sendStatus">
          <template #default="scope">
            <dict-tag :options="send_order_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <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="FBA列表" align="center" prop="handleFbaList">
          <template #default="scope">
            <el-button link type="primary" @click="handleFbaList(scope.row)"> 查看详情</el-button>
          </template>
        </el-table-column>

        <!--        <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="SKU" align="center" prop="sku" />
        <el-table-column label="发货数量" align="center" prop="quantitySend" />
        <el-table-column label="箱数" align="center" prop="boxCount">
          <template #default="{ row }">
            <el-popover placement="top" title="装箱明细" :width="500" trigger="click">
              <template #reference>
                <el-button v-if="row.sendDetail !== null" text size="small" type="primary"> {{ row.boxCount }}箱 </el-button>
                <el-tag type="info">暂无装箱数据</el-tag>
              </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">
          <template #default="scope">
            <el-tag v-if="scope.row.bizShipmentPlans != null" type="success">已关联</el-tag>
            <el-tag v-else type="info">未关联</el-tag>
          </template>
        </el-table-column>
        <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">
            <el-button
              v-if="scope.row.sendStatus === 'confirm' || scope.row.sendStatus === 'set_store'"
              size="small"
              link
              type="primary"
              @click="handleUpdate(scope.row)"
              v-hasRoles="['superadmin', 'gengdan', 'yunying']"
              >确认发货
            </el-button>

            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['amz:sendOrder: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="sendOrderFormRef" :model="form" :rules="rules" label-width="120px">
        <!--        <el-form-item label="主键ID" prop="id">-->
        <!--          <el-input v-model="form.id" placeholder="请输入主键ID" />-->
        <!--        </el-form-item>-->
        <el-form-item label="采购单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入采购单号" disabled />
        </el-form-item>

        <el-form-item label="采购店铺" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入采购店铺" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" disabled />
        </el-form-item>
        <!--        <el-form-item label="发货数量" prop="quantitySend">-->
        <!--          <el-input v-model="form.quantitySend" placeholder="请输入发货数量" disabled />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="单箱产品数量" prop="quantityPerBox">-->
        <!--          <el-input v-model="form.quantityPerBox" placeholder="请输入单箱产品数量" disabled />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="箱数" prop="boxCount">-->
        <!--          <el-input v-model="form.boxCount" placeholder="请输入箱数" disabled />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="箱子尺寸" prop="boxDimensions">-->
        <!--          <el-input v-model="form.boxDimensions" placeholder="请输入箱子尺寸" disabled />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="单箱重量" prop="weightPerBox">-->
        <!--          <el-input v-model="form.weightPerBox" placeholder="请输入单箱重量" disabled />-->
        <!--        </el-form-item>-->
        <el-form-item label="指定发货日期" prop="sendDate">
          <el-date-picker clearable v-model="form.sendDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际发货店铺" prop="realStoreName">
          <el-input v-model="form.realStoreName" placeholder="请输入实际采购店铺" />
        </el-form-item>
        <!--        <el-form-item label="发货状态" prop="sendStatus">-->
        <!--          <el-select v-model="form.sendStatus" placeholder="请选择发货状态">-->
        <!--            <el-option v-for="dict in send_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="fbaDialog.title" v-model="fbaDialog.visible" width="1200px" append-to-body>
      <el-table :data="fbaDataList">
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <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="750" trigger="hover">-->
        <!--                      <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="asin" label="asin" />-->
        <!--                        <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="shipToAddress.countryCode" />
        <el-table-column label="物流中心编码" align="center" prop="destination" />
        <el-table-column label="箱数" align="center" prop="boxQuantity" />
        <el-table-column label="申报量" property="setTotal" width="80">
          <template #default="scope">
            {{ scope.row.setTotal }}
          </template>
        </el-table-column>
        <el-table-column label="物流商地址" align="center" prop="address" />
        <el-table-column label="物流商名称" align="center" prop="logisticsProviderName" />
        <!--                <el-table-column label="关联的采购单" align="center">-->
        <!--                  <template #default="scope">-->
        <!--                    <el-tag v-if="scope.row.sendOrders != null" type="success">已关联</el-tag>-->
        <!--                    <el-tag v-else type="info">未关联</el-tag>-->
        <!--                  </template>-->
        <!--                </el-table-column>-->
        <!--                <el-table-column width="150" label="仓库配送地址" align="center" prop="shipToAddress">-->
        <!--                  <template #default="{ row }">-->
        <!--                    &lt;!&ndash;            <el-button @click="openAddressDialog(row.shipToAddress)"> 查看详情</el-button>&ndash;&gt;-->
        <!--                    <el-popover placement="left" :width="800" trigger="click">-->
        <!--                      <template #reference>-->
        <!--                        &lt;!&ndash;                <el-button style="margin-right: 16px">Click to activate</el-button>&ndash;&gt;-->
        <!--                        <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" width="180">-->
        <!--                  <template #default="scope">-->
        <!--                    <el-tag>{{ scope.row.shipmentStatus }}</el-tag>-->
        <!--                  </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="handleDelete(scope.row)" v-hasPermi="['amz:sendOrder:remove']"></el-button>-->
        <!--                  </el-tooltip>-->
        <!--                </template>-->
        <!--              </el-table-column>-->
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="SendOrder" lang="ts">
import { listSendOrder, getSendOrder, delSendOrder, addSendOrder, updateSendOrder } from '@/api/amz/sendOrder';
import { SendOrderVO, SendOrderQuery, SendOrderForm } from '@/api/amz/sendOrder/types';
import { formatText, parseTime } from '@/utils/asinkj';
import { ElTable } from 'element-plus';
import { ShipmentPlanVO } from '@/api/amz/shipmentPlan/types';

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

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

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

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

const sendOrderList = ref<SendOrderVO[]>([]);
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 sendOrderFormRef = ref<ElFormInstance>();

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

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

const fbaDataList = ref<ShipmentPlanVO[]>([]);

const initFormData: SendOrderForm = {
  id: undefined,
  orderSn: undefined,
  sendDate: undefined,
  storeName: undefined,
  productName: undefined,
  quantitySend: undefined,
  quantityPerBox: undefined,
  boxCount: undefined,
  boxDimensions: undefined,
  weightPerBox: undefined,
  realStoreName: undefined,
  sendStatus: undefined
};
const data = reactive<PageData<SendOrderForm, SendOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderSn: undefined,
    sendDate: undefined,
    storeName: undefined,
    productName: undefined,
    quantitySend: undefined,
    quantityPerBox: undefined,
    boxCount: undefined,
    boxDimensions: undefined,
    weightPerBox: undefined,
    realStoreName: undefined,
    sendStatus: undefined,
    params: {}
  },
  rules: {
    orderSn: [{ required: true, message: '采购单号不能为空', trigger: 'blur' }],
    sendDate: [{ required: true, message: '发货日期不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '采购店铺不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    quantitySend: [{ required: true, message: '发货数量不能为空', trigger: 'blur' }],
    // quantityPerBox: [{ required: true, message: '单箱产品数量不能为空', trigger: 'blur' }],
    boxCount: [{ required: true, message: '箱数不能为空', trigger: 'blur' }],
    boxDimensions: [{ required: true, message: '箱子尺寸不能为空', trigger: 'blur' }],
    weightPerBox: [{ required: true, message: '单箱重量不能为空', trigger: 'blur' }],
    realStoreName: [{ required: true, message: '实际采购店铺不能为空', trigger: 'blur' }]
    // sendStatus: [{ required: true, message: '发货状态不能为空', trigger: 'change' }]
  }
});

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

/** 查询供应商创建的发货单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSendOrder(queryParams.value);
  sendOrderList.value = res.rows;

  total.value = res.total;
  loading.value = false;
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: SendOrderVO[]) => {
  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?: SendOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getSendOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '确认发货';
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: SendOrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除供应商创建的发货单编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delSendOrder(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleFbaList = async (row?: SendOrderVO) => {
  fbaDataList.value = row.bizShipmentPlans;
  fbaDialog.visible = true;
  fbaDialog.title = 'FBA货件列表';
};

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

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

onActivated(() => {
  getList();
});
</script>
<!--<style scoped>-->
<!--/* 展开行容器 */-->
<!--:deep(.el-table__expanded-cell) {-->
<!--  background: #f5fbfd !important;-->
<!--  padding: 0 !important;-->
<!--  border-bottom: none !important;-->
<!--}-->

<!--/* 内嵌表格容器 */-->
<!--:deep(.el-table__expanded-cell) .el-table {-->
<!--  &#45;&#45;el-table-bg-color: #ebf3ff !important;-->
<!--  &#45;&#45;el-table-tr-bg-color: #f5fbfd !important;-->
<!--  &#45;&#45;el-table-header-bg-color: #cfe2ff !important; /* 表头变量 */-->
<!--  &#45;&#45;el-table-header-text-color: #2c3e50 !important; /* 新增文字颜色 */-->
<!--}-->

<!--/* 表格主体容器 */-->
<!--:deep(.el-table__expanded-cell) .el-table__body-wrapper {-->
<!--  background: #ebf3ff !important;-->
<!--}-->

<!--/* 表头单元格精准控制 */-->
<!--:deep(.el-table__expanded-cell) .el-table__header th {-->
<!--  background-color: #cfe2ff !important; /* 覆盖默认背景 */-->
<!--  border-bottom: 2px solid #a6c5ff !important; /* 表头下边框 */-->
<!--}-->

<!--/* 表头文字样式 */-->
<!--:deep(.el-table__expanded-cell) .el-table__header .cell {-->
<!--  color: #1a2b3c !important;-->
<!--  font-weight: 600; /* 加粗字体 */-->
<!--}-->

<!--/* 单元格背景 */-->
<!--:deep(.el-table__expanded-cell) .el-table__body tr td {-->
<!--  background-color: transparent !important;-->
<!--}-->

<!--/* 消除卡片干扰 */-->
<!--:deep(.el-card) {-->
<!--  background: transparent !important;-->
<!--  border: none !important;-->
<!--}-->

<!--/* 内嵌表格hover效果 */-->
<!--:deep(.el-table__expanded-cell) .el-table__body tr:hover > td {-->
<!--  background-color: #ffffff !important;-->
<!--}-->

<!--/* 表头hover状态 */-->
<!--:deep(.el-table__expanded-cell) .el-table__header tr:hover th {-->
<!--  background-color: #b6d4ff !important;-->
<!--}-->

<!--/* 表头排序按钮颜色 */-->
<!--:deep(.el-table__expanded-cell) .el-table__header .sort-caret.ascending {-->
<!--  border-bottom-color: #1a2b3c;-->
<!--}-->

<!--:deep(.el-table__expanded-cell) .el-table__header .sort-caret.descending {-->
<!--  border-top-color: #1a2b3c;-->
<!--}-->
<!--</style>-->
