<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="" prop="params.USERID">
              <CustomInput v-model:params="queryParams.params.USERID" placeholder="账号" clearable
                @keyUpEvent="handleQuery" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="" prop="params.USERNAME">
              <CustomInput v-model:params="queryParams.params.USERNAME" placeholder="用户名称" clearable
                @keyUpEvent="handleQuery" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQueryInfo">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <span>更新时间：{{ currentTime }}</span>
        <div class="page-table-operateBtns">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            创建
          </el-button>
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px" />
              </el-button>
            </template>
            <ConfigTable :list="column" @updateList="updateList" />
          </el-popover>
        </div>
      </div>
      <el-table :height="tableHeight" border v-loading="loading" :data="userList" highlight-current-row row-key="id" style="width: 100%">
        <template v-for="(col, index) in column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="col.field === 'status'">
                <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                <span v-else class="table-status-inActive">禁用</span>
              </span>
              <span v-else>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>

        <el-table-column width="300" label="操作" align="center" class-name="table-operation" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleUpdate(scope.row)" v-if="!scope.row.status"> 编辑
            </el-button>
            <div class="splitLine" v-if="!scope.row.status"></div>
            <el-button type="danger" link @click.stop="delConfirm(scope.row)" v-if="!scope.row.status"> 删除
            </el-button>
            <!-- <el-button type="primary" link v-if="!scope.row.status" @click="enable(scope.row)"> 启用 </el-button>
            <el-button type="primary" link v-if="!!scope.row.status" @click="disable(scope.row)"> 禁用 </el-button> -->
            <div class="splitLine" v-if="!scope.row.status"></div>
            <el-button type="primary" link @click.stop="handleRole(scope.row)"> 角色和组织 </el-button>
            <div class="splitLine" v-if="!scope.row.status"></div>
            <el-button type="primary" link @click.stop="resetConfirm(scope.row)"> 重置密码 </el-button>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <svg-icon icon-class="noData" width="160px" height="160px" />
        </template>
      </el-table>
      <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize" @pagination="handleQuery" />
    </div>
    <!--  新增或编辑  -->
    <el-drawer :title="dialog.title" v-model="dialog.visible" @close="cancel" @opened="dialogOpend">
      <el-form ref="formDataRef" :model="formData" :rules="rules" label-position="top">
        <el-form-item label="工厂名" prop="siteName">
          <el-input v-model="formData.siteName" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="账号" prop="userId" v-if="dialog.type === 'add'">
          <el-input v-model="formData.userId" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="姓名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialog.type === 'add'">
          <el-input name="password" show-password v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-drawer>
    <!--  分配角色和组织  -->
    <el-drawer v-model="roleDialog.visible" @close="cancelRoleDialog" @opened="roleDialogOpend"
      class="drawer-show-table" modal-class="userRoleModel">
      <template #header>
        <div class="drawer-show-table-title">
          <svg-icon icon-class="close" width="20px" height="20px" @click="cancelRoleDialog" />
          <span>{{ roleDialog.title }}</span>
        </div>
        <el-button type="primary" @click="submitUserRole()">确 定</el-button>
      </template>
      <el-table border ref="roleTableRef" :data="allRole" highlight-current-row row-key="USERGROUPNAME"
        style="width: 100%;height: 320px">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column prop="USERGROUPNAME" label="角色编码" show-overflow-tooltip></el-table-column>
        <el-table-column prop="DESCRIPTION" label="角色名称" show-overflow-tooltip></el-table-column>
      </el-table>
      <el-table border ref="orgTableRef" :data="allOrgList" highlight-current-row row-key="ORGNO"
        style="width: 100%;margin-top: 30px;">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column prop="ORGNO" label="组织编码" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ORGNAME" label="组织名称" show-overflow-tooltip></el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script lang="ts">
export default {
  name: "user",
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from "vue";
import { ElForm, ElTable } from "element-plus";

import { getUser, addUser, updateUser, deleteUser, updateUserRole } from "@/api/user";
import { getRoleList, getOrgList } from "@/api/role";
import { getRSAPublic } from "@/api/auth";
import { ElMessageBox } from 'element-plus'
import { bTableHeight } from "../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(180);
// 添加邮箱校验规则
const validateEmail = (rule: any, value: any, callback: any) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!value) {
    callback();
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'));
  } else {
    callback();
  }
};

