<template>
  <!-- 下发对话框 -->
  <el-dialog title="下发" v-model="visible" width="800px" append-to-body @close="cancel">
    <el-form ref="repairOrderRef" :model="form" :rules="rules" label-width="120px" label-position="top">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工单编码" prop="workOrderProjectNo" >
            <el-input v-model="form.workOrderProjectNo" placeholder="自动生成" :disabled="!!form.id" readonly maxlength="50" show-word-limit v-chinese-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="风机编号" prop="pcsDeviceName">
            <el-input v-model="form.pcsDeviceName" placeholder="请选择风机编号" readonly>
              <template #append>
                <el-button @click="handleSelectEquipment" icon="Search"></el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="维保中心" prop="gxtCenter">
            <el-input v-model="form.gxtCenter" placeholder="请选择风机编号自动填充" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="场站" prop="pcsStationName">
            <el-input v-model="form.pcsStationName" placeholder="请选择风机编号自动填充" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌" prop="brand">
            <el-input v-model="form.brand" placeholder="请选择风机编号自动填充" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="机型" prop="model">
            <el-input v-model="form.model" placeholder="请选择风机编号自动填充" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="发生时间" prop="occurTime">
            <el-date-picker
                v-model="form.occurTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                placeholder="请选择发生时间"
                style="width: 100%"
                :disabled-date="disabledDate"
                :disabled-time="disabledTime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障代码">
            <el-input
                v-model="form.faultCode"
                placeholder="请输入故障代码或点击选择"
                maxlength="20"
                show-word-limit
                clearable
                @focus="handleFaultCodeInputFocus"
                @blur="handleFaultCodeInputBlur"
                @input="handleFaultCodeInput"
                @clear="handleFaultCodeClear"
            />
            <!-- 故障代码快速检索下拉框 -->
            <div class="quick-select-dropdown" v-show="showFaultCodeQuickSelect && quickFaultInfoList.length > 0">
              <div
                  v-for="item in quickFaultInfoList"
                  :key="item.id"
                  class="quick-select-item"
                  @click="handleFaultCodeQuickSelect(item)">
                <span class="user-name">{{ item.faultCode }}</span>
                <span class="user-name">{{ item.faultBarcode }}</span>
              </div>
            </div>
            <div class="quick-select-dropdown no-data" v-show="showFaultCodeQuickSelect && quickFaultInfoList.length === 0 && form.faultCode && !faultInfoLoading">
              <div>未找到匹配的故障代码</div>
            </div>
            <div class="quick-select-dropdown no-data" v-show="showFaultCodeQuickSelect && faultInfoLoading">
              <div>
                <i class="el-icon-loading"></i>
                搜索中...
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="故障条文" prop="faultBarcode">
            <el-input
                v-model="form.faultBarcode"
                placeholder="请输入故障条文或点击选择"
                show-word-limit
                clearable
                @focus="handleFaultBarcodeInputFocus"
                @blur="handleFaultBarcodeInputBlur"
                @input="handleFaultBarcodeInput"
                @clear="handleFaultBarcodeClear"
            />
            <!-- 故障条文快速检索下拉框 -->
            <div class="quick-select-dropdown" v-show="showFaultBarcodeQuickSelect && quickFaultBarcodeList.length > 0">
              <div
                  v-for="item in quickFaultBarcodeList"
                  :key="item.id"
                  class="quick-select-item"
                  @click="handleFaultBarcodeQuickSelect(item)">
                <span class="user-name">{{ item.faultBarcode }}</span>
                <span class="user-name">{{ item.faultCode }}</span>
              </div>
            </div>
            <div class="quick-select-dropdown no-data" v-show="showFaultBarcodeQuickSelect && quickFaultBarcodeList.length === 0 && form.faultBarcode && !faultBarcodeLoading">
              <div>未找到匹配的故障条文</div>
            </div>
            <div class="quick-select-dropdown no-data" v-show="showFaultBarcodeQuickSelect && faultBarcodeLoading">
              <div>
                <i class="el-icon-loading"></i>
                搜索中...
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="故障描述" prop="faultDesc">
            <el-input
                v-model="form.faultDesc"
                type="textarea"
                placeholder="请输入故障描述或点击选择"
                maxlength="100"
                show-word-limit
                :rows="3"
                clearable
                @focus="handleFaultDescInputFocus"
                @blur="handleFaultDescInputBlur"
                @input="handleFaultDescInput"
                @clear="handleFaultDescClear"
            />
            <!-- 故障描述快速检索下拉框 -->
            <div class="quick-select-dropdown" v-show="showFaultDescQuickSelect && quickFaultDescList.length > 0">
              <div
                  v-for="item in quickFaultDescList"
                  :key="item.id"
                  @click="handleFaultDescQuickSelect(item)">
