<template>
  <Dialog v-model="dialogVisible"
          :title="t('iotMaintain.selectMaterials')"
          style="width: 1100px; max-height: 800px" @close="handleClose">
    <div>
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item :label="t('chooseMaintain.materialName')" prop="name" style="margin-left: 25px">
            <el-input
              v-model="queryParams.name"
              :placeholder="t('chooseMaintain.materialName')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-200px"
            />
          </el-form-item>
          <el-form-item :label="t('chooseMaintain.materialCode')" prop="code">
            <el-input
              v-model="queryParams.code"
              :placeholder="t('chooseMaintain.materialCode')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> {{ t('workOrderMaterial.search') }}</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('workOrderMaterial.reset') }}</el-button>
            <el-button @click="handleConfirm" class="custom-green-button"><Icon icon="ep:check" class="mr-5px" /> {{ t('workOrderMaterial.confirm') }}</el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table
          v-loading="loading"
          :data="list"
          :stripe="true"
          ref="tableRef"
          :show-overflow-tooltip="true"
          @row-click="handleRowClick"
        >
          <el-table-column width="80" :label="t('deviceList.select')">
            <template #default="{ row }">
              <el-checkbox
                :model-value="selectedRows.some(item => item.id === row.id)"
                @click.stop="toggleRow(row)"
                class="no-label-radio"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="t('chooseMaintain.materialCode')"
            align="center"
            prop="code"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('chooseMaintain.materialName')"
            align="center"
            prop="name"
            :show-overflow-tooltip="true"
          />
          <el-table-column :label="t('deviceForm.model')" align="center" prop="model" width="120" />
          <el-table-column :label="t('workOrderMaterial.unit')" align="center" prop="unit" width="120" />
          <el-table-column :label="t('workOrderMaterial.unitPrice')" align="center" prop="unitPrice">
            <template #default="scope">
              <el-input
                type="number"
                :controls="false"
                v-model="scope.row.unitPrice"
                @click.stop=""
                @focus="handleInputFocus(scope.row)"
                @blur="(event) => handleUnitPriceBlur(event, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('route.quantity')" align="center" prop="quantity">
            <template #default="scope">
              <el-input
                type="number"
                :controls="false"
                v-model="scope.row.quantity"
                @click.stop=""
                @focus="handleInputFocus(scope.row)"
                @blur="(event) => handleQuantityBlur(event, scope.row)"
              />
            </template>
          </el-table-column>
          <!--
          <el-table-column label="状态" key="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column> -->
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { DictDataVO } from '@/api/system/dict/dict.data'
import { dateFormatter } from '@/utils/formatTime'
import * as MaterialApi from '@/api/pms/material'
import {DICT_TYPE} from "@/utils/dict";
import {ContentWrap} from "@/components/ContentWrap";

defineOptions({ name: 'SelectMaterial' })
const { t } = useI18n() // 国际化
// 调整 emit 类型
const emit = defineEmits<{
  (e: 'choose', value: MaterialApi.MaterialVO[]): void
  (e: 'close'): void
}>()
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<DictDataVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const selectedRows = ref<MaterialApi.MaterialVO[]>([]); // 多选数据（存储所有选中行的数组）
const tableRef = ref();

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  label: '',
  name: undefined,
  code: undefined,
  status: undefined,
})

const selectedRow = ref(null)

// 多选 切换行选中状态
const toggleRow = (row) => {
  const index = selectedRows.value.findIndex(item => item.id === row.id);
  if (index > -1) {
    selectedRows.value.splice(index, 1); // 取消选中
  } else {
    selectedRows.value.push(row); // 选中
  }
};

// 关闭时清空选择
const handleClose = () => {
  tableRef.value?.clearSelection();
  selectedRows.value = []
  emit('close')
};

// 处理单选逻辑
const selectRow = (row) => {
  selectedRow.value = selectedRow.value?.id === row.id ? null : row
  emit('choose', row)
  dialogVisible.value = false
}

// 确认选择
const handleConfirm = () => {
  // 检查是否有未通过校验的行
  const invalidRows = selectedRows.value.filter(row => {
    const quantity = parseFloat(row.quantity);
    const unitPrice = parseFloat(row.unitPrice);
    return isNaN(quantity) || quantity <= 0 || isNaN(unitPrice) || unitPrice <= 0;
  });

  if (invalidRows.length > 0) {
    ElMessage.error('存在无效的 单价 或 数量，请检查');
    return;
  }

  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  // emit('choose', selectedRows.value);
  emit('choose', selectedRows.value.map(row => ({
    ...row,
    // 确保返回必要字段
    code: row.code,
    name: row.name,
    unit: row.unit
  })))
  dialogVisible.value = false;
  handleClose()
};

// 处理 单价 unitPrice 输入框失焦事件
const handleUnitPriceBlur = (event: Event, row: any) => {
  const inputValue = (event.target as HTMLInputElement).value;
  let num = parseFloat(inputValue);
  // 处理无效值
  if (isNaN(num)) {
    row.unitPrice = 0;
    return;
  }
  // 处理小于等于0的情况
  if (num <= 0) {
    row.unitPrice = 0;
    return;
  }
  // 保留两位小数
  row.unitPrice = parseFloat(num.toFixed(2));
};

// 处理 入库数量 quantity 输入框失焦事件
const handleQuantityBlur = (event: Event, row: any) => {
  const inputValue = (event.target as HTMLInputElement).value;
  let num = parseFloat(inputValue);
  // 处理无效值
  if (isNaN(num)) {
    row.quantity = 0;
    return;
  }
  // 处理小于等于0的情况
  if (num <= 0) {
    row.quantity = 0;
    return;
  }
  // 保留两位小数
  row.quantity = parseFloat(num.toFixed(2));
};

// 点击整行选中
const handleRowClick = (row) => {
  toggleRow(row);
}
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  await getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const getList = async () => {
  loading.value = true
  try {
    const data = await MaterialApi.getMaterialPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 处理输入框焦点事件（自动选中当前行）
const handleInputFocus = (row: MaterialApi.MaterialVO) => {
  // 如果未选中则添加到选中列表
  const exists = selectedRows.value.some(item => item.id === row.id)
  if (!exists) {
    selectedRows.value.push(row)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const choose = (row: DictDataVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 初始化 **/

</script>
<style lang="scss" scoped>
.no-label-radio .el-radio__label {
  display: none;
}
.no-label-radio .el-radio__inner {
  margin-right: 0;
}

/* 自定义淡绿色按钮 */
:deep(.custom-green-button) {
  background-color: #e1f3d8;
  border-color: #e1f3d8;
  color: #67c23a;
}

/* 悬停效果 */
:deep(.custom-green-button:hover) {
  background-color: #d1e8c0;
  border-color: #d1e8c0;
  color: #5daf34;
}

/* 点击效果 */
:deep(.custom-green-button:active) {
  background-color: #c2dca8;
  border-color: #c2dca8;
}

</style>
