<script setup>
import { Search } from '@element-plus/icons-vue'
import swiper from "/images/banner.jpg";
import { user } from "~/store/index";
import { downLoadFile } from "~/utils/download";
import { userDetailStore } from "~/store/detail";
const detailStore = userDetailStore();
const router = useRouter();

const catalog = ref("spjj");
const params = ref({
  create_user_id: user.value.user_id,
});

const fields = ref({
  id: "as_id",
  name: "as_title",
  img: "as_img",
  time: "create_dateline",
  file: "as_file",
  page: "grzx",
});

const spjjListRef = ref();
// #region 建立专题form
const scFormRef = ref();
const scForm = ref({
  az_name: "",
  az_img: "",
  az_file: "",
});
// #endregion
// #region 编辑form
const jjFormRef = ref();
let jjForm = ref({
  as_title: "",
  as_img: "",
  azz_ssnj_v2: "",
  azz_id_v2: "",
  azb_id_v2: "",
  as_zy_sm_id_v2: "",
});
const rules = reactive({
  as_title: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
  azz_ssnj_v2: [{ required: true, message: "请选择年级", trigger: "submit" }],
  azz_id_v2: [{ required: true, message: "请选择所属专业", trigger: "submit" }],
  as_img: [{ required: true, message: "请上传封面", trigger: "submit" }],
});

// #endregion

const status = ref();
const statusData = ref([
  {
    name: "个人空间",
    status: "1",
  },
  {
    name: "公共空间",
    status: "2",
  },
  // {
  //   name: "专题资源",
  //   status: "3",
  // },
]);

const form_query = $ref({
  page: 1,
  limit: 999,
});

// 标签列表
let tag_list = $ref([]);
async function getTagData() {
  const { code, data } = await request({
    url: "/aimooc/zyfl_bq_v2/index",
    data: {
      ...form_query,
    },
  });
  if (code === "1") {
    tag_list = [...data.page_data];
  }
}

// 学校列表
let school_list = $ref([]);
async function getSchoolData() {
  const { code, data } = await request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url: "/index.php?mod=school&action=main&do=index",
    data: {
      ...form_query,
    },
  });
  if (code === "1") {
    school_list = [...data.page_data];
  }
}

// changeForm学校
function handelChangeSchool(e) {
  initCamp(e);
}

const gradeData = $ref([
  {
    v: "1",
    n: "一年级",
  },
  {
    v: "2",
    n: "二年级",
  },
  {
    v: "3",
    n: "三年级",
  },
  {
    v: "4",
    n: "四年级",
  },
  {
    v: "5",
    n: "五年级",
  },
  {
    v: "6",
    n: "六年级",
  },
]);

initCamp(user.value.sm_info?.sm_id);
let campData = $ref([]);
// 学院信息
function initCamp(e) {
  request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url: "/school/main/get_camp",
    data: {
      ...form_query,
      sm_id: e,
    },
  }).then((res) => {
    const { code, data } = res;
    if (code === "1") {
      campData = data.camp;
      if (campData.length === 0) {
        handelChangeCamp();
      }
    }
  });
}

let subjectData = $ref([]);
// 筛选change学院
function handelChangeCamp(e) {
  params.value.azz_id_v2 = "";
  subjectData = [];
  request({
    url: `/aimooc/zyfl_zy_v2/index`,
    data: { ...form_query, sm_id: e },
  }).then((res) => {
    const { code, data } = res;
    if (code === "1") {
      subjectData = data.page_data;
    }
  });
}
// form change年级
function handleChangeFormGrade(e) {
  jjForm.value.azz_id_v2 = "";
  subjectData = [];
  if (!e) return;
  request({
    url: `/aimooc/zyfl_zy_v2/index`,
    data: { page: 1, limit: "99", azz_ssnj_v2: e },
  }).then((res) => {
    const { code, data } = res;
    if (code === "1") {
      subjectData = data.page_data;
    }
  });
}

const checkAll = ref(false);
const checkedData = ref([]);

// #region 切换tab
changeStatus("1");
function changeStatus(data) {
  status.value = data;
  checkAll.value = false;
  checkedData.value = [];
  if (data === "1") {
    // 个人空间
    params.value.public_space = "";
    params.value.as_zy_shzt_v2 = "4";
    params.value.as_status = "Success";
  } else if (data === "2") {
    // 公共空间
    params.value.as_zy_shzt_v2 = "";
    params.value.public_space = "1";
    params.value.as_status = "Success";
  } else {
    // 专题资源
  }
}
// #endregion

