<template>
  <!-- 艺术网址 -->
  <div class="yswzManage" v-loading="loading">
    <div class="searchDiv flex">
      <el-form ref="searchFormRef" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="名称：" prop="keyword">
          <el-input size="default" v-model="searchForm.keyword" placeholder="" />
        </el-form-item>
        <el-form-item>
          <el-button size="default" type="primary" @click="initData">搜索</el-button>
          <el-button size="default" type="warning" @click="resetForm(searchFormRef)">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="searchContent">
      <div class="searchBtn flex">
        <div class="flex">
          <!-- <el-button size="default" type="success" @click="handleDownload">导出</el-button> -->
          <el-button size="default" type="primary" @click="handleAddOrEdit()">添加</el-button>
          <el-button size="default" type="danger" @click="handleRemove()">删除</el-button>
        </div>
        <!-- <img src="/images/print.png" alt="" /> -->
      </div>
      <div class="tableList">
        <div class="tableDiv">
          <el-table ref="multipleTableRef" :data="tableData" height="100%" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="sz_name" width="" label="名称" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sz_img" width="" label="图片" show-overflow-tooltip>
              <template #default="{row}">
                <el-image style="width: 38px; height: 38px;display: block;" :src="getFullUrl(row.sz_img)" :preview-teleported="true" :preview-src-list="[getFullUrl(row.sz_img)]" />
              </template>
            </el-table-column>
            <el-table-column prop="sz_web_url" label="网址" show-overflow-tooltip>
              <template #default="{row}">
                <el-link @click="windowopen(row.sz_web_url)">{{ row.sz_web_url }}</el-link>
                <!-- <el-image style="width: 38px; height: 38px;display: block;" :src="getFullUrl(row.sz_img)" :preview-teleported="true" :preview-src-list="[getFullUrl(row.sz_img)]" /> -->
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{row}">
                <el-button text size="default" type="primary" @click="handleAddOrEdit(row.sz_id)">编辑</el-button>
                <el-button text size="default" type="primary" @click="handleRemove(row.sz_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="paginationDiv">
          <el-pagination background layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange" :page-size="limit" :currentPage="currentPage"></el-pagination>
        </div>
      </div>
    </div>

    <el-dialog width="500px" v-model="dialogVisible" :title="dialogTitle" custom-class="commonDialog" :show-close="false" :close-on-click-modal="false">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="60px" class="demo-ruleForm">
        <el-form-item label="名称" prop="sz_name">
          <el-input v-model="ruleForm.sz_name" />
        </el-form-item>
        <el-form-item label="图片" prop="sz_img">
          <file-upload-progress v-if="dialogVisible" v-model:part="ruleForm.sz_img" :limit="1" accept=".png,.jpg,.jpeg">
            <template #default>
              <div class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9">
                <i-akar-icons:plus class="text-xl" />
              </div>
            </template>
            <!-- <template #tip>
            <div class="mt-2">支持格式：jpg,png,jpeg（200kb以内） 建议尺寸12:5</div>
          </template> -->
          </file-upload-progress>
        </el-form-item>
        <el-form-item label="网址" prop="sz_web_url">
          <el-input v-model="ruleForm.sz_web_url" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose(2)">取消</el-button>
          <el-button type="primary" @click="commitData(ruleFormRef)">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup >
import { reactive, ref, onMounted } from "vue";
import Request, { download } from "~/utils/request";
// import AddAndEdit from "./components/AddAndEdit.vue";
// import Detail from "./components/Detail.vue";
import { zp_list, zp_add, zp_edit, zp_delete, zp_detail } from "./api.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { getFullUrl } from "~/utils/helper";
import { useRouter } from "vue-router";

const loading = ref(false);
const searchFormRef = ref();
const searchForm = reactive({
  keyword: "",
});

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  initData();
};

const tableData = ref([]);
const total = ref(0);
const limit = ref(10);
const currentPage = ref(1);
function handleCurrentChange(val) {
  currentPage.value = val;
  initData();
}

initData();
async function initData() {
  let obj = {
    limit: limit.value,
    page: currentPage.value,
    keyword: searchForm.keyword,
  };
  loading.value = true;
  let res = await zp_list(obj);
  if (res.code == 1) {
    total.value = parseInt(res.data.total_rows);
    tableData.value = res.data.page_data;
    loading.value = false;
  }
}

