<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="content">
        <el-card shadow="hover" style="margin-bottom: 10px">
          <el-button type="primary" @click="askOnline">在线提问</el-button>
        </el-card>
        <el-card shadow="hover">
          <div class="search-list">
            <div class="search-item">
              <div class="item-title">
                <span>答复状态：</span>
              </div>
              <div class="item-content">
                <span @click="handleFind('status', '')" class="item-text" :class="replyStatus == '' ? 'active' : ''">全部</span>
                <span
                  @click="handleFind('status', key)"
                  class="item-text"
                  :class="replyStatus == key ? 'active' : ''"
                  v-for="(value, key) in replyStatusOptions"
                >
                  {{ value }}
                </span>
              </div>
            </div>
            <div class="search-item">
              <div class="item-title">
                <span>答复时间：</span>
              </div>
              <div class="item-content">
                <span @click="handleFind('time', '')" class="item-text" :class="replyTime == '' ? 'active' : ''">全部</span>
                <span
                  @click="handleFind('time', key)"
                  class="item-text"
                  :class="replyTime == key ? 'active' : ''"
                  v-for="(value, key) in replyTimeOptions"
                >
                  {{ value }}
                </span>
              </div>
            </div>
          </div>
        </el-card>
        <el-card v-loading="loading" shadow="never" class="reply-main">
          <div v-if="dataList.length > 0" class="list">
            <div v-for="(item, index) in dataList">
              <div class="user-info">
                <div class="info-left">
                  <el-avatar size="small" :src="item.userPhotograph || defaultAvatar" />
                  <span>{{ item.userName }}</span>
                </div>
                <span class="time">发布于：{{ item.problemTime }}</span>
              </div>
              <div class="question">
                <div class="question-title">标题：{{ item.problemTitle }}</div>
                <div class="question-content">
                  {{ item.problem }}
                </div>
              </div>
              <div class="reply" v-if="item.status != 1">
                <div class="reply-content">
                  <div class="user-info">
                    <div class="info-left">
                      <el-avatar size="small" :src="item.replyPhotograph || defaultAvatar" />
                      <span>{{ item.replyName }}</span>
                    </div>
                    <span class="time">{{ item.replyTime }}</span>
                  </div>
                  <div class="question">
                    {{ item.reply }}
                  </div>
                </div>
              </div>
              <el-divider v-if="index < dataList.length - 1" />
            </div>
          </div>
          <el-empty v-else description="暂无数据"></el-empty>
          <pagination v-show="total > 0" :total="total" v-model:page="queryData.pageNum" v-model:limit="queryData.pageSize" @pagination="getList" />
        </el-card>
        <el-dialog title="在线提问" v-model="visible" width="600px" :before-close="Cancel">
          <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
            <el-form-item label="问题标题" prop="problemTitle">
              <el-input v-model="form.problemTitle" placeholder="请输入问题标题"></el-input>
            </el-form-item>
            <el-form-item label="问题内容" prop="problem">
              <el-input type="textarea" :rows="5" resize="none" v-model="form.problem" placeholder="请输入问题内容"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span>
              <el-button @click="Cancel">取消</el-button>
              <el-button type="primary" @click="confirmSubmit">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { getQuestionList, submitQuestion } from '@/api/question';
const defaultAvatar = new URL('@/assets/images/avatar.png', import.meta.url).href;

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_user_sex } = toRefs<any>(proxy?.useDict('sys_user_sex'));
const { project_type } = toRefs<any>(proxy?.useDict('project_type'));
const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));
const { information_classify } = toRefs<any>(proxy?.useDict('information_classify'));
const { work_professial_year } = toRefs<any>(proxy?.useDict('work_professial_year'));
const { unit_type } = toRefs<any>(proxy?.useDict('unit_type'));
const tech_qualification = ref([{ label: '全部', value: 0 }]);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const router = useRouter();
const searchName = ref('');
const searchContent = ref('');

const queryFormRef = ref<ElFormInstance>();
const expertFormRef = ref<ElFormInstance>();
const replyStatusOptions = ref({
  1: '未答复',
  2: '已答复'
});
const replyTimeOptions = ref({
  1: '仅三天',
  2: '近一个月',
  3: '近三个月',
  4: '近一年'
});

