<template>
  <div v-if="props.zsShow">
    <el-dialog title="证书模板列表" width="1200px" v-model="props.zsShow" :before-close="closeDialog">
      <div class="head">
        <div></div>
        <el-button @click="addShow = true" type="primary">
          <el-icon>
            <CirclePlusFilled />
          </el-icon>
          <span>新增</span>
        </el-button>
      </div>
      <div class="config">
        <el-table ref="multipleTableRef" :data="tableData" stripe style="width: 100%" v-loading="tableloading"
          element-loading-text="数据加载中..." border>
          <el-table-column label="模板名称" property="name"></el-table-column>
          <el-table-column label="模板序号" property="template"></el-table-column>
          <el-table-column label="模板图片">
            <template #default="{ row }">
              <el-image style="width: 50px; height: 50px" :src="row.url" fit="scale-down"
                :preview-src-list="[row.url]" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="350px">
            <template #default="{ row }">
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除该模板?"
                @confirm="handleDelete(row)">
                <template #reference>
                  <span class="operdel" size="small"><el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="fenye">
          <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
            layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" type="primary">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增 -->
    <el-dialog v-model="addShow" title="新增" :before-close="CloseEvent" width="800px">
      <div style='width:750px;'>
        <el-form ref="frombt" :model="dialogForm" :rules="rules" label-width="120px" style="display: block;">
          <el-form-item label="模板名称：" prop="name">
            <el-input v-model="dialogForm.name" maxlength="80" placeholder="不能超过80个字" autosize show-word-limit
              type="textarea" style="width: 500px"></el-input>
          </el-form-item>
          <el-form-item label="模板图片：" prop="file">
            <MOSTY.Upload v-model="dialogForm.file" :widthNumber="710" :showinput="true" :limit="1" :delrow="delrow"
              :showbut="true" :isEdit="true" :ShowfileList="true" :isImg="true" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="saveFrom(frombt)" :loading="loading">
            保存
          </el-button>
          <el-button @click="CloseEvent">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.head {
  display: flex;
  height: 50px;
  align-items: center;
  justify-content: space-between;
}

.config {
  height: 40vh;
  position: relative;

  .fenye {
    position: absolute;
    bottom: 0;
    text-align: right;
  }
}

::v-deep .el-table__cell {
  // 解决el-image 和 el-table冲突层级冲突问题
  position: static !important;
}
</style>
<script setup>
// 引入
import { ref, onMounted, defineProps, defineEmits, reactive, getCurrentInstance } from "vue";
import { createAndClickLink } from "@/utils/tools.js";
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
const loading = ref(false); //新增保存按钮截流
const { proxy } = getCurrentInstance();
const emits = defineEmits(["changeClose"]);
const props = defineProps({
  zsShow: {
    type: Boolean,
    default: false
  }
});
const tableData = ref(null)
const total = ref(0)
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 5
})
const frombt = ref(null)
const dialogForm = ref({})
const addShow = ref(false)
//规则校验
const rules = reactive({
  name: [{ required: true, message: "试卷类型不能为空", trigger: "blur" }],
  file: [{ required: true, message: '请上传证书模板图片', trigger: 'blur' }]
});
//获取详情
onMounted(() => {
  getTableData()
});
// 删除模板
const handleDelete = (row) => {
  deleteApi({}, "/mosty-jcgl/template/deleteTemplate/" + row.id).then((res) => {
    ElMessage.success('删除')
    getTableData()
  });
}
// 获取模板列表
const getTableData = () => {
  getApi(listQuery.value, "/mosty-jcgl/template/getTemplateList").then(async (res) => {
    if (res) {
      total.value = res.total
      for (let i = 0; i < res.records.length; i++) {
        res.records[i].url = await new Promise(async ok => {
          await getApi({}, `/mosty-base/minio/file/download/${res.records[i].file}`).then((res) => {
            if (res && res.url) {
              ok(res.url)
            } else {
              ok('')
            }
          })
        })
      }
      tableData.value = res.records
    }
  });
}
//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.value.pageCurrent = val;
  getTableData();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.value.pageSize = val;
  getTableData();
};
// 关闭
const closeDialog = () => {
  loading.value = false;
  emits("changeClose", false);
};
// 取消新增
const CloseEvent = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      addShow.value = false;
      frombt.value.clearValidate();
      dialogForm.value = {}
    })
    .catch(() => {
      // catch error
    })

}
// 保存
const saveFrom = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      dialogForm.value.file = dialogForm.value.file ? dialogForm.value.file.toString() : null;
      postApi(dialogForm.value, "/mosty-jcgl/template/addTemplate").then((res) => {
        loading.value = false;
        addShow.value = false;
        frombt.value.clearValidate();
        dialogForm.value = {}
        getTableData()
      });
    }
  });
};
</script>
