<template>
  <div>
    <Breadcrumb :items="['系统管理', '员工管理']" :title="'员工管理'" />
    <div class="container">
      <a-row :gutter="20" align="stretch">
        <a-col :span="24">
          <a-card class="general-card" style="min-height: 80vh">
            <template #title>
              <a-row>
                <a-col :flex="1">
                  <a-form
                    :model="filterForm"
                    :label-col-props="{ span: 6 }"
                    :wrapper-col-props="{ span: 18 }"
                    label-align="left"
                    auto-label-width
                  >
                    <a-row :gutter="[16, 16]">
                      <a-col :xxl="5" :xl="8" :lg="8" :md="12" :sm="24">
                        <a-form-item
                          field="keyword"
                          label="模糊匹配"
                          :no-style="true"
                          ><a-input-search
                            v-model="filterForm.keyword"
                            placeholder="根据员工名称模糊匹配"
                            allow-clear
                            @search="filterStaff()"
                            @clear="filterStaff()"
                            @keyup.enter="filterStaff()"
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :xxl="5" :xl="8" :lg="8" :md="12" :sm="24">
                        <a-form-item
                          field="groupId"
                          label="所属部门"
                          row-class="mb0"
                        >
                          <a-tree-select
                            v-model="filterForm.groupId"
                            :field-names="{
                              key: 'id',
                              title: 'name'
                            }"
                            :allow-search="false"
                            :allow-clear="true"
                            :data="groupTreeData"
                            placeholder="选中所属部门"
                            dropdown-class-name="tree-select-scrollbar"
                            @change="filterStaff()"
                          ></a-tree-select>
                        </a-form-item>
                      </a-col>
                      <a-col :span="6">
                        <a-space :size="18">
                          <a-button
                            v-permission="[Api.CFG_STAFF_ADD]"
                            type="outline"
                            @click="showStaffModal(0)"
                          >
                            <template #icon>
                              <icon-plus />
                            </template>
                            添加员工
                          </a-button>
                        </a-space>
                      </a-col>
                    </a-row>
                  </a-form>
                </a-col>
              </a-row>
            </template>
            <a-divider style="margin-top: 0" />
            <a-table
              :columns="tableColumns"
              :data="staffList"
              stripe
              :pagination="false"
              :bordered="{
                cell: false,
                headerCell: true,
                wrapper: false
              }"
              :hoverable="false"
            >
              <template #status="{ record }">
                <a-switch
                  v-model="record.status"
                  :checked-value="1"
                  unchecked-color="#F53F3F"
                  :unchecked-value="0"
                  @change="handleModifyStatus($event as number, record.id)"
                >
                  <template #checked> 启 </template>
                  <template #unchecked> 关 </template>
                </a-switch>
              </template>
              <template #email="{ record }">
                {{ record.email || '-' }}
              </template>
              <template #full_range="{ record }">
                <a-tag v-if="record.full_range" color="arcoblue">是</a-tag>
                <a-tag v-else color="gray">否</a-tag>
              </template>
              <template #operate="{ record }">
                <div class="operate-text-button">
                  <a-button
                    v-permission="[Api.CFG_STAFF_MODIFY]"
                    type="text"
                    @click="showStaffModal(1, record)"
                    >修改</a-button
                  >
                  <a-divider
                    v-permission="[Api.CFG_STAFF_MODIFY]"
                    direction="vertical"
                  />
                  <a-button
                    v-permission="[Api.CFG_STAFF_MODIFY]"
                    type="text"
                    @click="showStaffModal(2, record)"
                    >重置密码</a-button
                  >
                  <a-divider
                    v-permission="[Api.CFG_STAFF_REMOVE]"
                    direction="vertical"
                  />
                  <a-button
                    v-permission="[Api.CFG_STAFF_REMOVE]"
                    type="text"
                    status="danger"
                    @click="handleRemoveStaff(record)"
                    >删除</a-button
                  >
                </div>
              </template>
            </a-table>
            <Page :page="page" @change="pageChangehandle" />
          </a-card>
        </a-col>
      </a-row>
      <vModal
        v-model:visible="visibleStaffModal"
        :title="modalTitle"
        @modal-handle-ok="staffHandleOk"
        @modal-handle-cancel="staffHandleCancel"
      >
        <div style="padding: 10px 15px">
          <a-form
            ref="staffFormRef"
            :model="staffForm"
            :auto-label-width="true"
            label-align="right"
          >
            <a-form-item
              v-if="modalType !== 2"
              field="name"
              label="名称"
              show-colon
              :rules="[
                { required: true, message: '名称不能未空' },
                {
                  minLength: 2,
                  maxLength: 20,
                  message: '名称长度大于2个字节，且小于20个字节'
                }
              ]"
            >
              <a-input v-model="staffForm.name" placeholder="请输入员工名称" />
            </a-form-item>
            <a-form-item
              v-if="modalType !== 2"
              field="mobile"
              label="手机"
              show-colon
              :rules="[
                {
                  required: true,
                  message: '手机号格式不正确',
                  match:
                    /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
                }
              ]"
            >
              <a-input
                v-model="staffForm.mobile"
                placeholder="请输入手机号"
                :disabled="modalType === 1"
              />
            </a-form-item>
            <a-form-item
              v-if="modalType !== 2"
              field="groupId"
              label="部门"
              show-colon
              :rules="[
                {
                  required: true,
                  message: '部门不能未空'
                }
              ]"
            >
              <!-- <a-cascader
                v-model="staffForm.groupId"
                :field-names="{
                  value: 'id',
                  label: 'name'
                }"
                :options="groupTreeData"
                placeholder="请选择部门"
                multiple
              /> -->
              <a-tree-select
                v-model="staffForm.groupId"
                placeholder="请选择部门"
                :multiple="true"
                :allow-search="true"
                :data="groupTreeData"
                :field-names="{
                  key: 'id',
                  title: 'name'
                }"
              >
              </a-tree-select>
              <!-- <a-cascader
                v-model="staffForm.groupId"
                placeholder="请选择部门"
                :field-names="{
                  value: 'id',
                  label: 'name'
                }"
                :options="groupTreeData"
                multiple
              /> -->

              <!-- <a-tree-select
                v-model="staffForm.groupId"
                :multiple="true"
                placeholder="请选择分组"
                :field-names="{
                  key: 'id',
                  title: 'name'
                }"
                :allow-search="false"
                :allow-clear="false"
                :data="groupTreeData"
                dropdown-class-name="tree-select-scrollbar"
              ></a-tree-select> -->
            </a-form-item>
            <a-form-item
              v-if="modalType !== 2"
              field="roleId"
              label="职位"
              show-colon
              :rules="[{ required: true, message: '职位不能为空' }]"
            >
              <a-select
                v-model="staffForm.roleId"
                :multiple="true"
                placeholder="请选中员工职位"
                allow-search
              >
                <a-option
                  v-for="item in roleList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></a-option>
              </a-select>
            </a-form-item>
            <a-form-item
              v-if="modalType !== 1"
              field="pass"
              label="密码"
              show-colon
              :rules="[{ required: true, validator: validatePass }]"
            >
              <a-input-password
                v-model="staffForm.pass"
                placeholder="请输入登录密码"
              />
            </a-form-item>
            <a-form-item
              v-if="modalType !== 1"
              field="checkPass"
              label="确认"
              show-colon
              :rules="[{ required: true, validator: validatePass2 }]"
            >
              <a-input-password
                v-model="staffForm.checkPass"
                placeholder="再次确认密码"
              />
            </a-form-item>
            <a-form-item
              v-if="modalType !== 2"
              field="email"
              label="邮箱"
              show-colon
              :rules="[{ type: 'email', message: '邮箱格式不正确' }]"
            >
              <a-input v-model="staffForm.email" placeholder="请输入邮箱" />
            </a-form-item>
            <!-- <a-form-item
              v-if="modalType !== 2"
              field="level"
              label="级别"
              show-colon
              help="默认为0，数字越大，级别越高"
            >
              <a-input-number
                v-model="staffForm.level"
                :min="0"
                :default-value="0"
                :allow-clear="false"
              />
            </a-form-item> -->
            <a-form-item v-if="modalType !== 2" field="fullRange">
              <a-checkbox v-model="staffForm.fullRange">
                是否是特权人员
              </a-checkbox>
            </a-form-item>
          </a-form>
        </div>
      </vModal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, h } from 'vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { Modal, Message, TableColumnData } from '@arco-design/web-vue'
