<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import ElementPlus from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import moment from 'moment'
import { UserFilled } from '@element-plus/icons-vue'
import _ from 'lodash'
import request from '@/util/http'
import API from '@/util/http'
// 客户明细表格   什么表格？？？？？？？
const tableData = ref([])
const total = ref(100)
// 搜索admin
const admin = ref({
  account: '',
  market: '',
  postiton: ''
})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 10
})
// 新增用户权限弹窗
const userAddVisible = ref(false)
// 编辑用户权限弹窗
const userEditVisible = ref(false)
//选地区
const market = ref([])
// 选部门
const postiton = ref([])
// 新增用户对象
const userAddObj = ref({})
// 新增角色对象
const permissionAddObj = ref({})
// 新增角色弹窗
const permissionAddVisible = ref(false)
// 新增用户权限对象，机器码要实现存储多个，addMachineIdInput方法实现
const addAdmin = ref({
  account: '',
  name: '',
  market: [],
  permission: '',
  postiton: '',
  machineId: '', // 初始机器码输入框
  machineIds: [], // 动态添加的机器码输入框
  remark: ''
})
// 新增角色对象
const addRole = ref({
  roleName: '',
  parentName: '',
  checkedKeys: [],
  grade: ''
})
// 新增角色的权限列表
const permissionSelect = ref()
const addMachineIdInput = function () {
  if (addAdmin.value.machineIds.length >= 1) {
    ElMessage.warning('设备数量已达上限')
    return
  }
  addAdmin.value.machineIds.push('')
}

// 编辑用户权限对象
const permissionEditObj = ref({})
// 删除权限对象
const delObj = ref({})
// 各角色权限列表
const lists = [
  { name: '管理员', value: '1', permissions: ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'] },
  { name: '总部财务', value: '2', permissions: ['2', '3', '4', '5', '6', '7', '8', '9'] },
  { name: '总部客服', value: '3', permissions: ['2', '3', '4', '5', '6', '7', '8'] },
  { name: '地区负责人', value: '4', permissions: ['2', '3', '4', '5', '6'] },
  { name: '地区财务', value: '5', permissions: ['2', '3', '4', '5'] },
  { name: '客服专员', value: '6', permissions: ['2', '3'] }
]

const get = async function (val) {
  try {
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    console.log('搜索参数', getObj.value, admin.value)
    const result = await request({
      url: '/permission/getPermission',
      data: {
        ...getObj.value,
        permission: {
          ...admin.value
        }
      }
    })
    tableData.value = result.data.list
    console.log('tableData', tableData.value)
    total.value = result.data.total
  } catch (error) {
    console.log('请求失败', error)
  }
}
const trimJwCode = () => {
  if (admin.value.account) {
    admin.value.account = admin.value.account.replace(/\s/g, '');
  }
}
const search = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  get()
}
// 重置
const reset = function () {
  admin.value = {}
}

