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

        <el-select
          v-model="logisticsCompanyCode"
          style="flex: 1"
          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"
          v-model="tableData"
          border
          :is-show-check-box="false"
          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 {
    orderWeighingApi({ podCnWeighingParams: tableData.value }).then((res) => {
      if (res.code === 200) {
        weight.clear()
        ElMessage.success('保存称重分拣成功')
        handleClose()
        emits('updateList')
      } else {
        ElMessage.error(res.message)
        handleClose()
        emits('updateList')
      }
    })
  } catch (error) {
    console.log(error)
  } finally {
    loading.close()
  }
}

const open = () => {
  isweight.value = true
  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>
.inputWeight {
  color: #666;
}

.inputWeight::placeholder {
  color: #aaa;
}
</style>
