<template>
  <div class="app-container">
    <el-row class="client-fix-height container">
      <el-col>
        <!-- 查询表单 -->
        <el-form :model="queryParams"
          inline
          label-position="left">
          <el-row>
            <el-form-item label="安徽/北京单据编号"
              prop="sentNo">
              <el-input v-model="queryParams.sentNo"
                clearable
                placeholder="输入要查询的安徽/北京单独单号"
                @input="getLogisticsReceiptList"
                style="width: 250px;" />
            </el-form-item>
            <el-form-item label="快递单号"
              prop="expressNo">
              <el-input v-model="queryParams.expressNo"
                clearable
                placeholder="输入要查询的快递单号"
                @input="getLogisticsReceiptList" />
            </el-form-item>
            <el-form-item label="DD 单号查询"
              prop="ddNo">
              <el-input v-model="queryParams.ddNo"
                clearable
                placeholder="输入要查询的 DD 单号"
                @input="getLogisticsReceiptList" />
            </el-form-item>
            <el-form-item label="物流公司编码"
              prop="transport">
              <el-input v-model="queryParams.transport"
                clearable
                placeholder="输入要查询的物流公司编码"
                @input="getLogisticsReceiptList"
                style="width: 220px;" />
            </el-form-item>
            <el-form-item label="订单状态"
              prop="isOperateEnd">
              <el-select v-model="queryParams.isOperateEnd"
                placeholder="查询订单状态"
                clearable
                @change="getLogisticsReceiptList">
                <el-option label="已完成"
                  value="true" />
                <el-option label="未完成"
                  value="false" />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
        <!-- 数据表格 -->
        <el-table :data="tableList"
          border
          style="width: 100%"
          class="table-container">
          <el-table-column v-for="item in columns"
            :key="item.label"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :fixed="item.fixed"
            :class-name="item.className">
            <template #header="{ column }"
              v-if="item.prop === 'receiptPhoto'">
              <div class="header-container">
                <span>{{ column.label }}</span>
                <el-button @click="showPhoto = !showPhoto"
                  style="margin-left: 10px;">{{ showPhoto ? '隐藏' : '显示' }}图片</el-button>
              </div>
            </template>
            <template #default="scope">
              <template v-if="item.prop === 'receiptPhoto'">
                <div class="receipt-photo-container"
                  v-if="showPhoto">
                  <span v-if="JSON.parse(scope.row[item.prop] || '[]').length === 0">暂无图片</span>
                  <el-image v-else
                    v-for="(urlStr, index) in JSON.parse(scope.row[item.prop] || '[]')"
                    :key="index"
                    :initial-index="index"
                    :preview-src-list="JSON.parse(scope.row[item.prop] || '[]')"
                    preview-teleported
                    :src="urlStr"
                    alt="图片"
                    class="receipt-photo-item"
                    fit="cover"
                    style="width: 80px; height: 50px; " />
                </div>
              </template>
              <template v-else-if="item.prop === 'logisticsTrack'">
                <el-button type="primary"
                  @click="handleLogisticsTrack(scope.row)"
                  text>
                  查看物流轨迹
                </el-button>
              </template>
              <template v-else-if="item.prop === 'receiptPhotoCompleteFlag'">
                <el-select v-model="scope.row[item.prop]"
                  placeholder="请选择"
                  style="width: 100%"
                  @change="handleReceiptPhotoChangeStatus(scope.row)">
                  <el-option v-for="item in receiptPhotoCompleteFlagOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </template>
              <template v-else-if="item.prop === 'sentStatus'">
                <el-select v-model="scope.row[item.prop]"
                  placeholder="请选择"
                  filterable
                  style="width: 100%"
                  @change="handleSentStatusChange(scope.row)">
                  <el-option v-for="item in sentStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </template>

              <template v-else>
                <!-- 其他字段显示原始值 -->
                {{ formatter(scope.row, scope.column, scope.row[item.prop]) }}
              </template>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作"
          width="200"
          fixed="right">
          <template #default="scope">
            <el-button type="danger"
              @click="deleteView(scope.row)"
              text>
              删除
            </el-button>
          </template>
        </el-table-column> -->
        </el-table>
        <!-- 分页 -->
        <pagination :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getLogisticsReceiptList" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { getLogisticsReceiptListAPI, setLogisticsReceiptStatusAPI } from '@/api'
