<template>
  <div style="margin-bottom: 10px; height: 100%; padding-left: 1%; padding-right: 1%;">
    <el-config-provider :locale="zhCn">
      <div style="display: flex;justify-content: space-between;">
        <el-row>
          <el-input v-model="userNameQuery" style="width: 216px; margin-right: 10px;" placeholder="用户名"
                    :suffix-icon="Search"/>
          <el-button type="primary" @click="search()">搜索</el-button>
          <el-button type="warning" @click="reset()">重置</el-button>
        </el-row>
        <el-row>
          <el-button type="success" @click="addOneUser()">新增用户</el-button>
        </el-row>
      </div>
      <br/>
      <el-table :data="userList" stripe border v-loading="loading" class="table-class" highlight-current-row
                max-height="650px" @row-click="getCurrentRow" :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }">
        <el-table-column width="65px" fixed="left">
          <template v-slot="scope">
            <el-radio :label="scope.row.loginAccount" v-model="loginAccount">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="loginAccount" label="登录账户" min-width="120px" show-overflow-tooltip/>
        <el-table-column prop="userName" label="用户名" min-width="120px" show-overflow-tooltip/>
        <el-table-column prop="addTime" label="添加时间" :formatter="timeFormat" show-overflow-tooltip
                         min-width="120px"/>
        <el-table-column prop="updateTime" label="更新时间" :formatter="timeFormat" min-width="120px"
                         show-overflow-tooltip/>
        <el-table-column prop="addUser" label="添加用户" min-width="120px" show-overflow-tooltip/>
        <el-table-column fixed="right" label="操作" min-width="220px">
          <template v-slot="scope">
            <div style="display: flex;justify-content: space-between;">
              <el-button style="width: 80px" plain type="primary" @click="editCurrentRow(scope.row)">编辑</el-button>
              <el-button style="width: 80px" plain type="warning" @click="changePassword(scope.row)">改密</el-button>
              <el-button v-if="store.getters.getUser?.roleId == 0"  style="width: 80px" plain type="success" @click="openPermissionDialog(scope.row)">权限</el-button>
              <el-button style="width: 80px" plain type="danger" @click="deleteCurrentRow(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 25, 50]"
                     :small="false" :disabled="false" :background="false" :default-page-size="10"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="search"
                     @current-change="search"/>
      <el-dialog v-model="dialogVisible" title="编辑用户信息" width="40%" draggable :show-close="false">
        <div
            style="max-width: 100%; max-height: 500px; overflow: auto; display: flex; justify-content: center;">
          <el-form ref="userFormRef" :model="userFormEntity" :label-position="labelPosition"
                   label-width="100px" style="width: 95%;" :rules="rules" status-icon>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="登录账户" prop="loginAccount">
                  <el-input v-model="userFormEntity.loginAccount" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="userName">
                  <el-input v-model="userFormEntity.userName" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitInfo(userFormEntity)">
                            确定
                        </el-button>
                    </span>
        </template>
      </el-dialog>
      <el-dialog v-model="addUserDialogVisible" title="添加用户信息" width="40%" draggable :show-close="false">
        <div
            style="max-width: 100%; max-height: 350px; overflow: auto; display: flex; justify-content: center;">
          <el-form ref="addUserFormRef" :model="addUserFormEntity" :label-position="labelPosition"
                   label-width="100px" style="width: 95%;" :rules="rules" status-icon>
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="用户名" prop="userNameUpdate">
                  <el-input v-model="addUserFormEntity.userNameUpdate" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12" :offset="0">
                <el-form-item label="登录账户" prop="loginAccountUpdate">
                  <el-input v-model="addUserFormEntity.loginAccountUpdate" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="登录密码" prop="loginPasswordUpdate">
                  <el-input v-model="addUserFormEntity.loginPasswordUpdate" show-password clearable/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="addUserDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitAddUser(addUserFormEntity)">
                            确认添加
                        </el-button>
                    </span>
        </template>
      </el-dialog>
      <el-dialog v-model="passwordDialogVisible" title="修改密码" width="40%" draggable :show-close="false">
        <div style="max-width: 100%; max-height: 350px; overflow: auto; display: flex; justify-content: center;">
          <el-form ref="passwordFormRef" :model="passwordFormEntity" :label-position="labelPosition"
                   label-width="100px" style="width: 95%;" :rules="passwordRules" status-icon>
            <el-row :gutter="16">
              <el-col :span="24">
                <el-form-item label="登录账户">
                  <el-input v-model="passwordFormEntity.loginAccount" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="24">
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input v-model="passwordFormEntity.oldPassword" show-password clearable/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="24">
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="passwordFormEntity.newPassword" show-password clearable/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="24">
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input v-model="passwordFormEntity.confirmPassword" show-password clearable/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPasswordChange(passwordFormEntity)">
          确认修改
        </el-button>
      </span>
        </template>
      </el-dialog>
      <!-- 替换原有的权限弹窗代码 -->
      <el-dialog v-model="permissionDialogVisible" title="设置权限" width="500px" draggable :show-close="false">
        <div style="padding: 20px;">
          <el-card shadow="never" style="margin-bottom: 20px;">
            <template #header>
              <div class="card-header">
                <span>用户信息</span>
              </div>
            </template>
            <el-descriptions :column="1" size="small" border>
              <el-descriptions-item label="登录账户">{{ currentEditUser?.loginAccount }}</el-descriptions-item>
              <el-descriptions-item label="用户名">{{ currentEditUser?.userName }}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <el-card shadow="never">
            <template #header>
              <div class="card-header">
                <span>权限配置</span>
              </div>
            </template>

            <div class="permission-section">
              <div class="section-title">
                <i class="el-icon-setting"></i>
                <span>WMS权限</span>
              </div>
              <el-checkbox-group v-model="wmsPermissions" class="permission-checkbox-group">
                <el-row :gutter="15">
                  <el-col :span="12" v-for="perm in wmsPermissionOptions" :key="perm.value">
                    <el-checkbox :label="perm.value" :border="true" style="width: 100%; margin-bottom: 10px;">
                      {{ perm.label }}
                    </el-checkbox>
                  </el-col>
                </el-row>
              </el-checkbox-group>
            </div>

            <div class="permission-section" style="margin-top: 20px;">
              <div class="section-title">
                <i class="el-icon-mobile"></i>
                <span>PDA权限</span>
              </div>
              <el-checkbox
                  v-model="hasPdaPermission"
                  label="E"
                  border
                  style="width: 100%; margin-top: 10px;">
                PDA操作权限
              </el-checkbox>
            </div>
          </el-card>
        </div>

        <template #footer>
    <span class="dialog-footer">
      <el-button @click="permissionDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitPermissionChange()">确 定</el-button>
    </span>
        </template>
      </el-dialog>

    </el-config-provider>
  </div>
