<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="称重分拣"
      :before-close="handleClose"
      v-model="isweight"
      width="1200px"
    >
      <div
        style="
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          gap: 10px;
        "
      >
        <el-select
          style="width: 100px; height: 100%; margin-right: 5px"
          v-model="selectType"
          placeholder=""
        >
          <el-option label="跟踪号" value="trackingNumber"></el-option>
          <el-option label="店铺单号" value="shopNumber"></el-option>
        </el-select>
        <input
          class="inputWeight"
          @keyup.enter="weightChange"
          style="flex: 1; border: 3px solid blue"
          ref="weighInput"
          :placeholder="
            weight.weightInput
              ? selectType === 'trackingNumber'
                ? '请输入跟踪号'
                : '请输入店铺单号'
              : '请输入重量'
          "
          v-model.lazy="weightText"
        />

        <el-select
          style="flex: 1"
          v-model="logisticsCompanyCode"
          placeholder="物流公司"
          filterable
          clearable
        >
          <el-option
            v-for="(item, index) in allCodelist"
            :key="index"
            :label="item.basicsName"
            :value="item.code"
          ></el-option>
        </el-select>

        <el-button type="primary" @click="weightChange"> 查询 </el-button>
      </div>
      <div>
        <CustomizeTable
          ref="tableRef"
          border
          :isShowCheckBox="false"
          v-model="tableData"
          height="400px"
          :config="tableConfig"
          align="center"
          :row-config="{ isCurrent: true }"
        ></CustomizeTable>
      </div>

      <div class="statistics" style="display: flex; margin-top: 10px">
        <div class="number">
          <span>数量</span>
          <span style="color: red">{{ tableData.length }}</span>
        </div>

        <div class="warehouse-weight" style="margin-left: 10px">
          <span> 出库总重量:</span>
          <span style="color: red">{{ warehouseWeightTotal() || 0 }}(g)</span>
        </div>
      </div>
      <template #footer>
        <div style="display: flex; justify-content: center">
          <el-button @click="handleClose()"> 取消 </el-button>
          <el-button type="primary" @click="weightGet"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
interface IpodCnWeighingParams {
  id?: string
  outWarehouseWeight?: string
  weight?: string
  trackingNumber?: string
  shopNumber?: string
  platform?: string
  logisticsCompanyName?: string
  logisticsCompanyId?: string
  wgap?: number | string
}
interface ILogisticsList {
  code: string
  basicsName: string
  apiData: unknown
}
import BigNumber from 'bignumber.js'
import weight from '../components/weigh.js'
import {
  listByNoApi,
  orderWeighingApi,
  allErpCodeListApi,
} from '@/api/podCnOrder'
// import { logisticsCompanyAllCodelist } from '@/api/logistics.ts'
import CustomizeTable from '@/components/VxeTable.tsx'
import { TableColumn } from '@/components/VxeTable'
const tableData = ref<IpodCnWeighingParams[]>([])
const isweight = ref(false)
const selectType = ref('trackingNumber')
const logisticsCompanyCode = ref('')
const weighInput = ref()
const weightText = ref('')
const allCodelist = ref<ILogisticsList[]>([])

const tableRef = ref()
const tableConfig = ref<TableColumn[]>([
  {
    prop: 'trackingNumber',
    label: '跟踪号',
    attrs: {
      minWidth: 120,
    },
  },
  {
    prop: 'shopNumber',
    label: '店铺单号',
    attrs: {
      minWidth: 120,
    },
  },
  {
    prop: 'platform',
    label: '销售平台',
    attrs: {
      width: 120,
    },
  },
  {
    prop: 'logisticsCompanyName',
    label: '物流公司',
    attrs: {
      width: 120,
    },
  },
  {
    prop: 'weight',
    label: '系统重量(g)',
    attrs: {
      width: 100,
    },
  },

  {
    prop: 'outWarehouseWeight',
    label: '出库重量(g)',
    attrs: {
      width: 100,
    },
  },
  {
    prop: 'wgap',
    label: '重量差(g)',
    attrs: {
      width: 100,
    },
  },

  {
    prop: 'opeare',
    label: '操作',
    attrs: {
      align: 'center',
      width: 80,
    },
    render: {
      default: ({ row }: { row: IpodCnWeighingParams }) => (
        <div>
          <el-button type="danger" onclick={() => deleteFn(row)}>
            删除
          </el-button>
        </div>
      ),
    },
  },
])
const emits = defineEmits<{
  (e: 'updateList'): void
}>()
const getlogisticsCompanyAllCodelist = async () => {
  try {
    const res = await allErpCodeListApi()
    if (res.code !== 200) return
    allCodelist.value = res.data
  } catch (e) {
    console.error(e)
  }
}

const warehouseWeightTotal = (): number => {
  if (!tableData.value) return 0

  return Number(
    tableData.value
      .reduce((prev: BigNumber, cur: IpodCnWeighingParams) => {
        const weight = new BigNumber(cur.outWarehouseWeight || 0)
        return prev.plus(weight)
      }, new BigNumber(0))
      .toFixed(2), // 保留两位小数
  )
}

const handleClose = () => {
  isweight.value = false
}

const weightChange = async () => {
  const noValue = weightText.value
  if (!noValue) return weight.playAudio('weight_search_error')
  if (weight.weightInput) {
    if (noValue.length < 7)
      return weight.playAudio(
        'weight_search_error',
        `没有该${
          selectType.value === 'trackingNumber' ? '跟踪号' : '店铺单号'
        }相关的订单`,
      )
  }

  weightText.value = ''
  console.log(343, weight.weightInput)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const params: {
      type: string
      no: string
      logisticsCompanyCode?: string
    } = {
      type: selectType.value,
      no: noValue,
    }
    if (logisticsCompanyCode.value)
      params.logisticsCompanyCode = logisticsCompanyCode.value
    weight.check(
      noValue,
      listByNoApi,
      params,
      (arr) => {
        tableData.value = [...arr]
        if (!(noValue.length < 7)) {
          tableData.value.forEach((el) => {
            if (el.trackingNumber === noValue || el.shopNumber === noValue) {
              console.log(1111, el)

              tableRef.value?.selectRowEvent(el)
            }
          })
        }
        console.log(284, arr)
      },
      selectType.value,
    )
    weighInput.value?.focus()
  } catch (error) {
    console.log(error)
  } finally {
    loading.close()
  }
  console.log('weightChange')
}

const weightGet = async () => {
  if (tableData.value.length < 1) {
    ElMessage.warning('当前没有可提交的数据！')
    return
  }
  for (const iterator of tableData.value) {
    if (!iterator.outWarehouseWeight) {
      ElMessage.warning('跟踪号：' + iterator.trackingNumber + '的出库重量为空')
      return
    }
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    await orderWeighingApi({ podCnWeighingParams: tableData.value })
    ElMessage.success('保存称重分拣成功')
    handleClose()
    emits('updateList')
  } catch (error) {
    console.log(error)
  } finally {
    loading.close()
  }
}

const open = () => {
  isweight.value = true
  weight.clear()
  tableData.value = []
  selectType.value = 'trackingNumber'
  logisticsCompanyCode.value = ''
  weightText.value = ''
  getlogisticsCompanyAllCodelist()
}

const deleteFn = (row: IpodCnWeighingParams) => {
  tableData.value = tableData.value.filter((el) => el.id !== row.id)
  weight.updatedList(tableData.value)
}

defineExpose({
  open,
})
</script>

<style scoped></style>
