<template>
  <div class="mszyTeamContent">
    <div class="searchContent bg-white p-4 pb-0 my-4 rounded-6px flex justify-between">
      <el-form ref="ruleFormRef" :inline="true" :model="searchForm" size="small">
        <el-form-item>
          <el-date-picker v-model="kssj" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" @change="handleDateChange" />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="initData">查询</el-button>
    </div>
    <div class="resultDiv bg-white p-4 rounded-6px">
      <div class="operateDiv flex justify-between">
        <div>
          <el-button type="primary" @click="handleExport">导出</el-button>
          <el-button type="primary" @click="dialogVisible=true">选择章节导入</el-button>
          <el-button type="danger" @click="handleDelete()">删除</el-button>
        </div>
        <div class="flex items-center space-x-4">
          <div class="cursor-pointer underline defaultColor whitespace-nowrap" @click="setTime()">批量设置开放时间</div>
          <el-input v-model="searchForm.keyword" placeholder="请输入搜索的关键词" size="small" :suffix-icon="Search" />
          <el-button type="primary" @click="initData">搜索</el-button>
        </div>
      </div>
      <div class="tableList">
        <div class="tableDiv my-20px">
          <el-table :data="tableData" size="large" height="100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column v-for="(item, index) in columnData" :key="index" :prop="item.key" :label="item.name" :width="item.width" :min-width="item.minWidth" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="{ row }">
                <el-button type="primary" text @click="handleSort(row)">排序</el-button>
                <el-divider direction="vertical" />
                <el-button type="primary" text @click="setTime(row)">开放时间设置</el-button>
                <el-divider direction="vertical" />
                <el-button type="primary" text @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
        <div class="flex justify-end">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="limit" :page-sizes="[10, 20, 50, 100]" :pager-count="5" :small="true" layout="total,sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <el-dialog class="chapterDialog" v-model="dialogVisible" width="1000px" destroy-on-close :close-on-click-modal="false" @close="handleClose">
      <chapter-list :parentId="parentId" @close="handleClose"></chapter-list>
    </el-dialog>

    <el-dialog v-model="operateDialogVisible" :title="operateType==1?'排序':'开放时间设置'" width="400px" destroy-on-close :close-on-click-modal="false" @close="handleClose">
      <el-form v-if="operateType==1" class="text-center" ref="ruleFormRef" :inline="true" size="small">
        <el-form-item label="序号:" class="w-200px">
          <el-input type="number" v-model="sortValue" :min="0"></el-input>
        </el-form-item>
      </el-form>
      <el-form v-if="operateType==2" class="text-center" ref="ruleFormRef" :inline="true" size="small">
        <el-form-item label="开始时间:">
          <date-time-picker type="datetime" value-format="YYYY-MM-DD HH:mm:ss" v-model="tmz_kckqsj" :end="tmz_kcjssj"></date-time-picker>
        </el-form-item>
        <el-form-item label="结束时间:">
          <date-time-picker type="datetime" value-format="YYYY-MM-DD HH:mm:ss" v-model="tmz_kcjssj" :start="tmz_kckqsj"></date-time-picker>
        </el-form-item>
      </el-form>
      <div class="mt-5 text-center">
        <el-button type="primary" plain @click="handleClose()">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import ChapterList from "./components/ChapterList.vue";
import { timestamp2string } from "~/utils/string";
const router = useRouter();
const parentId = router.currentRoute.value.params.id;

const searchForm = ref({});

watch(() => searchForm.value, () => {
  initData();
}, { deep: true })

const kssj = ref([]);
const handleDateChange = (val) => {
  if (val) {
    searchForm.value.time_range = val[0] + " - " + val[1];
  } else {
    searchForm.value.time_range = "";
  }
}

const total = ref(0)
const limit = ref(10)
const currentPage = ref(1);
const columnData = ref([
  {
    name: "章节ID",
    key: "tmz_id",
  },
  {
    name: "名称",
    key: "tmz_zjmc",
  },
  {
    name: "责任教师",
    key: "tmz_zrjs_mc",
  },
  {
    name: "开放时间",
    key: "kfsj",
  },
  {
    name: "报名量",
    key: "tmk_bml",
  },
  {
    name: "浏览量",
    key: "tmk_lll",
  },
  {
    name: "点赞量",
    key: "tmz_dzl",
  }
]);