import { parseTime, isExternal } from '@/utils'

const { proxy } = getCurrentInstance()
const { supply_logistics_shipping_order_type: typeDict } = proxy.useDict("supply_logistics_shipping_order_type")

/********************  发货单列表  ********************/
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
})
const showPhoto = ref(false)
const total = ref(0)
const tableList = ref([])
// 物流轨迹链接：对应编码和地址列表
const logisticsTrack = ref([
  {
    code: [134, 109],
    url: '#/logistics?sentNo=', // 拼接 AHSD 安徽单据编号跳转项目路由页面查看
    dataKey: 'ahSentNo'
  },
  {
    code: [132],
    url: 'https://gps.rrswl.com/GPSTrackWeb/sqmmap.jsp?orderno=', // 拼接物流单号（DD 单号）
    dataKey: 'expressNo'
  },
  {
    code: [104],
    url: 'https://cloud.region2.qince.com/openplat/app/dingzhi/wangxiaolu/delivery_url/redirect.do?sentNo=', // DD 单号
    dataKey: 'ddNo'
  }
])
const columns = ref([
  {
    label: '安徽单据编号',
    prop: 'ahSentNo',
    width: 180,
    fixed: 'left'
  },

  {
    label: '北京单据编号',
    prop: 'bjSentNo',
    width: 180,
  },
  {
    label: '快递单号',
    prop: 'expressNo',
    width: 150
  },
  {
    label: 'DD 单号',
    prop: 'ddNo',
    width: 170
  },
  {
    label: '版本号',
    prop: 'bjSentVersion',
    width: 80
  },
  {
    label: '单据类型',
    prop: 'type', // X06: 销售出库单，N02：杂发单
    width: 100
  },
  {
    label: '过账日期',
    prop: 'postDate',
    width: 180
  },
  {
    label: '运输公司编码',
    prop: 'transport',
    width: 120
  },
  {
    label: '运输公司',
    prop: 'transportName',
    width: 100
  },
  {
    label: '签收时间',
    prop: 'operateEndDatetime',
    width: 180
  },
  {
    label: '回单状态',
    prop: 'receiptFlag', // 有/无/回单异常
    width: 100
  },
  {
    label: '回单照片',
    prop: 'receiptPhoto',
    width: 200,
    className: 'col-receipt-photo',
    // 根据图片数量动态计算宽度，确保图片能两列显示
    // width: computed(() => {
    //   const maxPhotos = Math.max(...tableList.value.map(row => {
    //     try {
    //       const photos = JSON.parse(row.receiptPhoto || '[]')
    //       return photos.length
    //     } catch {
    //       return 0
    //     }
    //   }))
    //   console.log(maxPhotos, 'maxphotos')
    //   // 计算需要的列数，每列最多2张图片
    //   const columns = Math.ceil(maxPhotos / 2)
    //   if (columns === 0) return 200
    //   // 每列宽度：80px + 5px gap 间距 + 外层容器左右 padding 共 30px 
    //   return Math.max(columns * 80 + 5 + 30)
    // })
  },
  {
    label: '创建时间',
    prop: 'createTime',
    width: 180
  },
  {
    label: '更新时间',
    prop: 'updateTime',
    width: 180
  },
  {
    label: '发货单 ID',
    prop: 'sendId',
    width: 100,
  },
  {
    label: '物流轨迹',
    prop: 'logisticsTrack',
    width: 140,
    fixed: 'right'
  },
  {
    label: '回单照片是否完整',
    prop: 'receiptPhotoCompleteFlag', // 完整/不完整
    width: 150,
    fixed: 'right'
  },
  {
    label: '物流状态',
    prop: 'sentStatus',
    width: 180,
    fixed: 'right'
  }
])

