<template>
  <!-- 下发对话框 -->
  <el-dialog title="下发" v-model="visible" width="800px" append-to-body @close="cancel">
    <div style="max-height: 500px; overflow-y: auto; padding-right: 10px;">
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="120px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单编码" prop="workOrderProjectNo">
              <el-input v-model="form.workOrderProjectNo" placeholder="自动生成" maxlength="50" show-word-limit v-chinese-limit readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号" prop="pcsDeviceName">
              <el-input v-model="form.pcsDeviceName" readonly>
                <template #append>
                  <el-button @click="handleSelectEquipment" icon="Search"></el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维保中心" prop="gxtCenter">
              <el-input v-model="form.gxtCenter" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站" prop="pcsStationName">
              <el-input v-model="form.pcsStationName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机型" prop="model">
              <el-input v-model="form.model" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维保类型" prop="inspectionType">
              <el-select v-model="form.inspectionType" multiple placeholder="请选择维保类型" clearable>
                <el-option
                    v-for="dict in inspectionTypeOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="维保内容" prop="content">
              <el-input v-model="form.content" type="textarea" :rows="3" maxlength="500" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm('assigned')">确认下发</el-button>
      </div>
    </template>
  </el-dialog>

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

<script setup>
import {ref, reactive, nextTick, watch, getCurrentInstance, defineProps} from 'vue';
import EquipmentSelect from '@/components/equipmentSelect/single.vue'; // 根据实际情况调整路径
import { updateGxtOrder } from '@/api/gxt/gxtOrder';

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

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  },
  // 维保类型字典
  inspectionTypeOptions: {
    type: Array,
    default: () => ([])
  },
});

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

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

// 表单验证规则
const rules = ref({
  pcsDeviceName: [
    { required: true, message: "风机编号不能为空", trigger: "change" }
  ],
  inspectionType: [
    { required: true, message: "请选择维保类型", trigger: "change" }
  ],
  content: [
    { required: true, message: "维保内容不能为空", trigger: "blur" },
    { max: 500, message: "维保内容长度不能超过500个字符", trigger: "blur" }
  ]
});

// 监听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 (orderRef.value) {
        orderRef.value.clearValidate()
      }
    })
  }
})

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

// 取消操作
function cancel() {
  visible.value = false;
}

// 提交表单
async function submitForm(status) {
  if (!orderRef.value) return
  await orderRef.value.validate((valid) => {
    if (valid) {
      form.value.workOrderStatus = status;
      form.value.inspectionType = Array.isArray(form.value.inspectionType) ? form.value.inspectionType.join(',')
          : form.value.inspectionType || ''
      updateGxtOrder(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;
}

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;
  transition: background-color 0.2s;
}

.quick-select-item:hover {
  background-color: #f5f7fa;
}

.quick-select-item .mis-no {
  display: inline-block;
  margin-right: 10px;
  font-weight: bold;
  color: #409eff;
}

.quick-select-item .mis-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  flex: 1;
  margin-left: 10px;
}

.quick-select-item .mis-info .device {
  color: #606266;
  font-size: 12px;
  margin-bottom: 2px;
}

.quick-select-item .mis-info .station {
  color: #909399;
  font-size: 11px;
}

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

/* 输入框样式调整 */
:deep(.el-input-group__append) {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}
</style>
