<script setup>
import { computed, getCurrentInstance, reactive, ref, nextTick } from "vue";
import MyTable from "@/components/aboutTable/MyTable.vue";
import { fetchTbAppendList, fetchTbZdxlFgdwBddSelectList } from "@/api/service/dailyTaskPackage";

const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  disabledIds: {
    type: Array,
    default: () => []
  },
  bddList: {
    type: Array,
    default: () => []
  }
})

const formRef = ref(null)
const emits = defineEmits(["update:modelValue", "change"]);
const visible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  }
})

const selectList = ref([])
const pageData = reactive({
  tableConfiger: {
    rowKey: 'bddId',
    rowHieght: 61,
    haveControls: false,
    showSelectType: 'checkBox',
    defaultSelectKeys: [],
    loading: false
  },
  data: {},
  tableData: [],
  total: 0,
  tableColumn: [
    {
      label: "必到点",
      prop: "bddMc"
    },
    {
      label: "打卡次数",
      prop: "xlghDkcs",
      showSolt:true
    }
  ]
})

// 打卡点验证规则
const checkPointRules = [
  { required: true, message: '请输入打卡次数', trigger: 'change' },
  {
    validator: (rule, value, callback) => {
      if (value < 1) {
        callback(new Error('打卡次数必须大于0'));
      } else {
        callback();
      }
    },
    trigger: 'change'
  }
];

const handleClickClose = () => {
  visible.value = false;
}

const handleChooseDataChange = (event) => {
  if (!Array.isArray(event)) return
  selectList.value = [...event]

  // 重新初始化验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

const selectable = (row) => {
  return !props.disabledIds.has(row.bddId)
}

// 自定义验证
const fieldErrors = ref({})

// 判断行是否被选中
const isRowSelected = (row) => {
  return selectList.value.some(selected => selected.bddId === row.bddId)
}

// 检查指定索引是否有错误
const hasError = (index) => {
  const propPath = `tableData[${index}].xlghDkcs`
  return !!fieldErrors.value[propPath]
}

// 获取指定索引的错误信息
const getError = (index) => {
  const propPath = `tableData[${index}].xlghDkcs`
  return fieldErrors.value[propPath] || ''
}

// 验证单个字段（只为选中的行验证）
const validateField = async (index) => {
  const row = pageData.tableData[index]
  if (!isRowSelected(row)) return true // 未选中的行不验证

  const propPath = `tableData[${index}].xlghDkcs`
  return new Promise((resolve) => {
    formRef.value.validateField(propPath, (errorMessage) => {
      fieldErrors.value[propPath] = errorMessage
      console.log(errorMessage);
      resolve(!errorMessage)
    })
  })
}

// 只为选中的行验证
const validateSelectedCheckpoints = async () => {
  if (!pageData.tableData) return true

  const validations = pageData.tableData
    .map((item, index) => isRowSelected(item) ? validateField(index) : Promise.resolve(true))

  const results = await Promise.all(validations)
  return results.every(result => result)
}

// // 防抖验证，避免频繁触发
// const debouncedValidate = debounce((index) => {
//   validateField(index)
// }, 300)
//
// const handleInputChange = (index) => {
//   debouncedValidate(index)
// }
//
// // 监听数据变化，自动验证选中的行
// watch(() => pageData.tableData,
//   (newData) => {
//     newData.forEach((row, index) => {
//       if (isRowSelected(row)) {
//         validateField(index)
//       }
//     })
//   },
//   { deep: true }
// )

const open = async (data) => {
  selectList.value = [];
  fieldErrors.value = {}
  const res = await fetchTbZdxlFgdwBddSelectList(data?.id)

  if (res && res.length > 0) {
    pageData.tableData = res
    pageData.tableConfiger.defaultSelectKeys = props.bddList?.map(i => {
      if (i?.selected) return i?.bddId
    })

    pageData.data = data
    visible.value = true;
  } else {
    proxy.$message({
      type: "warning",
      message: "所有必到点已全部下发任务"
    })
  }
}

const onSubmit = async () => {
  if (selectList.value.length === 0) {
    proxy.$message({
      type: "warning",
      message: "请选择打卡数据"
    });
    return
  }


  try {
    const allValid = await validateSelectedCheckpoints()
    if (!allValid) {
      throw new Error('请完善选中的打卡点信息')
    }
    await formRef.value.validate()

    await fetchTbAppendList({
      bddList: selectList.value || [],
      fgxlrwId: pageData.data?.id
    })

    emits("change", selectList.value)
    visible.value = false;
  } catch(error) {
    console.log(error);
  }
}

defineExpose({ open })
</script>

<template>
  <el-form ref="formRef" :model="pageData">
    <el-dialog v-model="visible" @close="handleClickClose">
      <MyTable
        :tableData="pageData.tableData"
        :tableColumn="pageData.tableColumn"
        :tableConfiger="pageData.tableConfiger"
        @chooseData="handleChooseDataChange"
        :selectable="selectable"
      >
        <template #xlghDkcs="{ row, $index }">
          <div class="validation-container">
            <el-input-number
              style="width: 30%;"
              :placeholder="`输入打卡点${$index + 1}需打卡次数`"
              clearable
              min="0"
              :disabled="!selectable(row)"
              v-model="row.xlghDkcs"
              :class="{ 'is-error': hasError($index) }"
              @blur="validateField($index)"
            />

            <!-- 展示错误信息 -->
            <span
              v-if="hasError($index)"
              class="error-message"
            >
              {{ getError($index) }}
            </span>
          </div>
        </template>
      </MyTable>

      <!-- 用于处理验证-->
      <div style="display: none">
        <template v-for="(item, index) in pageData.tableData" :key="index">
          <el-form-item v-if="isRowSelected(item)" :prop="`tableData[${index}].xlghDkcs`" :label="item?.bddMc" :rules="checkPointRules">
            <el-input-number
              style="width: 100%;"
              :placeholder="`输入打卡点${index + 1}需打卡次数`"
              clearable
              v-model="item.xlghDkcs"
            />
          </el-form-item>
        </template>
      </div>

      <template #footer>
        <el-button @click="handleClickClose">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-form>
</template>

<style scoped lang="scss">
::v-deep {
  .el-checkbox__input.is-disabled .el-checkbox__inner,
  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: var(--el-checkbox-checked-bg-color);
    border-color: var(--el-checkbox-checked-input-border-color);
  }

  .el-checkbox__input.is-disabled .el-checkbox__inner,
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
    border: 1px solid var(--el-checkbox-checked-icon-color);
    border-left: 0;
    border-top: 0;
  }
}

.validation-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
  min-height: 60px; /* 预留错误信息空间 */
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding: 2px 0;
  display: block;
}

.is-error .el-input-number__inner {
  border-color: #f56c6c;
}

/* 确保表格行高度适应错误信息 */
.el-table .cell {
  min-height: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>
