<template>
  <el-card class="account-container">
    <div class="experience">
      <div class="control">
        <p class="control_name">解忧杂货铺</p>
        <div>
          <el-button type="primary" @click="handleAdd" style="margin-right:20px;">发布</el-button>
          <el-button type="primary" @click="handleAudit" 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>
      <div class="btn_box">
        <span :class="showAll?'active':''" @click="handleChangeShowAll(true)">论坛</span>
        <span :class="!showAll?'active':''" @click="handleChangeShowAll(false)">我的问题</span>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%;cursor:pointer;" @row-click="handleRowClick" v-if="tableData.length>0">
        <el-table-column label="">
          <template #default="props">
            <p class="time">{{formatTime(props.row.createTime)}}</p>
            <p class="status" style="color:#fca130;" v-if="props.row.checkStatus==1">审核中</p>
            <p class="status" style="color:#f93e3e;" v-if="props.row.checkStatus==3">审核未通过</p>
          </template>
        </el-table-column>
        <el-table-column label="" min-width="220">
          <template #default="props">
            <p class="title">{{props.row.messageTitle}}</p>
            <p class="content">{{props.row.messageContent}}</p>
          </template>
        </el-table-column>
        <el-table-column label="" width="100">
          <template #default="props">
            <p class="reply" v-if="props.row.replyCount>0">{{props.row.replyCount}}条回复</p>
          </template>
        </el-table-column>
        <el-table-column label="" width="120">
          <template #default="scope">
            <el-popconfirm title="确定删除？" confirmButtonText="确认" cancelButtonText="取消" v-if="UserId==scope.row.userId" @confirm="handleDel(scope.row)">
              <template #reference>
                <el-button type="danger" @click.stop>删除提问</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-empty description="暂无内容" v-if="tableData.length==0"></el-empty>
      <el-pagination :hide-on-single-page="total<=5" background layout="prev, pager, next" :page-size='5' 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="MessageTitle">
            <el-input v-model="form.MessageTitle"></el-input>
          </el-form-item>
          <el-form-item label="问题内容：" prop="MessageContent">
            <el-input type="textarea" v-model="form.MessageContent" :autosize="{ minRows: 4}"></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>
    </div>
  </el-card>
</template>

<script>
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { formatTime } from '@/utils'
import axios from '@/utils/axios'
export default {
  name: 'Experience',
  setup () {
    const formRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const state = reactive({
      showAll: true,//显示全部或者显示个人
      search: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      loading: false,
      editBoxShow: false,//编辑框显示
      editTitle: '',
      form: {
        id: '',
        MessageTitle: '',
        MessageContent: ''
      },
      rules: {
        MessageTitle: [
          { required: 'true', message: '问题标题不能为空', trigger: ['change'] }
        ]
      },
      UserId: store.state.userInfo?.userId,
      userType: store.state.userInfo?.userType,
    })
    onMounted(() => {
      if (!state.UserId) return;
      getPostMessage()
    })
    // 经验分享
    const getPostMessage = () => {
      state.loading = true
      axios.post('/Exchange/PostMessage/List', {
        "MessageTitle": state.search,
        "CheckStatus": state.showAll ? 2 : 0,//我的问题可以查看审核中和审核失败
        "UserId": state.showAll ? '' : state.UserId,//显示全部userid传空
        "PageIndex": state.currentPage,
        "PageSize": 5
      }).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) => {
      getPostMessage()
    }
    // 新建
    const handleAdd = () => {
      state.editTitle = '发布问题或经验';
      state.form = {
        id: '',
        MessageTitle: '',
        MessageContent: ''
      };

      state.editBoxShow = true
    }
    // 删除
    const handleDel = (e) => {
      axios.delete('/Exchange/PostMessage', {
        params: {
          id: e.id
        }
      }).then(() => {
        ElMessage.success('删除成功')
        state.currentPage = 1;
        getPostMessage()
      })
    }
    // 提问
    const submitForm = () => {
      formRef.value.validate((vaild) => {
        if (vaild) {
          axios.post('/Exchange/PostMessage', {
            "Id": 0,
            "UserId": state.UserId,
            "MessageTitle": state.form.MessageTitle,
            "MessageContent": state.form.MessageContent,
            "CheckStatus": state.userType == 3 ? 2 : 1,//老师提问无需审核
          }).then(() => {
            ElMessage.success('提问成功')
            state.editBoxShow = false
            getPostMessage()
          })

        }
      })
    }
    // 页码改变时
    const handleCurrentChange = (e) => {
      state.currentPage = e;
      getPostMessage()
    }
    // 编辑窗点取消
    const hideEditBox = () => {
      state.editBoxShow = false
      resetForm()
    }
    // 重置表单
    const resetForm = () => {
      formRef.value.resetFields();
      state.form = {
        id: '',
        MessageTitle: '',
        MessageContent: ''
      };
    }
    // 点击某一行进入详情页
    const handleRowClick = (row) => {
      console.log(row)
      if (row.checkStatus == 3) {
        ElMessage.error('未通过审核的问题无法查看详情')
        return;
      }
      if (row.checkStatus == 1) {
        ElMessage.warning('审核中，审核通过后可查看详情')
        return;
      }
      router.push({ path: '/experience_detail', query: { PostId: row.id } })
    }
    // 显示全部或者我的问题
    const handleChangeShowAll = (boo) => {
      state.showAll = boo
      getPostMessage()
    }
    // 审核中心
    const handleAudit = () => {
      router.push({ path: '/experience_audit' })
    }
    return {
      ...toRefs(state),
      formRef,
      searchChange,
      handleAdd,
      handleDel,
      submitForm,
      handleCurrentChange,
      hideEditBox,
      handleRowClick,
      formatTime,
      handleChangeShowAll,
      handleAudit
    }
  }
}
</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;
  }
}
.btn_box {
  span {
    cursor: pointer;
    padding: 10px;
    margin-right: 50px;
    font-size: 16px;
  }
  .active {
    color: #3a84ff;
  }
}
.experience {
  background: #fff;
  padding: 0 20px;
  padding-bottom: 40px;
  .time {
    color: #999;
  }
  .status {
  }
  .title {
    font-size: 23px;
    color: #333;
  }
  .content {
    font-size: 16px;
    color: #999;
    margin-top: 16px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .reply {
    color: #3a84ff;
    font-size: 16px;
    text-align: right;
  }
  .del {
    color: rgb(249, 62, 62);
  }
}
</style>