<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch">
        <el-card class="mb-[10px]" shadow="hover">
          <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="auto">
            <el-form-item label="专家姓名" prop="expertName">
              <el-input v-model="queryParams.expertName" clearable placeholder="请输入专家姓名" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="内容名称" prop="suggestName">
              <el-input v-model="queryParams.suggestName" clearable placeholder="请输入内容名称" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button plain type="primary" @click="OpenPlan" v-hasPermi="['study:studyRecommend:add']">新增</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="RecommendLists">
            <el-table-column label="序号" type="index" width="50px"></el-table-column>
            <el-table-column
              v-for="{ label, prop, align, minWidth } in headers"
              :key="prop"
              :align="align || 'center'"
              :label="label"
              :min-width="minWidth || '100px'"
              :prop="prop"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleShow(row)">查看</el-button>
                <el-divider direction="vertical" />
                <el-button link type="primary" @click="deletePlan(row)" :disabled="!delPermission(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" v-model:limit="page.pageSize" v-model:page="page.pageNum" :total="page.total" @pagination="getList" />
        </el-card>
        <el-dialog v-model="showDialog" :before-close="closeDialog" title="详情" width="800px">
          <div class="flex justify-between lh-[20px]">
            <span class="text-[16px] font-600"> {{ activeRow.suggestName }} </span>
            <span class="text-[12px] color-[#999]"> {{ activeRow.createTime }} </span>
          </div>
          <p class="text-[14px]">{{ activeRow.contsuggestContentent }}</p>
          <div class="mt-[10px] mb-[10px] flex justify-between" v-if="fileLists?.[0]?.originalName">
            <div class="text-[14px] color-[#666] lh-[20px]">附件：{{ fileLists?.[0]?.originalName }}</div>
            <el-button link type="primary" @click="downloadFile">下载附件</el-button>
          </div>
          <template #footer>
            <el-button @click="closeDialog">关闭</el-button>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script lang="ts" setup>
import { getRecommendList, delRecommend } from '@/api/study/studyRecommend';
import { getFile } from '@/api/filemanage';
import useUserStore from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const RecommendLists = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);

const queryFormRef = ref<ElFormInstance>();

const userStore = useUserStore();
const roles = ref(userStore.roles);
const userId = ref(userStore.userId);

const delPermission = (row) => {
  if(!roles.value.includes('expert')) return true;
  return row.createBy === userId.value
}

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
}

const headers = ref<Header[]>([
  {
    label: '内容名称',
    prop: 'suggestName'
  },
  {
    label: '推荐专家',
    prop: 'expertName'
  },
  {
    label: '提交时间',
    prop: 'createTime'
  }
]);

const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<any>({
  expertName: '',
  suggestName: ''
});

/** 查询expert列表 */
const getList = async () => {
  loading.value = true;
  const res = await getRecommendList({
    ...queryParams.value,
    ...page.value
  });
  console.log(res);
  RecommendLists.value = res.rows;
  page.value.total = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  page.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const activeRow = ref<any>({});
const OpenPlan = () => {
  proxy.$router.push({
    path: '/study/studyRecommendAdd'
  });
};
const showDialog = ref(false);
const closeDialog = () => {
  showDialog.value = false;
};

const fileLists = ref([]);
const handleShow = async (row: any) => {
  activeRow.value = row;
  showDialog.value = true;
  let res = await getFile(row.fileId);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
  }
  fileLists.value = res.data;
};
const deletePlan = (row: any) => {
  activeRow.value = row;
  ElMessageBox.confirm('是否确认删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await delRecommend(row.id);
      if (res.code === 200) {
        ElNotification({
          title: '提示',
          message: '删除成功',
          type: 'success'
        });
        getList();
        return;
      }
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
    })
    .catch(() => {});
};

const downloadFile = async () => {
  let a = document.createElement('a');
  a.href = fileLists.value?.[0]?.url;
  a.target = '_blank';
  a.download = fileLists.value?.[0]?.originalName;
  document.body.appendChild(a);
  a.click();
  await nextTick();
  document.body.removeChild(a);
};
onActivated(() => {
  getList();
})
onMounted(() => {
  getList();
});
</script>