const tableData = ref([]);
initData();
async function initData() {
  let data = {
    page: currentPage.value,
    limit: limit.value,
    tmk_id: parentId
  };
  let res = await request({ url: "/txwx/mszy_zj/index", data: Object.assign(data, searchForm.value) });
  if (res.code == 1) {
    res.data.page_data.map(item => {
      item.time = item.ex.create_dateline;
      if (item.tmz_kckqsj && item.tmz_kcjssj) {
        item.kfsj = `${item.tmz_kckqsj} ~ ${item.tmz_kcjssj}`;
      }
    })
    tableData.value = res.data.page_data;
    total.value = Number(res.data.total_rows);
  }
}

function handleSizeChange(val) {
  limit.value = val;
  currentPage.value = 1;
  initData();
}

function handleCurrentChange(val) {
  currentPage.value = val;
  initData();
}

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

const dialogVisible = ref(false);
const operateDialogVisible = ref(false);
const operateType = ref("");
const currentData = ref({});
const sortValue = ref(0);
const tmz_kckqsj = ref("");
const tmz_kcjssj = ref("");

const handleClose = (type) => {
  dialogVisible.value = false;
  operateDialogVisible.value = false;
  operateType.value = "";
  currentData.value = {};
  sortValue.value = 0;
  tmz_kckqsj.value = "";
  tmz_kcjssj.value = "";
  if (type == 1) {
    initData();
  }
}

const handleDelete = (row) => {
  if (!row && multiSelection.value.length == 0) {
    ElMessage.error("请先选择数据！");
    return
  }
  ElMessageBox.confirm('确定要删除该数据吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning",
  })
    .then(async () => {
      let tmz_id;
      if (row) {
        tmz_id = row.tmz_id;
      } else {
        tmz_id = [];
        multiSelection.value.map(item => {
          tmz_id.push(item.tmz_id);
        })
      }
      let res = await request({ url: "/txwx/mszy_zj/delete", data: { tmz_id: tmz_id } });
      if (res.code == 1) {
        ElMessage.success("删除成功！");
        initData();
      }
    })
    .catch(() => { })
}


const handleExport = () => {
  let arr = [];
  multiSelection.value.map((item) => {
    arr.push(item.tmz_id);
  });
  let obj = {
    limit: "99999",
    tmk_id: parentId,
    tmz_id: arr.join(",")
  };
  download("/txwx/mszy_zj/index", obj);
}

const handleSort = (data) => {
  operateDialogVisible.value = true;
  currentData.value = data;
  operateType.value = 1;
}

const setTime = (data) => {
  if (!data && multiSelection.value.length == 0) {
    ElMessage.error("请先选择数据！");
    return
  }
  operateDialogVisible.value = true;
  if (data) {
    currentData.value = data;
  }
  operateType.value = 2;
}

const submit = async () => {
  if (operateType.value == 1) {
    if (parseInt(sortValue.value) != sortValue.value) {
      ElMessage.error("请输入整数！");
      return
    }
    let obj = {
      sort_string: `${currentData.value.tmz_id}-${sortValue.value}`
    }
    let { code } = await request({ url: "/txwx/mszy_zj/batch_sort", data: obj });
    if (code == 1) {
      ElMessage.success("保存成功！");
      handleClose(1);
    }
  } else if (operateType.value == 2) {
    if (!tmz_kckqsj.value || !tmz_kcjssj.value) {
      ElMessage.error("请输入开始时间和结束时间！");
      return
    }
    let arr = [];
    if (currentData.value.tmz_id) {
      arr = [currentData.value.tmz_id];
    } else {
      arr = multiSelection.value.map(item => {
        return item.tmz_id
      })
    }
    let obj = {
      tmz_id: arr.join(),
      tmz_kckqsj: tmz_kckqsj.value,
      tmz_kcjssj: tmz_kcjssj.value
    }
    let { code } = await request({ url: "/txwx/mszy_zj/zj_open", data: obj });
    if (code == 1) {
      ElMessage.success("保存成功！");
      handleClose(1);
    }
  }
}
</script>

<style lang="scss" scoped>
@use "~/styles/table.scss";
@use "~/styles/pagination.scss";
.font14 {
  font-size: 14px;
}
.font24 {
  font-size: 24px;
}
.defaultColor {
  color: var(--el-color-primary);
}
.mszyTeamContent {
  .resultDiv {
    .tableList {
      height: calc(100% - 32px);
      .tableDiv {
        height: calc(100% - 32px - 50px);
      }
    }
  }
  :deep() .el-dialog {
    .el-date-editor.el-input,
    .el-date-editor.el-input__wrapper {
      width: 100%;
    }
    .el-button--primary.is-plain {
      background: unset;
      &:hover {
        color: var(--el-color-primary);
      }
    }
    .el-button + .el-button {
      margin-left: 50px;
    }
  }
}
:deep() .chapterDialog {
  .el-dialog__header {
    display: none;
  }
}
</style>