import {
  getIncidentList,
  getIncidentItem,
  getHDIncidentList,
  GetIncidentListParams,
  IncidentItemDetail,
  IncidentListResponse,
  IncidentItem,
  putIncidentItem,
  postIncidentItem,
} from '@/api/incident';
import { ElMessage } from 'element-plus';
import { defineStore } from 'pinia';

export interface IncidentStateType {
  incidents: IncidentListResponse;
  loading: boolean;
  incidentDetail: IncidentItemDetail;
}

export interface IncidentActionsType {
  toggleLoading(): void;
  getIncidentList(params: GetIncidentListParams): void;
  getIncidentItem(id: number | string): void;
  putIncidentItem(params: IncidentItem): Promise<boolean | null | undefined>;
  postIncidentItem(params: IncidentItem): Promise<boolean | null | undefined>;
}

export default defineStore<
  'incident',
  IncidentStateType,
  {},
  IncidentActionsType
>('incident', {
  state: () => ({
    incidents: {
      data: [],
    },
    incidentDetail: {
      baseInfo: {},
      process: [],
      task: [],
    },
    loading: false,
  }),
  actions: {
    toggleLoading() {
      this.loading = !this.loading;
    },
    async getIncidentList(params) {
      try {
        this.toggleLoading();
        this.incidents = await getHDIncidentList(params);
      } finally {
        this.toggleLoading();
      }
    },
    async getIncidentItem(id) {
      try {
        this.loading = false;
        // this.toggleLoading();
        const { data } = await getIncidentItem(id);
        this.incidentDetail = data;
      } finally {
        // this.toggleLoading();
      }
    },

    async postIncidentItem(params) {
      try {
        this.toggleLoading();
        await postIncidentItem(params);
        ElMessage.success({ message: '修改成功' });
        return true;
      } catch {
        ElMessage.error({ message: '修改失败' });
      } finally {
        this.toggleLoading();
      }
    },
    /** 修改事件状态 */
    /**  */
    async putIncidentItem(params) {
      try {
        this.toggleLoading();
        await putIncidentItem(params);
        if (params.madinDept || params.assistDept) {
          ElMessage.success({ message: `派发成功` });
          return true;
        }
        ElMessage.success({ message: '修改成功' });
        return true;
      } catch {
        ElMessage.error({ message: '修改失败' });
      } finally {
        this.toggleLoading();
      }
    },
  },
});