function initCheckData(data) {
  checkedData.value = [...data];
}

// #region 弹出框
const dialogVisible = ref(false);
const dialogType = ref(0);
const dialogTitle = ref("");
const currentId = ref("");

function initDialog(show, title, type) {
  dialogVisible.value = show;
  dialogTitle.value = title;
  dialogType.value = type;

  if (!show) {
    handelChangeCamp("");
    currentId.value = "";
    for (const key in jjForm.value) jjForm.value[key] = "";
  }
}
// #endregion

// 批量推出
let ids = [];
let qxFormRef = $ref();
let qxForm = ref({});
let qxRules = reactive({
  as_open_set_v3: [{ required: true, message: "请选择权限", trigger: "blur" }],
  as_open_class_v3: [
    { required: true, message: "请选择指定班级", trigger: "submit" },
  ],
  as_open_user_v3: [
    { required: true, message: "请选择指定用户", trigger: "submit" },
  ],
});
let powerData = $ref([
  {
    text: "私密",
    value: "1",
  },
  {
    text: "公开",
    value: "2",
  },
  {
    text: "仅自己班级可见",
    value: "3",
  },
  {
    text: "指定账号可见",
    value: "4",
  },
]);
let powerSetShow = $ref(false);

// 班级信息
let classData = $ref([]);
async function getClassData() {
  const { code, data } = await request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url: "/index.php?mod=class&action=main&do=index",
    data: {
      ...form_query,
      // creatorid: user.value.user_id
    },
  });
  if (code === "1") {
    classData = [...data.page_data];
  }
}

// 用户列表
let userData = $ref([]);
let loading = $ref(false);
function getUserData() {
  loading = true;
  request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url: "/user/main/index",
    data: {
      ...form_query,
      // creatorid: user.value.user_id
    },
  }).then((res) => {
    if (res.code == "1") {
      loading = false;
      userData = res.data.page_data;
    }
  });
}

function getUserData2(){
  loading = true;
  let cm_id = [];
  user.value.cm_info.forEach(el=>{
    cm_id.push(el.cm_id);
  })
  request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url: "/class/main/detail_multi",
    data: {
      ...form_query,
      cm_id: cm_id.join(',')
    },
  }).then((res) => {
    if (res.code == "1") {
      loading = false;
      userData = [];
      if(res.data.one_info.length>0){
        res.data.one_info.forEach(item=>{
          userData.push(...item.teachers)
          userData.push(...item.students)
        })
        // 去重
        userData = userData.filter((el,index,self)=>{
          let idsList = [];
          userData.forEach((item,i)=>{
            idsList.push(item.user_id)
          })
          return idsList.indexOf(el.user_id) == index;
        })
      }
    }
  });
}

function handelChangeRadio(e) {
  console.log(e);
  if (e == "3" || e == "4") {
    console.log(qxForm.value, "444");
    qxForm.value.as_open_class_v3 = [];
    qxForm.value.as_open_user_v3 = [];
  }
}

function handleCreatePublic() {
  getClassData();
  if(user.value.user_role_id=='75'){
    getUserData2();
  }else{
    getUserData();
  }
  const arr = checkedData.value.map((item) => {
    return item[fields.value.id];
  });
  ids = arr;
  if (arr.length == 0) {
    return ElMessage.warning("请先选择需要推出的数据");
  }
  powerSetShow = true;
  initDialog(true, "公开设置权限", 3);
}

// 编辑
getSchoolData();
function handleEdit(data) {
  getTagData();
  handelChangeSchool(data.sm_id);
  handleChangeFormGrade(data.azz_ssnj_v2);
  currentId.value = data[fields.value.id];
  for (const key in jjForm.value) jjForm.value[key] = data[key];
  jjForm.value.as_zy_sm_id_v2 = data.sm_id;
  jjForm.value.azz_ssnj_v2 = data.azz_ssnj_v2 == "0" ? "" : data.azz_ssnj_v2;
  jjForm.value.camp_id_v3 = data.camp_id_v3
  initDialog(true, "编辑", 2);
}

