<script setup lang="ts">
import { courseCopy, setDepartment, setPlatform, setStatus, setBelong, courseAuthorization } from '../api'
import { useProjectList } from '@/composables/useGetProjectList'
import { ElMessage, ElMessageBox } from 'element-plus'
// 筛选部门
let departmentList: any = useProjectList('', '79806610719731712').departmentList

const router = useRouter()
const route = useRoute()
const props = defineProps(['data'])
const emit = defineEmits<{
  (e: 'update'): void
}>()
// 详情id
const id = route.query.id as string

// 数据回显
watch(
  () => props.data,
  value => {
    authorizeCheck.value = value.auth_departments.reduce((a: any, b: any) => a.push(b.department_id) && a, [])
  }
)

// 设置部门共享
const handleDepartment = () => {
  ElMessageBox.confirm(
    `
    ${
      parseInt(props.data.department_public) === 0
        ? `该操作将会使本课程在您所在的部门“${props.data.organ_id_name}”内部共享，管理者不变，其余人员只能共享使用该课程，确认部门共享吗？`
        : `该操作将会取消本课程在您所在的部门“${props.data.organ_id_name}”内部共享，部门其余人员将不能再看到该共享课程，确认取消部门共享吗？`
    }
  `,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    setDepartment({ id: id }).then((res: any) => {
      if (res.code === 0) {
        ElMessage({ message: '更改成功', type: 'success' })
        setTimeout(() => {
          router.go(0)
        }, 500)
        emit('update')
      }
    })
  })
}

// 设置平台共享
const handlePlatform = () => {
  ElMessageBox.confirm(
    `
    ${
      parseInt(props.data.platform_public) === 0
        ? '该操作将会使本课程在e-SaaS平台中公开共享供所有老师使用，课程的管理者不变，其余人员只能共享使用该课程，确认公开该课程吗？'
        : '该操作将会取消本课程在e-SaaS平台中公开共享，平台所有人员将不能再看到该共享课程，确认取消平台共享吗？'
    }
  `,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    setPlatform({ id: id }).then((res: any) => {
      if (res.code === 0) {
        ElMessage({ message: '更改成功', type: 'success' })
        setTimeout(() => {
          router.go(0)
        }, 500)
        emit('update')
      }
    })
  })
}

// 上下线设置
const handleStatus = () => {
  ElMessageBox.confirm(
    `
    ${
      parseInt(props.data.status) === 1
        ? '已下线的课程将不能被共享和使用，确认下线该课程吗？'
        : '确认再次上线该课程吗？'
    }
  `,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    setStatus({ id: id }).then((res: any) => {
      if (res.code === 0) {
        ElMessage({ message: '更改成功', type: 'success' })
        setTimeout(() => {
          router.go(0)
        }, 500)
        emit('update')
      }
    })
  })
}

// 更该负责人
const form = reactive({
  members: ''
})
const dialogFormVisible = ref(false)

// 人员列表
let members: any = ref([])

// 点击更改负责人按钮弹窗
const handleMembers = () => {
  dialogFormVisible.value = true
  members.value = useProjectList(props.data.organ_id).members
}

// 点击知识图谱
const handleChart = () => {
  router.push({ path: '/course/my/graph', query: { n: props.data?.name, bid: 19, cid: route.query.id } })
}

// 更改负责人确定
const handleSetBelong = () => {
  setBelong({ id: id, belong_operator: form.members }).then((res: any) => {
    if (res.code === 0) {
      ElMessage({ message: '更改成功', type: 'success' })
      emit('update')
      setTimeout(() => {
        dialogFormVisible.value = false
      }, 500)
    }
  })
}

// 授权
const dialogVisibleAuthorize = ref(false)
const authorizeCheck: any = ref([])
const courseAuthorizeConfirm = () => {
  const list: any = ref([])
  const newList = JSON.parse(JSON.stringify(departmentList.value))
  newList.map((item: any) => {
    authorizeCheck.value.map((it: any) => {
      delete item.semesters
      if (item.id === it) {
        list.value.push(item)
        return item
      }
    })
  })
  courseAuthorization({ id: id, organ_ids: JSON.stringify(list.value) }).then((res: any) => {
    if (res.code === 0) {
      ElMessage({ message: '授权成功', type: 'success' })
      dialogVisibleAuthorize.value = false
      emit('update')
    }
  })
}

const changeDepartment = () => {
  departmentList.value.map((i: any) => {
    const find = authorizeCheck.value.find((item: any) => item === i.id)
    if (!find) {
      i.auth_type = '1'
      i.auth_semester_id = ''
      i.auth_start_time = ''
      i.auth_end_time = ''
    }
    return i
  })
}

