<template>
  <div class="tzkcSettingManage" v-loading="loading">
    <div class="breadDiv">
      <span>艺术视野</span>
      <el-icon>
        <ArrowRight />
      </el-icon>
      <span>拓展课程</span>
      <el-icon>
        <ArrowRight />
      </el-icon>
      <span>学校设置</span>
      <el-icon>
        <ArrowRight />
      </el-icon>
      <span style="color: #6E6E6E;">{{tabData[activeTab]}}</span>
    </div>
    <div class="tabDiv">
      <el-tabs v-model="activeTab" class="demo-tabs" @tab-change="initData">
        <el-tab-pane v-for="(item, index) in tabData" :key="index" :label="item" :name="index"></el-tab-pane>
      </el-tabs>
    </div>

    <div class="searchContent">
      <div class="searchBtn flex">
        <div class="flex">
          <el-button size="default" type="success" @click="handleDownload" v-if="activeTab!=0">导出</el-button>
          <el-button size="default" type="primary" @click="handleAddOrEdit(1)">添加</el-button>
          <el-button size="default" type="danger" @click="handleRemove()">删除</el-button>
        </div>
        <div class="flex" v-if="activeTab!=0">
          <el-input v-model="searchForm.keyword" size="default" placeholder="请输入搜索的关键词" style="margin: 0 10px;" :suffix-icon="Search" />
          <el-button size="default" type="primary" @click="initData">搜索</el-button>
        </div>
      </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" />
            <template v-if="activeTab==0">
              <el-table-column prop="banner_name" width="" label="banner名字" show-overflow-tooltip></el-table-column>
              <el-table-column width="" label="图片" show-overflow-tooltip>
                <template #default="{row}">
                  <el-image style="width: 38px; height: 38px;display: block;" :src="getFullUrl(row.banner_img)" :preview-teleported="true" :preview-src-list="[getFullUrl(row.banner_img)]" />
                </template>
              </el-table-column>
              <el-table-column prop="banner_sort" width="" label="顺序" show-overflow-tooltip></el-table-column>
            </template>
            <template v-if="activeTab==1">
              <el-table-column prop="ssz_name" width="" label="课程名称" show-overflow-tooltip>
                <template #default="{row}">
                  <span style="color: #00A3FF;">{{row.ssz_name}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="grade_name" width="" label="年级" show-overflow-tooltip></el-table-column>
              <el-table-column prop="subject_name" width="" label="学科" show-overflow-tooltip></el-table-column>
              <el-table-column prop="ssz_zjls_name" width="" label="主讲老师" show-overflow-tooltip></el-table-column>
            </template>
            <template v-if="activeTab==2">
              <el-table-column prop="ssn_title" width="" label="标题" show-overflow-tooltip>
                <template #default="{row}">
                  <span style="color: #00A3FF;">{{row.ssn_title}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="ssn_fbr" width="" label="创建人" show-overflow-tooltip></el-table-column>
              <el-table-column prop="ssn_lx" width="" label="类型" show-overflow-tooltip></el-table-column>
              <el-table-column prop="ssn_glr_json" width="" label="关联的人" show-overflow-tooltip></el-table-column>
              <el-table-column label="详情" width="">
                <template #default="{row}">
                  <el-button text size="default" type="primary" @click="lookDetail(row)">查看</el-button>
                </template>
              </el-table-column>
            </template>
            <el-table-column label="操作" width="130">
              <template #default="{row}">
                <el-button text size="default" type="primary" @click="handleAddOrEdit(2, row)">编辑</el-button>
                <el-button text size="default" type="primary" @click="handleRemove(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="paginationDiv" v-if="activeTab!=0">
          <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="showAttach?'80%':'600px'" v-model="dialogVisible" :title="dialogTitle" custom-class="commonDialog" :show-close="showAttach?true:false" :close-on-click-modal="false" @close="handleClose">
      <preview-attach v-if="showAttach" :commonUrl="commonUrl" :suffix="suffix" style="width: 100%; height: 600px;"></preview-attach>
      <template v-else>
        <banner-create v-if="activeTab==0 && dialogVisible" :editForm="editForm" @update="handleClose" @data="initBannerData"></banner-create>
        <course-create v-if="activeTab==1 && dialogVisible" :parentId="parentId" :current="currentId" @update="handleClose" @load="handleLoad"></course-create>
        <inform-create v-if="activeTab==2 && dialogVisible" :parentId="parentId" :current="currentId" :typeData="typeData" @update="handleClose" @load="handleLoad"></inform-create>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { Search, ArrowRight } from "@element-plus/icons-vue";
import BannerCreate from "./components/BannerCreate.vue";
import CourseCreate from "./components/CourseCreate.vue";
import InformCreate from "./components/InformCreate.vue";
import { getFullUrl } from "~/utils/helper";
import { download } from "~/utils/request";
import { schoolDetail, schoolEdit, gradeList, subjectList, schoolZpList, schoolZpDelete, schoolNoticeList, schoolNoticeDelete } from "./api";
import { useRouter } from "vue-router";
const router = useRouter();
const parentId = ref(router.currentRoute.value.params.id);

const typeData = ref([]);
const loading = ref(false);
const activeTab = ref(0);
const tabData = ["banner", "学校课程", "通知公告"];

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

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

initSelectData();
const gradeData = ref([]);
const subjectData = ref([]);
async function initSelectData() {
  let data1 = await gradeList();
  gradeData.value = data1.page_data;

  let data2 = await subjectList();
  subjectData.value = data2.page_data;

  initData(1);
}

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

async function initData(flag) {
  loading.value = true;
  if (activeTab.value == 0) {
    let data = await schoolDetail({ ss_id: parentId.value });
    if (data.one_info.ss_banner_img != "") {
      try {
        let imgData = JSON.parse(data.one_info.ss_banner_img);
        imgData.sort((a, b) => {
          return Number(a.banner_sort) - Number(b.banner_sort)
        })
        imgData.map((item, index) => {
          item.id = index;
        })
        tableData.value = [...imgData];
      } catch (error) {

      }
    }
  } else {
    let data = {};
    let obj = {
      limit: limit.value,
      page: currentPage.value,
      keyword: searchForm.keyword,
      ss_id: parentId.value
    }
    if (activeTab.value == 1) {
      data = await schoolZpList(obj);
      // data.page_data.map(item => {
      //   gradeData.value.map(v => {
      //     if (item.grade_id == v.grade_id) {
      //       item.grade_name = v.grade_name;
      //     }
      //   })
      //   subjectData.value.map(v => {
      //     if (item.subject_id == v.subject_id) {
      //       item.subject_name = v.subject_name;
      //     }
      //   })
      // })
    } else if (activeTab.value == 2) {
      obj.site = "tyyx";
      data = await schoolNoticeList(obj);

      // if (flag == 1) {
      typeData.value = data.table_structure.field.ssn_lx.option;
      // }
    }
    total.value = parseInt(data.total_rows);
    tableData.value = data.page_data;
  }
  loading.value = false;
}


const dialogVisible = ref(false);
const dialogType = ref(0);
const dialogTitle = ref("");
const currentId = ref("");
const editForm = ref();
function handleAddOrEdit(type, row) {
  dialogVisible.value = true;
  dialogType.value = 1;
  if (type == 1) {
    dialogTitle.value = "添加";
  } else {
    dialogTitle.value = "编辑";
    if (activeTab.value == 0) {
      editForm.value = row;
    } else if (activeTab.value == 1) {
      currentId.value = row.ssz_id;
    } else if (activeTab.value == 2) {
      currentId.value = row.ssn_id;
    }
  }
}


const showAttach = ref(false);
const commonUrl = ref("");
const suffix = ref("");
const lookDetail = (data) => {
  dialogVisible.value = true;
  showAttach.value = true;
  dialogTitle.value = "详情";

  commonUrl.value = data.ssn_file;
  suffix.value = commonUrl.value.substr(commonUrl.value.lastIndexOf(".") + 1);
}


function handleClose(type) {
  dialogVisible.value = false;
  currentId.value = "";
  editForm.value = undefined;
  showAttach.value = false;
  if (type == 1) {
    initData();
  }
}


async function initBannerData(data) {
  // tableData.value = tableData.value || [];
  loading.value = true;
  let arr = [...tableData.value];
  if (data.id === undefined) {
    arr = arr.concat([data]);
  } else {
    let rIndex = 0;
    arr.map((item, index) => {
      if (item.id == data.id) {
        rIndex = index;
      }
    })
    arr[rIndex] = data;
  }
  let obj = {
    ss_id: parentId.value,
    szmsg_school: {
      ss_banner_img: JSON.stringify(arr)
    }
  }
  await schoolEdit(obj);
  loading.value = false;
  ElMessage.success("保存成功！");
  handleClose(1);
}

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

const handleRemove = (row) => {
  if ((row == undefined || row == "") && multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除的数据！");
    return;
  }

  ElMessageBox.confirm("是否确定删除当前数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    buttonSize: "default",
  })
    .then(async () => {
      loading.value = true;
      if (activeTab.value == 0) {
        let arr = [];
        if (row) {
          arr = tableData.value.filter(item => row.id != item.id);
        } else {
          let vData = [];
          multipleSelection.value.map(value => {
            vData.push(value.id)
          })
          arr = tableData.value.filter(item => vData.indexOf(item.id) == -1);
        }
        let obj = {
          ss_id: parentId.value,
          szmsg_school: {
            ss_banner_img: JSON.stringify(arr)
          }
        }
        await schoolEdit(obj);
      } else if (activeTab.value == 1) {
        if (row != undefined && row != "") {
          await schoolZpDelete({ ssz_id: row.ssz_id });
        } else {
          let arr = [];
          multipleSelection.value.map((item) => {
            arr.push(item.ssz_id);
          });
          await schoolZpDelete({ ssz_id: arr });
        }
      } else if (activeTab.value == 2) {
        if (row != undefined && row != "") {
          await schoolNoticeDelete({ ssn_id: row.ssn_id });
        } else {
          let arr = [];
          multipleSelection.value.map((item) => {
            arr.push(item.ssn_id);
          });
          await schoolNoticeDelete({ ssn_id: arr });
        }
      }
      ElMessage.success("删除成功！");
      loading.value = false;
      initData();
    })
    .catch(() => { });
}


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

    download("/szmsg/school_zp/index", obj);
  } else if (activeTab.value == 2) {
    let arr = [];
    multipleSelection.value.map((value) => {
      arr.push(value.ssn_id);
    });
    let obj = {
      limit: limit.value,
      page: currentPage.value,
      keyword: searchForm.keyword,
      ss_id: parentId.value,
      checkedidstring: arr.join(","),
    };

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


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

<style lang="scss" scoped>
@import "~/styles/dialog.scss";
.tzkcSettingManage {
  height: calc(100vh - 50px - 2rem);
  .flex {
    display: flex;
    align-items: center;
  }
  .breadDiv {
    color: #00a3ff;
    display: flex;
    align-items: center;
    .el-icon {
      margin: 0 5px;
    }
  }
  .tabDiv {
    margin-top: 10px;
  }
  .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>