<!--                  <span class="user-name">{{ item.faultCode }}</span>-->
<!--                  <span class="user-name">{{ item.faultBarcode }}</span>-->
                <div class="quick-select-item" v-if="item.faultDescription">
                <span class="user-name" >{{ item.faultDescription }}</span>
                </div>
              </div>
            </div>
            <div class="quick-select-dropdown no-data" v-show="showFaultDescQuickSelect && quickFaultDescList.length === 0 && form.faultDesc && !faultDescLoading">
              <div>未找到匹配的故障描述</div>
            </div>
            <div class="quick-select-dropdown no-data" v-show="showFaultDescQuickSelect && faultDescLoading">
              <div>
                <i class="el-icon-loading"></i>
                搜索中...
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="24">
        <el-form-item label="附件（可选）">
          <preview :limit="8" v-model="form.orderAttachment" :filesize="5"></preview>
        </el-form-item>
      </el-col>
<!--        <el-row>
        <el-col :span="24">
          <el-form-item label="故障描述" prop="faultDesc">
            <el-input
                v-model="form.faultDesc"
                type="textarea"
                placeholder="请输入故障描述"
                maxlength="500"
                show-word-limit
                :rows="3"
            />
          </el-form-item>
        </el-col>
      </el-row>-->
      <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="图片">
              <image-upload :limit="10" v-model="form.workUrl" :fileSize="5"></image-upload>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确认下发</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 设备选择对话框 -->
  <equipment-select
      v-model="equipmentSelectVisible"
      @onSelected="onEquipmentSelected"
  />

  <!-- 通过slot传递可能需要的其他选择器组件 -->
  <slot name="mis-info-select" v-if="misInfoSelectVisible"></slot>
</template>

<script setup>
import {ref, reactive, nextTick, watch, defineProps} from 'vue';
import EquipmentSelect from '@/components/equipmentSelect/single.vue'; // 根据实际情况调整路径
import { addRepairOrder, updateRepairOrder } from '@/api/gxt/repairOrder';
import {listFaultCodes} from "@/api/gxt/faultCodes.js";
import Preview from "@/components/FileUpload/preview.vue";

// 获取当前实例
const { proxy } = getCurrentInstance()

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  }
});

// 定义事件
const emit = defineEmits(['update:modelValue', 'success']);

// 响应式数据
const visible = ref(false);
const repairOrderRef = ref()
const form = ref({});
const optType = ref('add');
const equipmentSelectVisible = ref(false);
const misInfoSelectVisible = ref(false);

