<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'

// 客户明细表格
const tableData = ref([])
// 搜索===========================================
//分页总条目
const total = ref(100)
// 搜索admin
const admin = ref({})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 10
})
// 新增用户权限弹窗
const permissionAddVisible = ref(false)
// 编辑用户权限弹窗
const permissionEditVisible = ref(false)
//选地区
const area = ref([])
// 选部门
const store = ref([])
// 新增用户权限对象
const permissionAddObj = ref({})
// 新增用户权限对象
const addAdmin = ref({})
// 编辑用户权限对象
const permissionEditObj = ref({})
// 删除权限对象
const delObj = ref({})

// 搜索接口search
const get = async function (val) {
  try {
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    console.log('搜索参数', getObj.value)
    // 发送POST请求
    const result = await request({
      url: '/admin/search',
      data: {
        ...getObj.value,
        admin: { ...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.jwcode) {
    admin.value.jwcode = admin.value.jwcode.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: '/admin/area',
      data: {}
    })
    area.value = result.data
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
// 获取部门
const getStore = async function () {
  try {
    const result = await request({
      url: '/admin/store',
      data: {}
    })
    store.value = result.data
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}

// 验证跳转输入框的数字是否合法
const checkNumber = function () {
  if (typeof parseInt(getObj.value.pageNum) === 'number') {
    console.log('总共有多少页' + Math.ceil(total.value / getObj.value.pageSize))
    if (
      getObj.value.pageNum > 0 &&
      getObj.value.pageNum <= Math.ceil(total.value / getObj.value.pageSize)
    ) {
      getObj.value.pageNum = parseInt(getObj.value.pageNum)
      console.log('输入的数字合法')
      get()
    } else {
      //提示
      ElMessage({
        type: 'error',
        message: '请检查输入内容'
      })
    }
  } else {
    //提示
    ElMessage({
      type: 'error',
      message: '请检查输入内容'
    })
  }
}

// 打开新增用户权限弹窗
const openPermissionAddVisible = function () {
  permissionAddVisible.value = true
}
// 关闭新增用户权限弹窗
const closePermissionAddVisible = function () {
  permissionAddVisible.value = false
}
// 新增用户权限初始化
const permissionAddInit = function () {
  permissionAddObj.value = {}
  openPermissionAddVisible()
}
// 通过精网号查询没有权限的用户
const getAdminByJwcodeWithoutPermission = async function () {
  try {
    const result = await request({
      url: '/admin/selectNo',
      data: permissionAddObj.value
    })
    if (result.code == 200) {
      permissionAddObj.value = result.data[0]
      ElMessage.success('精网号查询成功')
    } else {
      ElMessage.error(result.msg)
    }
    console.log('精网号查询没有权限的用户', permissionAddObj.value)
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
// 新增用户权限提交
// const permissionAdd = async function () {
//   try {
//     if (
//       permissionAddObj.value.jwcode == "" ||
//       permissionAddObj.value.jwcode == null ||
//       permissionAddObj.value.name == "" ||
//       permissionAddObj.value.name == null
//     ) {
//       ElMessage.error("请选择要添加权限的用户");
//       return;
//     }
//     if (
//       permissionAddObj.value.permisson == "" ||
//       permissionAddObj.value.permission == null
//     ) {
//       ElMessage.error("请选择权限");
//       return;
//     }
//     console.log("新增用户权限提交", permissionAddObj.value);

//     const result = await request(
//       {
// url: "/admin/update",
//       data: permissionAddObj.value}
//     );

//     // 将响应结果存储到响应式数据中
//     console.log("请求成功", result);

//     ElMessage.success("添加成功");

//     get();

//     closePermissionAddVisible();
//   } catch (error) {
//     console.log("新增用户权限失败", error);
//     // 在这里可以处理错误逻辑，比如显示错误提示等

//     ElMessage.error("新增用户权限失败");
//     closePermissionAddVisible();
//   }
// };
const permissionAdd = async function () {
  Ref.value.validate(async (valid) => {
    console.log('valid', valid)
    if (valid) {
      try {
        addAdmin.value.adminFlag = 1
        addAdmin.value.status1 = 1
        const result = await request({
          url: '/admin/add',
          data: addAdmin.value
        })

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

        addAdmin.value = {}
        get()

        closePermissionAddVisible()
      } catch (error) {
        console.log('新增用户权限失败', error)
        // 在这里可以处理错误逻辑，比如显示错误提示等

        ElMessage.error('新增用户权限失败')
        closePermissionAddVisible()
      }
    } else {
      //提示
      ElMessage({
        type: 'error',
        message: '请检查输入内容'
      })
    }
  })
}
// 表格添加的条件
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 permissionList = [
  {
    label: '总部',
    value: '1'
  },
  {
    label: '地区经理',
    value: '5'
  },
  {
    label: '财务',
    value: '3'
  },
  {
    label: '客服',
    value: '2'
  }
]
// 获取地区
// 获取地区
const areaList = ref([])
const getAreas = async function () {
  try {
    // 发送POST请求
    const result = await request({
      url: '/recharge/user/search',
      data: {}
    })

    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 存储地区信息
    areaList.value = result.data
    console.log('地区', area.value)
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
getAreas()
// 打开编辑用户权限弹窗
const openPermissionEditVisible = function () {
  permissionEditVisible.value = true
}
// 关闭编辑用户权限弹窗
const closePermissionEditVisible = function () {
  permissionEditVisible.value = false
}
// 编辑用户权限初始化
const permissionEditInit = function (row) {
  permissionEditObj.value = {}
  permissionEditObj.value.jwcode = row.jwcode
  permissionEditObj.value.name = row.name
  permissionEditObj.value.area = row.area
  permissionEditObj.value.store = row.store
  permissionEditObj.value.permission = row.permission
  console.log('编辑用户权限', permissionEditObj.value)
  openPermissionEditVisible()
}
// 编辑用户权限提交
const permissionEdit = async function () {
  try {
    const result = await request({
      url: '/admin/update',
      data: permissionEditObj.value
    })

    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)

    ElMessage.success('编辑用户权限成功')

    get()

    closePermissionEditVisible()
  } catch (error) {
    console.log('编辑用户权限失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
    ElMessage.error('编辑用户权限失败')

    closePermissionEditVisible()
  }
}
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: '/admin/update',
      data: delObj.value
    })

    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)

    ElMessage.success('删除权限成功')
    delObj.value = {}
    get()
  } catch (error) {
    console.log('删除权限失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
    ElMessage.error('删除权限失败')
  }
}
// 禁用启用用户权限
const editStatus = async function (row) {
  try {
    console.log(row)

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

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

    const result = await request({
      url: '/admin/update',
      data: permissionEditObj.value
    })

    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)

    ElMessage.success(
      permissionEditObj.value.status1 == 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()
}
</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">精网号：</el-text>
            <el-input
              v-model="admin.jwcode"
              style="width: 240px"
              placeholder="请输入精网号"
              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.area"
              placeholder="请选择所属地区"
              style="width: 240px"
              clearable
            >
              <el-option
                v-for="item in area"
                :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.store"
              placeholder="请选择职位名称"
              style="width: 240px"
              clearable
            >
              <el-option
                v-for="item in store"
                :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="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">
                <span>{{
                  scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="jwcode" label="精网号" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="area" label="所属地区" />
            <el-table-column prop="store" label="职位" />
            <el-table-column prop="permission" label="部门权限">
              <template #default="scope">
                <span v-if="scope.row.permission === '1'"> 总部管理员 </span>
                <span v-if="scope.row.permission === '2'"> 分部财务 </span>
                <span v-if="scope.row.permission === '3'"> 分部客服 </span>
                <span v-if="scope.row.permission === '5'"> 分部经理 </span>
              </template>
            </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.status1 === 0"
                >
                  修改权限
                </el-button>
                <el-popconfirm
                  title="确定将此用户删除吗？"
                  @confirm="delConfirm"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      text
                      @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="状态">
              <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="禁用"
                  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="permissionAddVisible"
    title="新增用户权限"
    width="800px"
    :close-on-click-modal="false"
  >
    <template #footer>
      <!-- 居中显示 -->

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

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

        <el-form-item prop="area" label="所属地区:">
          <el-select
            v-model="addAdmin.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="addAdmin.permission"
            placeholder="请选择权限"
            style="width: 220px"
            @change="() => Ref.value.validateField('permission')"
          >
            <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="store" label="职位:">
          <el-input
            v-model="addAdmin.store"
            placeholder="请输入职称"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item prop="machineId" label="机器码:">
          <el-input
            v-model="addAdmin.machineId"
            placeholder="请输入机器码"
            style="width: 220px"
          />
        </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="closePermissionAddVisible()">取消</el-button>
        <el-button type="primary" @click="throttledPermissionAdd()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 这是新增用户权限弹窗
  <el-dialog
    v-model="permissionAddVisible"
    title="新增用户权限"
    width="800px"
    :close-on-click-modal="false"
  >
    <div style="display: flex; margin: 20px 0px 20px 0px">
      <span class="permissionVisible" style="margin-right: 10px">精网号:</span>
      <el-input
        placeholder="请输入精网号"
        v-model="permissionAddObj.jwcode"
        style="width: 240px; margin-right: 10px"
        clearable
      ></el-input>
      <el-button type="primary" @click="getAdminByJwcodeWithoutPermission()"
        >查询</el-button
      >
    </div>

    <el-descriptions
      class="margin-top"
      :column="2"
      :size="size"
      border
      label-width="200px"
    >
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon>
              <UserFilled />
            </el-icon>
            员工精网号
          </div>
        </template>
        {{ permissionAddObj.jwcode }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon>
              <User />
            </el-icon>
            员工姓名
          </div>
        </template>
        {{ permissionAddObj.name }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon :style="iconStyle">
              <location />
            </el-icon>
            所属地区
          </div>
        </template>
        {{ permissionAddObj.area }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon>
              <OfficeBuilding />
            </el-icon>
            部门
          </div>
        </template>
        {{ permissionAddObj.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="permissionAddObj.permission">
        <el-radio value="1" border>总部管理员</el-radio>
        <el-radio value="5" border>分部经理</el-radio>
        <el-radio value="2" border>分部财务</el-radio>
        <el-radio value="3" border>分部客服</el-radio>
      </el-radio-group>
    </div>
    <template #footer>
      <div>
        <el-button @click="closePermissionAddVisible()">取消</el-button>
        <el-button type="primary" @click="throttledPermissionAdd()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog> -->

  <!-- 这是编辑用户权限弹窗 -->
  <el-dialog
    v-model="permissionEditVisible"
    title="编辑用户权限"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-descriptions
      class="margin-top"
      :column="2"
      :size="size"
      border
      label-width="200px"
    >
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon>
              <UserFilled />
            </el-icon>
            员工精网号
          </div>
        </template>
        {{ permissionEditObj.jwcode }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon>
              <User />
            </el-icon>
            员工姓名
          </div>
        </template>
        {{ permissionEditObj.name }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon :style="iconStyle">
              <location />
            </el-icon>
            所属地区
          </div>
        </template>
        {{ permissionEditObj.area }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="permissionVisible">
            <el-icon>
              <OfficeBuilding />
            </el-icon>
            部门
          </div>
        </template>
        {{ permissionEditObj.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="permissionEditObj.permission">
        <el-radio value="1" border>总部管理员</el-radio>
        <el-radio value="5" border>分部经理</el-radio>
        <el-radio value="2" border>分部财务</el-radio>
        <el-radio value="3" border>分部客服</el-radio>
      </el-radio-group>
    </div>
    <template #footer>
      <div>
        <el-button @click="closePermissionEditVisible()">取消</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;
}

.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>