</template>

<script setup>
import store from '@/store'
import {setUserPermission, getUserPermission, getUserList, getRoleOptions, updateUserInfo, addUserInfo, deleteUserInfo, changePasswordInfo} from '@/api/user.js'
import {errorBox} from '@/utils/myMessageBox.js'
import {ElMessageBox, ElMessage} from 'element-plus'
import {ref, reactive} from 'vue'
import {dateFormatter, timeFormatter} from '@/utils/formatter.js'
import {Search} from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
</script>
<script>

export default {
  name: 'role_user',
  data() {
    // 密码确认规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.passwordFormEntity.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      userList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userNameQuery: '',
      loading: true,
      dialogVisible: false,
      loginAccount: '',
      userFormEntity: reactive({}),
      userFormRef: ref(),
      labelPosition: 'top',
      rules: reactive({}),
      roleOptions: [],
      addUserDialogVisible: false,
      addUserFormEntity: reactive({}),
      addUserFormRef: ref(),


// 在 data 的 return 中添加以下内容
      permissionDialogVisible: false,
      permissionFormEntity: reactive({}),
      permissionFormRef: ref(),
      currentEditUser: null,
      wmsPermissions: [],
      hasPdaPermission: false,
      wmsPermissionOptions: [
        { value: 'A', label: '下发盘点' },
        { value: 'B', label: '出库单编排' },
        { value: 'C', label: '出空箱' },
        { value: 'D', label: '拣选任务状态编辑' }
      ],

      passwordDialogVisible: false,
      passwordFormEntity: reactive({
        loginAccount: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }),
      passwordFormRef: ref(),
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }

    }
  },
  mounted() {
    this.search()
    console.log('当前用户信息:', store.getters.getUser)
    console.log('当前用户roleId:', store.getters.getUser?.roleId)
  },
  methods: {
    // 添加修改密码相关方法
    changePassword(row) {
      this.passwordFormEntity = {
        loginAccount: row.loginAccount,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      this.passwordDialogVisible = true
    },

    getRoleOptions() {
      const request = {
        roleId: store.getters.getUser.roleId,
      }
      getRoleOptions(request).then(res => {
        const tableResponse = res.data
        if (tableResponse.code == 0) {
          this.roleOptions = tableResponse.data
        } else {
          this.roleOptions = []
        }
      }).catch(err => {
        console.log(err)
        this.roleOptions = []
      })
    },
    search() {
      this.loading = true
      const request = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        userName: store.getters.getUserName,
        roleId: store.getters.getUser.roleId,
      }
      getUserList(request).then(res => {
        const tableResponse = res.data
        if (tableResponse.code == 0) {
          this.userList = tableResponse.data.lists
          this.total = tableResponse.data.total
        } else {
          errorBox(tableResponse.message)
        }
      }).catch(err => {
        console.log(err)
        errorBox('查询用户列表错误')
      })
      this.loading = false
    },
    dateFormat: (row, column, cellValue, index) => {
      return dateFormatter(cellValue)
    },
    timeFormat: (row, column, cellValue, index) => {
      return timeFormatter(cellValue)
    },
    roleFormat(row, column, cellValue, index) {
      const roleOptionInfo = this.roleOptions.find(item => {
        return item.value == cellValue
      })
      return roleOptionInfo == null | undefined ? '未知角色' : roleOptionInfo.label
    },
    reset() {
      this.userNameQuery = ''
      this.search()
    },
    editCurrentRow(row) {
      this.userId = row.userId
      this.userFormEntity = {
        userId: row.userId,
        userName: row.userName,
        loginAccount: row.loginAccount,
        roleId: row.roleId,
      }
      // this.getRoleOptions()
      this.dialogVisible = true
    },
    submitPasswordChange(formData) {
      this.$refs.passwordFormRef.validate((valid) => {
        if (valid) {
          const params = {
            loginAccountUpdate: formData.loginAccount,
            oldPassword: formData.oldPassword,
            newPassword: formData.newPassword,
            roleIdOp: store.getters.getUser.roleId,
            userName: store.getters.getUserName
          }

          // 调用修改密码的API（假设为 changePassword API）
          changePasswordInfo(params).then(res => {
            if (res.data.code === 0) {
              this.passwordDialogVisible = false
              ElMessage.success('密码修改成功。')
            } else {
              errorBox(res.data.message)
            }
          }).catch(err => {
            console.log(err)
            errorBox('密码修改失败。')
          })
        }
      })
    },
    deleteCurrentRow(row) {
      this.loginAccount = row.loginAccount
      ElMessageBox.confirm(
          '该操作会从数据库中删除用户。\n是否继续',
          '警告',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        const params = {
          loginAccountUpdate: row.loginAccount,
          roleIdOp: store.getters.getUser.roleId,
          userName: store.getters.getUserName
        }
        deleteUserInfo(params).then(res => {
          if (res.data.code == 0) {
            ElMessage.success('删除用户信息成功。')
            this.search()
          } else {
            errorBox(res.data.message)
          }
        }).catch(err => {
          console.log(err)
          errorBox('删除用户信息失败。')
        })
      }).catch(() => {
        ElMessage.info('操作取消')
      })
    },
    addOneUser() {
      this.addUserFormEntity = {
        roleIdUpdate: null,
        userNameUpdate: '',
        loginAccountUpdate: '',
        loginPasswordUpdate: '',
      }
      this.getRoleOptions()
      this.addUserDialogVisible = true
    },
    submitInfo(formData) {
      const params = {
        roleIdUpdate: formData.roleId,
        userNameUpdate: formData.userName,
        loginAccountUpdate: formData.loginAccount,
        roleIdOp: store.getters.getUser.roleId,
        userName: store.getters.getUserName
      }
      updateUserInfo(params).then(res => {
        if (res.data.code == 0) {
          this.dialogVisible = false
          ElMessage.success('更新用户信息成功。')
          this.search()
        } else {
          errorBox(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        errorBox('更新用户信息失败。')
      })
    },
    submitAddUser(formData) {
      const params = {
        roleIdUpdate: formData.roleIdUpdate,
        userNameUpdate: formData.userNameUpdate,
        loginAccountUpdate: formData.loginAccountUpdate,
        loginPasswordUpdate: formData.loginPasswordUpdate,
        roleIdOp: store.getters.getUser.roleId,
        userName: store.getters.getUserName
      }
      addUserInfo(params).then(res => {
        if (res.data.code === 0) {
          this.addUserDialogVisible = false
          ElMessage.success('添加用户信息成功。')
          this.search()
        } else {
          errorBox(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        errorBox('添加用户信息失败。')
      })
    },

    // 在 methods 中添加以下方法
    openPermissionDialog(row) {
      this.currentEditUser = row;

      // 调用后端接口获取用户权限
      const params = {
        loginAccountUpdate: row.loginAccount,
        roleIdOp: store.getters.getUser.roleId,
        userName: store.getters.getUserName
      };

      getUserPermission(params).then(res => {
        if (res.data.code === 0) {
          // 解析后端返回的权限字符串
          const permissionStr = res.data.message || '';
          this.wmsPermissions = [];
          this.hasPdaPermission = false;

          console.log(permissionStr);
          if (permissionStr.includes('A')) this.wmsPermissions.push('A');
          if (permissionStr.includes('B')) this.wmsPermissions.push('B');
          if (permissionStr.includes('C')) this.wmsPermissions.push('C');
          if (permissionStr.includes('D')) this.wmsPermissions.push('D');
          if (permissionStr.includes('E')) this.hasPdaPermission = true;
        } else {
          // 如果获取失败，使用默认空值
          this.wmsPermissions = [];
          this.hasPdaPermission = false;
          errorBox(res.data.message);
        }

        this.permissionDialogVisible = true;
      }).catch(err => {
        console.log(err);
        // 如果请求失败，使用默认空值
        this.wmsPermissions = [];
        this.hasPdaPermission = false;
        this.permissionDialogVisible = true;
        errorBox('获取用户权限失败');
      });
    },


    submitPermissionChange() {
      // 构建权限字符串
      let permissionStr = '';
      permissionStr += this.wmsPermissions.join('');
      if (this.hasPdaPermission) permissionStr += 'E';

      // 这里调用设置权限的API
      // 示例:
      const params = {
        loginAccountUpdate: this.currentEditUser.loginAccount,
        userPermission: permissionStr,
        roleIdOp: store.getters.getUser.roleId,
        userName: store.getters.getUserName
      };

      setUserPermission(params).then(res => {
        if (res.data.code === 0) {
          this.permissionDialogVisible = false;
          ElMessage.success('权限设置成功。');
          this.search(); // 刷新列表
        } else {
          errorBox(res.data.message);
        }
      }).catch(err => {
        console.log(err);
        errorBox('权限设置失败。');
      });


      // 暂时只是演示逻辑，实际需要调用后端API
      ElMessage.success('权限设置成功。');
      console.log(permissionStr)
      this.permissionDialogVisible = false;
    },


    getCurrentRow(row) {
      this.userId = row.userId
    },
  },
}
</script>

<style scoped>
.el-pagination {
  padding-left: 5px;
}

.el-row .el-button {
  width: 72px;
  margin-left: 0px;
  margin-right: 5px;
}

.table-class {
  width: 100%;
}

.el-row .el-form-item {
  width: 10% inherit;
  justify-content: center;
}

.el-row .el-form-item .el-select-v2 {
  width: 100% !important;
}

.el-row .el-form-item .el-input-number {
  width: 100% !important;
}

.el-row .el-form-item .el-button {
  margin: auto;
}

.title-area {
  display: flex;
  /* min-height: 10%; */
  max-height: max-content;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  flex-direction: column;
  padding: 10px;
}
</style>
<style scoped>/* 在原有样式基础上添加以下内容 */
.card-header {
  font-weight: bold;
  color: #303133;
}

.permission-section {
  padding: 10px 0;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #606266;
  display: flex;
  align-items: center;
}

.section-title i {
  margin-right: 8px;
  font-size: 18px;
}

.permission-checkbox-group {
  width: 100%;
}

.permission-checkbox-group .el-checkbox {
  margin-right: 0;
}

:deep(.el-card__header) {
  background-color: #f5f7fa;
  padding: 10px 20px;
}

:deep(.el-descriptions__label) {
  width: 100px !important;
}

:deep(.el-checkbox.is-bordered) {
  padding: 8px 15px;
}

:deep(.el-checkbox.is-bordered:hover) {
  border-color: #409eff;
}

.dialog-footer {
  padding: 15px 20px;
}
</style>