import vModal from '@/components/modal/index.vue'

import Page from '@/components/page/index.vue'
import { Base as Api } from '@/enums/api'
import usePage, { IPage } from '@/components/page/index'
import { Md5 } from 'ts-md5'
import { getOrgTree } from '@/api/base/org'
import {
  addStaff,
  getStaffList,
  getStaffRoleList,
  modifyStaff,
  removeStaff
} from '@/api/base/staff'
import { ModifyStaffReqParams, Staff } from '@/types/staff'
import { DomainTree, DomainTreeResParams } from '@/types/domain'

const staffFormRef = ref<FormInstance>()
const visibleStaffModal = ref(false) // 是否显示员工对话框
const modalType = ref(0) // 对话框类型，0：添加，1：修改
const modalTitle = ref('') // 对话框标题
const groupTreeData = ref<DomainTree[]>([]) // 分组树

/**
 * 条件筛选表单
 */
const filterForm = reactive<{
  keyword?: string
  groupId?: number
}>({
  keyword: undefined,
  groupId: undefined
})

const staffForm = reactive<{
  id: string
  status: number
  mobile?: string
  groupId?: number[]
  name: string
  email?: string
  pass: string
  checkPass: string
  roleId?: string[]
  fullRange: boolean
  level: number
}>({
  id: '',
  groupId: undefined,
  status: 1,
  name: '',
  email: '',
  mobile: undefined,
  pass: '',
  checkPass: '',
  roleId: undefined,
  fullRange: false,
  level: 0
})

