<template>
  <el-dialog 
    :title="form.id ? '缂栬緫' : '鏂板'" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="800px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      :validate-on-rule-change="false"
      v-loading="loading">
      <el-row :gutter="24">
        <!-- 缂栬緫鏃舵樉绀哄闄?-->
  
        <el-col :span="12" class="mb20">
          <el-form-item label="鐝彿" prop="classCode">
            <el-select 
              v-model="form.classCode" 
              placeholder="璇烽€夋嫨鐝彿" 
              clearable
              filterable
              style="width: 100%" >
              <el-option
                v-for="item in (form.id && form.id !== '' && form.deptCode) ? filteredClassList : classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="妫€鏌ユ棩鏈? prop="recordDate">
            <el-date-picker
              v-model="form.recordDate"
              type="date"
              placeholder="閫夋嫨妫€鏌ユ棩鏈?
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="鎵ｅ垎" prop="score">
            <el-input-number
              v-model="form.score"
              :precision="0"
              :step="1"
              :min="0"
              placeholder="璇疯緭鍏ユ墸鍒?
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="妫€鏌ヨ褰? prop="note">
            <el-input
              v-model="form.note"
              type="textarea"
              :rows="4"
              placeholder="璇疯緭鍏ユ鏌ヨ褰?
              maxlength="500"
              show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">鍙?娑?/el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">纭?璁?/el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="classroomhygienedailyDialog">
import { ref, reactive, nextTick, computed, onMounted } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/stuwork/classroomhygienedaily'
import { getDeptList } from '/@/api/basic/basicclass'
import { getClassListByRole, queryClassByDeptCode } from '/@/api/basic/basicclass'

const emit = defineEmits(['refresh']);

// 瀹氫箟鍙橀噺鍐呭
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const deptList = ref<any[]>([])
const classList = ref<any[]>([])

// 鎻愪氦琛ㄥ崟鏁版嵁
const form = reactive({
  id: '',
  deptCode: '',
  classCode: '',
  recordDate: '',
  score: 0,
  note: ''
});

// 鏍规嵁瀛﹂櫌绛涢€夌彮绾у垪琛?
const filteredClassList = computed(() => {
  if (!form.deptCode) {
    return []
  }
  return classList.value.filter((item: any) => item.deptCode === form.deptCode)
})

// 瀹氫箟鏍￠獙瑙勫垯
const dataRules = computed(() => ({
  deptCode: form.id ? [
    { required: true, message: '瀛﹂櫌涓嶈兘涓虹┖', trigger: 'change' }
  ] : [],
  classCode: [
    { required: true, message: '鐝彿涓嶈兘涓虹┖', trigger: 'change' }
  ],
  recordDate: [
    { required: true, message: '妫€鏌ユ棩鏈熶笉鑳戒负绌?, trigger: 'blur' }
  ],
  score: [
    { required: true, message: '鎵ｅ垎涓嶈兘涓虹┖', trigger: 'blur' }
  ],
  note: [
    { required: true, message: '妫€鏌ヨ褰曚笉鑳戒负绌?, trigger: 'blur' }
  ]
}))

// 瀛﹂櫌閫夋嫨鍙樺寲
const handleDeptChange = () => {
  // 娓呯┖鐝彿閫夋嫨
  form.classCode = ''
}

// 鎵撳紑寮圭獥
const openDialog = (id?: string) => {
  visible.value = true
  
  // 閲嶇疆琛ㄥ崟鏁版嵁
  Object.assign(form, {
    id: '',
    deptCode: '',
    classCode: '',
    recordDate: '',
    score: 0,
    note: ''
  })

  // 娓呴櫎琛ㄥ崟楠岃瘉鐘舵€侊紝涓嶈Е鍙戦獙璇?
  nextTick(() => {
    dataFormRef.value?.clearValidate();
    dataFormRef.value?.resetFields();
  });

  // 鑾峰彇璇︽儏
  if (id) {
    form.id = id
    getclassroomhygienedailyData(id)
  }  
    // 鏂板鏃讹紝纭繚楠岃瘉鐘舵€佸凡娓呴櫎
  nextTick(() => {
    dataFormRef.value?.clearValidate();
  });
   
};

// 鎻愪氦
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '淇敼鎴愬姛' : '娣诲姞鎴愬姛');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || '鎿嶄綔澶辫触');
  } finally {
    loading.value = false;
  }
};

// 鍒濆鍖栬〃鍗曟暟鎹?
const getclassroomhygienedailyData = (id: string) => {
  loading.value = true
  getObj({ id: id }).then((res: any) => {
    if (res.data) {
      // 澶勭悊杩斿洖鏁版嵁锛屽彲鑳芥槸瀵硅薄鎴栨暟缁?
      const data = Array.isArray(res.data) ? res.data[0] : res.data
      if (data) {
        Object.assign(form, {
          id: data.id || '',
          deptCode: data.deptCode || '',
          classCode: data.classCode || '',
          recordDate: data.recordDate || '',
          score: data.score || 0,
          note: data.note || ''
        })
        
        // 濡傛灉缂栬緫鏃?deptCode 涓虹┖锛屼絾 classCode 鏈夊€硷紝灏濊瘯浠?classList 涓壘鍒板搴旂殑 deptCode
        if (!form.deptCode && form.classCode && classList.value.length > 0) {
          const classItem = classList.value.find((item: any) => item.classCode === form.classCode)
          if (classItem && classItem.deptCode) {
            form.deptCode = classItem.deptCode
          }
        }
        
        // 鏁版嵁鍔犺浇瀹屾垚鍚庯紝娓呴櫎楠岃瘉鐘舵€侊紝閬垮厤瑙﹀彂楠岃瘉
        nextTick(() => {
          dataFormRef.value?.clearValidate();
        });
      }
    }
  }).catch((err: any) => {
    console.error('鑾峰彇璇︽儏澶辫触', err)
    useMessage().error('鑾峰彇璇︽儏澶辫触')
  }).finally(() => {
    loading.value = false
  })
}

// 鑾峰彇瀛﹂櫌鍒楄〃
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data) {
      deptList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('鑾峰彇瀛﹂櫌鍒楄〃澶辫触', err)
    deptList.value = []
  }
}

// 鑾峰彇鐝彿鍒楄〃
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('鑾峰彇鐝彿鍒楄〃澶辫触', err)
    classList.value = []
  }
}

// 鍒濆鍖?
onMounted(() => {
  getDeptListData()
  getClassListData()
})

// 鏆撮湶鍙橀噺
defineExpose({
  openDialog
});
</script>
