<template>
  <div class="science">
    <div class="control">
      <el-button type="primary" @click="handleAdd" v-if="userType == 3">新增</el-button>
      <div v-else></div>
      <el-input placeholder="搜索" v-model="search" clearable prefix-icon="el-icon-search" @change="searchChange"> </el-input>
    </div>
    <div class="science_box">
      <div class="science_item" v-for="item in tableData" :key="item.id">
        <img :src="item.showImg ? item.showImg : logo2" alt="" @click="handleDetail(item)" />
        <div class="bottom">
          <p @click="handleDetail(item)">{{ item.typeName }}</p>
          <el-dropdown trigger="click" v-if="userType == 3">
            <span class="el-dropdown-link"> ··· </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit" @click="handleEdit(item)"><i class="el-icon-edit"></i>重命名</el-dropdown-item>
                <el-dropdown-item command="del" @click="handleDel(item)">
                  <el-popconfirm title="确定删除？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDel(item)">
                    <template #reference>
                      <p class="del" style="margin: 0"><i class="el-icon-delete"></i>删除</p>
                    </template>
                  </el-popconfirm>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <i></i><i></i><i></i><i></i><i></i>
    </div>
    <el-empty description="暂无内容" v-if="tableData.length == 0"></el-empty>
    <el-dialog :title="editTitle" v-model="editBoxShow">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="标题：" prop="typeName">
          <el-input v-model="form.typeName"></el-input>
        </el-form-item>
        <el-form-item label="封面：">
          <el-upload class="uploader" action="" :http-request="upload" :show-file-list="false">
            <i v-if="form.coverUrl" class="el-icon-document-checked uploader-icon" style="border-color: #67c23a; color: #67c23a"></i>
            <i v-else class="el-icon-plus uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editBoxShow = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { deepClone } from '@/utils'
import axios from '@/utils/axios'
import logo2 from '@/assets/logo2.png'
export default {
  name: 'Study',
  setup() {
    const formRef = ref(null)
    const router = useRouter()
    const state = reactive({
      search: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      loading: false,
      editBoxShow: false,
      editTitle: '',
      form: {
        id: '0',
        typeName: '',
        coverUrl: '',
      },
      rules: {
        typeName: [{ required: 'true', message: '标题不能为空', trigger: ['change'] }],
      },
      userType: '', //用户身份 部分功能仅心理老师3可用
    })
    onMounted(() => {
      getScienceModule()
      const userType = JSON.parse(localStorage.getItem('userInfo'))?.userType
      state.userType = userType
    })
    // 数字学习馆1级列表
    const getScienceModule = () => {
      state.loading = true
      axios
        .post('/Resource/ResourceType/List', {
          TypeName: state.search,
          PageIndex: state.currentPage,
          PageSize: 1000,
        })
        .then((res) => {
          // console.log('数字学习馆1级列表:', res)

          let tableData = res.data
          for (let i in tableData) {
            let showImg = tableData[i].coverUrl
              ? tableData[i].coverUrl.replace(
                  'D:\\网站\\PyhsicalAdmin\\wwwroot\\wwwroot\\UploadSysBaseSettingFile',
                  'http://10.238.0.182:8090/UploadSysBaseSettingFile'
                )
              : '' //新昌内网
            tableData[i].showImg = showImg
          }

          state.tableData = tableData
          state.total = res.count
          state.loading = false
        })
        .catch((err) => {
          console.log('err', err)
        })
    }
    // 搜索
    const searchChange = (e) => {
      getScienceModule()
    }
    // 新建
    const handleAdd = () => {
      state.editTitle = '新建'
      state.form = {
        id: '0',
        typeName: '',
      }

      state.editBoxShow = true
    }
    // 编辑修改
    const handleEdit = (e) => {
      state.form = deepClone(e)
      state.editTitle = '编辑'
      state.editBoxShow = true
    }
    // 删除
    const handleDel = (e) => {
      axios
        .delete('/Resource/ResourceType', {
          params: {
            id: e.id,
          },
        })
        .then(() => {
          ElMessage.success('删除成功')
          state.currentPage = 1
          getScienceModule()
        })
    }
    // 新建或修改提交
    const submitForm = () => {
      formRef.value.validate((vaild) => {
        if (vaild) {
          if (state.form.id == 0) {
            // 新建
            axios
              .post('/Resource/ResourceType', {
                Id: '0',
                TypeName: state.form.typeName,
                CoverUrl: state.form.coverUrl,
              })
              .then(() => {
                ElMessage.success('新建成功')
                state.editBoxShow = false
                getScienceModule()
              })
          } else {
            // 修改
            axios
              .put('/Resource/ResourceType', {
                Id: state.form.id,
                TypeName: state.form.typeName,
                CoverUrl: state.form.coverUrl,
              })
              .then(() => {
                ElMessage.success('修改成功')
                state.editBoxShow = false
                getScienceModule()
              })
          }
        }
      })
    }
    // 上传
    const upload = (param) => {
      // console.log(param)
      const formData = new FormData()
      formData.append('file', param.file)
      axios.post('/Upload/SysBaseSettingFile', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then((res) => {
        state.form.size = res.size
        state.form.coverUrl = res.urlAddress
      })
    }
    const handleDetail = (item) => {
      router.push({ path: '/study_second', query: { typeId: item.id, typeName: item.typeName } })
    }
    return {
      ...toRefs(state),
      formRef,
      searchChange,
      handleAdd,
      handleEdit,
      handleDel,
      submitForm,
      handleDetail,
      upload,
      logo2
    }
  },
}
</script>
<style lang="scss" scoped>
.control {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .el-input {
    width: 300px;
  }
}
.science {
  .science_box {
    padding-top: 60px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    width: calc(100% + 20px);
    margin-left: -10px;
    > i {
      width: 270px;
      margin: 0 10px;
    }
    .science_item {
      width: 270px;
      height: 290px;
      background: #fff;
      position: relative;
      margin: 0 10px;
      margin-bottom: 50px;
      img {
        width: 204px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        margin-top: -10px;
        cursor: pointer;
      }
      .bottom {
        width: 100%;
        height: 66px;
        position: absolute;
        bottom: 0;
        padding: 12px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        p {
          width: 80%;
          margin: 0;
          cursor: pointer;
        }
        .el-dropdown-link {
          font-weight: bold;
          cursor: pointer;
          padding: 10px;
        }
        .del {
          margin: 0;
        }
      }
    }
  }
  .uploader {
    margin-bottom: 50px;
  }
  .uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .el-upload__tip {
    display: inline-block;
    font-size: 16px;
    color: #999;
    margin-left: 50px;
  }
}
</style>
