<template>
  <div class="box-border bg-white m-4 py-4 rounded-6px overflow-auto" style="height: calc(100% - 48px - 10px - 1rem);">
    <el-scrollbar class="px-4" view-class="h-full">
      <div class="title ml-4 mb-4">新增课程/编辑</div>
      <div class="mszyCourseContent">
        <el-form ref="ruleFormRef" :rules="rules" label-position="right" label-width="150px" :model="ruleForm">
          <el-form-item class="formFlex" label="责任教师:" prop="tmk_zrjs_user_id">
            <remote-user-select style="width: auto;" placeholder="责任教师编号" size="small" v-model="ruleForm.tmk_zrjs_user_id" v-model:model-name="ruleForm.tmk_zrjs_user_name" v-model:model-real-name="ruleForm.tmk_zrjs_xm" :d="{user_role_id:'75'}" showKey="user_name"></remote-user-select>
            <el-input v-model="ruleForm.tmk_zrjs_xm" size="small" placeholder="责任教师姓名"></el-input>
          </el-form-item>
          <el-form-item label="协作教师:">
            <div class="showDiv">
              <div class="flex" style="flex-wrap: wrap;">
                <div class="flex" style="margin-right: 20px;align-items: center;padding: 4px 0;" v-for="(item, index) in activeTeacherData" :key="index">
                  <div class="typeItem">{{item.user_realname}}</div>
                  <el-icon color="#00A3FF" class="cursor-pointer" @click="handleRemoveTeacher(index)">
                    <CircleClose />
                  </el-icon>
                </div>
              </div>
              <el-icon class="drop cursor-pointer" color="#a8abb2" :size="12" @click="showTeacher=!showTeacher">
                <ArrowDownBold />
              </el-icon>
            </div>
            <div class="jdlsDiv" v-show="showTeacher">
              <div class="operate">
                <div class="searchValue">
                  <input type="text" placeholder="搜索老师名字" v-model="searchKey">
                  <div class="searchBtn cursor-pointer" @click="initTeacherData(false)">
                    <img src="/images/searchIcon.png" alt="">
                  </div>
                </div>
                <div>
                  <el-button @click="backTeacher">
                    <el-icon>
                      <Back />
                    </el-icon>
                  </el-button>
                  <el-button @click="nextTeacher">
                    <el-icon>
                      <Right />
                    </el-icon>
                  </el-button>
                </div>
              </div>
              <div v-if="teacherData.length!=0">
                <el-checkbox-group v-model="activeTeacher" @change="initActiveTeacher">
                  <el-checkbox v-for="(item, index) in teacherData" :key="index" :label="item.teacherVal">{{item.user_realname}}({{item.user_name}})</el-checkbox>
                </el-checkbox-group>
              </div>
              <el-empty v-if="teacherData.length==0" image-size="100" description="无数据" style="padding: 10px 0;" />
            </div>
          </el-form-item>
          <el-form-item label="课程封面图:" prop="tmk_img">
            <file-upload-progress v-model:part="ruleForm.tmk_img" :limit="1" class="w-520px" accept=".jpg,.jpeg,.webp,.png" :size-limit="500 * 1024">
              <template #default>
                <el-button type="primary" size="large">点击上传</el-button>
              </template>
              <template #tip>
                <div class="mt-2 text-xs">
                  只能上传jpg/png/jpeg文件，且不超过500kb，建议尺寸600x337
                </div>
              </template>
            </file-upload-progress>
          </el-form-item>
          <div class="grid grid-cols-2 gap-x-10">
            <el-form-item label="课程名:" prop="tmk_kcm">
              <el-input v-model="ruleForm.tmk_kcm" size="small"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="课程简介:">
            <el-input v-model="ruleForm.tmk_kcjj" type="textarea" size="small" rows="5"></el-input>
          </el-form-item>
          <div class="grid grid-cols-2 gap-x-10">
            <el-form-item label="年级:" prop="tjzn_id">
              <!-- <remote-multi-select v-model="ruleForm.tjzn_id" v-model:model-name="ruleForm.tjzn_name" to="jcxxgl_zyflgl_nj" :fields="['tjzn_id', 'tjzn_njmc']"></remote-multi-select> -->
              <remote-select size="small" v-model="ruleForm.tjzn_id" v-model:model-name="ruleForm.tjzn_name" to="jcxxgl_zyflgl_nj" :fields="['tjzn_id', 'tjzn_njmc']"></remote-select>
            </el-form-item>
            <el-form-item label="学科:" prop="tjzx_id">
              <remote-select size="small" v-model="ruleForm.tjzx_id" v-model:model-name="ruleForm.tjzx_name" to="jcxxgl_zyflgl_xk" :fields="['tjzx_id', 'tjzx_xkmc']"></remote-select>
            </el-form-item>
            <el-form-item label="所属机构:" prop="tmk_ssjg_id">
              <remote-select size="small" v-model="ruleForm.tmk_ssjg_id" v-model:model-name="ruleForm.tmk_ssjg_name" url="/school/main/index" :fields="['id', 'sm_name']"></remote-select>
            </el-form-item>
            <el-form-item label="周期" prop="tmk_zq">
              <el-select v-model="ruleForm.tmk_zq" size="small">
                <el-option v-for="(item, index) in termData" :key="index" :label="item.n" :value="item.v" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程权限设置:" prop="tmk_kcqxsz">
              <el-radio-group v-model="ruleForm.tmk_kcqxsz">
                <el-radio label="1">公开</el-radio>
                <el-radio label="2">私有</el-radio>
                <el-radio label="3">指定可见</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </el-form>
        <div class="mt-5 pb-8 text-center">
          <el-button type="primary" plain @click="handleCancel">取消</el-button>
          <el-button style="margin-left: 50px;" type="primary" @click="handleSubmit(ruleFormRef)">确定</el-button>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { Close, CircleClose, ArrowDownBold, Back, Right } from '@element-plus/icons-vue'
