<template>
  <el-dialog
    v-model="dialogVisible"
    title="客户"
    width="1000px"
    :close-on-click-modal="false"
    destroy-on-close
    @close="handleClose"
  >
    <el-form :model="form" label-width="100px" label-position="right">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="车号">
            <el-select
              v-model="form.truckNo"
              clearable
              filterable
              allow-create
              default-first-option
              placeholder="请选择"
              style="width: 100%;"
              @change="handleTruckChange"
            >
              <el-option
                v-for="item in truckOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="司机姓名">
            <el-input v-model="form.driverName" placeholder="司机姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系方式">
            <el-input v-model="form.driverPhone" placeholder="联系方式" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="总重量">
            <el-input :value="totalWeight" placeholder="总重量" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总数量">
            <el-input :value="totalQuantity" placeholder="总数量" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="过磅重量">
            <el-input v-model="form.suttle" placeholder="过磅重量" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="理货人员">
            <el-select
              v-model="form.tallyPeople"
              clearable
              filterable
              placeholder="理货人员"
              style="width: 100%;"
            >
              <el-option
                v-for="item in tallyPeopleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label=" ">
            <el-button type="success" @click="handleOutStock">出库</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否打印地址">
            <el-switch v-model="form.printAddress" active-color="#13ce66" inactive-color="#ff4949" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否打印备注">
            <el-switch v-model="form.printRemark" active-color="#13ce66" inactive-color="#ff4949" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px;"
      max-height="400"
    >
      <el-table-column
        prop="layerNo"
        label="层数"
        width="80"
        header-align="center"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row.outLayerNo ?? row.layerNo ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column
        label="垛位"
        width="120"
        header-align="center"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row.outStackName ?? row.stackName ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column
        label="物料"
        min-width="140"
        header-align="center"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row.materialName ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column
        label="钢种"
        width="120"
        header-align="center"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row.ST_GRADE ?? row.stGrade ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="inProdNo"
        label="钢板号"
        min-width="160"
        header-align="center"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="materialStandard"
        label="规格型号"
        min-width="140"
        header-align="center"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="数量"
        width="100"
        header-align="center"
        align="right"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row.outQuantity ?? row.OUT_QUANTITY ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column
        label="重量"
        width="100"
        header-align="center"
        align="right"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row.outWeight ?? row.OUT_WEIGHT ?? '-' }}
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance()

const dialogVisible = ref(false)
const truckOptions = ref([])
const tallyPeopleOptions = ref([])
const tableData = ref([])

const form = ref({
  truckNo: '',
  driverName: '',
  driverPhone: '',
  suttle: '',
  tallyPeople: '',
  printAddress: true,
  printRemark: true
})

// 计算总重量和总数量
const totalWeight = computed(() => {
  const total = tableData.value.reduce((sum, row) => {
    const weight = parseFloat(row.outWeight ?? row.OUT_WEIGHT ?? 0) || 0
    return sum + weight
  }, 0)
  return total.toFixed(3)
})

const totalQuantity = computed(() => {
  const total = tableData.value.reduce((sum, row) => {
    const quantity = parseFloat(row.outQuantity ?? row.OUT_QUANTITY ?? 0) || 0
    return sum + quantity
  }, 0)
  return total.toFixed(0)
})

// 获取车辆列表
const fetchTrucks = async () => {
  try {
    const response = await proxy.$axios.get('WareDistribution/queryWaitTrucks.do', {})
    if (response.data.code === 0 || response.data.code === '0') {
      const trucks = response.data.data || []
      truckOptions.value = trucks.map(item => ({
        label: item.truckNo || item.label || '',
        value: item.truckNo || item.value || ''
      })).filter(item => item.label && item.value)
    }
  } catch (error) {
    console.error('获取车辆列表失败:', error)
  }
}

// 获取理货人员选项
const fetchTallyPeopleOptions = async () => {
  try {
    const response = await proxy.$axios.get('Common/querySelector.do', {
      type: 'TALLY_PEOPLE'
    })
    if (response.data.code === 0 || response.data.code === '0') {
      const options = response.data.data || []
      tallyPeopleOptions.value = options.map(item => ({
        label: item.dicName || item.label || '',
        value: item.dicCode || item.value || ''
      })).filter(item => item.label && item.value)
    }
  } catch (error) {
    console.error('获取理货人员选项失败:', error)
  }
}

// 车号选择变化
const handleTruckChange = (val) => {
  if (val) {
    const truck = truckOptions.value.find(item => item.value === val)
    if (truck && truck.originalData) {
      form.value.driverName = truck.originalData.driverName || ''
      form.value.driverPhone = truck.originalData.driverPhone || ''
    }
  }
}

// 打开弹窗
const open = (selectedRows) => {
  if (!selectedRows || selectedRows.length === 0) {
    ElMessage.warning('请先选择要出库的数据')
    return
  }
  
  // 重置表单
  form.value = {
    truckNo: '',
    driverName: '',
    driverPhone: '',
    suttle: '',
    tallyPeople: '',
    printAddress: true,
    printRemark: true
  }
  
  // 设置表格数据为选中的行
  tableData.value = selectedRows.map(row => ({ ...row }))
  
  // 获取车辆列表和理货人员选项
  fetchTrucks()
  fetchTallyPeopleOptions()
  
  dialogVisible.value = true
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  tableData.value = []
  form.value = {
    truckNo: '',
    driverName: '',
    driverPhone: '',
    suttle: '',
    tallyPeople: '',
    printAddress: true,
    printRemark: true
  }
}

// 出库
const handleOutStock = async () => {
  if (!form.value.truckNo) {
    ElMessage.warning('请选择车号')
    return
  }
  
  try {
    const distribution = {
      truckNo: form.value.truckNo,
      driverName: form.value.driverName,
      driverPhone: form.value.driverPhone,
      sumWeight: totalWeight.value,
      sumCount: totalQuantity.value,
      suttle: form.value.suttle || 0,
      tallyPeople: form.value.tallyPeople,
      printAddress: form.value.printAddress,
      printRemark: form.value.printRemark,
      listDetail: tableData.value
    }
    
    const param = {
      json: JSON.stringify(distribution)
    }
    
    const response = await proxy.$axios.post('WareOut/outByDistribution.do', param)
    
    if (response.data.code === 0 || response.data.code === '0') {
      // 如果存在现金支付方式，显示警告
      if (response.data.payWay === '现金') {
        await ElMessageBox.alert(
          `存在支付方式为现金的材料，价格为${response.data.InvoicePrice}，请在出库界面确认价格`,
          '警告',
          {
            confirmButtonText: '确定',
            type: 'warning'
          }
        )
      }
      
      ElMessage.success('出库成功')
      handleClose()
      emit('success')
    } else {
      ElMessage.error(`出库失败：${response.data.msg || ''}`)
    }
  } catch (error) {
    ElMessage.error(`出库失败：${error.message || ''}`)
  }
}

const emit = defineEmits(['success'])

defineExpose({
  open
})
</script>

<style scoped>
</style>



