<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import ElementPlus from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import moment from 'moment'
import { ta } from 'element-plus/es/locales.mjs'
import { UserFilled } from '@element-plus/icons-vue'
import _ from 'lodash'
import request from '@/util/http'

<<<<<<< HEAD
=======
// 客户明细表格
>>>>>>> milestone-20250623-金币前端
const tableData = ref([])
//分页总条目
const total = ref(100)
<<<<<<< HEAD
=======
// 搜索admin
>>>>>>> milestone-20250623-金币前端
const admin = ref({})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 10
})
// 控制新增权限弹窗的
const addVisible = ref(false)
// 控制编辑权限弹窗的
const editVisible = ref(false)
const area = ref([])
const store = ref([])// 好像是部门
// 新增权限的对象，做初始化的
const addInit = ref({})
// 新增权限对象，传给后端的
const addObj = ref({})
// 编辑权限的对象
const editObj = ref({})
// 删除权限的对象
const delObj = ref({})

<<<<<<< HEAD
=======
// 搜索接口search
>>>>>>> milestone-20250623-金币前端
const get = async function (val) {
  try {
    if (admin.value.jwcode) {
      admin.value.jwcode = admin.value.jwcode.replace(/\s/g, '');
    }
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    } else {
      getObj.value.pageNum = 1
    }
    const result = await request({
      url: '',// 待补充
      data: {
        ...getObj.value,
        admin: { ...admin.value }
      }
    })
    tableData.value = result.data.list
    total.value = result.data.total
  } catch (error) {
    console.log('请求失败', error)
  }
}