// 提交
function handleSubmit() {
  // spjjListRef.value.initData();
  // 编辑
  if (dialogType.value === 2) {
    jjFormRef.value?.validate(async (valid, fields1) => {
      if (valid) {
        const { code, data } = await request({
          url: `/aimooc/${catalog.value}/edit`,
          data: {
            [fields.value.id]: currentId.value,
            aimooc_spjj: jjForm.value,
          },
        });
        if (code === "1") {
          initDialog(false, "", 0);
          ElMessage.success("保存成功！");
          spjjListRef.value.initData();
        }
      } else {
        console.log("error submit!", fields1);
      }
    });
  }
  // 公共权限
  else if (dialogType.value === 3 || dialogType.value === 4) {
    qxFormRef.validate(async (valid, fields2) => {
      if (valid) {
        ElMessageBox.confirm(
          dialogType.value === 3 ? "确定要推送这些数据吗？" : "确定要更改权限?",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            let data = {
              [fields.value.id]: dialogType.value === 3 ? ids.join(",") : ids,
              aimooc_spjj: {
                as_open_set_v3: qxForm.value.as_open_set_v3,
                as_open_class_v3: qxForm.value.as_open_class_v3?.join(","),
                as_open_user_v3: qxForm.value.as_open_user_v3?.join(","),
              },
            };
            if (dialogType.value === 3) {
              data.push = "1";
            }
            const { code } = await request({
              url: `/aimooc/${catalog.value}/edit`,
              data,
            });
            if (code === "1") {
              ElMessage.success(
                dialogType.value === 3 ? "推送成功！" : "更改权限成功！"
              );
              initDialog(false, "", 0);
              spjjListRef.value.initData();
            }
          })
          .catch(() => {});
      } else {
        console.log("error submit!", fields2);
      }
    });
  }
}

// 删除
function handleMutiDelete() {
  const arr = checkedData.value.map((item) => {
    return item[fields.value.id];
  });
  if (arr.length == 0) {
    return ElMessage.warning("请先选择需要删除的数据");
  }
  ElMessageBox.confirm("确定要删除这些数据吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const { code } = await request({
        url: `/aimooc/${catalog.value}/delete`,
        data: { [fields.value.id]: arr },
      });
      if (code === "1") {
        ElMessage.success("删除成功！");
        spjjListRef.value.initData();
      }
    })
    .catch(() => {});
}

// 下载
const handleDownload = (item) => {
  if (!item[fields.value.file]) {
    ElMessage.error("暂无资源！");
    return;
  }
  const arr = item[fields.value.file].split(".");
  const ext = arr[arr.length - 1].split("?")[0].toLowerCase();
  downLoadFile(item[fields.value.file], `${item[fields.value.name]}.${ext}`);
};

//进入详情
function handleEnter(data) {
  if (status.value == "2") {
    // 公共空间
    router.push({
      path: "/home/grzx/detail",
      query: {
        [fields.value.id]: data[fields.value.id],
      },
    });
  } else if (status.value == "1") {
    // 个人空间
    detailStore.setParams({
      catalog: catalog.value,
      idKey: fields.value.id,
      id: data[fields.value.id],
      cover: fields.value.img,
      name: fields.value.name,
      file: fields.value.file,
    });
    router.push("/home/enter");
  }
}

// 公共空间权限编辑
function handlePower(data) {
  ids = data.as_id;
  getClassData();
  if(user.value.user_role_id=='75'){
    getUserData2();
  }else{
    getUserData();
  }
  initDialog(true, "公开设置权限", 4);
  for (const key in qxForm.value) qxForm.value[key] = data[key];
  qxForm.value.as_open_set_v3 =
    data.as_open_set_v3 == "0" ? "" : data.as_open_set_v3;
  qxForm.value.as_open_user_v3 = data.as_open_user_v3?.split(",");
  qxForm.value.as_open_class_v3 = data.as_open_class_v3?.split(',')
}
</script>