// 表单验证规则
const rules = ref({
  // workOrderProjectNo: [
  //   { required: true, message: "工单编码不能为空", trigger: "blur" }
  // ],
  pcsDeviceName: [
    { required: true, message: "风机编号不能为空", trigger: "change" }
  ],
  /*faultCode: [
    { required: true, message: "请选择故障代码", trigger: "change" }
  ],*/
  occurTime: [
    { required: true, message: "请选择发生时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && new Date(value) > new Date()) {
          callback(new Error('发生时间不能大于当前时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  // maintenanceType: [
  //   { required: true, message: "请选择检修类型", trigger: "change" }
  // ],
  /* priorityType: [
     { required: true, message: "请选择优先级", trigger: "change" }
   ],*/
  faultBarcode: [
    { required: true, message: "故障条文不能为空", trigger: "change" }
  ],
  faultCode: [
    { required: true, message: "故障代码不能为空", trigger: "change" }
  ],
});

// 故障代码快速检索相关响应式数据
const showFaultCodeQuickSelect = ref(false)
const showFaultBarcodeQuickSelect = ref(false)
const showFaultDescQuickSelect = ref(false)
const quickFaultInfoList = ref([])
const quickFaultBarcodeList = ref([])
const quickFaultDescList = ref([])
const faultInfoLoading = ref(false)
const faultBarcodeLoading = ref(false)
const faultDescLoading = ref(false)
const faultInfoSearchTimer = ref(null)
const faultBarcodeSearchTimer = ref(null)
const faultDescSearchTimer = ref(null)
const allFaultInfoList = ref([]) // 存储所有故障数据用于快速检索


// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    // 初始化表单数据
    form.value = { ...props.data, selectedMembers: [] }
  }
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
  if (val) {
    // 打开对话框后重置表单验证错误
    proxy.$nextTick(() => {
      if (repairOrderRef.value) {
        repairOrderRef.value.clearValidate()
      }
    })
  }
})
// 日期禁用函数
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};

const disabledTime = (date) => {
  // 可根据需要实现时间禁用逻辑
  return {};
};

// 重置表单
function reset() {
  form.value = {};
  // 重置验证
  nextTick(() => {
    const repairOrderRef = getCurrentInstance()?.refs?.repairOrderRef;
    if (repairOrderRef && repairOrderRef.resetFields) {
      repairOrderRef.resetFields();
    }
  });
}

// 取消操作
function cancel() {
  visible.value = false;
  emit('cancel');
  emit('update:modelValue', false);
}

// 提交表单
async function submitForm() {
  if (!repairOrderRef.value) return
  await repairOrderRef.value.validate((valid) => {
    if (valid) {
      form.value.workOrderStatus = "assigned"
      updateRepairOrder(form.value).then(response => {
        proxy.$modal.msgSuccess("下发成功")
        visible.value = false;
        emit('success');
      }).catch(error => {

      });
    }
  });
}

// 设备选择相关方法
function handleSelectEquipment() {
  equipmentSelectVisible.value = true;
}

function onEquipmentSelected(row) {
  if (row) {
    // 检查维保中心ID和场站ID是否存在
    if (!row.maintenanceCenterId) {
      proxy.$modal.msgError("该设备的维保中心没有对应的部门，请完善部门信息后再更新设备数据！");
      return;
    }
    if (!row.stationId) {
      proxy.$modal.msgError("该设备的场站没有对应的部门，请完善部门信息后再更新设备数据！");
      return;
    }
    form.value.pcsDeviceId = row.equipmentId
    form.value.pcsDeviceName = row.equipmentCode
    form.value.gxtCenterId = row.maintenanceCenterId
    form.value.gxtCenter = row.maintenanceCenter
    form.value.pcsStationId = row.stationId
    form.value.pcsStationName = row.station
    form.value.brand = row.brand
    form.value.model = row.model
  }
  equipmentSelectVisible.value = false
}

/** 加载所有故障信息列表 */
const loadAllFaultInfoList = async () => {
  try {
    // 构建查询参数，包含风机编号和场站信息
    const queryParams = {
      pageNum: 1,
      pageSize: 1000, // 获取所有故障代码
      isActive: 0
    };

    // 如果表单中有风机编号和场站信息，则添加到查询参数中
    if (form.value.pcsDeviceName) {
      queryParams.model = form.value.model;
    }
    if (form.value.pcsStationName) {
      queryParams.station = form.value.pcsStationName;
    }

    // 加载故障代码数据
    const response = await listFaultCodes(queryParams);
    allFaultInfoList.value = response.rows || [];
  } catch (error) {
    console.error('加载故障信息列表失败:', error);
    allFaultInfoList.value = [];
  }
}