const ruleFormRef = ref(null);
const ruleForm = reactive({
  sz_name: "",
  sz_img: "",
  sz_web_url: ""
});
const rules = reactive({
  sz_name: [{ required: true, message: "请输入艺术网址名称", trigger: "blur" }],
  sz_img: [{ required: true, message: "请输入艺术网址图片", trigger: "submit" }],
  sz_web_url: [{ required: true, message: "请输入艺术网址地址", trigger: "blur" }],
});

const dialogVisible = ref(false);
const dialogType = ref(0);
const dialogTitle = ref("");
const currentId = ref("");
function handleAddOrEdit(id) {
  dialogVisible.value = true;
  dialogType.value = 1;
  if (!id) {
    dialogTitle.value = "添加";
  } else {
    dialogTitle.value = "编辑";
    currentId.value = id;
    initDetailInfo();
  }
}

const initDetailInfo = async () => {
  let res = await zp_detail({ sz_id: currentId.value });
  if (res.code == 1) {
    for (let key in ruleForm) {
      ruleForm[key] = res.data.one_info[key];
    }
  }
}


const windowopen = (url) => {
  window.open(url, '_blank');
}

const commitData = (formEl) => {
  if (!formEl) return;

  formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      let data = {
        szmsg_zp: ruleForm,
      };
      if (currentId.value == "") {
        await zp_add(data);
      } else {
        data = Object.assign({ sz_id: currentId.value }, data);
        await zp_edit(data);
      }
      loading.value = false;
      ElMessage.success("保存成功！");
      handleClose(1);
    } else {
      console.log("error submit!", fields);
    }
  });
}

function handleClose(type) {
  dialogVisible.value = false;
  currentId.value = "";
  resetForm(ruleFormRef.value);
  if (type == 1) {
    initData();
  }
}

const handleRemove = async (id) => {
  if ((id == undefined || id == "") && multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除的数据！");
    return;
  }
  ElMessageBox.confirm("是否确定删除当前数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    buttonSize: "default",
  })
    .then(async () => {
      loading.value = true;
      if (id != undefined && id != "") {
        await zp_delete({ sz_id: id });
      } else {
        let arr = [];
        multipleSelection.value.map((item) => {
          arr.push(item.sz_id);
        });
        await zp_delete({ sz_id: arr });
      }
      ElMessage.success("删除成功！");
      loading.value = false;
      initData();
    })
    .catch(() => { });
};

const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const handleDownload = () => {
  let arr = [];
  multipleSelection.value.map((value) => {
    arr.push(value.sz_id);
  });
  let obj = {
    limit: limit.value,
    page: currentPage.value,
    keyword: searchForm.keyword,
    checkedidstring: arr.join(","),
  };

  download("/szmsg/school/index", obj);
};
</script>

<style lang="scss" scoped>
@import "~/styles/dialog.scss";
.yswzManage {
  height: calc(100vh - 50px - 2rem);
  .flex {
    display: flex;
    align-items: center;
  }
  .searchDiv {
    height: 62px;
    background: #fff;
    border-radius: 6px;
    // box-shadow: 0 0 5px rgba($color: #000000, $alpha: 0.1);
    // padding: 0 20px;
    .el-form-item::v-deep {
      margin-bottom: 0;
      .el-form-item__label {
        padding: 0;
      }
    }
  }
  .searchContent {
    margin-top: 12px;
    height: calc(100% - 62px - 12px);
    background: #fff;
    border-radius: 6px;
    // box-shadow: 0 0 5px rgba($color: #000000, $alpha: 0.1);
    // padding: 0 20px;
    .searchBtn {
      justify-content: space-between;
      padding: 10px 0;
      border-bottom: 1px solid #e3e3e3;
      ::v-deep .el-button {
        height: 32px;
      }
    }
    .tableList {
      height: calc(100% - 52px - 10px);
      position: relative;
      .tableDiv {
        // background: #ddd;
        height: calc(100% - 42px);
        .el-button {
          padding: 0;
        }
        .split {
          color: #00a3ff;
          margin: 0 10px;
        }
      }
      .paginationDiv {
        position: absolute;
        bottom: -5px;
        padding: 3px;
        width: 100%;
        display: -webkit-box;
        -webkit-box-pack: end;
      }
    }
  }
}
</style>