<template>
  <div>
    <div class="flex">
      <el-form :inline="true">
        <el-form-item prop="" label="活动名称: ">
          <el-input
            placeholder="请输入活动名称"
            v-model="searchData.keyword"
            clearable
            @clear="getListData"
          ></el-input>
        </el-form-item>
        <el-form-item prop="" label="时间">
          <el-date-picker
            v-model="searchData.time"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
            type="datetime"
            @change="timeClear"
            placeholder="请选择时间"
          />
        </el-form-item>
      </el-form>
      <el-button type="primary" style="padding-bottom" @click="searchList"
        >搜索</el-button
      >
      <el-button type="warning" @click="clearData">清空</el-button>
    </div>

    <div class="flex justify-between items-center border-bottom">
      <div>
        <el-button @click="exportData" type="success">导出</el-button>
        <el-button
          type="danger"
          @click="delData"
          :disabled="multipleSelection?.length == 0"
          >删除</el-button
        >
      </div>
      <div class="print flex items-center">
        <img
          class="w-20px h-20px cursor-pointer"
          src="/images/print.png"
          alt=""
        />
      </div>
    </div>
    <el-table
      :data="tableData"
      tooltip-effect="dark"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      class="mt20"
      style="width: 100%"
    >
      <el-table-column type="selection" align="center" width="55">
      </el-table-column>
      <el-table-column label="活动名称">
        <template #default="scope">
          <el-popover
            placement="top-start"
            :width="150"
            trigger="hover"
            content="点击查看作品"
          >
            <template #reference>
              <div @click="handleLink(scope.row)" class="cursor-pointer">
                {{ scope.row.yz_name }}
              </div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="活动类型" prop="yz_cate"></el-table-column>
      <el-table-column label="活动级别" prop="yz_hdjb"></el-table-column>
      <el-table-column
        label="活动时间"
        prop="yz_time"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="text" @click="auditData(scope.row)">上传</el-button>
        </template>
      </el-table-column>
    </el-table>
    <footer
      class="flex-item-none"
      style="display: flex; justify-content: flex-end; margin-top: 30px"
    >
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
        :page-size="limit"
        :currentPage="currentPage"
      ></el-pagination>
    </footer>
    <el-dialog v-model="dialogVisible" title="上传" width="950px">
      <el-form
        :model="form"
        :label-width="formLabelWidth"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="作品封面图" prop="yzcz_img">
          <file-upload-progress
            v-model:part="form.yzcz_img"
            :limit="1"
            list-type="picture-card"
            accept=".jpg,.png,.jpeg"
            :size-limit="200"
          >
            <template #default>
              <i-akar-icons:plus class="text-4xl" />
            </template>
            <template #tip>
              <div class="mt-2">
                支持格式：jpg,png,jpeg（200kb以内） 建议尺寸600x320
              </div>
            </template>
          </file-upload-progress>
        </el-form-item>
        <el-form-item label="活动名称" prop="yz_name">
          <el-input v-model="form.yz_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="作品名称" prop="yzcz_name">
          <el-input v-model="form.yzcz_name" />
        </el-form-item>
        <el-form-item label="简介" prop="yzcz_brief">
          <el-input
            v-model="form.yzcz_brief"
            type="textarea"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="作者" prop="yzcz_author">
          <el-input v-model="form.yzcz_author" autocomplete="off" />
        </el-form-item>
        <div class="flex w-450px">
          <el-form-item label="年级" prop="grade">
            <el-select-v2
              v-model="form.grade"
              placeholder="请选择年级"
              size="large"
              :options="SelectOptionMap.grade"
              @change="handleSelectV2Change($event, 'grade', 'grade')"
            >
            </el-select-v2>
          </el-form-item>
          <el-form-item label="学科" prop="subject">
            <el-select-v2
              v-model="form.subject"
              placeholder="请选择学科"
              size="large"
              :options="SelectOptionMap.subject"
              @change="handleSelectV2Change($event, 'subject', 'subject')"
            >
            </el-select-v2>
          </el-form-item>
        </div>
        <el-form-item label="附件" prop="yzcz_fj">
          <file-upload-progress
            v-model:part="form.yzcz_fj"
            :limit="1"
            accept=".doc,.docx,.xls,.xlsx"
          >
            <template #default>
              <div
                class="
                  flex_center
                  w-65px
                  h-65px
                  border border-dashed border-hex-E4E6E8
                  bg-hex-F9F9F9
                  text-hex-9D9AB9
                "
              >
                <i-ant-design:folder-open-outlined class="text-xl" />
              </div>
            </template>
          </file-upload-progress>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer w-180px">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addWork">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { hdgl_list, grade_list, subject_list, hdzp_add, hd_del } from "./api";
import { ElMessageBox } from "element-plus";
import { download } from "~/utils/request";
import { useRouter } from "vue-router";
let total = $ref(0);
const limit = $ref("10");
let currentPage = $ref("1");
let loading = $ref(false);
let tableData = $ref([]);
let hdData = {
  site: "tyyx",
  admin: "1",
  limit,
  page: currentPage,
};
// 初始化
function getList() {
  loading = true;
  hdgl_list(hdData).then((res) => {
    if (res.code === "1") {
      res.data.page_data.forEach((item) => {
        item.yz_time =
          item.yz_start_datetime.split(" ")[0] +
          "--" +
          item.yz_end_datetime.split(" ")[0];
      });
      tableData = res.data.page_data;
      total = parseInt(res.data.total_rows);
      loading = false;
    }
  });
}
getList();
// 分页
function handleCurrentChange(val) {
  currentPage = val;
  hdData.page = currentPage;
  getList();
}
// 搜索
let searchData = $ref({
  keyword: "",
  time: "",
});
function searchList() {
  const { keyword, time } = searchData;
  Object.assign(hdData, {
    keyword: keyword,
    create_dateline: time,
  });
  getList();
}
function timeClear(time) {
  if (!time) {
    time = "";
    searchList();
  }
}
function getListData() {
  searchList();
}
// 清空
function clearData() {
  searchData = {
    keyword: "",
    time: "",
  };
  searchList();
}