// 故障代码快速检索方法
/** 故障代码输入框获取焦点 */
const handleFaultCodeInputFocus = async () => {
  if (form.value.faultCode) return
  showFaultCodeQuickSelect.value = true;

  // 加载所有故障信息
  await loadAllFaultInfoList();

  // 如果已有输入内容，立即搜索
  if (form.value.faultCode && form.value.faultCode.trim()) {
    handleFaultCodeInput(form.value.faultCode);
  } else {
    // 如果没有输入内容，显示所有故障信息
    quickFaultInfoList.value = allFaultInfoList.value;
  }
};

/** 故障代码输入框失去焦点 */
const handleFaultCodeInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showFaultCodeQuickSelect.value = false;
  }, 200);
};

/** 故障代码输入事件 - 实时搜索 */
const handleFaultCodeInput = (value) => {
  const searchText = value.trim();

  if (!searchText) {
    quickFaultInfoList.value = [];
    showFaultCodeQuickSelect.value = false;
    return;
  }

  showFaultCodeQuickSelect.value = true;

  // 清除之前的定时器
  if (faultInfoSearchTimer.value) {
    clearTimeout(faultInfoSearchTimer.value);
  }

  // 过滤故障信息列表
  const lowerKeyword = searchText.toLowerCase();
  quickFaultInfoList.value = allFaultInfoList.value.filter(item =>
      (item.faultCode && item.faultCode.toLowerCase().includes(lowerKeyword)) ||
      (item.faultBarcode && item.faultBarcode.toLowerCase().includes(lowerKeyword)) ||
      (item.faultDescription && item.faultDescription.toLowerCase().includes(lowerKeyword))
  );

  // 设置新的定时器，防抖处理（500ms）
  faultInfoSearchTimer.value = setTimeout(() => {
    // 由于我们已经在上面过滤了，这里不需要额外的API调用
  }, 500);
};

/** 快速选择故障代码 */
const handleFaultCodeQuickSelect = (item) => {
  form.value.faultCode = item.faultCode;
  form.value.faultBarcode = item.faultBarcode;
  form.value.faultDesc = item.faultDescription;
  showFaultCodeQuickSelect.value = false;
};

/** 清空故障代码 */
const handleFaultCodeClear = () => {
  form.value.faultCode = '';
  form.value.faultBarcode = '';
  form.value.faultDesc = '';
  quickFaultInfoList.value = [];
  showFaultCodeQuickSelect.value = false;
};

// 故障条文快速检索方法
/** 故障条文输入框获取焦点 */
const handleFaultBarcodeInputFocus = async () => {
  if (form.value.faultBarcode) {
    return
  }
  showFaultBarcodeQuickSelect.value = true;

  // 加载所有故障信息
  await loadAllFaultInfoList();

  // 如果已有输入内容，立即搜索
  if (form.value.faultBarcode && form.value.faultBarcode.trim()) {
    handleFaultBarcodeInput(form.value.faultBarcode);
  } else {
    // 如果没有输入内容，显示所有故障信息
    quickFaultBarcodeList.value = allFaultInfoList.value;
  }
};

/** 故障条文输入框失去焦点 */
const handleFaultBarcodeInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showFaultBarcodeQuickSelect.value = false;
  }, 200);
};

/** 故障条文输入事件 - 实时搜索 */
const handleFaultBarcodeInput = (value) => {
  const searchText = value.trim();

  if (!searchText) {
    quickFaultBarcodeList.value = [];
    showFaultBarcodeQuickSelect.value = false;
    return;
  }

  showFaultBarcodeQuickSelect.value = true;

  // 清除之前的定时器
  if (faultBarcodeSearchTimer.value) {
    clearTimeout(faultBarcodeSearchTimer.value);
  }

  // 过滤故障信息列表
  const lowerKeyword = searchText.toLowerCase();
  quickFaultBarcodeList.value = allFaultInfoList.value.filter(item =>
      (item.faultCode && item.faultCode.toLowerCase().includes(lowerKeyword)) ||
      (item.faultBarcode && item.faultBarcode.toLowerCase().includes(lowerKeyword)) ||
      (item.faultDescription && item.faultDescription.toLowerCase().includes(lowerKeyword))
  );

  // 设置新的定时器，防抖处理（500ms）
  faultBarcodeSearchTimer.value = setTimeout(() => {
    // 由于我们已经在上面过滤了，这里不需要额外的API调用
  }, 500);
};

