<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="量表名称" prop="scaleName">
            <el-input v-model="queryParams.scaleName" placeholder="请输入量表名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="量表编码" prop="scaleCode">
            <el-input v-model="queryParams.scaleCode" placeholder="请输入量表编码" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="量表类型" prop="scaleType">
            <el-select v-model="queryParams.scaleType" placeholder="请选择量表类型" style="width: 240px"
              @keyup.enter="handleQuery">
              <el-option v-for="item in scaleTypeList" :key="item.dictCode" :label="item.dictLabel"
                :value="item.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd(1)"
              v-hasPermi="['scale:publish:add']">量表普测发布</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd(0)"
              v-hasPermi="['scale:publish:add']">量表个测发布</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="SysScaleList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="封面" align="center" prop="cover" width="150">
          <template #default="scope">
            <image-preview :src="scope.row.coverUrl" :width="150" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="量表名称" align="center" prop="scaleName" />
        <el-table-column label="量表编码" align="center" prop="scaleCode" />
        <el-table-column label="量表类型" align="center" prop="scaleTypeName">
          <template #default="scope">
            <el-space wrap>
              <el-tag type="primary" disable-transitions v-for="(item, index) in scope.row.scaleTypeName" :key="index">
                {{ item }}
              </el-tag>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column label="测评详情" align="center" prop="scaleDetails">
          <template #default="scope">
            <el-popover placement="top-start" title="测评详情" :width="400" trigger="hover"
              :content="scope.row.scaleDetails">
              <template #reference>
                <span class="text-ellipsis">{{ scope.row.scaleDetails }}</span>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="维度类型" align="center" prop="dimensionType">
          <template #default="scope">
            <el-tag v-if="scope.row.dimensionType === 0" type="primary">单项单维</el-tag>
            <el-tag v-else-if="scope.row.dimensionType === 1" type="primary">多项单维型</el-tag>
            <el-tag v-else-if="scope.row.dimensionType === 2" type="primary">多项多维型</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布次数" align="center" prop="publishNums" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看量表详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"
                v-hasPermi="['scale:info:query']">查看量表详情</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改心理测评量对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" :width="publishType == 0 ? '700px' : '500px'"
      append-to-body>
      <el-form ref="SysScaleFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="场次名称" prop="sessionName">
          <el-input v-model="form.sessionName" placeholder="请输入量表名称" />
        </el-form-item>
        <el-form-item label="是否预约发布" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="1">是</el-radio>
            <el-radio value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="查看结果" prop="allowQueryResult">
          <el-radio-group v-model="form.allowQueryResult">
            <el-radio value="1">允许</el-radio>
            <el-radio value="0">不允许</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始日期" prop="startTime">
          <el-date-picker v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="截止日期" prop="expireTime">
          <el-date-picker v-model="form.expireTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择截止日期" style="width: 100%" />
        </el-form-item>

        <el-form-item label="量表" prop="scaleIds">
          <el-select multiple v-model="form.scaleIds" placeholder="请选择量表" style="width: 100%">
            <el-option v-for="item in scaleOptions" :key="item.scaleId" :label="item.scaleName" :value="item.scaleId" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="publishType == 1" label="归属部门" prop="deptIds">
          <el-tree-select v-model="form.deptIds" :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }" node-key="id" placeholder="请选择归属部门" multiple
            show-checkbox />
        </el-form-item>

        <el-form-item v-if="publishType == 0" label="归属部门" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }" node-key="id" placeholder="请选择归属部门"
            @change="deptChange" />
        </el-form-item>

        <el-table v-if="publishType == 0" :data="userTableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column property="userName" label="用户名称" />
          <el-table-column property="nickName" label="用户昵称" />
          <el-table-column property="phonenumber" label="手机号码" />
        </el-table>
        <pagination v-show="userTotal > 0" :total="userTotal" v-model:page="userParams.pageNum"
          v-model:limit="userParams.pageSize" @pagination="getUserList" />

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="查看量表详情" v-model="detailVisible" width="800px" append-to-body>
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane v-for="item in factorList" :label="item.factorName" :name="item.factorName" :key="item.factorId">
          <p v-for="q in item.questionList" :key="q.questionId">
            {{ q.questionOrder + "、" + q.questionContent }}
          </p>
        </el-tab-pane>
      </el-tabs>

      <!-- <el-card v-for="item in factorList" style="margin-bottom: 10px;">
        <template #header>
          <div class="card-header">
            <span>{{ item.factorName }}</span>
          </div>
        </template>

        <p v-for="q in item.questionList" :key="q.questionId">
          {{ q.questionOrder + "、" + q.questionContent }}
        </p>
      </el-card> -->
    </el-dialog>

  </div>
