<style scoped lang="scss">

</style>
<template>
  <div class="system-dialog-container">
    <el-drawer
        :title="state.dialog.title"
        v-model="state.dialog.isShowDialog"
        size="500px"
        append-to-body
        destroy-on-close
        class="pd10"
        :close-on-click-modal="false"
        @close="onClose">
      <el-form
          :model="state.ruleForm"
          :rules="state.rules"
          label-position="top"
          ref="formRef"
          size="default"
          label-width="100px"
          class="mt5 pd10">
        
        <el-form-item label="选择站点" prop="stationId">
          <ext-select
              v-model="state.ruleForm.stationId"
              placeholder="请选择站点"
              url="station/listStation"
              urlMethod="get"
              data-key=""
              label-key="stationName"
              value-key="stationId"
              clearable
              class="w100"
              @on-change="handleStationChange">
          </ext-select>
        </el-form-item>

        <el-form-item label="选择用户" prop="userId">
          <el-select-v2
              v-model="state.ruleForm.userId"
              :options="state.userList"
              filterable
              remote
              :remote-method="handleUserSearch"
              placeholder="请输入手机号搜索用户"
              class="w100"
              clearable>
            <template #default="{ item }">
              <span>{{ item.label }}</span>
            </template>
          </el-select-v2>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="state.ruleForm.remark"
              placeholder="请输入备注"
              type="textarea"
              :rows="3"
              class="w100">
          </el-input>
        </el-form-item>
      </el-form>

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

<script setup lang="ts" name="WhitelistDialog">
import { reactive, ref } from 'vue';
import { Msg } from "/@/utils/message";
import { $body, $get } from "/@/utils/request";
import u from '/@/utils/u';
import type { FormInstance, FormRules } from 'element-plus';
import ExtSelect from "/@/components/form/ExtSelect.vue";

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

const initState = () => ({
  ruleForm: {
    id: 0,
    stationId: null as string | null,
    userId: null as number | null,
    remark: ''
  },
  btnLoading: false,
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  rules: {
    stationId: [{ required: true, message: '请选择站点', trigger: 'change' }],
    userId: [{ required: true, message: '请选择用户', trigger: 'change' }]
  },
  userList: [] as Array<{ value: number, label: string }>
})

const state = reactive(initState());

const open = (action: string = 'add', row: any) => {
  state.dialog.title = u.dialog.actions[action].title + "『白名单用户』"
  state.dialog.submitTxt = u.dialog.actions[action].btn + "『白名单用户』"
  state.dialog.isShowDialog = true;
  state.dialog.type = action;
  
  if (action !== 'add' && row) {
    state.ruleForm.id = row.id;
    state.ruleForm.stationId = row.stationId;
    state.ruleForm.userId = row.userId;
    state.ruleForm.remark = row.remark;
    if (row.userPhone) {
      state.userList = [{ value: row.userId, label: `${row.userPhone} (${row.userNickname || ''})` }];
    }
  }
};

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

const onCancel = () => {
  onClose();
};

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      state.btnLoading = true;
      $body(`/station-whitelist/add`, state.ruleForm).then(() => {
        Msg.message('操作成功', 'success');
        emit('refresh');
        state.btnLoading = false;
        onClose();
      }).catch(() => {
        state.btnLoading = false;
      })
    } else {
      Msg.message('表单校验失败', 'error');
    }
  })
};

const handleUserSearch = (query: string) => {
  if (!query || query.length < 4) {
    return;
  }
  $get(`/custom/simpleList`, { mobilePhone: query, pageNum: 1, pageSize: 20 }).then((res: any) => {
    let { list } = res;
    state.userList = list.map((k: any) => {
      return { value: k.id, label: `${k.mobilePhone} (${k.nickname || '未设置昵称'})` }
    });
  }).catch(() => {
    state.userList = [];
  });
};

const handleStationChange = (val: any) => {
  state.ruleForm.stationId = val;
  formRef.value?.clearValidate('stationId');
};

defineExpose({
  open
});
</script>
