<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="900px" append-to-body
    :close-on-click-modal="false">
    <div v-loading="scLoading">
      <!-- 新增抽查：先选择演练实施记录（仅未抽查记录） -->
      <el-form v-if="!props.row.drGuid" :model="scForm" label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择演练记录" prop="drGuid">
              <el-select v-model="scForm.drGuid" filterable remote :remote-method="searchDrillRecords"
                :loading="drillLoading" placeholder="请输入演练名称搜索（仅未抽查记录）" style="width: 100%"
                @change="handleDrillSelected">
                <el-option v-for="item in drillOptions" :key="item.drGuid"
                  :label="`${item.orgName || ''} - ${item.drillName || ''}`" :value="item.drGuid">
                  <span>{{ item.orgName || '--' }} - {{ item.drillName || '--' }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px;">{{ item.drillTime }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 块一：演练实施记录信息 -->
      <el-divider content-position="left">
        <el-icon><OfficeBuilding /></el-icon>
        <span style="margin-left:6px;font-weight:600;">演练实施记录信息</span>
      </el-divider>
      <DrillDetail v-if="scDrGuid" :key="'sc-' + scDrGuid + '-' + scSeq" :dr-guid="scDrGuid" inline />

      <!-- 块二：预案演练抽查 -->
      <el-divider content-position="left">
        <el-icon><Checked /></el-icon>
        <span style="margin-left:6px;font-weight:600;">预案演练抽查</span>
      </el-divider>
      <el-form :model="scForm" :rules="scRules" ref="scFormRef" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="抽查时间" prop="scTime">
              <el-date-picker v-model="scForm.scTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抽查单位" prop="orgGuid">
              <el-input :model-value="userStore.orgName || userStore.orgGuid" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="抽查结果" prop="spotCheck">
              <el-select v-model="scForm.spotCheck" placeholder="请选择" style="width: 100%">
                <el-option v-for="dict in scResultOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="抽查结果说明" prop="scExplain">
              <el-input v-model="scForm.scExplain" type="textarea" :rows="3" maxlength="200" show-word-limit
                placeholder="请输入抽查结果说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitScForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, getCurrentInstance, reactive, ref, toRefs, watch } from 'vue'
import { getDrillSc, saveDrillSc, listDrillSc } from "@/api/slaj/eme"
import { parseTime } from '@/utils/goldenwater'
import useUserStore from '@/store/modules/user'
import DrillDetail from '@/components/DrillDetail/index.vue'

const props = defineProps({
  /** v-model 控制显隐 */
  modelValue: { type: Boolean, default: false },
  /** 当前演练实施记录行（含 drGuid / basicId） */
  row: { type: Object, default: () => ({}) }
})
const emit = defineEmits(['update:modelValue', 'saved'])

const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const { eme_drill_sc_status } = proxy.useDict("eme_drill_sc_status")

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})
const dialogTitle = computed(() =>
  (props.row && props.row.drGuid) ? '应急演练记录抽查' : '新增预案演练抽查'
)

const scLoading = ref(false)
const scDrGuid = ref('')
const scSeq = ref(0)
const drillOptions = ref([])
const drillLoading = ref(false)
const scData = reactive({
  scForm: {
    drGuid: undefined,
    basicId: undefined,
    orgGuid: undefined,
    scTime: undefined,
    spotCheck: undefined,
    scExplain: undefined
  },
  scRules: {
    orgGuid: [{ required: true, message: "抽查单位不能为空", trigger: "change" }],
    scTime: [{ required: true, message: "抽查时间不能为空", trigger: "change" }],
    spotCheck: [{ required: true, message: "抽查结果不能为空", trigger: "change" }],
    scExplain: [{ required: true, message: "抽查结果说明不能为空", trigger: "blur" }]
  }
})
const { scForm, scRules } = toRefs(scData)

/** 抽查结果选项：合格 / 打回整改（不含“未抽查”） */
const scResultOptions = computed(() =>
  (eme_drill_sc_status.value || []).filter(dict => dict.value !== '0')
)

function openLoad() {
  const row = props.row || {}
  scSeq.value++
  scForm.value = {
    drGuid: row.drGuid,
    basicId: row.basicId,
    orgGuid: userStore.orgGuid || '',
    scTime: parseTime(new Date(), '{y}-{m}-{d}'),
    spotCheck: undefined,
    scExplain: undefined
  }
  // 新增抽查：先加载未抽查的演练记录供选择
  if (!row.drGuid) {
    scDrGuid.value = ''
    loadDrillOptions('')
    return
  }
  scDrGuid.value = row.drGuid
  // 已抽查过的记录回显
  scLoading.value = true
  getDrillSc(row.drGuid).then(r => {
    const d = r.data || {}
    if (d.ccGuid) {
      scForm.value.scTime = d.scTime || scForm.value.scTime
      scForm.value.spotCheck = d.spotCheck
      scForm.value.scExplain = d.scExplain
    }
  }).finally(() => {
    scLoading.value = false
  })
}

/** 加载未抽查的演练实施记录（新增抽查选择器） */
function loadDrillOptions(query) {
  drillLoading.value = true
  listDrillSc({
    pageNum: 1,
    pageSize: 20,
    spotCheck: '0',
    drillName: query || undefined
  }).then(res => {
    drillOptions.value = res.rows || []
  }).finally(() => {
    drillLoading.value = false
  })
}

function searchDrillRecords(query) {
  loadDrillOptions(query)
}

function handleDrillSelected(val) {
  if (!val) {
    scDrGuid.value = ''
    return
  }
  scDrGuid.value = val
  scSeq.value++
}

watch(() => props.modelValue, (val) => {
  if (val) openLoad()
})

function submitScForm() {
  if (!scForm.value.drGuid) {
    proxy.$modal.msgWarning('请先选择演练记录')
    return
  }
  proxy.$refs["scFormRef"].validate(valid => {
    if (!valid) return
    saveDrillSc(scForm.value).then(() => {
      proxy.$modal.msgSuccess("操作成功")
      dialogVisible.value = false
      emit('saved')
    })
  })
}
</script>
