import { ref } from 'vue';
import { getGoafSelectOption } from '../../monitor/sealedMonitor/monitor.api';
import { useMineDepartmentStore } from '/@/store/modules/mine';
import { resolveAlarm } from '../warningAnalysis/airLeakStatus/airLeak.api';
import { message } from 'ant-design-vue';
import { useModal } from '/@/components/Modal';
import { TableActionType } from '/@/components/Table';

/** 风险分析等级选项 — 与表格中"风险分析"列的 alarmName 映射一致 */
export const RISK_ANALYSIS_OPTIONS = [
  { label: '低风险', value: '1' },
  { label: '一般风险', value: '2' },
  { label: '较高风险', value: '3' },
  { label: '高风险', value: '4' },
];

export function useInitForm(ctx?: TableActionType) {
  const mineStore = useMineDepartmentStore();
  // 给历史数据默认填充的矿码
  const leaf = mineStore.findDepart((e) => e.isLeaf, mineStore.getDepart || mineStore.getRoot);
  const hiscode = leaf?.id;

  if (hiscode) {
    // mineStore.setDepartById(code as string);
    initGoafOptions(hiscode);
  }

  // 采空区选择器
  const goafId = ref('');
  const goafOptions = ref<any[]>([]);

  function initGoafOptions(deptId) {
    return getGoafSelectOption({ deptId }).then(({ options, defaultValue }) => {
      goafOptions.value = options;
      if (options.some((e) => e.value === goafId.value)) return;
      goafId.value = defaultValue;
    });
  }

  const [registerModal, modalCtx] = useModal();

  function openModal(record) {
    resolveId.value = record.id;
    modalCtx.openModal(true);
  }

  const resolveId = ref('');
  const resolveValue = ref('');

  function handleResolve() {
    const params = {
      id: resolveId.value,
      content: resolveValue.value,
    };

    resolveAlarm(params)
      .then(() => {
        message.success('操作成功');
        modalCtx.closeModal();
        if (ctx) ctx.reload();
      })
      .catch(() => {
        message.error('操作失败');
      });
  }

  return {
    goafOptions,
    goafId,
    hiscode,
    resolveId,
    resolveValue,
    registerModal,
    openModal,
    initGoafOptions,
    handleResolve,
  };
}