const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();

const roleTableRef = ref();
const orgTableRef = ref();

const state = reactive({
  rsa: "",
  queryParams: {
    queryId: "GetUserList",
    version: "sdk001",
    params: {
      // SITENAME: localStorage.getItem("siteName"),
      USERID: "",
      // USERGROUPNAME: "",
    },
    pageNum: 1,
    pageSize: 10
  },
  total: 0,
  loading: false,
  userList: [] as any,
  dialog: {
    title: "新增用户",
    type: 'add',
    visible: false,
  },
  formData: {
    siteName: "",
    userId: "",
    username: "",
    password: "",
    email: "",
  } as any,
  rules: {
    siteName: [{ required: true, message: "请输入工厂名", trigger: "blur" }],
    userId: [{ required: true, message: "请输入账号", trigger: "blur" }],
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>]).{6,}$/,required: true, message: "请输入有大小写特殊字符不小于6位的密码", trigger: "blur" }],
    email: [{ validator: validateEmail, trigger: 'blur' }],
  },
  column: [] as any,
  selectItem: undefined as any,
  currentTime: "",
  roleDialog: {
    title: "分配角色和组织",
    visible: false,
  },
  allRole: [] as any,
  allOrgList: [] as any,
});
const { allOrgList, rsa, queryParams, total, loading, userList, dialog, formData, rules, column, selectItem, currentTime, roleDialog, allRole } = toRefs(state);

onMounted(() => {
  (state.column = [
    { header: "账号", field: "USERID", hide: false },
    { header: "用户名", field: "USERNAME", hide: false },
    { header: "工厂名", field: "SITENAME", hide: false },
    { header: "邮箱", field: "EMAIL", hide: false },
  ]),
    handleQuery();
  //getRSA();
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});
// 更新列
function updateList(col: any) {
  state.column = col;
}
function getRSA() {
  getRSAPublic()
    .then((res: any) => {
      state.rsa = res.data;
    })
    .catch(() => { });
}
function handleQueryInfo() {
  state.queryParams.pageNum = 1
  handleQuery()
}
function handleQuery() {
  state.userList = []
  getUser(state.queryParams)
    .then((res: any) => {
      if(res.data.userList.list.length == 0){
        ElMessageBox.alert('查无数据', '提醒框', {
          confirmButtonText: 'OK',
        })
      } else {
        state.userList = res.data.userList.list;
        state.total = res.data.userList.total;
        showCurrentTime();
      }
    })
    .catch(() => { });
}
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}
function showCurrentTime() {
  let date = new Date();
  state.currentTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
}


/**
 * 新增用户 dialog
 */
function handleAdd() {
  selectItem.value = undefined;
  dialog.value = {
    title: "新增用户",
    visible: true,
    type: 'add'
  };
}
/**
 * 编辑用户 dialog
 */
function handleUpdate(row: any) {
  state.dialog = {
    title: "编辑用户",
    visible: true,
    type: 'edit'
  };
  state.selectItem = row;
}

function delConfirm(row: any) {
  ElMessageBox.confirm('确认删除?',
    '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    distinguishCancelAndClose: true,
    type: 'warning',
  }).then(() => {
    handleDelete(row);
  })
}
/**
 * 删除
 * */
function handleDelete(row: any) {
  const params = {
    userId: row.USERID,
  };
  deleteUser(params).then((res: any) => {
    if (res.code === "0") {
      proxy.$ElMessage.success("删除成功");
      handleQuery();
    } else {
      proxy.$ElMessage.console.error("删除失败");
    }
  });
}

function dialogOpend() {
  formDataRef.value.resetFields();
  state.formData.password = ''
  state.formData.userId = ''
  if (state.selectItem && state.dialog.type === 'edit') {
    state.formData = {
      siteName: state.selectItem.SITENAME,
      userId: state.selectItem.USERID,
      username: state.selectItem.USERNAME,
      password: state.selectItem.PASSWORD,
      email: state.selectItem.EMAIL,
    };
  }
}

/**
 * 取消关闭弹窗
 */
function cancel() {
  state.dialog.visible = false;
}

/**
 * 保存
 */
