<style scoped lang="scss">

</style>
<template>
  <div class="system-dialog-container">
    <el-drawer
        title="批量添加白名单用户"
        v-model="state.dialog.isShowDialog"
        size="600px"
        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="searchPhone">
          <div class="search-container w100">
            <el-input
                v-model="state.searchPhone"
                placeholder="请输入手机号搜索用户"
                clearable
                class="search-input">
              <template #append>
                <el-button @click="handleSearchUser" :loading="state.searchLoading">
                  <SvgIcon name="ele-Search"/>
                  搜索
                </el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>

        <el-form-item label="搜索结果">
          <div class="search-result w100">
            <el-table
                :data="state.searchResult"
                border
                stripe
                max-height="200"
                v-loading="state.searchLoading"
                @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column prop="mobilePhone" label="手机号" width="130"/>
              <el-table-column prop="nickname" label="昵称"/>
            </el-table>
            <div class="selected-info mt10" v-if="state.selectedUsers.length > 0">
              <el-tag type="success">已选择 {{ state.selectedUsers.length }} 个用户</el-tag>
            </div>
          </div>
        </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" :disabled="state.selectedUsers.length === 0">
            批量添加
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

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

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

const initState = () => ({
  ruleForm: {
    stationId: '',
    remark: ''
  },
  searchPhone: '',
  searchLoading: false,
  searchResult: [] as Array<any>,
  selectedUsers: [] as Array<any>,
  btnLoading: false,
  dialog: {
    isShowDialog: false
  },
  rules: {
    stationId: [{ required: true, message: '请选择站点', trigger: 'change' }]
  }
})

const state = reactive(initState());

const open = () => {
  state.dialog.isShowDialog = true;
};

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

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

const handleStationChange = () => {
  state.selectedUsers = [];
  state.searchResult = [];
};

const handleSearchUser = () => {
  if (!state.searchPhone || state.searchPhone.length < 4) {
    Msg.message('请输入至少4位手机号', 'warning');
    return;
  }
  state.searchLoading = true;
  $get(`/custom/simpleList`, { mobilePhone: state.searchPhone, pageNum: 1, pageSize: 50 }).then((res: any) => {
    let { list } = res;
    state.searchResult = list || [];
    state.searchLoading = false;
  }).catch(() => {
    state.searchResult = [];
    state.searchLoading = false;
  });
};

const handleSelectionChange = (selection: any) => {
  state.selectedUsers = selection;
};

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (state.selectedUsers.length === 0) {
        Msg.message('请选择要添加的用户', 'warning');
        return;
      }
      state.btnLoading = true;
      const userIds = state.selectedUsers.map(u => u.id);
      $body(`/station-whitelist/batchAdd`, {
        stationId: state.ruleForm.stationId,
        userIds: userIds,
        remark: state.ruleForm.remark
      }).then(() => {
        Msg.message(`成功添加 ${userIds.length} 个用户`, 'success');
        emit('refresh');
        state.btnLoading = false;
        onClose();
      }).catch(() => {
        state.btnLoading = false;
      })
    } else {
      Msg.message('表单校验失败', 'error');
    }
  })
};

defineExpose({
  open
});
</script>

<style scoped lang="scss">
.search-container {
  display: flex;
  
  .search-input {
    width: 100%;
  }
}

.search-result {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.selected-info {
  text-align: right;
}
</style>
