<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="设施名称" prop="facilitiesName">
            <el-input v-model="queryParams.facilitiesName" placeholder="请输入设施名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="设施标题" prop="facilitiesTitle">
            <el-input v-model="queryParams.facilitiesTitle" placeholder="请输入设施标题" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="设施描述" prop="facilitiesDesc">
            <el-input v-model="queryParams.facilitiesDesc" 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>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:facilities:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:facilities:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:facilities:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:facilities:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="facilitiesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设施id" align="center" prop="facilitiesId" v-if="true" />
        <el-table-column label="设施名称" align="center" prop="facilitiesName" />
        <el-table-column label="设施标题" align="center" prop="facilitiesTitle" />

        <el-table-column label="主图展示" align="center" prop="url">
          <template #default="scope">
            <ImagePreview :width="100" :height="100" :src="scope.row.url" :preview-src-list="[scope.row.url]" />
          </template>
        </el-table-column>

        <el-table-column label="设施描述" align="center" prop="facilitiesDesc" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:facilities:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:facilities:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设施对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <el-form ref="facilitiesFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设施名称" prop="facilitiesName">
              <el-input v-model="form.facilitiesName" placeholder="请输入设施名称" style="width: 400px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设施标题" prop="facilitiesTitle">
              <el-input v-model="form.facilitiesTitle" placeholder="请输入设施标题" style="width: 400px;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-row :span="12">
        <el-form-item label="设施类型" prop="facilitiesType">
          <el-select v-model="form.facilitiesType" placeholder="设施类型" clearable style="width:400px">
            <el-option v-for="dict in facilities_type" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>
      </el-row>
      </el-row>
        <el-form-item label="设施描述" prop="facilitiesDesc">
          <el-input v-model="form.facilitiesDesc" maxlength="200" placeholder="请输入设施描述" show-word-limit
            type="textarea" rows="5" style="width: 800px;" />
        </el-form-item>

        <el-upload v-model:file-list="fileList" :multiple="true" :action="upload.url" :on-preview="handlePreview"
          :on-remove="handleRemove" :before-remove="beforeRemove" :headers="upload.headers"
          :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" list-type="picture-card">
          上传设施图
          <template #tip>
            <div class="el-upload__tip">
              小于500KB的jpg/png/jpeg文件
            </div>
          </template>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
                <span @click="onClickDefaultPhoto(file)">
                  <el-icon v-if="file.defaults">
                    <Open />
                  </el-icon>
                  <el-icon v-else>
                    <TurnOff />
                  </el-icon>
                </span>
                <span v-if="!disabled" @click="onClickDeletePhoto(file)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Facilities" lang="ts">
import { listFacilities, getFacilities, delFacilities, addFacilities, updateFacilities } from '@/api/system/facilities';
import { FacilitiesVO, FacilitiesQuery, FacilitiesForm } from '@/api/system/facilities/types';
import { globalHeaders } from "@/utils/request";
import { propTypes } from '@/utils/propTypes';
import type { UploadProps } from 'element-plus'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { facilities_type } = toRefs<any>(proxy?.useDict("facilities_type"));
const disabled = ref(false)
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload',
});

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: propTypes.number.def(5),
  // 大小限制(MB)
  fileSize: propTypes.number.def(5),
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: propTypes.array.def(["png", "jpg", "jpeg"]),
  // 是否显示提示
  isShowTip: propTypes.bool.def(true),
});

const facilitiesList = ref<FacilitiesVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const fileList = ref<any[]>([]);
const emit = defineEmits(['update:modelValue']);

const queryFormRef = ref<ElFormInstance>();
const facilitiesFormRef = ref<ElFormInstance>();
const number = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const onClickDefaultPhoto = (file: any) => {
  if (file.defaults) {
    file.defaults = false;
    file.enumC = '1'; //主图标识
  } else {
    file.defaults = true;
    file.enumC = '0'; //主图标识
    fileList.value.forEach(item => {
      if (item.uid !== file.uid) {
        item.defaults = false;
        item.enumC = '1'; //主图标识
      }
    })
  }
}

const onClickDeletePhoto = (file: any) => {
  const index = fileList.value.findIndex((item) => {
    return item.uid === file.uid;
  })
  fileList.value.splice(index, 1);
  emit("update:modelValue", listToString(fileList.value));
}

const initFormData: FacilitiesForm = {
  facilitiesId: undefined,
  facilitiesName: undefined,
  facilitiesTitle: undefined,
  facilitiesDesc: undefined,
  facilitiesType: undefined,
}
const data = reactive<PageData<FacilitiesForm, FacilitiesQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    facilitiesName: undefined,
    facilitiesTitle: undefined,
    facilitiesDesc: undefined,
    facilitiesType: undefined,
    params: {
    }
  },
  rules: {
    facilitiesId: [
      { required: true, message: "设施id不能为空", trigger: "blur" }
    ],
    facilitiesName: [
      { required: true, message: "设施名称不能为空", trigger: "blur" }
    ],
    facilitiesTitle: [
      { required: true, message: "设施标题不能为空", trigger: "blur" }
    ],
    facilitiesDesc: [
      { required: true, message: "设施描述不能为空", trigger: "blur" }
    ],
  }
});

const handleUploadError = () => {
  proxy?.$modal.msgError("上传文件失败");
}

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy?.$modal.loading("正在上传文件，请稍候...");
  number.value++;
  return true;
}

const listImgInfo: any[] = [];
const handleUploadSuccess = (res: any) => {
  // 如果上传成功
  if (res.code === 200) {
    proxy?.$modal.closeLoading();
  } else {
    proxy?.$modal.loading(res.msg);
    proxy?.$modal.closeLoading();
  }
}

const { queryParams, form, rules } = toRefs(data);

/** 查询设施列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFacilities(queryParams.value);
  facilitiesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  facilitiesFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: FacilitiesVO[]) => {
  ids.value = selection.map(item => item.facilitiesId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加设施";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: FacilitiesVO) => {
  reset();
  const _facilitiesId = row?.facilitiesId || ids.value[0]
  const res = await getFacilities(_facilitiesId);
  fileList.value = [];
  res.data.sysimg.forEach((_s: any) => {
    const imgData = { fileName: _s.fileName, e: _s.enumC, url: _s.url, ossId: _s.ossId };
    fileList.value.push(imgData);
    console.info(fileList.value, 'fileList.value');
  });

  fileList.value.forEach(item => {
    if (item.e === '0') {
      item.defaults = true;
    }
  });

  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改设施";
}

/** 提交按钮 */
const submitForm = () => {
  facilitiesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      console.info(form.value, 'region data');
      data.form.sysimg = fileList.value;
      if (form.value.facilitiesId) {
        await updateFacilities(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addFacilities(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: FacilitiesVO) => {
  const _facilitiesIds = row?.facilitiesId || ids.value;
  await proxy?.$modal.confirm('是否确认删除设施编号为"' + _facilitiesIds + '"的数据项？').finally(() => loading.value = false);
  await delFacilities(_facilitiesIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/facilities/export', {
    ...queryParams.value
  }, `facilities_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
// 对象转成指定字符串分隔
const listToString = (list: any[], separator?: string) => {
  let strs = "";
  separator = separator || ",";
  list.forEach(item => {
    if (item.ossId) {
      strs += item.ossId + separator;
    }
  })
  return strs != "" ? strs.substring(0, strs.length - 1) : "";
}
</script>
