<template>
  <!-- 艺术视野 -->
  <div class="tzkcManage" 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="ss_name" width="" label="学校/机构" show-overflow-tooltip></el-table-column>
            <el-table-column prop="ss_home_display" label="是否放在推荐页"></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{row}">
                <el-button text size="default" type="primary" @click="goToPage(row.ss_id)">设置</el-button>
                <el-button text size="default" type="primary" @click="handleAddOrEdit(row.ss_id)">编辑</el-button>
                <el-button text size="default" type="primary" @click="handleRemove(row.ss_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="130px" class="demo-ruleForm">
        <el-form-item label="学校/机构" prop="ss_name">
          <el-input v-model="ruleForm.ss_name" />
        </el-form-item>
        <el-form-item label="是否放在推荐页" prop="ss_home_display">
          <el-radio-group v-model="ruleForm.ss_home_display">
            <el-radio label="1" size="large">是</el-radio>
            <el-radio label="2" size="large">否</el-radio>
          </el-radio-group>
        </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 { schoolList, schoolAdd, schoolEdit, schoolDetail, schoolDelete } 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 data = await schoolList(obj);
  total.value = parseInt(data.total_rows);
  tableData.value = data.page_data;
  loading.value = false;
}

const ruleFormRef = ref(null);
const ruleForm = reactive({
  ss_name: "",
  ss_home_display: "1"
});
const rules = reactive({
  ss_name: [{ required: true, message: "请输入学校/机构名称", trigger: "blur" }],
  ss_home_display: [{ required: true, message: "请选择是否放在推荐页", trigger: "change" }],
});

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 data = await schoolDetail({ ss_id: currentId.value });
  for (let key in ruleForm) {
    ruleForm[key] = data.one_info[key];
  }
  ruleForm.ss_home_display = data.one_info.ss_home_display_option_k;
}

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

  formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      let data = {
        szmsg_school: ruleForm,
      };
      if (currentId.value == "") {
        await schoolAdd(data);
      } else {
        data = Object.assign({ ss_id: currentId.value }, data);
        await schoolEdit(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 schoolDelete({ ss_id: id });
      } else {
        let arr = [];
        multipleSelection.value.map((item) => {
          arr.push(item.ss_id);
        });
        await schoolDelete({ ss_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.ss_id);
  });
  let obj = {
    limit: limit.value,
    page: currentPage.value,
    keyword: searchForm.keyword,
    checkedidstring: arr.join(","),
  };

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

const router = useRouter();
function goToPage(id) {
  router.push({ name: "szmsg_tzkc_setting", params: { id } })
}


onMounted(() => {
  setTimeout(() => {
    let searchContent = document.querySelector(".searchContent");
    let offset = document.querySelector(".searchDiv");
    let parentObj = document.querySelector(".tzkcManage");
    searchContent.style.height = parentObj.clientHeight - offset.clientHeight + "px";
    window.onresize = function () {
      let searchContent = document.querySelector(".searchContent");
      let parentObj = document.querySelector(".tzkcManage");
      searchContent.style.height = parentObj.clientHeight - offset.clientHeight + "px";
    }
  }, 0)
})
</script>

<style lang="scss" scoped>
@import "~/styles/dialog.scss";
.tzkcManage {
  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>