<style scoped lang="scss">

</style>
<template>
  <div class="system-dialog-container">
    <el-drawer
        :title="state.dialog.title"
        v-model="state.dialog.isShowDialog"
        size="620px"
        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="头像">
          <ext-upload v-model="state.ruleForm.avatar" @on-change="handleAvatarChange"></ext-upload>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="state.ruleForm.username"
              placeholder="用户名"
              clearable
              class="w100">
          </el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
              v-model="state.ruleForm.nickname"
              placeholder="昵称"
              clearable
              class="w100">
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!state.ruleForm.id">
          <el-input
              v-model="state.ruleForm.password"
              placeholder="密码"
              clearable
              show-password
              type="password"
              class="w100">
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobilePhone">
          <el-input
              v-model="state.ruleForm.mobilePhone"
              placeholder="手机号"
              clearable
              class="w100">
          </el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <ext-d-select
              type="AdminUser.status"
              v-model="state.ruleForm.status"
              placeholder="状态"
              clearable
              class="w100">
          </ext-d-select>
        </el-form-item>
        <el-form-item label="最后登录时间" v-if="state.ruleForm.id>0">
          <el-input
              v-model="state.ruleForm.lastLoginTime"
              placeholder="最后登录时间"
              clearable
              readonly
              class="w100">
          </el-input>
        </el-form-item>

        <el-card header="角色">
          <el-checkbox-group
              v-model="state.checkRoleIdList"
              @change="handleCheckedRoleChange"
          >
            <el-checkbox v-for="role in state.roleList" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-card>

        <el-card header="管理站点" style="margin-top: 20px;">
          <ext-select
              v-model="state.adminUserStationIdList"
              multiple
              placeholder="关联站点"
              url="station/list"
              url-method="get"
              label-key="stationName"
              value-key="stationId"
              data-key=""
              clearable
              class="w100 mt5">
          </ext-select>
        </el-card>
      </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="AdminUserDialog">
import {defineAsyncComponent, reactive, onMounted, 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 ExtDSelect from "/@/components/form/ExtDSelect.vue";
import ExtUpload from "/@/components/form/ExtUpload.vue";
import ExtSelect from "/@/components/form/ExtSelect.vue";
import {Session} from "/@/utils/storage";

// 引入组件
// const ExtDetailForm = defineAsyncComponent(() => import('/@/components/form/ExtDetailForm.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const formRef = ref();
//定义初始变量，重置使用
const initState = () => ({
  ruleForm: {
    id: 0
  },
  btnLoading: false,
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  rules: {
    username: [u.validator.required],
    mobilePhone: [u.validator.required, u.validator.mobile],
    nickname: [u.validator.required],
    status: [u.validator.required],
    password: [u.validator.required],
  },
  roleList: [],
  checkRoleIdList: [],
  adminUserStationList: [],
  adminUserStationIdList: []
})

// 定义变量内容
const state = reactive(initState());


// 打开弹窗
const open = (action: string = 'add', row: any) => {
  console.log(state.ruleForm)
  loadRole(row);
  state.dialog.title = u.dialog.actions[action].title + "『运营用户』"
  state.dialog.submitTxt = u.dialog.actions[action].btn + "『运营用户』"
  state.dialog.isShowDialog = true;
  if (action !== 'add') {
    loadData(row.id);

  }

};

const handleCheckedRoleChange = () => {
}

const handleAvatarChange = (val: string) => {
  console.log("avatar:", val)
}

// 关闭弹窗
const onClose = () => {
  state.dialog.isShowDialog = false;
  Object.assign(state, initState())
  console.log(state.ruleForm)
};
// 取消
const onCancel = () => {
  onClose();
};
// 提交
const onSubmit = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      state.btnLoading = true;
      const url = state.ruleForm.id > 0 ? "admin-user/modify" : "admin-user/add"
      $body(url, state.ruleForm).then((id) => {
        if (id) {
          state.ruleForm.id = id;
        }

        Msg.message('操作成功');
        if (state.ruleForm.id > 0) {
          $body(`admin-user/updateRole`, {userId: state.ruleForm.id, roleIdList: state.checkRoleIdList}).then(() => {
            emit('refresh');
            state.btnLoading = false;
            if(state.adminUserStationIdList.length ===0){
              onClose()
            }
          })
        } else {
          emit('refresh');
        }
        if (state.adminUserStationIdList.length > 0) {
          let adminUserStationList = state.adminUserStationIdList.map(k => {
            return {
              adminUserId: state.ruleForm.id,
              stationId: k
            }
          })
          $body(`admin-user-station/save`, adminUserStationList).then(() => {
            emit('refresh');
            state.btnLoading = false;
            onClose()
          })
        }
      }).catch(() => {
        state.btnLoading = false;
      })
    } else {
      state.btnLoading = false;
      Msg.message('表单校验失败', 'error');
    }
  })

  // formRef.value.checkForm().then(() => {
  //
  // }).catch(() => {
  //     state.btnLoading = false;
  //     Msg.message('表单校验失败', 'error');
  // })
};

const handleFormChange = (formData: any) => {
  console.log(formData)
}

const loadRole = (row: any) => {
  $get(`role/list`).then((res: any) => {
    state.roleList = res;
    if (!row || !row.id) {
      if (res && !u.isEmptyOrNull(res)) {
        state.checkRoleIdList = [res[0].id]
      }
    }
  })
}

// 初始化表格数据
const loadData = (id: number) => {
  $get(`admin-user/detail/${id}`).then((res: any) => {
    let {adminUser, roles} = res;
    state.ruleForm = adminUser;
    state.checkRoleIdList = roles.map(k => k.roleId)
    loadAdminUserStationList()
  })
}

const loadAdminUserStationList = () => {
  if(state.ruleForm.id<=0){
    return;
  }
  let param = {
    userId: state.ruleForm.id,
    pageNum: 1,
    pageSize: 1024
  }
  $get(`admin-user-station/list`, param).then((res: any) => {
    let {list} = res;
    state.adminUserStationIdList = list.map(k => k.stationId)
    state.adminUserStationList = res.list;
  })
}

// 暴露变量
defineExpose({
  open
});


</script>