<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" v-if="adminFlag" style="height: 65px;" @keyup.enter.native="queryList">
      <el-form-item label="用户名称">
        <el-input v-model="queryParams.userName" placeholder="用户名称" width="120px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="queryList">查询用户</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="handleAdd">新增用户</el-button>
      </el-form-item>
    </el-form>
    <!-- <div class="wrapper"> -->
    <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" :height="tableHeight"
      highlight-current-row @current-change="handleCurrentRowChange"
      :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
      <el-table-column fixed type="index" width="50" align="center" />
      <el-table-column fixed prop="userName" label="用户名称" header-align="center" width="120" />
      <el-table-column prop="loginId" label="登录ID" header-align="center" width="120" />
      <!-- <el-table-column prop="loginPwd" label="登录密码" header-align="center" width="120" /> -->
      <el-table-column label="管理员" header-align="center" align="center" width="100">
        <template #default="scope">
          <span v-if="scope.row.adminFlag === '0'" style="color:red;">✖</span>
          <span v-if="scope.row.adminFlag === '1'" style="color:green;">✔</span>
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称" header-align="center" width="120" />
      <el-table-column label="角色状态" header-align="center" align="center" width="100">
        <template #default="scope">
          <el-tag :type="mapColorMap[scope.row.useFlag]">{{ UseStateMap[scope.row.useFlag] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column fit prop="userMemo" label="备注" header-align="center" min-width="120" />
      <el-table-column fixed="right" label="" align="left" width="120">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="submitDeleteForm(scope.row)" :disabled="!adminFlag">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- </div> -->
    <el-config-provider :locale="locale">
      <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
        :page-sizes="[10, 15, 20, 25, 100]" :small="state.small" :disabled="state.disabled"
        :background="state.background" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
        style="text-align: center;margin-top: 10px;" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-config-provider>

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="450px" draggable center>
      <el-form ref="dataFormRef" :model="formData" label-width="100px" :rules="state.rules">
        <el-form-item label="用户名称:" prop="userName">
          <el-input v-model="formData.userName" placeholder="用户名称" width="120px" />
        </el-form-item>
        <el-form-item label="登录账户:" prop="loginId">
          <el-input v-model="formData.loginId" placeholder="登录ID" width="120px" />
        </el-form-item>
        <el-form-item label="登录密码:" prop="loginPwd">
          <el-input v-model="formData.loginPwd" placeholder="登录密码" width="120px" show-password />
        </el-form-item>
        <el-form-item label="所属角色:" v-if="adminFlag">
          <el-select v-model="formData.roleId" class="filter-item" placeholder="所属角色" style="width: 300px;">
            <el-option v-for="item in roleData" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息:">
          <el-input v-model="formData.userMemo" type="textarea" />
        </el-form-item>
        <el-form-item label="管理员:"  v-if="adminFlag">
          <el-switch v-model="formData.adminFlag" inline-prompt="true" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="在用状态:"  v-if="adminFlag">
          <el-switch v-model="formData.useFlag" inline-prompt="true" active-value="1" inactive-value="0"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import FacUserAction from "@/api/usermanagement/facuser";
import FacUserRoleAction from "@/api/usermanagement/facuserrole";
import { FacUserQueryParam, FacUserModel, FacUserRoleModel, Dialog, PageResult } from '@/types';

import zhCn from 'element-plus/lib/locale/lang/zh-cn';

let locale = ref(zhCn)

const queryFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
let userId = localStorage.getItem("CustomerId") + '';
const adminFlag=localStorage.getItem("AdminFlag")?.toString()==='1';
type mapStatee = Record<string, string>;
const UseStateMap: mapStatee = {
  0: '停用',
  1: '使用中',
};

const mapColorMap: mapStatee = {
  0: 'danger',
  1: 'success',
};

const loading = ref(false)

const state = reactive({
  currentType: 0,
  queryParams: { page: 1, rows: 10 } as FacUserQueryParam,
  total: 0,
  small: false,
  background: false,
  disabled: false,
  dialog: {} as Dialog,
  formData: {} as FacUserModel,
  UseStateMap,
  tableData: [] as FacUserModel[],
  roleData: [] as FacUserRoleModel[],
  rules: {
    userName: [{ required: true, message: "用户名称不能为空", trigger: "blur", },],
    loginId: [{ required: true, message: "登陆ID不能为空", trigger: "blur", },],
    loginPwd: [
      { required: true, message: "登陆密码不能为空", trigger: "blur", },
      { min: 6, max: 20, message: "登陆密码不能少于6位", trigger: "blur" },]
  }
});

const {
  queryParams,
  dialog,
  formData,
  tableData,
  roleData
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 200);
const currentRow = ref()

const handleCurrentRowChange = (val: FacUserModel | undefined) => {
  currentRow.value = val
}

async function handleAdd() {
  await queryRoleList();
  state.currentType = 0;
  state.formData = {} as FacUserModel;
  state.formData.useFlag='1';
  state.dialog = {
    title: '新增用户',
    visible: true,
    disabled: false,
  };
}

async function handleEdit(row: any) {
  await queryRoleList();
  state.currentType = 1;
  state.formData = JSON.parse(JSON.stringify(row));;
  state.dialog = {
    title: '编辑用户',
    visible: true,
    disabled: false,
  };
}

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryList();
};

const queryList = () => {
  loading.value = true;
  state.queryParams.userId=userId;
  FacUserAction.QueryFacUserList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<FacUserModel[]>;
        state.tableData = pageData.list;
        state.total = pageData.total;
      } else {
        ElMessage.error(error);
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
  })
  loading.value = false;
};

const submitForm = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      if (state.currentType == 0) {
        state.formData.createMan = localStorage.getItem("UserName") || "";
        FacUserAction.AddFacUser(state.formData).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('新增成功');
              cancel();
              queryList();
            } else {
              ElMessage.error(error);
            }
          }
        });
      }
      else {
        FacUserAction.EditFacUser(state.formData).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('编辑成功');
              cancel();
              queryList();
            } else {
              ElMessage.error(error);
            }
          }
        });
      }
    }
  });
};

const submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(
    ' 是否删除用户[' + row.userName + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      FacUserAction.DeleteFacUser(row.id).then(result => {
        if (result.status === 200) {
          const { res, flag, error } = result.data;
          if (flag === "1") {
            ElMessage.success('删除成功');
            queryList();
          } else {
            ElMessage.error(error);
          }
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除成功!',
      })
    })
};

const cancel = () => {
  dataFormRef.value.resetFields();
  state.formData = {} as FacUserModel;
  state.dialog.visible = false;
}

const queryRoleList = () => {
  FacUserRoleAction.QueryRoleList().then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag != undefined && flag == 1) {
        state.roleData = res as FacUserRoleModel[];
      } else {
        ElMessage.error(error);
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
  })
};

onMounted(() => {
  window.onresize = function () {
    tableHeight.value = document.documentElement.clientHeight - 200
  }

  queryList();
})
</script>

<style lang="scss" scoped>
.button {
  margin: 10px 0;
}
</style>