function submitForm() {
  formDataRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (state.selectItem) {
        // 编辑
        let params = {
          ...state.formData,
        };

        updateUser(params).then(() => {
          proxy.$ElMessage.success("修改成功");
          cancel();
          handleQuery();
        });
      } else {
        addUser(state.formData).then(() => {
          proxy.$ElMessage.success("新增成功");
          cancel();
          handleQuery();
        });
      }
    }
  });
}

function resetConfirm(row: any) {
  ElMessageBox.confirm('确认重置?',
    '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    distinguishCancelAndClose: true,
    type: 'warning',
  }).then(() => {
    resetPass(row);
  })
}
/**
 * 重置密码
 * */
function resetPass(row: any) {
  let params = {
    siteName: row.SITENAME,
    userId: row.USERID,
    username: row.USERNAME,
    password: "123456",
    email: row.EMAIL
  }

  updateUser(params).then(() => {
    proxy.$ElMessage.success("密码重置成功，当前密码 123456");
    handleQuery();
  });
}
/****************************** 分配角色 ***************************/
function handleRole(row: any) {
  state.roleDialog.visible = true;
  state.allRole = [];
  state.allOrgList = [];
  state.selectItem = row;
}

function cancelRoleDialog() {
  state.roleDialog.visible = false;
}
async function roleDialogOpend() {
  let queryParams = {
    queryId: 'GetRoleList',
    version: 'sdk001',
    params: {
      USERID: localStorage.getItem('userId'),
      USERGROUPNAME: null,
    },
    pageNum: 1,
    pageSize: 100
  };

  getRoleList(queryParams)
    .then((res: any) => {
      state.allRole = res.data.roleList.list;
      // state.total = res.data.roleList.total;

      if (state.selectItem.USERGROUPNAME) {
        let str = state.selectItem.USERGROUPNAME;
        if (str.indexOf(',') != -1) {
          let groupNameList = str.split(',');
          groupNameList.forEach((groupName: any) => {
            const row = state.allRole.find((item: any) => item.USERGROUPNAME === groupName);
            nextTick(() => {
              roleTableRef.value!.toggleRowSelection(row, true);
            });
          })
        } else {
          const row = state.allRole.find((item: any) => item.USERGROUPNAME === str)
          nextTick(() => {
            roleTableRef.value!.toggleRowSelection(row, true);
          });
        }

      }
    })
    .catch(() => { });
    
    let queryOrgParams = {
    queryId: 'GetOrgList',
    version: 'sdk001',
    params: {
      USERID: localStorage.getItem('userId'),
      ORGNO: null,
    },
    pageNum: 1,
    pageSize: 100
  };

    getOrgList(queryOrgParams)
    .then((res: any) => {

      let arrayList = res.data?.orgList?.list || [];
      state.allOrgList = arrayList.filter((item: any) => item.ORGNO !='A' && item.ORGNO !='10101' && item.ORGNO !='116').sort(((a:any,b:any) => a.ORGNO-b.ORGNO));
      
      if (state.selectItem.ORGNO) {
        let str = state.selectItem.ORGNO;
        if (str.indexOf(',') != -1) {
          let groupNameList = str.split(',');
          groupNameList.forEach((groupName: any) => {
            const row = state.allOrgList.find((item: any) => item.ORGNO === groupName);
            nextTick(() => {
              orgTableRef.value!.toggleRowSelection(row, true);
            });
          })
        } else {
          const row = state.allOrgList.find((item: any) => item.ORGNO === str)
          nextTick(() => {
            orgTableRef.value!.toggleRowSelection(row, true);
          });
        }
      }  
    })
    .catch(() => { });
    
}

function submitUserRole() {

  let checkedRole = [] as any;
  roleTableRef.value!.getSelectionRows().forEach((item: any) => {
    checkedRole.push(item.USERGROUPNAME);
  });
  let roleStr = checkedRole.join(',');

  let checkedOrg = [] as any;
  orgTableRef.value!.getSelectionRows().forEach((item: any) => {
    checkedOrg.push(item.ORGNO);
  });
  let orgStr = checkedOrg.join(',');

  updateUserRole({
    userId: state.selectItem.USERID,
    userGroupNames: roleStr,
    orgNo: orgStr
  })
    .then((res: any) => {
      if (res.code === '0') {
        proxy.$ElMessage.success("更新成功");
        cancelRoleDialog();
        handleQuery();
      }

    })
    .catch(() => { });
}
</script>

<style scoped lang="scss">
.el-overlay.userRoleModel {}
</style>
