<template>
  <div>
    <p class="sub_back" @click="handleBack">&#60;返回</p>
    <p class="sub_title">心晴悦读室</p>
    <div class="science_detail">
      <div class="control">
        <p class="control_name">{{scienceName}}</p>
        <div>
          <el-button type="primary" @click="handleAdd" style="margin-right:20px;" v-if="userType==3">新增</el-button>
          <el-input placeholder="搜索" v-model="search" clearable prefix-icon="el-icon-search" @change="searchChange">
          </el-input>
        </div>
      </div>

      <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe v-if="tableData.length>0&&userType==3">
        <el-table-column prop="title" label="文章标题">
        </el-table-column>
        <el-table-column label="文章链接地址">
          <template #default="scope">
            <a target="_black" :href="scope.row.url">{{scope.row.url}}</a>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <a @click="handleEdit(scope.row)" style="cursor: pointer; margin-right: 10px">修改</a>
            <el-popconfirm title="确定删除？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDel(scope.row)">
              <template #reference>
                <a style="cursor: pointer; margin-right: 10px">删除</a>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe v-if="tableData.length>0&&userType!=3">
        <el-table-column label="文章标题" align="center">
          <template #default="scope">
            <a target="_black" :href="scope.row.url">{{scope.row.title}}</a>
          </template>
        </el-table-column>
      </el-table>

      <el-empty description="暂无内容" v-if="tableData.length==0"></el-empty>
      <el-pagination :hide-on-single-page="total<=10" background layout="prev, pager, next" v-model="currentPage" :total="total" @current-change="handleCurrentChange">
      </el-pagination>
      <el-dialog :title="editTitle" v-model="editBoxShow">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="文章标题：" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="文章链接：" prop="url">
            <el-input v-model="form.url"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="hideEditBox">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <transition name="el-fade-in">
        <div class="iframe_mask" v-if="iframeMaskShow" @click="handleIframeMask">
          <iframe :src="iframeUrl" frameborder="0"></iframe>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { deepClone } from '@/utils'
import axios from '@/utils/axios'
export default {
  name: 'ScienceDetail',
  setup () {
    const formRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const { scienceId, scienceName } = route.query
    const urlReg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;

    const state = reactive({
      search: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      loading: false,
      editBoxShow: false,//编辑框显示
      iframeMaskShow: false,//iframe显示
      iframeUrl: '',//iframe链接
      editTitle: '',
      form: {
        id: '0',
        title: '',
        url: ''
      },
      rules: {
        title: [
          { required: 'true', message: '文章标题不能为空', trigger: ['change'] }
        ],
        url: [
          { required: 'true', message: '文章链接不能为空', trigger: ['change'] },
          { pattern: urlReg, message: '文章链接须以http://或https://开头' }
        ]
      },
      userType: '',//用户身份 部分功能仅心理老师3可用
    })
    onMounted(() => {
      getScienceTopic()
      const userType = JSON.parse(localStorage.getItem('userInfo'))?.userType
      state.userType = userType
    })
    // 科普调适详情
    const getScienceTopic = () => {
      state.loading = true
      axios.post('/ScienceForum/ScienceTopic/List', {
        "ModuleId": scienceId,
        "Title": state.search,
        "PageIndex": state.currentPage,
        "PageSize": 10
      }).then(res => {
        // console.log('科普调适详情:', res)

        state.tableData = res.data
        state.total = res.count
        state.loading = false
      }).catch(err => {
        console.log('err', err)

      })
    }
    // 搜索
    const searchChange = (e) => {
      getScienceTopic()
    }
    // 新建
    const handleAdd = () => {
      state.editTitle = '新建';
      state.form = {
        id: '0',
        title: '',
        url: ''
      };

      state.editBoxShow = true
    }
    // 编辑修改
    const handleEdit = (e) => {
      state.form = deepClone(e);
      state.editTitle = '编辑';
      state.editBoxShow = true
    }
    // 删除
    const handleDel = (e) => {
      axios.delete('/ScienceForum/ScienceTopic', {
        params: {
          "ModuleId": scienceId,
          "Id": e.id,
        }
      }).then(() => {
        ElMessage.success('删除成功')
        state.currentPage = 1;
        getScienceTopic()
      })
    }
    // 新建或修改提交
    const submitForm = () => {
      formRef.value.validate((vaild) => {
        if (vaild) {
          if (state.form.id == 0) {
            // 新建
            axios.post('/ScienceForum/ScienceTopic', {
              "ModuleId": scienceId,
              "Id": '0',
              "Title": state.form.title,
              "Detail": "",
              "IsOpen": true,
              "Url": state.form.url
            }).then(() => {
              ElMessage.success('新建成功')
              state.editBoxShow = false
              getScienceTopic()
            })
          } else {
            // 修改
            axios.put('/ScienceForum/ScienceTopic', {
              "ModuleId": scienceId,
              "Id": state.form.id,
              "Title": state.form.title,
              "Detail": "",
              "IsOpen": true,
              "Url": state.form.url
            }).then(() => {
              ElMessage.success('修改成功')
              state.editBoxShow = false
              getScienceTopic()
            })
          }
        }
      })
    }
    // 页码改变时
    const handleCurrentChange = (e) => {
      state.currentPage = e;
      getScienceTopic()
    }
    // 点击iframe遮罩
    const handleIframeMask = () => {
      state.iframeMaskShow = false;
    }
    // 编辑窗点取消
    const hideEditBox = () => {
      state.editBoxShow = false
      resetForm()
    }
    // 点击查看
    const handleView = (e) => {
      const url = e.url;
      console.log(url)
      if (urlReg.test(url)) {
        state.iframeUrl = url
        state.iframeMaskShow = true;
      } else {
        ElMessage.error('请检查文章链接,以http://或https://开头')
      }
    }
    const handleBack = () => {
      router.back()
    }
    // 重置表单
    const resetForm = () => {
      formRef.value.resetFields();
      state.form = {
        id: '0',
        title: '',
        url: ''
      };
    }
    return {
      ...toRefs(state),
      formRef,
      searchChange,
      handleAdd,
      handleEdit,
      handleDel,
      submitForm,
      scienceName,
      handleCurrentChange,
      handleIframeMask,
      hideEditBox,
      handleBack
    }
  }
}
</script>
<style lang="scss" scoped>
.control {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .control_name {
    font-size: 23px;
    font-weight: bold;
  }
  .el-input {
    width: 300px;
  }
}
.science_detail {
  background: #fff;
  padding: 0 20px;
  padding-bottom: 40px;
  // position: relative;
  .iframe_mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99;
    iframe {
      width: 70%;
      height: 70%;
      background: #fff;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>