const replyTimeValue = (key) => {
  const json = {
    1: () => {
      const start = dayjs().subtract(2, 'day');
      const end = dayjs();
      return [start.format('YYYY-MM-DD 00:00:00'), end.format('YYYY-MM-DD 23:59:59')];
    },
    2: () => {
      const start = dayjs().subtract(1, 'month');
      const end = dayjs();
      return [start.format('YYYY-MM-DD 00:00:00'), end.format('YYYY-MM-DD 23:59:59')];
    },
    3: () => {
      const start = dayjs().subtract(3, 'month');
      const end = dayjs();
      return [start.format('YYYY-MM-DD 00:00:00'), end.format('YYYY-MM-DD 23:59:59')];
    },
    4: () => {
      const start = dayjs().subtract(1, 'year');
      const end = dayjs();
      return [start.format('YYYY-MM-DD 00:00:00'), end.format('YYYY-MM-DD 23:59:59')];
    }
  };
  return json[key]?.() || null;
};

const queryData = reactive({
  pageNum: 1,
  pageSize: 10
});
const replyStatus = ref('');
const replyTime = ref('');
const query = computed(() => {
  let time = replyTimeValue(replyTime.value);
  return {
    status: replyStatus.value,
    replyStartTime: time?.[0] || '',
    replyEndTime: time?.[1] || ''
  };
});
const dataList = ref([]);

/** 查询帖子信息 */
const getList = async () => {
  loading.value = true;
  const res = await getQuestionList({ ...queryData, ...query.value });
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  dataList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 条件查询列表 */
const handleFind = async (key, value) => {
  let json = {
    status: () => {
      replyStatus.value = value;
    },
    time: () => {
      replyTime.value = value;
    }
  };
  json[key]();
  getList();
};

const visible = ref(false);
const formQuery = {
  problemTitle: '',
  problem: ''
};
const form = ref({
  ...formQuery
});
const rules = {
  problemTitle: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  problem: [{ required: true, message: '请输入内容', trigger: 'blur' }]
};
const askOnline = () => {
  form.value = { ...formQuery };
  visible.value = true;
};

const formRef = ref(null);
const Cancel = () => {
  formRef.value.resetFields();
  visible.value = false;
};
const confirmSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) return;
    ElMessageBox.confirm('确定提交吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const params = {
          ...form.value
        };
        let res = await submitQuestion(params);
        if (res.code != 200) {
          ElNotification({
            title: '提示',
            message: res.msg,
            type: 'error'
          });
          return;
        }
        ElNotification({
          title: '提示',
          message: '提交成功，等待管理员解答',
          type: 'success'
        });
        Cancel();
        getList();
      })
      .catch(() => {});
  });
};

onActivated(() => {
  getList();
});
onMounted(async () => {
  getList();
});
</script>

<style scoped lang="scss">
.p-2 {
  height: calc(100vh - 84px);
  .content {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 10px;
    .reply-main {
      flex: 1;
      overflow: auto;
      font-size: 14px;
      .user-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .info-left {
          display: flex;
          align-items: center;
          gap: 10px;
        }
        .time {
          color: #999;
        }
      }
      .question {
        padding: 10px 0 0;
        .question-title {
          font-size: 16px;
        }
        .question-content {
          text-indent: 2em;
          margin-top: 10px;
        }
      }
      .reply {
        padding-left: 50px;
        margin-top: 20px;
        .reply-content {
          padding: 16px;
          background-color: #f1f1f1;
          border-radius: 4px;
        }
      }
    }
  }
}
.search-list {
  width: 100%;
  .search-item {
    width: 100%;
    display: flex;
    margin-bottom: 1vh;
    font-size: 14px;
    .item-title {
      width: auto;
      span {
        display: inline-block;
        text-wrap: nowrap;
        width: 7vw;
      }
    }
    .item-content {
      span {
        display: inline-block;
        margin-right: 1vw;
        cursor: pointer;
        font-weight: bolder;
        padding: 1px 4px;
      }
      span {
        &:hover {
          background-color: rgba(0, 0, 0, 0.1);
        }
        &.active {
          background-color: #36d;
          color: #fff;
        }
      }
    }
  }
}
</style>