// 回单图片是否完整选项组
const receiptPhotoCompleteFlagOptions = ref([
  {
    value: '完整',
    label: '完整'
  },
  {
    value: '不完整',
    label: '不完整'
  }
])
// 物流状态选项组
const sentStatusOptions = ref([
  {
    value: '整单签收',
    label: '整单签收'
  },
  {
    value: '整单拒收',
    label: '整单拒收'
  },
  {
    value: '部分退回在途',
    label: '部分退回在途'
  },
  {
    value: '部分退回已完结',
    label: '部分退回已完结'
  },
  {
    value: '整单退回在途',
    label: '整单退回在途'
  },
  {
    value: '整单退回完结',
    label: '整单退回完结'
  },
  {
    value: '发货在途',
    label: '发货在途'
  },
  {
    value: '部分滞留',
    label: '部分滞留'
  },
  {
    value: '整单滞留',
    label: '整单滞留'
  }
])

// 获取发货单列表
const getLogisticsReceiptList = async () => {
  const { data: { rows, total: totalNum } } = await getLogisticsReceiptListAPI(queryParams)
  tableList.value = rows
  total.value = totalNum
}
getLogisticsReceiptList()

// 查看物流轨迹
const handleLogisticsTrack = (row) => {
  const obj = logisticsTrack.value.find(item => item.code.includes(row.transport * 1))
  console.log(obj)
  if (isExternal(obj?.url)) {
    window.open(obj.url + row[obj.dataKey], '_blank')
  } else {
    window.open(window.location.href.split('/')[0] + obj.url + row[obj.dataKey], '_blank')
  }
}

// 格式化表格列
const formatter = (row, columns, value) => {
  // 判断有值再转换
  if (columns.property === 'type') {
    return typeDict.value.find(item => item.value === value)?.label
  } else if (columns.property === 'createTime' || columns.property === 'updateTime' || columns.property === 'operateEndDatetime') {
    return parseTime(value, '{y}-{m}-{d} {h}:{i}:{s}')
  } else if (columns.property === 'postDate') {
    return parseTime(value, '{y}-{m}-{d}')
  } else {
    return value
  }
}

// 修改回单照片是否完整
const handleReceiptPhotoChangeStatus = async (row) => {
  await setLogisticsReceiptStatusAPI({
    sendId: row.sendId,
    receiptPhotoCompleteFlag: row.receiptPhotoCompleteFlag
  })
  proxy.$modal.msgSuccess('修改成功')
  getLogisticsReceiptList()
}
// 修改物流状态
const handleSentStatusChange = async (row) => {
  await setLogisticsReceiptStatusAPI({
    sendId: row.sendId,
    sentStatus: row.sentStatus
  })
  proxy.$modal.msgSuccess('修改成功')
  getLogisticsReceiptList()
}

</script>

<style scoped
  lang="scss">
  .app-container {
    >.el-row {
      .el-col {
        display: flex;
        flex-direction: column;
        height: 100%;

        .table-container {
          margin-top: 20px;

          .header-container {
            display: flex;
            align-items: center;
          }

          ::v-deep(.el-image) {
            img {
              width: 80px !important;
              height: 50px !important;
            }
          }
        }

        .receipt-photo-container {
          padding: 0 15px;
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          min-width: 200px;
          /* justify-content: center; // 内容整体居中
    align-items: flex-start; // 顶部对齐 */
          justify-content: flex-start; // 改为左对齐，让每行都从左边开始
          align-items: flex-start; // 顶部对齐

          .receipt-photo-item {
            border-radius: 4px;
            border: 1px solid #e4e7ed;
            transition: all 0.3s;
            flex: 0 0 80px; // 固定宽度，不伸缩

            &:hover {
              border-color: #409eff;
              box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
            }
          }
        }

        // 让表格列宽自适应内容
        ::v-deep(.el-table) {
          .el-table__body-wrapper {
            .el-table__body {
              .el-table__row {
                .cell {
                  white-space: nowrap;
                  overflow: visible;
                }
              }

              td.el-table__cell.col-receipt-photo {
                .cell {
                  padding-right: 0px; // 给回单照片列补充右内边距
                  padding-left: 0px; // 给回单照片列补充左内边距
                  text-align: center; // 内容居中
                }
              }
            }
          }
        }
      }


    }
  }

</style>