// 复制
const copyCourse = () => {
  courseCopy({ id: id }).then((res: any) => {
    if (res.code === 0) {
      ElMessage({ message: '复制成功', type: 'success' })
      router.push({ path: '/course/update-course', query: { id: res.data.id } })
    }
  })
}
watch(
  () => dialogVisibleAuthorize.value,
  value => {
    if (value === true) {
      departmentList.value.map((i: any) => {
        i.auth_type = '1'
        props.data.auth_departments.map((item: any) => {
          if (item.organ_id === i.id) {
            i.auth_type = item.auth_type
            if (item.auth_semester_id === '0') {
              i.auth_semester_id = ''
            } else {
              i.auth_semester_id = item.auth_semester_id
            }
            i.auth_start_time = item.auth_start_time
            i.auth_end_time = item.auth_end_time
          }
        })
      })
    }
  }
)
</script>
<template>
  <div class="tool-btn-box" v-if="route.query.id" style="margin-bottom: 20px">
    <router-link :to="`/course/update-course?id=${route.query.id}`">
      <div class="btn-item">编辑课程信息</div>
    </router-link>
    <div v-if="props.data.auth_authorized" class="btn-item" @click="dialogVisibleAuthorize = true">授权</div>
    <div v-if="props.data.auth_copy" class="btn-item" @click="copyCourse">复制</div>
    <div v-if="props.data.auth_department" class="btn-item" @click="handleDepartment">
      {{ props.data.department_public == 0 ? '部门共享' : '取消部门共享' }}
    </div>
    <div v-if="props.data.auth_platform" class="btn-item" @click="handlePlatform">
      {{ props.data.platform_public == 0 ? '平台共享' : '取消平台共享' }}
    </div>
    <div v-if="props.data.auth_status" class="btn-item" @click="handleStatus">
      {{ props.data.status == 0 ? '课程上线' : '课程下线' }}
    </div>
    <div v-if="props.data.auth_belong" class="btn-item" @click="handleMembers">更改负责人</div>
    <div class="btn-item" @click="handleChart">知识图谱</div>
  </div>
  <el-dialog v-if="props.data.auth_belong" v-model="dialogFormVisible" title="更改负责人" center>
    <el-form :model="form">
      <el-form-item>
        <div style="width: 500px">
          <el-row>
            <el-col :span="12"
              ><div class="grid-content ep-bg-purple" />
              资源创建人: {{ props.data.created_operator_name }}
            </el-col>
            <el-col :span="12"
              ><div class="grid-content ep-bg-purple-light" />
              创建时间: {{ props.data.created_time }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12"
              ><div class="grid-content ep-bg-purple" />
              资源负责人: {{ props.data.belong_operator_name }}
            </el-col>
            <el-col :span="12"
              ><div class="grid-content ep-bg-purple-light" />
              更新时间: {{ props.data.updated_time }}
            </el-col>
          </el-row>
        </div>
        <el-select style="width: 500px; margin-top: 20px" v-model="form.members" placeholder="请选择新的资源负责人">
          <el-option v-for="item in members.value" :label="item.name" :value="item.id" :key="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSetBelong">确认</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisibleAuthorize" title="项目/学校" width="50vw">
    <div style="overflow: auto; min-height: 30vh; max-height: 60vh">
      <el-checkbox-group v-model="authorizeCheck" style="display: flex; flex-direction: column">
        <div v-for="item in departmentList" :key="item.id">
          <el-checkbox :label="item.id" @change="changeDepartment"> {{ item.name }} </el-checkbox>
          <span v-if="authorizeCheck.filter((it:any)=>it === item.id).length >0" style="margin-top: 10px">
            <el-radio-group v-model="item.auth_type">
              <div class="item">
                <el-radio label="1">长期有效</el-radio>
              </div>
              <div class="item">
                <el-radio label="2">学期有效</el-radio>
                <el-select v-model="item.auth_semester_id">
                  <el-option v-for="(it, id) in item.semesters" :key="id" :label="it.name" :value="it.id"></el-option>
                </el-select>
              </div>
              <div class="item">
                <el-radio label="3">时间范围</el-radio>
                <el-date-picker v-model="item.auth_start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
                <el-date-picker
                  v-model="item.auth_end_time"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="margin-left: 10px"
                />
              </div>
            </el-radio-group>
          </span>
        </div>
      </el-checkbox-group>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisibleAuthorize = false">取消</el-button>
        <el-button type="primary" @click="courseAuthorizeConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.tool-btn-box {
  display: flex;
  justify-content: right;
  .btn-item {
    width: 127px;
    line-height: 36px;
    background: #aa1941;
    border-radius: 20px;
    margin-right: 10px;
    font-size: 14px;
    color: #ffffff;
    text-align: center;
    cursor: pointer;
  }
}
:deep(.el-checkbox) {
  margin-top: 20px;
}
:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: flex-start;
  margin-left: 20px;
}

:deep(.el-date-editor.el-input) {
  margin-top: 10px;
}
:deep(.el-select) {
  margin-top: 10px;
}
</style>
