<script setup lang="ts">
import { ref, watch } from "vue";
import { DIALOG_WIDTH } from "../../../constants/ui";
import { ElMessage } from "element-plus";
import { updateMeetingInvoiceConfig } from "../../../api/modules";

const dialogVisible = defineModel<boolean>("dialogVisible", { required: true });

const props = defineProps<{
  meetingId: number | null;
  initialConfigJson: string | null;
  meetingInvoiceSectionDefs: any[];
}>();

const emit = defineEmits<{
  success: [];
}>();

const saving = ref(false);
const selectedModules = ref<string[]>([]);
const checkAll = ref(false);
const isIndeterminate = ref(false);

const updateCheckAllState = (val: string[]) => {
  const checkedCount = val.length;
  checkAll.value = checkedCount === props.meetingInvoiceSectionDefs.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < props.meetingInvoiceSectionDefs.length;
};

const handleCheckAllChange = (val: boolean) => {
  selectedModules.value = val ? props.meetingInvoiceSectionDefs.map(def => def.code) : [];
  isIndeterminate.value = false;
};

const handleCheckedModulesChange = (value: string[]) => {
  updateCheckAllState(value);
};

watch(() => dialogVisible.value, (visible) => {
  if (visible) {
    if (!props.initialConfigJson) {
      // 默认全选
      selectedModules.value = props.meetingInvoiceSectionDefs.map(def => def.code);
    } else {
      try {
        const arr = JSON.parse(props.initialConfigJson);
        if (Array.isArray(arr) && arr.length > 0) {
          selectedModules.value = arr;
        } else {
          selectedModules.value = props.meetingInvoiceSectionDefs.map(def => def.code);
        }
      } catch (e) {
        selectedModules.value = props.meetingInvoiceSectionDefs.map(def => def.code);
      }
    }
    updateCheckAllState(selectedModules.value);
  }
});

const handleSave = async () => {
  if (!props.meetingId) return;
  if (selectedModules.value.length === 0) {
    ElMessage.warning("请至少选择一项发票模块");
    return;
  }
  
  saving.value = true;
  try {
    await updateMeetingInvoiceConfig(props.meetingId, {
      invoiceModules: selectedModules.value,
    });
    ElMessage.success("会议发票模块配置成功");
    dialogVisible.value = false;
    emit("success");
  } catch (error: any) {
    ElMessage.error(error.message || "配置失败");
  } finally {
    saving.value = false;
  }
};
</script>

<template>
  <el-dialog v-model="dialogVisible" title="配置会议发票模块" :width="DIALOG_WIDTH.sm" :close-on-click-modal="false">
    <div class="mb-md">
      <el-alert title="勾选的模块将在该会议的“会议发票”页签中必填并显式要求上传相应材料。" type="info" :closable="false" />
    </div>
    
    <div class="mt-md mb-sm">
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
    </div>
    
    <el-checkbox-group v-model="selectedModules" @change="handleCheckedModulesChange">
      <div class="flex-col gap-sm">
        <el-checkbox
          v-for="def in meetingInvoiceSectionDefs"
          :key="def.code"
          :label="def.code"
          :value="def.code"
        >
          {{ def.order }}、{{ def.title }}
        </el-checkbox>
      </div>
    </el-checkbox-group>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.flex-col {
  display: flex;
  flex-direction: column;
}
.gap-sm {
  gap: 8px;
}
</style>
