<!-- 明信片 -->
<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]" id="search_div">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="名称" prop="name">
              <el-input class="inputWidth" v-model="queryParams.name" placeholder="请输入明信片类别名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <!-- <el-input class="inputWidth" v-model="queryParams.sortNum" placeholder="请输入排序" clearable
                @keyup.enter="handleQuery" /> -->
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="inputWidth">
                <el-option label="已上架" :value="1"></el-option>
                <el-option label="未上架" :value="0"></el-option>
              </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-button type="primary" plain icon="Plus" @click="handleAdd"
                v-hasPermi="['manage:mkPostcard:add']">新增</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-table v-loading="loading" border :data="mkPostcardList" :height="autoTableHeight"
      @selection-change="handleSelectionChange">
      <el-table-column label="ID" align="center" prop="id" v-if="true" width="150" />
      <el-table-column label="明信片名称" align="center" prop="name" />
      <el-table-column label="关联景点" align="center" prop="articleId">
        <template #default="scope">
          <span>{{ formatterArticleId(scope.row.articleId)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortNum" />
      <el-table-column label="封面" align="center" prop="">
        <template #default="scope">
          <el-image :src="scope.row.imgUrl" :preview-src-list="[scope.row.imgUrl]" :initial-index="0" fit="cover"
            style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="明信片" align="center" prop="">
        <template #default="scope">
          <el-button link type="primary" @click="handlePostcard(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <!-- 0-未上架 1-已上架 -->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span>{{ scope.row.status == 1 ? '已上架' : '未上架'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="updateByName" />
      <el-table-column label="创建时间" align="center" prop="updateTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleStatus(scope.row,'1')" v-if="scope.row.status == 0"
            v-hasPermi="['manage:mkPostcard:edit']">上架</el-button>
          <el-button link type="primary" @click="handleStatus(scope.row,'0')" v-if="scope.row.status == 1"
            v-hasPermi="['manage:mkPostcard:edit']">下架</el-button>
          <el-tooltip content="编辑" placement="top" v-if="scope.row.status == 0">
            <el-button link type="primary" @click="handleUpdate(scope.row)"
              v-hasPermi="['manage:mkPostcard:edit']">编辑</el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.status == 0">
            <el-button link type="primary" @click="handleDelete(scope.row)"
              v-hasPermi="['manage:mkPostcard:remove']">删除</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" id="table_page" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改明信片类别对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="mkPostcardFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入明信片名称" />
        </el-form-item>
        <el-form-item label="关联景点" prop="articleId">
          <el-select v-model="form.articleId" placeholder="请选择关联景点" clearable>
            <el-option v-for="(item,index) in contentAllList" :key="item.id" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortNum">
          <el-input-number v-model="form.sortNum" :min="1" :max="10000" />
        </el-form-item>
        <el-form-item label="封面" prop="coverImage">
          <image-upload v-model="form.coverImage" />
        </el-form-item>
        <el-form-item label="明信片" prop="postcardImage">
          <image-upload v-model="form.postcardImage" />
        </el-form-item>
      </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>
    <!-- 明显片详情 -->
    <el-dialog :title="postcardInfo.title" v-model="postcardInfo.visible" width="700px" append-to-body>
      <el-table v-loading="loading" border :data="postcardInfo.dataList" :height="300">
        <el-table-column label="明信片" align="center" prop="name">
          <template #default="scope">
            <el-image :src="scope.row.pic" style="width: 50px; height: 50px" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column label="打卡人数" align="center" prop="clockInCount" />
        <el-table-column label="邮寄人数" align="center" prop="mailingCount" />
      </el-table>
      <pagination v-show="postcardInfo.params.total > 0" :total="postcardInfo.params.total"
        v-model:page="postcardInfo.params.pageNum" v-model:limit="postcardInfo.params.pageSize" @pagination="getList" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MkPostcard" lang="ts">
import { contentAll } from '@/api/manage/scenic';
import { listMkPostcard, getMkPostcard, delMkPostcard, addMkPostcard, updateMkPostcard,listMkPostcardDetail } from '@/api/manage/mkPostcard';
import { MkPostcardVO, MkPostcardQuery, MkPostcardForm } from '@/api/manage/mkPostcard/types';
import { Postcard } from '@element-plus/icons-vue';
import { title } from 'process';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const autoTableHeight = ref<number>(750);
const mkPostcardList = ref<MkPostcardVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const mkPostcardFormRef = ref<ElFormInstance>();

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

const initFormData: MkPostcardForm = {
  id: undefined,
  name: undefined,
  articleId: undefined,
  status: 0,
  sortNum: 0,
  postcardImage: undefined,
  coverImage: undefined,
}
const data = reactive<PageData<MkPostcardForm, MkPostcardQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    articleId: undefined,
    status: undefined,
    sortNum: undefined,
    params: {
    }
  },
  rules: {
    name: [
      { required: true, message: "明信片名称不能为空", trigger: "blur" }
    ],
    articleId: [
      { required: true, message: "关联景点不能为空", trigger: "change" }
    ],
    sortNum: [
      { required: true, message: "排序不能为空", trigger: "change" }
    ],
    coverImage: [
      { required: false, message: "封面不能为空", trigger: "blur" }
    ],
    postcardImage: [
      { required: false, message: "明信片不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询明信片类别列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMkPostcard(queryParams.value);
  mkPostcardList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}
/**
 * 查询景点下拉列表
 */
const contentAllList= ref([]);
const getContentAll = async () => {
  const res = await contentAll({type:'0',status:2});
  Object.assign(contentAllList.value, res);
}
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  postcardInfo.visible=false;
  postcardInfo.params.pageNum=1;
}

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

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

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

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

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

/** 修改按钮操作 */
const handleUpdate = async (row?: MkPostcardVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getMkPostcard(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改明信片";
}

/** 提交按钮 */
const submitForm = () => {
  mkPostcardFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMkPostcard(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addMkPostcard(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: MkPostcardVO) => {
  const _ids = row?.id;
  await proxy?.$modal.confirm('是否确认删除名称为"' + row.name + '"的明信片？').finally(() => loading.value = false);
  await delMkPostcard(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('manage/mkPostcard/export', {
    ...queryParams.value
  }, `mkPostcard_${new Date().getTime()}.xlsx`)
}
/**
 * 明信片 上下架
 * @param row 
 * @param type 
 */
const handleStatus=async (row:MkPostcardVO,type:string)=>{
  if (type=='1') {
  await proxy?.$modal.confirm('是否确认上架名称为"' + row.name + '"的明信片？')
  }else{
  await proxy?.$modal.confirm('是否确认下架名称为"' + row.name + '"的明信片？')
  }
  row.status=type;
  loading.value=true;
  await updateMkPostcard(row).finally(() => loading.value = false);
  proxy?.$modal.msgSuccess("操作成功");
  await getList();
}
/**
 * 格式化列表景点名称
 * @param row 
 */
const formatterArticleId = (id: string) => {
  for (let i = 0; i < contentAllList.value.length; i++) {
    const element = contentAllList.value[i];
    if (element.id == id) {
      return element.name;
    }
  }
}
/**
 * 查看明信片详情
 * @param row 
 */
const postcardInfo=reactive({
  visible:false,
  dataList:[],
  title:'',
  params:{
    postcardId:null,
    total:0,
    pageNum:1,
    pageSize:10,
  }
})
const handlePostcard = async (row:MkPostcardVO)=>{
  postcardInfo.title=row.name+'明信片';
  postcardInfo.visible=true;
  postcardInfo.params.postcardId=row.id;
  let res=await listMkPostcardDetail(postcardInfo.params);
  postcardInfo.dataList=res.rows;
  postcardInfo.params.total=res.total;
}
onMounted(() => {
  getList();
  getContentAll();
  nextTick(() => {
    autoTableHeight.value = proxy?.autoTableHeight();
  });
  window.onresize = () => {
    autoTableHeight.value = proxy?.autoTableHeight();
  };
});
</script>
<style lang="scss" scoped>
.el-card :deep(.el-card__body) {
  padding-bottom: 0px !important;
}

#table_page {
  height: 50px !important;
  margin-top: 10px !important;
  padding-bottom: 10px !important;
}

.el-upload {
  :deep(.el-upload-dragger) {
    padding: 0;
    height: 100%;

    i {
      top: 30%;
      left: 50%;
      position: absolute;
      transform: translateX(-50%);
      font-size: 45px;
    }
  }
}
</style>