const validatePass = (value: any, callback: any) => {
  if (value === undefined || value.length <= 5) {
    callback('密码不能为空，且必须不能小于六位')
  } else {
    if (staffForm.checkPass !== '') {
      if (!staffFormRef.value) return
      staffFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (value: any, callback: any) => {
  if (value === '') {
    callback('请再次输入密码')
  } else if (value !== staffForm.pass) {
    callback('两次密码不匹配')
  } else {
    callback()
  }
}

const tableColumns: TableColumnData[] = [
  {
    title: '手机号',
    dataIndex: 'mobile',
    align: 'left',
    width: 105
  },
  {
    title: '员工名称',
    dataIndex: 'name',
    align: 'left',
    fixed: 'right',
    width: 95
  },
  {
    title: '所属部门',
    dataIndex: 'domain_names',
    align: 'left',
    width: 95,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '员工职位',
    dataIndex: 'role_names',
    align: 'left',
    width: 95,
    ellipsis: true,
    tooltip: true
  },

  {
    title: '邮箱号',
    dataIndex: 'email',
    align: 'center',
    slotName: 'email',
    width: 95,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '注册时间',
    dataIndex: 'reg_time',
    width: 170,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '最近活动时间',
    dataIndex: 'act_time',
    width: 170,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 75,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '是否是特权人员',
    dataIndex: 'full_range',
    width: 90,
    align: 'left',
    slotName: 'full_range'
  },
  {
    title: '操作',
    slotName: 'operate',
    align: 'left',
    fixed: 'right',
    width: 225
  }
]

const options = [
  {
    id: 20061,
    name: '牧云环保',
    children: [
      {
        id: 2065,
        name: '测试部门一'
      },
      {
        id: 2066,
        name: '测试部门二'
      }
    ]
  }
]
const { page } = usePage()
const staffList = ref<Staff[]>([]) // 员工列表
const roleList = ref<{ id: string; name: string }[]>([])

/**
 * 根据表单按条件筛选列表
 */
const filterStaff = (): void => {
  getList().then(() => console.log('获取列表'))
}

/**
 * 分页变化事件
 * @param argPage
 */
const pageChangehandle = (argPage: IPage): void => {
  page.pageIndex = argPage.pageIndex
  page.pageSize = argPage.pageSize
  getList().then(() => console.log('获取列表'))
}

/**
 * 递归获取ng-tree需要的结构体
 * @param groups 接口返回的树状数组
 */
const getNodesTree = (groups: DomainTree): DomainTree => {
  groups.key = groups.id.toString()
  groups.title = groups.name
  if (groups.children && groups.children.length > 0) {
    groups.children.map(res => getNodesTree(res))
  } else {
    groups.children = undefined
  }
  return groups
}

/**
 * 获取域树
 */
const getTree = async () => {
  try {
    const { tree }: DomainTreeResParams = await getOrgTree()
    groupTreeData.value = tree.map(groups => {
      return getNodesTree(groups)
    })
  } catch (e) {
    console.error(e)
  }
}

/**
 * 获取员工列表
 */
const getList = async () => {
  try {
    const { groupId, keyword } = filterForm
    const { pageIndex, pageSize } = page
    const { list, total } = await getStaffList({
      page_no: pageIndex,
      page_size: pageSize,
      domain_id: groupId
    })
    page.total = total
    staffList.value = list
  } catch (e) {
    console.error(e)
  }
}

/**
 * 隐藏role 对话框，重置表单
 */
const staffHandleCancel = () => {
  staffFormRef.value!.resetFields() // 初始化表单值
}

/**
 * 显示modal
 * @param type modal 类型
 * @param staff
 */
const showStaffModal = (type: number, staff?: Staff) => {
  console.log(staff)
  // const isAdd = type === 0
  modalType.value = type
  if (type === 0) {
    modalTitle.value = `添加员工`
    visibleStaffModal.value = true
    // staffForm.groupId = filterForm.groupId ? [filterForm.groupId] : []
    // console.log(staffForm.groupId)
  } else if (type === 1) {
    modalTitle.value = `修改 ${staff!.name} 员工信息`
    const {
      id,
      name,
      mobile,
      email,
      role_ids: roleId,
      domain_ids: domainId,
      full_range: fullRange,
      level
    } = staff!
    visibleStaffModal.value = true
    nextTick(() => {
      staffForm.id = id
      staffForm.name = name
      staffForm.mobile = mobile!
      staffForm.email = email
      staffForm.roleId = roleId
      staffForm.groupId = domainId
      staffForm.fullRange = fullRange
      staffForm.level = level
    })
  } else if (type === 2) {
    modalTitle.value = `重置 ${staff!.name} 员工密码`
    const { id } = staff!
    visibleStaffModal.value = true
    nextTick(() => {
      staffForm.id = id
    })
  }
}

/**
 * 点击确认按钮时，cb(false)时不会继续后续操作
 * @param cb 回调函数，
 */
const staffHandleOk = async (cb: (closed: boolean) => void) => {
  const isValid = await staffFormRef.value?.validate()
  if (isValid) {
    return cb(false)
  }
  const {
    id,
    name,
    mobile,
    groupId,
    pass,
    email,
    status,
    roleId,
    fullRange,
    level
  } = staffForm
  const md5Pwd: any = Md5.hashStr(pass) // 密码按照md5加密传输
  try {
    if (modalType.value === 0) {
      await addStaff({
        domain_ids: groupId,
        name: name!,
        mobile: mobile!,
        email,
        pass: md5Pwd!,
        role_ids: roleId!,
        full_range: fullRange,
        level
      })
      Message.success('添加成功')
      getList().then(() => console.log('获取员工列表'))
    } else if (modalType.value === 1) {
      const staff: ModifyStaffReqParams = {
        id, // 员工ID
        name, // 名称
        email, // 邮箱
        role_ids: roleId,
        domain_ids: groupId,
        full_range: fullRange,
        level
      }
      await modifyStaff(staff)
      getList().then(() => console.log('获取员工列表'))
      Message.success('修改成功')
    } else if (modalType.value === 2) {
      const staff = {
        id, // 员工ID
        pass: md5Pwd // 密码
      }
      await modifyStaff(staff)
      Message.success('重置成功')
    }
  } catch (e) {
    console.error(e)
  }
  return cb(true)
}

/**
 * 修改员工状态
 * @param val 状态值
 * @param userId
 */
const handleModifyStatus = async (val: number, userId: string) => {
  try {
    const staff = {
      id: userId, // 员工ID
      status: val
    }
    await modifyStaff(staff)
    const message = val === 1 ? '已开启' : '已锁定'
    Message.success(message)
  } catch (e) {
    setTimeout(() => {
      val = 1
    })
    // console.error(e)
  }
}

/**
 * 删除角色
 * @param role
 */
const handleRemoveStaff = async (staff: Staff) => {
  const { id, name } = staff
  const title = {
    setup() {
      return () => h('strong', '警告')
    }
  }
  const ModalContent = {
    setup() {
      return () =>
        h('span', { style: 'margin-left: 10px;' }, [
          h('span', `确认删除 `),
          h('strong', `${name}`),
          h('span', ` 员工吗？`)
        ])
    }
  }
  Modal.warning({
    title: () => h(title),
    content: () => h(ModalContent),
    alignCenter: true,
    titleAlign: 'start',
    draggable: true,
    escToClose: true,
    width: 300,
    simple: true,
    hideCancel: false,
    onOk: async () => {
      try {
        await removeStaff(id)
        const index = staffList.value.findIndex(
          (item: { id: string }) => item.id === staff.id
        )
        staffList.value.splice(index, 1)
        Message.success('删除成功')
      } catch (e) {
        console.error(e)
      }
    }
  })
}

const getRoles = async () => {
  const { roles } = await getStaffRoleList()
  roleList.value = roles
}

onMounted(async () => {
  try {
    await Promise.all([getTree(), getRoles()])
    getList().then(() => console.log('获取员工列表'))
  } catch (e) {
    console.log(e)
  }
})
</script>

<script lang="ts">
export default {
  name: 'Staff'
}
</script>

<style scoped lang="less">
.container {
  padding: 20px;
}
.dtree {
  padding: 0 10px;
  // max-height: 350px;
  :deep(.arco-tree-node-selected) {
    background-color: rgb(var(--gray-2));
  }
  :deep(.arco-tree-node:hover) {
    background-color: rgb(var(--gray-2));
  }
  :deep(.arco-tree-node-title:hover) {
    background-color: transparent;
  }
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
</style>