const getArea = async function () {
  try {
    const result = await request({
      url: '/permission/getmarket',
      data: {}
    })
    market.value = result.data
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 获取部门
const getStore = async function () {
  try {
    const result = await request({
      url: '/permission/getposition',
      data: {}
    })
    postiton.value = result.data
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 打开新增用户权限弹窗
const openUserAddVisible = function () {
  userAddVisible.value = true
  addAdmin.value = {
    account: '',
    name: '',
    market: '',
    permission: '',
    postiton: '',
    machineId: '',
    machineIds: [],
    remark: ''
  };

}
// 新增角色弹窗
const openPermissionAddVisible = function () {
  permissionAddVisible.value = true
}
// 关闭新增用户权限弹窗，并刷新表单
const closeUserAddVisible = function () {
  addAdmin.value = {
    account: '',
    name: '',
    market: '',
    permission: '',
    postiton: '',
    machineId: '',
    machineIds: [],
    remark: ''
  };
  userAddVisible.value = false;
  // 清除表单验证状态
  Ref.value.resetFields();
}
const closePermissionAddVisible = function () {
  permissionAddVisible.value = false
  Ref.value.resetFields();
}
// 新增用户权限初始化
const userAddInit = function () {
  userAddObj.value = {}
  openUserAddVisible()
}
// 新增角色初始化
const permissionAddInit = function () {
  permissionAddObj.value = {}
  openPermissionAddVisible()
}

const permissionAdd = async function () {
  Ref.value.validate(async (valid) => {
    console.log('addRole', addRole.value)
    console.log('valid', valid)
    if (valid) {
      try {
        addAdmin.value.adminFlag = 1
        addAdmin.value.status1 = 1
        if (addAdmin.value.postiton == '管理员') {
          addAdmin.value.postiton == 1
        }
        const params = {
          "account": addAdmin.value.account,//OA号
          "adminName": addAdmin.value.name,//姓名
          "market": addAdmin.value.market,//地区
          "roleId": addAdmin.value.permission,//权限ID
          "postiton": addAdmin.value.postiton,//职位
          "machineId": addAdmin.value.machineId,//机器码
          "remark": addAdmin.value.remark//备注
        }
        const result = await request({
          url: '/permission/addPermission',
          data: params
        })
        console.log(addAdmin.value)

        if (result.code == 200) {
          ElMessage.success('添加成功')
        } else {
          ElMessage.error(result.msg)
        }

        addAdmin.value = {}
        get()

        closeUserAddVisible()
      } catch (error) {
        console.log('新增用户权限失败', error)

        ElMessage.error('新增用户权限失败')
        closeUserAddVisible()
      }
    } else {
      ElMessage({
        type: 'error',
        message: '请检查输入内容'
      })
    }
  })
}
// 表单验证ref
const Ref = ref(null)
// 使用 _.throttle 并设置 trailing 为 false 实现严格节流，只执行一次
const throttledPermissionAdd = _.throttle(permissionAdd, 5000, {
  trailing: false
})
// 权限类别
const permissionList = [
  {
    label: '管理员',
    value: '1'
  },
  {
    label: '总部财务',
    value: '2'
  },
  {
    label: '总部客服',
    value: '3'
  },
  {
    label: '地区负责人',
    value: '4'
  },
  {
    label: '地区财务',
    value: '5'
  },
  {
    label: '客服专员',
    value: '6'
  }
]

// 打开编辑用户权限弹窗
const openUserEditVisible = function () {
  userEditVisible.value = true
}
// 关闭编辑用户权限弹窗
const closeUserEditVisible = function () {
  userEditVisible.value = false
}
// 编辑用户权限初始化
const permissionEditInit = function (row) {
  permissionEditObj.value = {}
  permissionEditObj.value.id = row.id
  permissionEditObj.value.account = row.account
  permissionEditObj.value.name = row.name
  permissionEditObj.value.market = row.market
  permissionEditObj.value.postiton = row.postiton
  permissionEditObj.value.permission = row.permission
  permissionEditObj.value.roleId = row.roleId
  console.log('编辑用户权限', permissionEditObj.value)
  openUserEditVisible()
}
// 编辑用户权限提交
const permissionEdit = async function () {
  try {
    const result = await request({
      url: '/permission/updateAdminRole',
      data: permissionEditObj.value
    })
    console.log('请求成功3', result)
    ElMessage.success('编辑用户权限成功')
    get()
    closeUserEditVisible()
  } catch (error) {
    console.log('编辑用户权限失败', error)
    ElMessage.error('编辑用户权限失败')
    closeUserEditVisible()
  }
}
const throttledPermissionEdit = _.throttle(permissionEdit, 5000, {
  trailing: false
})
// 删除初始化
const del = function (row) {
  delObj.value = {}
  console.log(row, '删除初始化')
  delObj.value.account = row.account
  delObj.value.id = row.id
}
// 删除权限
const delConfirm = async function () {
  try {
    const result = await request({
      url: '/permission/deleteAdmin',
      data: delObj.value
    })
    console.log('看看删除对象', delObj.value)
    console.log('请求成功1', result)

    ElMessage.success('删除权限成功')
    delObj.value = {}
    get()
  } catch (error) {
    console.log('删除权限失败', error)
    ElMessage.error('删除权限失败')
  }
}
const handleAddRole = async function () {
  try {
    const res = await API({
      url: '/role/add',
      data: {
        "roleName": addRole.value.roleName,
        "menuIds": addRole.value.checkedKeys,
        "priority": addRole.value.grade,
        "fatherId": addRole.value.parentName
      }
    })
    console.log('成功了，看看addRole', addRole.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 禁用启用用户权限
const editStatus = async function (row) {
  try {
    console.log(row)

    permissionEditObj.value = {}
    permissionEditObj.value.id = row.id
    permissionEditObj.value.account = row.account
    permissionEditObj.value.adminStatus = row.adminStatus
    console.log('修改用户权限状态', permissionEditObj.value)

    const result = await request({
      url: '/permission/upadatePermission',
      data: permissionEditObj.value
    })
    console.log('请求成功2', result)
    ElMessage.success(
      permissionEditObj.value.adminStatus == 1 ? '启用成功' : '禁用成功'
    )
    permissionEditObj.value = {}
    get()
  } catch (error) {
    console.log('修改用户权限失败', error)
  }
}

// 挂载
onMounted(async function () {
  await get()
  await getArea()
  await getStore()
})
const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  get()
}
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  get()
}

const data = [
  {
    value: '2',
    label: '工作台'
  },
  {
    value: '3',
    label: '财务审核',
    children: [
      {
        value: '11',
        label: '充值审核'
      },
      {
        value: '13',
        label: '退款审核'
      }, {
        value: '12',//14
        label: '审核操作'
      }
    ]
  },
  {
    value: '4',
    label: '汇率管理'
  }, {
    value: '5',
    label: '充值管理',
    children: [
      {
        value: '17',
        label: '新增充值'
      },
      {
        value: '18',
        label: '金币充值明细'
      }
    ]
  }, {
    value: '6',
    label: '消耗管理',
    children: [
      {
        value: '19',
        label: '新增消耗'
      },
      {
        value: '20',
        label: '金币消耗明细'
      }
    ]
  }, {
    value: '7',
    label: '退款管理',
    children: [
      {
        value: '21',
        label: '新增退款'
      },
      {
        value: '22',
        label: '金币退款明细'
      }
    ]
  }, {
    value: '8',
    label: '客户账户明细',
    children: [
      {
        value: '23',
        label: '客户金币明细'
      },
      {
        value: '24',
        label: '客户金币余额'
      }
    ]
  }, {
    value: '9',
    label: '权限管理'
  }, {
    value: '100',
    label: '地区数据',
    children: [
      {
        value: '101',
        label: '总部'
      },
      {
        value: '102',
        label: '香港'
      },
      {
        value: '103',
        label: '新加坡'
      },
      {
        value: '104',
        label: '马来西亚'
      },
      {
        value: '105',
        label: '越南'
      },
      {
        value: '106',
        label: '韩国'
      }
    ]
  }
]
const filteredData = ref([...data])

watch(() => addRole.value.parentName, (newValue) => {
  if (newValue) {
    const selectedRole = lists.find(role => role.value === newValue)
    if (selectedRole) {
      const allowedPermissions = selectedRole.permissions
      filteredData.value = filterPermissions(data, allowedPermissions)
    } else {
      filteredData.value = data
    }
  } else {
    filteredData.value = data
  }
})

const filterPermissions = (permissions, allowedPermissions) => {
  return permissions.filter(permission => {
    if (allowedPermissions.includes(permission.value)) {
      if (permission.children) {
        permission.children = filterPermissions(permission.children, allowedPermissions)
      }
      return true
    }
    return false
  })
}
const includeHq = computed(() => {
  const i = addAdmin.value.market.includes('总部')
  return (item) => i && item != '总部'
})
const handleCheckChange = (checkedNodes, { checkedKeys }) => {
  addRole.value.checkedKeys = checkedKeys;
};
</script>

<template>
  <!-- 搜索表单 -->
  <el-row>
    <el-col>
      <el-card style="margin-bottom: 20px">
        <div class="head-card">
          <div class="head-card-element">
            <el-text class="mx-1" size="large">OA号：</el-text>
            <el-input v-model="admin.account" style="width: 240px" placeholder="请输入OA号" clearable />
          </div>
          <div class="head-card-element" style="margin-left: 50px">
            <el-text class="mx-1" size="large">所属地区：</el-text>
            <el-select v-model="admin.market" placeholder="请选择所属地区" style="width: 240px" clearable>
              <el-option v-for="item in market" :key="item" :label="item" :value="item" />
            </el-select>
          </div>
          <div class="head-card-element" style="margin-left: 50px">
            <el-text class="mx-1" size="large">职位名称：</el-text>
            <el-select v-model="admin.postiton" placeholder="请选择职位名称" style="width: 240px" clearable>
              <el-option v-for="item in postiton" :key="item" :label="item" :value="item" />
            </el-select>
          </div>

          <div class="head-card-btn">
            <el-button type="success" @click="reset()">重置</el-button>
            <el-button type="primary" @click="search()">查询</el-button>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>

  <el-row>
    <el-col>
      <el-card>
        <!-- 展示表单 -->
        <div class="add-item">
          <el-button style="color: #048efb; border: 1px solid #048efb" @click="userAddInit()">新增用户</el-button>
          <el-button style="color: #048efb; border: 1px solid #048efb" @click="permissionAddInit()">新增角色</el-button>
        </div>

        <div>
          <el-table :data="tableData" style="width: 100%" show-overflow-tooltip>
            <el-table-column type="index" label="序号" width="100px" fixed="left">
              <template #default="scope">
                <span>{{
                  scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="account" label="OA号" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="market" label="所属地区" />
            <el-table-column prop="postiton" label="职位" />
            <el-table-column prop="roleName" label="部门权限">
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
            <el-table-column prop="operation" label="操作" width="200px">
              <template #default="scope">
                <el-button type="warning" text @click="permissionEditInit(scope.row)"
                  :disabled="scope.row.adminStatus === 0">
                  修改权限
                </el-button>
                <el-popconfirm title="确定将此用户删除吗？" @confirm="delConfirm">
                  <template #reference>
                    <el-button type="danger" text @click="del(scope.row)" :disabled="scope.row.adminStatus === 0">
                      删除
                    </el-button>
                  </template>
                  <template #actions="{ confirm, cancel }">
                    <el-button size="small" @click="cancel">取消</el-button>
                    <el-button type="primary" size="small" @click="confirm">
                      确定
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
            <el-table-column prop="adminStatus" label="状态">
              <template #default="scope">
                <el-switch v-model="scope.row.adminStatus" :active-value="1" :inactive-value="0" size="large"
                  @change="editStatus(scope.row)" style="
                    --el-switch-on-color: #13ce66;
                    --el-switch-off-color: #ff4949;
                  " active-text="启用" inactive-text="禁用" inline-prompt />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px">
          <el-pagination background :page-size="getObj.pageSize" :page-sizes="[5, 10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handlePageSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
        </div>
      </el-card>
    </el-col>
  </el-row>
  <!-- 新增用户权限 -->
  <el-dialog v-model="userAddVisible" title="新增用户权限" width="800px" :close-on-click-modal="false">
    <template #footer>
      <!-- 居中显示 -->

      <el-form ref="Ref" :model="addAdmin" label-width="auto" style="max-width: 600px; align-items: center">
        <el-form-item prop="account" label="OA号:" required clearable>
          <el-input v-model="addAdmin.account" placeholder="请输入OA号" style="width: 220px" />
        </el-form-item>

        <el-form-item prop="name" label="用户名:" required clearable>
          <el-input v-model="addAdmin.name" placeholder="请输入用户名" style="width: 220px" />
        </el-form-item>

        <el-form-item prop="market" label="所属地区:" required clearable>
          <el-select multiple v-model="addAdmin.market" placeholder="请选择所属地区" style="width: 440px" clearable>
            <el-option v-for="item in market" :key="item" :label="item" :value="item" :disabled="includeHq(item)" />
          </el-select>
        </el-form-item>
        <el-form-item prop="permission" label="角色名称:" required>
          <el-select v-model="addAdmin.permission" placeholder="请选择角色名称" style="width: 220px" clearable>
            <el-option v-for="item in permissionList" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="postiton" label="职位:" required>
          <el-input v-model="addAdmin.postiton" placeholder="请输入职位" style="width: 220px" clearable />
        </el-form-item>
        <el-form-item prop="machineId" label="机器码:" required>
          <div style="display: flex; align-items: center; flex-wrap: wrap;">
            <el-input v-model="addAdmin.machineId" placeholder="请输入机器码" style="width: 220px; margin-right: 10px;"
              clearable />
            <el-button type="primary" @click="addMachineIdInput">添加</el-button>
            <!-- 动态添加的机器码输入框 -->
            <div v-for="(item, index) in addAdmin.machineIds" :key="index" style="margin-left: 10px;">
              <el-input v-model="addAdmin.machineIds[index]" placeholder="请输入机器码"
                style="width: 180px; margin-right: 10px;" />
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="addAdmin.remark" style="width: 300px" :rows="2" maxlength="100" show-word-limit
            type="textarea" />
        </el-form-item>
      </el-form>

      <div>
        <el-button @click="closeUserAddVisible()">取消</el-button>
        <el-button type="primary" @click="throttledPermissionAdd()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 这是编辑用户权限弹窗 -->
  <el-dialog v-model="userEditVisible" title="编辑用户权限" width="800px" :close-on-click-modal="false">
    <el-form ref="Ref" :model="permissionEditObj" label-width="auto" style="max-width: 600px; align-items: center">
      <el-form-item prop="userName" label="用户名称:" required>
        <el-input v-model="permissionEditObj.userName" placeholder="请输入用户名" style="width: 220px" />
      </el-form-item>
      <el-form-item prop="roleName" label="角色名称:" required>
        <el-input v-model="permissionEditObj.roleName" placeholder="请输入用户名" style="width: 220px" />
      </el-form-item>
      <el-form-item prop="parentName" label="上级角色:" required>
        <el-select v-model="permissionEditObj.parentName" placeholder="请选择上级角色" style="width: 220px">
          <el-option v-for="item in permissionList" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="permissionSelect" label="权限列表:" required>
        <el-tree multiple v-model="permissionEditObj.permissionSelect" :data="data" :render-after-expand="false"
          show-checkbox style="width: 700px" />
      </el-form-item>
    </el-form>
    <div>
    </div>
    <template #footer>
      <div>
        <el-button @click="closeUserEditVisible()">取消</el-button>
        <el-button type="primary" @click="throttledPermissionEdit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增角色 -->
  <el-dialog v-model="permissionAddVisible" title="新增角色" width="800px" :close-on-click-modal="false">
    <template #footer>
      <el-form ref="Ref" :model="addRole" label-width="auto" style="max-width: 600px; align-items: center">
        <el-form-item prop="roleName" label="角色名称:" required>
          <el-input v-model="addRole.roleName" placeholder="请输入用户名" style="width: 220px" />
        </el-form-item>
        <el-form-item prop="parentName" label="上级角色:">
          <el-select v-model="addRole.parentName" placeholder="请选择上级角色" style="width: 220px" clearable>
            <el-option v-for="item in permissionList" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="checkedKeys" label="权限列表:" required>
          <el-tree :data="filteredData" show-checkbox node-key="value" :props="{ label: 'label', children: 'children' }"
            :checked-keys="addRole.checkedKeys" @check="handleCheckChange" />
        </el-form-item>
        <el-form-item prop="grade" label="优先级:" required>
          <el-input v-model="addRole.grade" placeholder="数字1~999" style="width: 220px" />
        </el-form-item>
      </el-form>

      <div>
        <el-button @click="closePermissionAddVisible()">取消</el-button>
        <el-button type="primary" @click="handleAddRole">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.pagination {
  display: flex;
}

.status {
  display: flex;
}

.head-card {
  display: flex;
}

.head-card-element {
  margin-right: 20px;
}

.head-card-btn {
  margin-left: auto;
}

/* 新增样式让弹窗内容居中 */
.el-dialog__body {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-dialog__footer {
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>