<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="url" prop="url">
            <el-input v-model="queryParams.url" placeholder="请输入url" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="名称" prop="fileName">
            <el-input v-model="queryParams.fileName" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="图片类型" prop="imgType">
            <el-select v-model="form.imgType" placeholder="图片类型" clearable>
              <el-option v-for="dict in picture_type" :label="dict.label" :value="dict.value" :key="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="主图标识" prop="enumC">
            <el-select v-model="form.enumC" placeholder="图片类型" clearable>
              <el-option v-for="dict in enum_type" :label="dict.label" :value="dict.value" :key="dict.value" />
            </el-select>
          </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:img:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:img:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:img:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:img:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="imgList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="图片id" align="center" prop="ossId" v-if="false" />
        <el-table-column label="图片类型" align="center" prop="imgType" />
        <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="fileName" />
        <el-table-column label="主图标识" align="center" prop="enumC" />
        
        <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:img:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:img: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="1000px" append-to-body>
      <el-form ref="imgFormRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="url" prop="url">
          <el-input v-model="form.url" placeholder="请输入url" />
        </el-form-item> 
        <el-form-item label="名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入名称" />
        </el-form-item> -->
        <el-form-item label="图片类型" prop="imgType">
          <el-select v-model="form.imgType" placeholder="图片类型" clearable style="width:300px" @change="handleChange">
            <el-option v-for="dict in picture_type" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="定位" prop="positionId" v-show="showPosition">
        <el-select v-model="form.positionId" filterable placeholder="请选择" style="width: 200px">
          <el-option v-for="item in positionList" :key="item" :label="item.positionName" :value="item.positionId"> </el-option>
        </el-select>
      </el-form-item>
        <!-- <el-form-item label="主图标识" prop="enumC">
          <el-select v-model="form.enumC" placeholder="主图标识" clearable style="width:500px">
            <el-option v-for="dict in enum_type" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </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 @click="() => { }">
                  <el-icon>
                    <zoom-in />
                  </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="Img" lang="ts">
import { listImg, getImg, delImg, addImg, updateImg, listPosition } from '@/api/system/img';
import { ImgVO, ImgQuery, ImgForm } from '@/api/system/img/types';
import type { UploadProps } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import { propTypes } from '@/utils/propTypes';
import { any } from 'vue-types';

const number = ref(0);
const fileList = ref<any[]>([]);
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),
});

interface PositionVO {
  positionId: string;
  positionName: string;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { picture_type } = toRefs<any>(proxy?.useDict("picture_type"));
const { enum_type } = toRefs<any>(proxy?.useDict("enum_type"));

const imgList = ref<ImgVO[]>([]);
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 emit = defineEmits(['update:modelValue']);
const queryFormRef = ref<ElFormInstance>();
const imgFormRef = ref<ElFormInstance>();
const positionList = ref<PositionVO[]>([]);
const showPosition = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 上传失败
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 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;
        file.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: ImgForm = {
  ossId: undefined,
  imgType: undefined,
  enumC: undefined,
  sysimg: undefined,
  positionId: undefined,
}
const data = reactive<PageData<ImgForm, ImgQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    imgType: undefined,
    enumC: undefined,
    params: {
    }
  },
  rules: {
    // ossId: [
    //   { required: true, message: "图片id不能为空", trigger: "blur" }
    // ],
    imgType: [
      { required: true, message: "图片类型不能为空", trigger: "change" }
    ],
  }
});

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

/** 查询图片列表 */
const getList = async () => {
  console.info(queryParams.value, 'queryParams.value');
  loading.value = true;
  const res = await listImg(queryParams.value);
  imgList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

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

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

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

  fileList.value.forEach(item => {
    if (item.e === '0') {
      item.defaults = true;
    }
  })
  if(res.data.imgType === '0'){
    showPosition.value = true;
  }
  Object.assign(form.value, res.data);
  getPositionList();
  dialog.visible = true;
  dialog.title = "修改图片";
}

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

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

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

onMounted(() => {
  getList();
  getPositionList();
  showPosition.value = false;
});
// 对象转成指定字符串分隔
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) : "";
}

const getPositionList = async () => {
  const res = await listPosition();
  positionList.value = res.data;
}

const handleChange = (val: string) => {
  console.info(val === '0', 'val === 0');
  if(val === '0') {
    showPosition.value = true;
  }else{
    showPosition.value = false;
  }
};
</script>