<template>
  <div class="h-full flex flex-col">
    <el-scrollbar view-class="h-full flex flex-col">
      <img :src="swiper" class="w-full" alt="" />
      <div class="my-15px flex items-center justify-between">
        <div class="flex space-x-6">
          <div
            v-for="(item, index) in statusData"
            :key="index"
            class="pageTitle"
            :class="status === item.status && 'active'"
            @click="changeStatus(item.status)"
          >
            {{ item.name }}
          </div>
        </div>
        <div class="flex items-center">
          <el-checkbox v-model="checkAll">全选</el-checkbox>
          <el-button
            plain
            class="ml-33px h-42px w-130px del_btn"
            @click="handleMutiDelete"
          >
            删除
          </el-button>
          <template v-if="status === '1'">
            <el-button
              type="primary"
              class="ml-20px h-42px w-130px"
              @click="handleCreatePublic"
              >批量推出</el-button
            >
            <!-- <el-button
            type="primary"
            class="h-42px w-130px"
            @click="initDialog(true, '建立专题', 1)"
            >建立专题</el-button
          > -->
          </template>
          <el-input
            v-model="params.keyword"
            class="ml-20px h-42px rounded-8px"
            placeholder="搜索"
            :prefix-icon="Search"
          />
        </div>
      </div>

      <CommonList
        class="flex-1"
        ref="spjjListRef"
        :to="catalog"
        :d="params"
        :fields="fields"
        @edit="handleEdit"
        @download="handleDownload"
        @enter="handleEnter"
        @power="handlePower"
        :show-check="true"
        :check-all="checkAll"
        @checkValue="initCheckData"
      >
        <template #search>
          <div class="flex items-center justify-end">
            <div
              v-if="status === '2'"
              class="flex items-center justify-end pr-10px pt-20px space-x-4"
            >
              <div>审核状态</div>
              <el-select
                v-model="params.as_zy_shzt_v2"
                class="select"
                size="large"
                clearable
              >
                <el-option label="全部" value="" />
                <el-option label="通过" value="1" />
                <el-option label="不通过" value="2" />
                <el-option label="待审核" value="3" />
              </el-select>
            </div>
            <div
              class="flex items-center justify-end pr-80px pt-20px space-x-4"
            >
              <div>筛选</div>

              <el-select
                v-if="campData.length > 0"
                v-model="params.camp_id"
                class="select_half"
                size="large"
                clearable
                placeholder="请选择学院"
                @change="handelChangeCamp"
              >
                <!-- <el-option label="全部" value="" /> -->
                <el-option
                  v-for="(item, index) in campData"
                  :key="index"
                  :label="item.camp_name"
                  :value="item.camp_id"
                />
              </el-select>
              <el-select
                v-model="params.azz_id_v2"
                class="select_half"
                size="large"
                placeholder="请选择专业"
                clearable
              >
                <el-option label="全部" value="" />
                <el-option
                  v-for="item in subjectData"
                  :key="item.azz_id_v2"
                  :label="item.azz_name_v2"
                  :value="item.azz_id_v2"
                />
              </el-select>
              <el-select
                v-model="params.azz_ssnj_v2"
                class="select_half"
                size="large"
                clearable
                placeholder="请选择年级"
              >
                <el-option label="全部" value="" />
                <el-option
                  v-for="(item, index) in gradeData"
                  :key="index"
                  :label="item.n"
                  :value="item.v"
                />
              </el-select>
            </div>
          </div>
        </template>
      </CommonList>
    </el-scrollbar>
    <el-dialog
      v-model="dialogVisible"
      class="_"
      :title="dialogTitle"
      width="362px"
      destroy-on-close
      :close-on-click-modal="false"
      @close="initDialog(false, '', 0)"
    >
      <!-- 建立专题 -->
      <el-form
        v-if="dialogType === 1"
        ref="scFormRef"
        label-position="top"
        :model="scForm"
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item label="专题名称">
          <el-input v-model="scForm.az_name" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="scForm.az_name" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="scForm.az" class="form_select">
            <el-option label="11" value="11"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级">
          <el-select v-model="scForm.az" class="form_select">
            <el-option label="11" value="11"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学科">
          <el-select v-model="scForm.az" class="form_select">
            <el-option label="11" value="11"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属学校">
          <el-select v-model="scForm.az" class="form_select">
            <el-option label="11" value="11"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面上传">
          <common-upload v-model="scForm.as_img" tip="上传比例限制308:200" />
        </el-form-item>
      </el-form>
      <!-- 编辑 -->
      <el-form
        v-else-if="dialogType === 2"
        ref="jjFormRef"
        label-position="top"
        :model="jjForm"
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item label="课程名称" prop="as_title">
          <el-input placeholder="请输入课程名称" v-model="jjForm.as_title" />
        </el-form-item>
        <el-form-item label="年级" prop="azz_ssnj_v2">
          <el-select
            v-model="jjForm.azz_ssnj_v2"
            filterable
            clearable
            class="w-full"
            @change="handleChangeFormGrade"
          >
            <el-option
              v-for="item in gradeData"
              :key="item.v"
              :label="item.n"
              :value="item.v"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属专业" prop="azz_id_v2">
          <el-select
            v-model="jjForm.azz_id_v2"
            filterable
            clearable
            class="w-full"
          >
            <el-option
              v-for="item in subjectData"
              :key="item.azz_id_v2"
              :label="item.azz_name_v2"
              :value="item.azz_id_v2"
            />
          </el-select> </el-form-item
        ><el-form-item label="所属学校" prop="as_zy_sm_id_v2">
          <el-select
            v-model="jjForm.as_zy_sm_id_v2"
            filterable
            clearable
            class="w-full"
            @change="handelChangeSchool"
          >
            <el-option
              v-for="item in school_list"
              :key="item.sm_id"
              :label="item.sm_name"
              :value="item.sm_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学院" prop="camp_id_v3" v-if="campData.length > 0">
          <el-select
            v-model="jjForm.camp_id_v3"
            class="w-full"
            size="large"
            clearable
            placeholder="请选择学院"
            @change="handelChangeCamp"
          >
            <!-- <el-option label="全部" value="" /> -->
            <el-option
              v-for="(item, index) in campData"
              :key="index"
              :label="item.camp_name"
              :value="item.camp_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="azb_id_v2">
          <el-select
            v-model="jjForm.azb_id_v2"
            filterable
            clearable
            class="w-full"
          >
            <el-option
              v-for="item in tag_list"
              :key="item.azb_id_v2"
              :label="item.azb_name_v2"
              :value="item.azb_id_v2"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面上传" prop="as_img">
          <common-upload
            v-model="jjForm.as_img"
            tip="上传比例限制308:200<br />建议上传小于500KB的jpg,jpeg,png格式图片"
          />
        </el-form-item>
      </el-form>
      <!-- 公开权限设置 -->
      <el-form
        v-else-if="dialogType === 3 || dialogType === 4"
        ref="qxFormRef"
        label-position="top"
        :model="qxForm"
        :rules="qxRules"
        class="demo-ruleForm"
        v-loading="loading"
      >
        <el-form-item prop="as_open_set_v3">
          <el-radio-group
            v-model="qxForm.as_open_set_v3"
            @change="handelChangeRadio"
          >
            <el-radio
              :label="item.value"
              v-for="item in powerData"
              :key="item.value"
              >{{ item.text }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="qxForm.as_open_set_v3 == '3'"
          label="仅自己班级可见"
          prop="as_open_class_v3"
        >
          <el-select
            class="w-full"
            collapse-tags
            multiple
            filterable
            clearable
            v-model="qxForm.as_open_class_v3"
          >
            <el-option
              v-for="item in classData"
              :key="item.cm_id"
              :label="item.cm_name"
              :value="item.cm_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="qxForm.as_open_set_v3 == '4'"
          label="指定账号可见"
          prop="as_open_user_v3"
        >
          <el-select
            class="w-full user_select"
            multiple
            filterable
            reserve-keyword
            clearable
            v-model="qxForm.as_open_user_v3"
          >
            <el-option
              v-for="item in userData"
              :key="item.user_id"
              :label="user.user_role_id == '75'? `${item.realname} ${item.username}`:`${item.user_realname} ${item.user_phone}`"
              :value="item.user_id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button
        class="mt-30px h-48px w-full"
        type="primary"
        @click="handleSubmit"
      >
        确认
      </el-button>
    </el-dialog>
  </div>
</template>

<route lang="json">
  {
    "meta":{
      "title":"个人中心",
      "img":"/images/grzx.png",
      "sort":0
    }
  }
</route>

<style lang="scss" scoped>
@use "~/styles/page.scss";
@use "~/styles/dialog.scss";
@use "~/styles/checkbox.scss";
:deep {
  .el-input__wrapper {
    // background: #f7f7f7;
    box-shadow: none;
  }
  .form_select {
    width: 100%;
    .el-input__wrapper {
      background: #f3f3f3;
      width: 100%;
    }
    &.el-select .el-input.is-focus .el-input__wrapper {
      box-shadow: none !important;
    }
  }
  .select,
  .select_half {
    .el-input__wrapper {
      background: #f3f3f3;
    }
    &.el-select .el-input.is-focus .el-input__wrapper {
      box-shadow: none !important;
    }
  }
  .select_half {
    width: 150px;
  }
  .el-upload {
    width: 100% !important;
  }
  .del_btn {
    background: transparent;
    color: #ff6a55;
    border-color: #ff6a55;
  }
  .is-checked .el-radio__inner {
    background: #f4cba2;
    border-color: #f4cba2;
  }
  .is-checked .el-radio__label {
    color: #f4cba2;
  }
  .user_select {
    .el-input {
      height: unset !important;
      min-height: 40px;
      padding: 5px;
    }
    .el-select__input {
      margin-left: unset !important;
      padding-left: 11px;
    }
  }
}
</style>