const router = useRouter();
const parentId = router.currentRoute.value.params.id;
if (parentId) {
  initDetailInfo();
}

const termData = ref([
  { v: "1", n: "春季" },
  { v: "2", n: "暑期" },
  { v: "3", n: "秋季" },
  { v: "4", n: "寒假" }
])

const ruleForm = ref({
  tmk_zrjs_user_id: "",
  tmk_zrjs_user_name: "",
  tmk_zrjs_xm: "",
  tmk_img: "",
  tmk_kcm: "",
  tjzn_id: "",
  tjzn_name: "",
  tjzx_id: "",
  tjzx_name: "",
  tmk_ssjg_id: "",
  tmk_ssjg_name: "",
  tmk_zq: "",
  tmk_kcjj: "",
  tmk_kcqxsz: "",
  tmk_xzjs_user_id: "",
  tmk_xzjs_user_xm: "",
  tmk_sftjmszx: "3"
});
const ruleFormRef = ref(null);
const rules = reactive({
  tmk_zrjs_user_id: [{ required: true, message: "请输入责任教师姓名和编号", trigger: "blur" }],
  tmk_img: [{ required: true, message: "请选择课程封面图", trigger: "submit" }],
  tmk_kcm: [{ required: true, message: "请输入课程名", trigger: "blur" }],
  tjzn_id: [{ required: true, message: "请选择年级", trigger: "change" }],
  tjzx_id: [{ required: true, message: "请选择学科", trigger: "change" }],
  tmk_ssjg_id: [{ required: true, message: "请选择所属机构", trigger: "change" }],
  tmk_zq: [{ required: true, message: "请选择周期", trigger: "change" }],
  tmk_kcqxsz: [{ required: true, message: "请选择课程权限设置", trigger: "change" }],
})

const searchKey = ref("");
const teacherData = ref([]);
const activeTeacherData = ref([]);
const activeTeacher = ref([]);
const currentPage = ref(1);
const limit = ref(20);
const totalPage = ref(0);
const showTeacher = ref(true);

initTeacherData();
async function initTeacherData() {
  let data = {
    page: currentPage.value,
    limit: limit.value,
    keyword: searchKey.value,
    user_role_id: "75"
  };
  let res = await request({ url: "/user/main/index", data });
  if (res.code == 1) {
    teacherData.value = [];
    res.data.page_data.map(item => {
      let obj = {
        user_id: item.user_id,
        user_realname: item.user_realname
      }
      teacherData.value.push({
        user_realname: item.user_realname,
        user_name: item.user_name,
        teacherVal: JSON.stringify(obj)
      })
    })
    totalPage.value = res.data.total_page;
  }
}

const backTeacher = () => {
  if (currentPage.value == 1) {
    return false;
  }
  currentPage.value--;
  initTeacherData();
}
const nextTeacher = () => {
  if (currentPage.value == totalPage.value) {
    return false;
  }
  currentPage.value++;
  initTeacherData();
}

