<script lang="ts">
export default {
  name: 'employee'
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete  } from '@element-plus/icons-vue';
import {
  queryEmployee,
  addAuditEmployee,
  delEmployee
} from '@/api/system/employee';
import {
  EmployeeQueryParam,
  EmployeeItem,
  EmployeeFormData
} from '@/types/api/system/employee';

import {
  departmentManage
} from '@/api/system/dept';
import {
  DeptItem
} from '@/types/api/system/dept';

import {
  roleManage
} from '@/api/system/role';
import {
  RoleItem
} from '@/types/api/system/role';

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const validatePasswdCheck = (rule: any, value: any, callback: any) => {
  if (value !== state.formData.password) {
    callback(new Error("两次输入密码不一致"))
  } else {
    callback()
  }
}

const state = reactive({
  loading: true,
  // 选中ids数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  deptList: [] as DeptItem[],
  roleList: [] as RoleItem[],
  queryParams: {
    pageNo: 1,
    pageSize: 15,
  } as EmployeeQueryParam,
  list: [] as EmployeeItem[],
  total: 0,
  isCreate: false,
  dialog: {
    title: '',
    visible: false
  },
  formData: {} as EmployeeFormData,
  createRules: {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    passwdCheck: [
      { required: true, message: '请输入确认密码', trigger: 'blur' },
      { validator: validatePasswdCheck, required: true, trigger: 'blur' }
    ],
    realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    mobilePhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
    roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
    departmentId: [{ required: true, message: '请选择部门 ', trigger: 'blur' }]
  },
  updateRules: {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    mobilePhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
    passwdCheck: [
      { validator: validatePasswdCheck, required: false, trigger: 'blur' }
    ],
    roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
    departmentId: [{ required: true, message: '请选择部门 ', trigger: 'blur' }]
  }
});

const {
  loading,
  multiple,
  queryParams,
  list,
  total,
  isCreate,
  dialog,
  formData,
  createRules,
  updateRules
} = toRefs(state);

function handleQuery() {
  state.loading = true;
  queryEmployee(state.queryParams).then(({ data }) => {
    state.list = data.content;
    state.total = data.totalElements;
    state.loading = false;
  });
}

function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
  state.single = selection.length !== 1;
  state.multiple = !selection.length;
}

function handleAdd() {
  state.dialog = {
    title: '添加用户',
    visible: true
  };
  isCreate.value = true;
  formData.value.id = null;
  formData.value.username = "";
  formData.value.password = "";
  formData.value.passwdCheck = "";
  formData.value.realName = "";
  formData.value.mobilePhone = "";
  formData.value.roleId = "";
  formData.value.departmentId = "";
  formData.value.enable = 0;
  formData.value.qq = "";
  formData.value.email = "";
  formData.value.avatar = "";
}

/**
 * 提交新增/编辑
 */
function submitFormData() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      addAuditEmployee(state.formData).then(() => {
        ElMessage.success(state.formData.id ? '修改成功' : '添加成功');
        cancel();
        handleQuery();
        loading.value = false;
      });
    }
  });
}

/**
 * 取消
 */
function cancel() {
  dialog.value.visible = false;
  formData.value.id = null;
  formData.value.username = "";
  formData.value.password = "";
  formData.value.passwdCheck = "";
  formData.value.realName = "";
  formData.value.mobilePhone = "";
  formData.value.roleId = "";
  formData.value.departmentId = "";
  formData.value.enable = 0;
  formData.value.qq = "";
  formData.value.email = "";
  formData.value.avatar = "";
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 *  删除
 */
function handleDelete() {
  const ids = [state.ids].join(',');
  ElMessageBox.confirm('确认删除已选中的' + state.ids.length + '条数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(() => {
    delEmployee({ ids: ids }).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
  })
  .catch(() => ElMessage.info('已取消删除'));
}

/**
 * 编辑用户
 * @param row 
 */
const viewEdit = (row: any) => {
  state.dialog = {
    title: '编辑用户',
    visible: true
  };
  isCreate.value = false;
  formData.value.id = row.id;
  formData.value.username = row.username;
  formData.value.password = "";
  formData.value.passwdCheck = "";
  formData.value.realName = row.realName;
  formData.value.mobilePhone = row.mobilePhone;
  formData.value.roleId = row.roleId;
  formData.value.departmentId = row.department.id;
  formData.value.enable = row.enable;
  formData.value.qq = row.qq;
  formData.value.email = row.email;
  formData.value.avatar = row.avatar;
}

const initSelectOpt = () => {
  departmentManage(state.queryParams).then(({ data }) => {
    state.deptList = data.content;
  });
  roleManage(state.queryParams).then(({ data }) => {
    state.roleList = data.content;
  });
}

onMounted(() => {
  initSelectOpt()
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item>
        <el-button type="success" :icon="Plus" @click="handleAdd">添加</el-button>
        <el-button
          type="danger"
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      highlight-current-row
      border
      >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" prop="id" align="center" />
      <el-table-column label="用户名" prop="username" align="center" />
      <el-table-column label="真实姓名" prop="realName" align="center" />
      <el-table-column label="所在部门" prop="department.name" align="center" />
      <el-table-column label="角色" prop="roleName" align="center" />
      <el-table-column label="手机号" prop="mobilePhone" align="center" />
      <el-table-column label="邮箱" prop="email" align="center" />
      <el-table-column label="状态" prop="status" align="center">
        <template #default="scope">
          <el-button type="success" size="small" v-if="scope.row.status==0">正常</el-button>
          <el-button type="danger" size="small" v-else-if="scope.row.status==1">禁用</el-button>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="viewEdit(scope.row)">查看 / 编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页工具条 -->
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <!-- 表单弹窗 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="isCreate?createRules:updateRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="确认密码" prop="passwdCheck">
          <el-input type="password" v-model="formData.passwdCheck" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input type="text" v-model="formData.realName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="联系电话" prop="mobilePhone">
          <el-input type="text" v-model="formData.mobilePhone" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
              v-model="formData.roleId"
              class="filter-item"
              placeholder="请选择"
              style="width: 100px;"
              >
              <el-option
                v-for="item in state.roleList"
                :key="item.id"
                :value="item.id"
                :label="item.role"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-select
              v-model="formData.departmentId"
              class="filter-item"
              placeholder="请选择"
              style="width: 100px;"
              >
              <el-option
                v-for="item in state.deptList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="enable">
          <el-radio-group v-model="formData.enable">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="qq" prop="qq">
          <el-input type="text" v-model="formData.qq" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="formData.email" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormData">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