const reset = function () {
  admin.value = {}
}
const getArea = async function () {
  try {
    const result = await request({
      url: '',
      data: {}
    })
    area.value = result.data
  } catch (error) {
    console.log('请求失败', error)
  }
}
const getStore = async function () {
  try {
    const result = await request({
      url: '',
      data: {}
    })
    store.value = result.data
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 打开新增用户权限弹窗
const openaddVisible = function () {
  addVisible.value = true
}
// 关闭新增用户权限弹窗
const closeaddVisible = function () {
  addVisible.value = false
}
// 新增用户权限初始化
const permissionAddInit = function () {
  addInit.value = {}
  openaddVisible()
}

const permissionAdd = async function () {
  Ref.value.validate(async (valid) => {
    if (valid) {
      try {
        addObj.value.adminFlag = 1
        addObj.value.status1 = 1
        const result = await request({
          url: '',
          data: addObj.value
        })

        if (result.code == 200) {
          ElMessage.success('添加成功')
        } else {
          ElMessage.error(result.msg)
        }
        addObj.value = {}
        closeaddVisible()
        get()
      } catch (error) {
        console.log('新增用户权限失败', error)
        ElMessage.error('新增用户权限失败')
        closeaddVisible()
      }
    } else {
      ElMessage({
        type: 'error',
        message: '请检查输入内容'
      })
    }
  })
} // 这个要简化，哪来那么多if-else

const rules = reactive({// 只有一个必填属性的话，能否直接设置在表单中
  jwcode: [{ required: true, message: '请输入精网号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  store: [{ required: true, message: '请输入职称', trigger: 'blur' }],
  machineId: [{ required: true, message: '请输入精网号', trigger: 'blur' }],
  area: [{ required: true, message: '请选择所属地区', trigger: 'blur' }],
  permission: [{ required: true, message: '请选择权限', trigger: 'blur' }]
})
// 表单验证ref
const Ref = ref(null)
// 使用 _.throttle 并设置 trailing 为 false 实现严格节流，只执行一次  节吗呢?什么鬼
const throttledPermissionAdd = _.throttle(permissionAdd, 5000, {
  trailing: false
})
// 权限类别
const list = [
  {
    label: '总部',
    value: '1'
  },
  {
    label: '',
    value: ''
  }
]
// 地区列表
const areaList = ref([])
const getAreas = async function () {
  try {
    const result = await request({
      url: '',
      data: {}
    })
    console.log('result', result)
    areaList.value = result.data
    console.log('地区', area.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 打开编辑用户权限弹窗
const openVisable = function () {
  editVisible.value = true
}
// 关闭编辑用户权限弹窗
const closeEdit = function () {
  editVisible.value = false
}
// 编辑用户权限初始化
const editInit = function (row) {
  editObj.value = {}
  editObj.value.jwcode = row.jwcode
  editObj.value.name = row.name
  editObj.value.area = row.area
  editObj.value.store = row.store
  editObj.value.permission = row.permission
  console.log('编辑用户权限', editObj.value)
  openVisable()
}
// 编辑用户权限提交
const permissionEdit = async function () {
  try {
    const result = await request({
      url: '',
      data: editObj.value
    })
    console.log('请求成功', result)
    ElMessage.success('编辑用户权限成功')
    closeEdit()
    get()
  } catch (error) {
    ElMessage.error('编辑用户权限失败')
    closeEdit()
  }
}
const throttledPermissionEdit = _.throttle(permissionEdit, 5000, {
  trailing: false
})
// 删除初始化
const del = function (row) {
  delObj.value = {}
  console.log(row, '删除初始化')
  delObj.value.jwcode = row.jwcode
}
// 删除权限
const delConfirm = async function () {
  try {
    delObj.value.permission = '4'
    console.log(delObj.value)

    const result = await request({
      url: '',
      data: delObj.value
    })

    console.log('请求成功', result)
    ElMessage.success('删除权限成功')
    delObj.value = {}
    get()
  } catch (error) {
    console.log('删除权限失败', error)
    ElMessage.error('删除权限失败')
    get()
  }
}
// 禁用启用用户权限
const editStatus = async function (row) {
  try {
    console.log(row)

    editObj.value = {}
    editObj.value.jwcode = row.jwcode
    editObj.value.status1 = row.status1

    console.log('修改用户权限状态', editObj.value)

    const result = await request({
      url: '',
      data: editObj.value
    })
    console.log('请求成功', result)

    ElMessage.success(
      editObj.value.status1 == 1 ? '启用成功' : '禁用成功'
    )
    editObj.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()
}
</script>

<template>
  <el-row>
    <el-col>
      <el-card style="margin-bottom: 20px">
        <div style="display:flex">
          <div>
            <el-text size="large">OA号：</el-text>
            <el-input v-model="admin.jwcode" style="width: 240px" placeholder="请输入OA号" clearable />
          </div>
          <div style="margin-left: 50px">
            <el-text size="large">所属地区：</el-text>
            <el-select v-model="admin.area" placeholder="请选择所属地区" style="width: 240px" clearable>
              <el-option v-for="item in area" :key="item" :label="item" :value="item" />
            </el-select>
          </div>
          <div style="margin-left: 50px">
            <el-text size="large">职位名称：</el-text>
            <el-select v-model="admin.store" placeholder="请选择职位名称" style="width: 240px" clearable>
              <el-option v-for="item in store" :key="item" :label="item" :value="item" />
            </el-select>
          </div>
          <div style="margin-left:20px">
            <el-button type="success" @click="reset()">重置</el-button>
            <el-button type="primary" @click="get()">查询</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="permissionAddInit()">新增用户</el-button>
        </div>

        <div>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="100px" fixed="left"><!-- 序号始终固定在左边 -->
              <template #default="scope">
                <!-- index下标从0开始，计算时要+1；后面算页数，(num页码数-1) * 每页记录数，加起来是总条数 -->
                <span>{{ scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="jwcode" label="精网号" width="120px" />
            <el-table-column prop="name" label="姓名" width="120px" />
            <el-table-column prop="area" label="所属地区" width="120px" />
            <el-table-column prop="store" label="职位" width="120px" />
            <el-table-column prop="permission" label="部门权限" width="120px">
              <template #default="scope">
                <span v-if="scope.row.permission === '1'">总部管理员</span>
                待补充..................................................................................................
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="200px" show-overflow-tooltip />
            <el-table-column prop="operation" label="操作" width="200px">
              <template #default="scope">
                <el-button type="warning" @click="editInit(scope.row)"
                  :disabled="scope.row.status1 === 0">修改权限</el-button>
                <el-popconfirm title="确定将此用户删除吗？" @confirm="delConfirm">
                  <template #reference>
                    <el-button type="danger" @click="del(scope.row)" :disabled="scope.row.status1 === 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="status1" label="状态" width="200px">
              <template #default="scope">
                <el-switch v-model="scope.row.status1" :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="禁用" />
              </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="addVisible" title="新增用户权限" :close-on-click-modal="false">
    <template #footer>
      <el-form ref="Ref" :rules="rules" :model="addObj" label-width="auto" style="align-items: center"  >
        <el-form-item prop="jwcode" label="精网号:">
          <el-input v-model="addObj.jwcode" placeholder="请输入精网号" style="width: 220px" />
        </el-form-item>
        <el-form-item prop="name" label="用户名:">
          <el-input v-model="addObj.name" placeholder="请输入用户名" style="width: 220px" />
        </el-form-item>
        <el-form-item prop="area" label="所属地区:">
          <el-select v-model="addObj.area" placeholder="请选择所属地区" style="width: 220px"
            @change="() => Ref.value.validateField('area')">
            <el-option v-for="item in areaList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="permission" label="权限类别:">
          <el-select v-model="addObj.permission" placeholder="请选择权限" style="width: 220px"
            @change="() => Ref.value.validateField('permission')">
            <el-option v-for="item in list" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="store" label="职位:">
          <el-input v-model="addObj.store" placeholder="请输入职称" style="width: 220px" />
        </el-form-item>
        <el-form-item prop="machineId" label="机器码:">
          <el-input v-model="addObj.machineId" placeholder="请输入机器码" style="width: 220px" />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="addObj.remark" style="width: 300px" :rows="2" maxlength="100" show-word-limit
            type="textarea" />
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="closeaddVisible()">取消</el-button>
        <el-button type="primary" @click="throttledPermissionAdd()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 这是编辑用户权限弹窗 -->
  <el-dialog v-model="editVisible" title="编辑用户权限" width="800px" :close-on-click-modal="false">
    <el-descriptions :column="2" :size="size" border label-width="200px">
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon><UserFilled /></el-icon>
            员工精网号
          </div>
        </template>
        {{ editObj.jwcode }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon><User /></el-icon>
            员工姓名
          </div>
        </template>
        {{ editObj.name }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon><location /></el-icon>
            所属地区
          </div>
        </template>
        {{ editObj.area }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon><OfficeBuilding /></el-icon>
            部门
          </div>
        </template>
        {{ editObj.store }}
      </el-descriptions-item>
    </el-descriptions>
    <el-divider>
      <el-icon><star-filled /></el-icon>
    </el-divider>
    <div>
      <span class="permissionVisible" style="margin-right: 20px">权限设置:</span>
      <el-radio-group v-model="editObj.permission">
        <el-radio value="1" border>总部管理员</el-radio>
        ..............................................................................待补充
      </el-radio-group>
    </div>
    <template #footer>
      <div>
        <el-button @click="closeEdit()">取消</el-button>
        <el-button type="primary" @click="throttledPermissionEdit()">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.permissionVisible {
  font-size: 16px;
  font-weight: bold;
}

.pagination {
  display: flex;
}

.head-card {
  display: flex;
}

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

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