const handleRemoveTeacher = (index) => {
  activeTeacherData.value.splice(index, 1);
  activeTeacher.value.splice(index, 1);
}

const initActiveTeacher = (value) => {
  activeTeacherData.value = value.map(item => JSON.parse(item));
}

async function initDetailInfo() {
  let res = await request({ url: "/txwx/mszy_kc/detail", data: { tmk_id: parentId } });
  if (res.code == 1) {
    for (let key in ruleForm.value) {
      ruleForm.value[key] = res.data.one_info[key];
    }
    ruleForm.value.tmk_sftjmszx = res.data.one_info.tmk_sftjmszx_option_k;
    ruleForm.value.tmk_kcqxsz = res.data.one_info.tmk_kcqxsz_option_k;
    ruleForm.value.tmk_zq = res.data.one_info.tmk_zq_option_k;

    activeTeacher.value = [];
    activeTeacherData.value = [];
    let arr1 = res.data.one_info.tmk_xzjs_user_id.split(",");
    let arr2 = res.data.one_info.tmk_xzjs_user_xm.split(",");
    arr1.map((item, i) => {
      let obj = {
        user_id: item,
        user_realname: arr2[i]
      }
      activeTeacher.value.push(JSON.stringify(obj));
      activeTeacherData.value.push(obj);
    })
  }
}


const handleCancel = () => {
  router.back();
}

const handleSubmit = async (formEl) => {
  if (!formEl) return;

  formEl.validate(async (valid, fields) => {
    if (valid) {
      let arr1 = [];
      let arr2 = [];
      activeTeacherData.value.map(item => {
        arr1.push(item.user_id);
        arr2.push(item.user_realname);
      })
      ruleForm.value.tmk_xzjs_user_id = arr1.join(",");
      ruleForm.value.tmk_xzjs_user_xm = arr2.join(",");

      let data = {
        txwx_mszy_kc: ruleForm.value
      }
      let res = {};
      if (!parentId) {
        res = await request({ url: "/txwx/mszy_kc/add", data });
      } else {
        data.tmk_id = parentId;
        res = await request({ url: "/txwx/mszy_kc/edit", data });
      }
      if (res.code == 1) {
        ElMessage.success("保存成功！");
        handleCancel();
      }
    } else {
      console.log("error submit!", fields);
    }
  });
}
</script>

<style lang="scss" scoped>
@use "~/styles/scroll.scss";
.title {
  font-size: 16px;
  font-weight: 400;
  color: var(--el-color-primary);
  line-height: 22px;
}
.mszyCourseContent {
  width: 1100px;
  margin: auto;
  :deep() {
    .formFlex {
      .el-form-item__content {
        display: flex;
        .el-input {
          width: 200px;
          margin-right: 20px;
        }
      }
    }
    .el-select {
      width: 100%;
    }
    .el-date-editor {
      width: 180px;
      .el-input__wrapper {
        width: 100%;
      }
    }
    // .el-date-editor .el-range-input {
    //   width: 44%;
    // }
  }

  .showDiv {
    position: relative;
    width: 100%;
    min-height: 32px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    padding: 0 30px 0 15px;
    .el-icon.drop {
      position: absolute;
      right: 15px;
      top: 9px;
    }
    .typeItem {
      background: #00a3ff;
      color: #fff;
      font-size: 13px;
      padding: 0 8px;
      border-radius: 6px;
      line-height: 22px;
      margin-right: 1px;
    }
  }
  .jdlsDiv {
    border: 1px solid #e4e6e8;
    border-radius: 6px;
    padding: 10px 12px;
    width: 100%;
    .operate {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      .el-button {
        width: 32px;
        height: 32px;
      }
    }
    .searchValue {
      width: 278px;
      height: 40px;
      background: #ffffff;
      border-radius: 8px;
      overflow: hidden;
      position: relative;
      input {
        width: 100%;
        height: 100%;
        outline: 0;
        box-sizing: border-box;
        padding-left: 10px;
        background: #f6f8fa;
      }
      .searchBtn {
        width: 26px;
        height: 26px;
        background: #00a3ff;
        border-radius: 6px;
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
        vertical-align: middle;
        img {
          display: block;
          text-align: center;
          margin: 6px auto 0;
        }
      }
    }
    .el-checkbox.el-checkbox--large {
      min-width: 80px;
      margin-right: 25px;
    }
  }

  .el-button--primary.is-plain {
    background: unset;
    &:hover {
      color: var(--el-color-primary);
    }
  }
}
</style>