<template>
  <div class="system-dialog-container">
    <el-dialog
        title="关联站点到分组"
        v-model="state.dialog.isShowDialog"
        width="500px"
        draggable
        destroy-on-close
        :close-on-click-modal="false"
        align-center>
      <el-form :model="state.ruleForm" label-position="top" ref="formRef" size="default">
        <el-form-item label="选择站点">
          <el-select-v2
              v-model="state.ruleForm.stationId"
              :options="state.stationOptions"
              placeholder="选择要关联的站点"
              filterable
              style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="onCancel" size="default">取 消</el-button>
        <el-button :loading="state.btnLoading" type="primary" @click="onSubmit" size="default">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="AssignStationDialog">
import { reactive, ref } from 'vue';
import { Msg } from "/@/utils/message";
import { $body } from "/@/utils/request";

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

const initState = () => ({
  ruleForm: { groupId: null as number | null, stationId: null as string | null },
  btnLoading: false,
  dialog: { isShowDialog: false },
  stationOptions: [] as Array<{ value: string; label: string }>,
})

const state = reactive(initState());

const open = (groupId: number) => {
  state.ruleForm.groupId = groupId;
  state.ruleForm.stationId = null;
  state.dialog.isShowDialog = true;

  $body('/washStation/list', { pageNum: 1, pageSize: 200 }).then((res: any) => {
    state.stationOptions = (res.list || []).map((s: any) => ({
      value: s.stationId,
      label: s.stationName + ' (' + s.stationId + ')',
    }));
  });
};

const onClose = () => {
  state.dialog.isShowDialog = false;
  Object.assign(state, initState());
};
const onCancel = () => onClose();

const onSubmit = () => {
  if (!state.ruleForm.stationId) {
    Msg.message('请选择站点', 'warning');
    return;
  }
  state.btnLoading = true;
  $body('/rechargeConfig/group/assignStation', {
    groupId: state.ruleForm.groupId,
    stationId: state.ruleForm.stationId,
  }).then(() => {
    state.btnLoading = false;
    Msg.message('操作成功');
    onClose();
    emit('refresh');
  }).catch(() => {
    state.btnLoading = false;
    Msg.message('操作失败', 'error');
  });
};

defineExpose({ open });
</script>