// 选中表格数据
let multipleSelection = $ref([]);
function handleSelectionChange(val) {
  multipleSelection = [];
  val.forEach((item) => {
    multipleSelection.push(item.yz_id);
  });
}
// 导出
function exportData() {
  const { keyword, time } = searchData;
  let data = {
    // admin: "1",
    site: "tyyx",
    keyword,
    create_dateline: time,
    yz_id: multipleSelection,
  };
  download("/ysgc/ztyshd/index", data);
}
// 删除活动
function delData() {
  let data = {
    yz_id: multipleSelection,
  };
  ElMessageBox.confirm("确认删除?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      hd_del(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            type: "success",
            message: "操作成功",
          });
          getList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "操作失败",
      });
    });
}
function handleSelectV2Option(data, value, label, name) {
  const res = data.map((item) => {
    if (!SelectMap[name]) {
      SelectMap[name] = {};
    }
    SelectMap[name][item[value]] = item[label];
    return { value: item[value], label: item[label] };
  });
  SelectOptionMap[name] = res;
  return res;
}
// 年级
let gradeData = $ref([]);
function getGrade() {
  gradeData = [];
  grade_list().then((res) => {
    if (res.code == "1") {
      gradeData = res.data.page_data;
      handleSelectV2Option(gradeData, "grade_id", "grade_name", "grade");
    }
  });
}
// 学科
let subjectData = $ref([]);
function getSubject() {
  subjectData = [];
  subject_list().then((res) => {
    if (res.code == "1") {
      subjectData = res.data.page_data;
      handleSelectV2Option(subjectData, "subject_id", "subject_name", "subject");
    }
  });
}

// 上传作品
let form = $ref({
  yz_img: "",
  yz_name: "",
  yzcz_name: "",
  yzcz_brief: "",
  yzcz_author: "",
  grade: {},
  subject: {},
  yzcz_fj: "",
});
const rules = {
  yzcz_img: [{ required: true, message: "请选择作品封面", trigger: "submit" }],
  yz_name: [{ required: true, message: "请输入活动名称", trigger: "submit" }],
  yzcz_name: [{ required: true, message: "请输入作品名称", trigger: "submit" }],
  yzcz_brief: [
    { required: true, message: "请输入作品简介", trigger: "submit" },
  ],
  yzcz_author: [{ required: true, message: "请输入作者", trigger: "submit" }],
  grade: [{ required: true, message: "请选择年级", trigger: "submit" }],
  subject: [{ required: true, message: "请选择学科", trigger: "submit" }],
  yzcz_fj: [{ required: true, message: "请上传附件", trigger: "submit" }],
};
let SelectOptionMap = $ref({});
let SelectMap = $ref({});
function handleSelectV2Change(val, name, key) {
  console.log("handleSelectV2Change :>> ", SelectMap[name]);
  form[key] = SelectMap[name][val];
}
const formLabelWidth = "260px";
let dialogVisible = $ref(false);
let yz_id;
let yzcz_cate_name;
function auditData(item) {
  handleSelectV2Option(gradeData, "grade_id", "grade_name", "grade");
  handleSelectV2Option(subjectData, "subject_id", "subject_name", "subject");
  try {
    Object.keys(form).forEach((key) => {
      form[key] = "";
    });
    yzcz_cate_name = item.yz_cate;
    yz_id = item.yz_id;
    form.yz_name = item.yz_name;
    getGrade();
    getSubject();
    dialogVisible = true;
  } catch (error) {
    console.error(error);
  }
}
let formRef = $ref();
function addWork() {
  console.log(form.yzcz_fj);
  formRef.validate().then((res) => {
    console.log(res, 11111);
    if (res === true) {
      let addData = {
        ysgc_ztyshd_cyxx_zp: {
          yzcz_name: form.yzcz_name,
          yzcz_img: form.yzcz_img,
          yzcz_author: form.yzcz_author,
          yzcz_brief: form.yzcz_brief,
          grade_id: form.grade.grade_id,
          grade_name: form.grade.grade_name,
          subject_id: form.subject.subject_id,
          subject_name: form.subject.subject_name,
          yz_id,
          yzcz_cate_name,
          yz_name: form.yz_name,
          yzcz_fj: form.yzcz_fj,
        },
      };
      ElMessageBox.confirm("确认上传?", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(1111111);
          hdzp_add(addData).then((res) => {
            if (res.code == 1) {
              ElMessage({
                type: "success",
                message: "上传成功",
              });
              dialogVisible = false;
            }
          });
        })
        .catch(() => {
          console.log(222222222222);
          ElMessage({
            type: "info",
            message: "上传失败",
          });
        });
    }
  });
}
// 跳转查看详情
const router = useRouter();
function handleLink(item) {
  router.push({
    name: "hdgl_detail",
    params: {
      id: item.yz_id,
    },
  });
}
</script>
<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-input,
.el-select,.el-select-v2 {
  width: 160px;
}
.el-textarea {
  width: 450px;
}
.dialog-footer {
  margin: 0 auto;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>