/** 快速选择故障条文 */
const handleFaultBarcodeQuickSelect = (item) => {
  form.value.faultCode = item.faultCode;
  form.value.faultBarcode = item.faultBarcode;
  form.value.faultDesc = item.faultDescription;
  showFaultBarcodeQuickSelect.value = false;
};

/** 清空故障条文 */
const handleFaultBarcodeClear = () => {
  form.value.faultCode = '';
  form.value.faultBarcode = '';
  form.value.faultDesc = '';
  quickFaultBarcodeList.value = [];
  showFaultBarcodeQuickSelect.value = false;
};

// 故障描述快速检索方法
/** 故障描述输入框获取焦点 */
const handleFaultDescInputFocus = async () => {
  if (form.value.faultDesc) return
  showFaultDescQuickSelect.value = true;

  // 加载所有故障信息
  await loadAllFaultInfoList();

  // 如果已有输入内容，立即搜索
  if (form.value.faultDesc && form.value.faultDesc.trim()) {
    handleFaultDescInput(form.value.faultDesc);
  } else {
    // 如果没有输入内容，显示所有故障信息
    quickFaultDescList.value = allFaultInfoList.value;
  }
};

/** 故障描述输入框失去焦点 */
const handleFaultDescInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showFaultDescQuickSelect.value = false;
  }, 200);
};

/** 故障描述输入事件 - 实时搜索 */
const handleFaultDescInput = (value) => {
  const searchText = value.trim();

  if (!searchText) {
    quickFaultDescList.value = [];
    showFaultDescQuickSelect.value = false;
    return;
  }

  showFaultDescQuickSelect.value = true;

  // 清除之前的定时器
  if (faultDescSearchTimer.value) {
    clearTimeout(faultDescSearchTimer.value);
  }

  // 过滤故障信息列表
  const lowerKeyword = searchText.toLowerCase();
  quickFaultDescList.value = allFaultInfoList.value.filter(item =>
      (item.faultCode && item.faultCode.toLowerCase().includes(lowerKeyword)) ||
      (item.faultBarcode && item.faultBarcode.toLowerCase().includes(lowerKeyword)) ||
      (item.faultDescription && item.faultDescription.toLowerCase().includes(lowerKeyword))
  );

  // 设置新的定时器，防抖处理（500ms）
  faultDescSearchTimer.value = setTimeout(() => {
    // 由于我们已经在上面过滤了，这里不需要额外的API调用
  }, 500);
};

/** 快速选择故障描述 */
const handleFaultDescQuickSelect = (item) => {
  form.value.faultCode = item.faultCode;
  form.value.faultBarcode = item.faultBarcode;
  form.value.faultDesc = item.faultDescription;
  showFaultDescQuickSelect.value = false;
};

/** 清空故障描述 */
const handleFaultDescClear = () => {
  form.value.faultCode = '';
  form.value.faultBarcode = '';
  form.value.faultDesc = '';
  quickFaultDescList.value = [];
  showFaultDescQuickSelect.value = false;
};

defineExpose({
  visible,
  form,
  optType,
  reset,
  submitForm
});
</script>

<style scoped>
.quick-select-dropdown {
  position: absolute;
  top: calc(100% + 2px);
  left: 0;
  right: 0;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.quick-select-item {
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-select-item:hover {
  background-color: #f5f7fa;
}
.quick-select-item .user-name {
  display: inline-block;
  margin-right: 10px;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 10px;
}

/* 输入框样式调整 */
:deep(.el-input-group__append) {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}
/* 表单中的列间距调整 */
:deep(.el-col) {
  padding-left: 5px;
  padding-right: 5px;
}
</style>
