<template>
  <div class="p-2 auto-overflow-y" style="overflow-x: hidden">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :lg="5" :xs="24" style="">
        <el-card shadow="hover">
          <el-input v-model="deptName" placeholder="请输入部门名称" prefix-icon="Search" clearable />
          <el-tree
            ref="deptTreeRef"
            class="mt-2 w-300px h-148 inline-block overflow-auto"
            node-key="id"
            :data="deptOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            :default-expanded-keys="expandKeys"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="19" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="姓名" prop="realName">
                  <el-input v-model="queryParams.realName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="学/工号" prop="userNumb">
                  <el-input v-model="queryParams.userNumb" placeholder="请输入学/工号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-button v-has-permi="['payment:ptUserAccount:edit']" type="primary" plain @click="dialogVisible = true">批量上传照片</el-button>
          </template>
          <div class="list-image" style="height: 52vh; overflow-y: auto">
            <div v-for="user in ptUserAccountList" :key="user.userNumb" class="block">
              <span>姓名：{{ user.realName }}</span>
              <span class="demonstration">学号：{{ user.userNumb }}</span>

              <el-upload
                class="avatar-uploader"
                :action="baseUrl + '/backstage/payment/ptUserAccount/photoUpload?userId=' + user.userId"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                :headers="headers"
                accept=".jpg,.jpeg,.png"
                :limit="1"
              >
                <el-image v-if="user.photo" :src="baseUrl + '/backstage/upload/' + user.photo" fit="fill" class="imageClass" />
                <el-icon v-else class="avatar-uploader-icon-2"><Plus /></el-icon>
              </el-upload>
            </div>
          </div>
        </el-card>
        <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      </el-col>
    </el-row>

    <!--批量上传照片弹窗-->
    <el-dialog v-model="dialogVisible" title="批量上传人员照片" width="30%" @close="handleClickClose">
      <el-upload
        ref="upload"
        :headers="headers"
        :show-file-list="true"
        :auto-upload="false"
        accept=".jpg,.png,.jpeg"
        multiple
        :limit="20"
        :on-change="onChange"
        :before-remove="beforeRemove"
        :file-list="fileList"
        action="#"
        class="flex w-full h-full items-center justify-center overflow-auto"
      >
        <el-icon class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      <div class="flex justify-between mt-5">
        <div class="mt-3 mb-3 font-20" style="color: crimson">*照片名称必须是身份证号</div>
        <el-button type="primary" @click="uploadBatch">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="facePhoto" lang="ts">
import { ref } from 'vue';
import api from '@/api/payment/account/';
import { PtUserAccountForm, PtUserAccountQuery, PtUserAccountVO } from '@/api/payment/account/types';
import { DeptVO } from '@/api/system/dept/types';

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
/** 当前页面引用的数据字典 */
const { sys_normal_disable, CATEGORY, sys_yes_no, account_open_status } = toRefs<any>(
  proxy?.useDict('sys_normal_disable', 'CATEGORY', 'sys_yes_no', 'account_open_status')
);
const ptUserAccountList = ref<PtUserAccountVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const deptName = ref('');
const deptOptions = ref<DeptVO[]>([]);
const fileList = ref<UploadFile[]>([]);

const deptTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();

const upload = ref();

const expandKeys = ref([]);
const dialogVisible = ref(false);
const initFormData: PtUserAccountForm = {
  userId: undefined,
  deptId: undefined,
  postId: undefined,
  userName: '',
  userNumb: '',
  realName: '',
  category: '',
  phone: undefined,
  accountStatus: '1',
  freezeStatus: 'N',
  consumePwd: undefined,
  cardType: 1,
  lifespan: '2050-12-31 23:59:59',
  status: '0',
  remark: '',
  accountBalance: '0'
};

const initData: PageData<PtUserAccountForm, PtUserAccountQuery> = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    realName: '',
    userNumb: '',
    phone: ''
  },
  rules: {}
};
const data = reactive<PageData<PtUserAccountForm, PtUserAccountQuery>>(initData);