</template>

<script setup name="SysScale" lang="ts">
import { listSysScale, findAll } from '@/api/scale/SysScale';
import { SysScaleVO } from '@/api/scale/SysScale/types';

import { addScalePublish } from '@/api/scale/scalePublish';

import { findByScaleId } from '@/api/scale/SysScaleQuestion'

import { getDicts } from '@/api/system/dict/data';
import { DictDataVO } from '@/api/system/dict/data/types';

import { deptTreeSelect } from "@/api/system/user"
import { listUser } from '@/api/system/user';
import { UserVO } from '@/api/system/user/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const SysScaleList = ref<SysScaleVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const SysScaleFormRef = ref<ElFormInstance>();

const multipleSelection = ref<any[]>([])
const userTotal = ref(0)
const userParams = ref({
  pageNum: 1,
  pageSize: 5,
  userType: 'student',
  deptId: ''
})
const userTableData = ref<UserVO[]>([])
async function getUserList() {
  const res = await listUser(userParams.value)
  userTableData.value = res.rows
  userTotal.value = res.total
}

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const detailVisible = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询心理测评量列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSysScale(queryParams.value);
  SysScaleList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {};
  SysScaleFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const publishType = ref();
const handleAdd = (type: any) => {
  reset();

  publishType.value = type

  dialog.visible = true;

  if (publishType.value == 0) {
    dialog.title = "量表个测发布";
  } else {
    dialog.title = "量表普测发布";
  }
}

/** 提交按钮 */
const submitForm = () => {
  SysScaleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.publishType = publishType.value

      if (publishType.value == 0) {
        const userIds = multipleSelection.value.map(v => v.userId)
        form.value.userIds = userIds
      }

      await addScalePublish(form.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess("发布成功");
      dialog.visible = false;
      await getList();
    }
  });
}

const scaleTypeList = ref<DictDataVO[]>([])

async function getScaleTypeList() {
  const res = await getDicts('scale_type')
  scaleTypeList.value = res.data
}

const deptOptions = ref<any[]>([]);
/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await deptTreeSelect();
  deptOptions.value = res.data;
};

const scaleOptions = ref<any[]>([]);
const getScaleOptions = async () => {
  const res = await findAll({ status: 1 });
  scaleOptions.value = res.data;
}

watch(() => dialog.visible, (visible) => {
  if (visible) {
    getTreeSelect()
    getScaleOptions()
  }
})

const factorList = ref<any[]>([])
const activeName = ref()
async function handleDetail(row: any) {
  const res = await findByScaleId({ scaleId: row.scaleId })
  factorList.value = res.data
  detailVisible.value = true

  activeName.value = factorList.value[0].factorName
}

function deptChange(val: any) {
  // console.log('deptChange', treeToList(deptOptions.value));
  userParams.value.deptId = val
  getUserList()
}

// function treeToList(treeData) {
//   const result = [];

//   function traverse(node) {
//     // 将当前节点信息添加到结果列表中
//     result.push({
//       id: node.id,
//       label: node.label,
//       parentId: node.parentId
//     });

//     // 如果当前节点有子节点，则递归遍历子节点
//     if (node.children && node.children.length > 0) {
//       for (const child of node.children) {
//         traverse(child);
//       }
//     }
//   }

//   // 遍历树的根节点
//   if (Array.isArray(treeData)) {
//     for (const root of treeData) {
//       traverse(root);
//     }
//   } else {
//     // 如果传入的是单个根节点对象而非数组
//     traverse(treeData);
//   }

//   return result;
// }

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