const { queryParams, form, rules } = toRefs<PageData<PtUserAccountForm, PtUserAccountQuery>>(data);

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

/** 查询用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.listPtUserAccount4Select(proxy?.addDateRange(queryParams.value, dateRange.value));
  loading.value = false;
  ptUserAccountList.value = res.rows;
  total.value = res.total;
};

/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.deptId = data.id;
  handleQuery();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = undefined;
  deptTreeRef.value?.setCurrentKey(undefined);
  handleQuery();
};

onMounted(async () => {
  await getTreeSelect(); // 初始化部门数据
  getList(); // 初始化列表数据
  const first = deptOptions.value[0];
  expandKeys.value = [first.id as number];
});

import type { UploadFiles, UploadProps } from 'element-plus';
import { globalHeaders } from '@/utils/request';

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const headers = ref(globalHeaders());

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('请上传jpg、jepg、png格式图片');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

const ACCEPTED_EXTENSIONS = ['png', 'jpg', 'jpeg'];

/**
 * 请求前判断文件是否符合要求
 * 如果符合则添加到上传队列
 */
function beforeUpload(file) {
  console.log('beforeUpload', file);
  const extension = file.name.split('.').pop().toLowerCase();
  if (!ACCEPTED_EXTENSIONS.includes(extension)) {
    ElMessage({
      type: 'error',
      message: '仅支持 png, jpg 和 jpeg 格式的文件'
    });
    return false;
  }
  if (file.size / 1024 / 1024 > 2) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  return true;
}

/**
 * 文件选择改变时触发
 */
function onChange(file, fileListVal) {
  fileList.value = fileListVal;
}

function beforeRemove(file: UploadFile, fileListVal: UploadFiles) {
  fileList.value = fileListVal;
  return true;
}

// 清空附件列表
const clearAttachments = () => {
  if (upload.value) {
    upload.value.clearFiles(); // 调用实例方法 `clearFiles` 清空附件列表
    console.log('已清空附件列表');
  }
};

/**点击close触发 */
const handleClickClose = () => {
  fileList.value = [];
  clearAttachments();
  dialogVisible.value = false;
};
const uploadBatch = async () => {
  if (!fileList.value.length) {
    ElMessage.error('请先选择文件');
    return;
  }
  for (let i = 0; i < fileList.value.length; i++) {
    console.log('fileList.value[i]', fileList.value[i]);
    let rs = beforeUpload(fileList.value[i]);
    if (!rs) {
      return;
    }
  }
  const formData = new FormData();
  console.log('fileList', fileList.value);
  fileList.value.forEach((file) => {
    formData.append('file', file.raw);
  });
  const res = await api.photoBatchUpload(formData);
  ElMessage.success(res.msg);
  dialogVisible.value = false;
  getList();
};

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log('uploadFile', uploadFile);
  getList();
};
</script>

<style lang="scss" scoped>
.list-image .block {
  padding: 15px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 20%;
  box-sizing: border-box;
  vertical-align: top;
}
.list-image .block:last-child {
  border-right: none;
}
.list-image .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 15px;
}

.avatar-uploader {
  width: 160px;
  height: 150px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed var(--el-border-color);
}

.avatar-uploader:hover {
  border: 1px dashed blue;
  height: 150px;
  width: 160px;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  border: 1px dashed #8c939d;
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon-2 {
  padding: 2px;
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 150px;
  text-align: center;
}
.imageClass {
  padding: 2px;
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 150px;
  text-align: center;
}

.el-icon.avatar-uploader-icon:hover {
  border-color: blue;
}

.el-tree > :nth-child(n + 1) {
  display: inline-block !important;
  min-width: 100% !important;
  vertical-align: top !important; /* 清除默认的 vertical-align */
}

:deep(ul.el-upload-list div.el-upload-list__item-info) {
  width: 100% !important;
}

:deep(.el-upload-list__item .el-icon--close) {
  right: -0.8rem;
}
</style>
