<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="questionOrder">
            <el-input v-model="queryParams.questionOrder" placeholder="请输入问题序号" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="问题内容" prop="questionContent">
            <el-input v-model="queryParams.questionContent" placeholder="请输入问题内容" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="因子维度" prop="factorId">
            <el-select v-model="queryParams.factorId" placeholder="请输入因子维度" style="width: 240px">
              <el-option v-for="item in scaleFactorList" :key="item.factorId" :label="item.factorName"
                :value="item.factorId" />
            </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"
              v-hasPermi="['scale:question:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['scale:question:edit']">修改</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['scale:question:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['scale:question:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="SysScaleQuestionList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- <el-table-column label="测评量表标题" align="center" prop="scaleTitle" /> -->
        <el-table-column label="问题序号" align="center" prop="questionOrder" />
        <el-table-column label="问题内容" align="center" prop="questionContent" />
        <!-- <el-table-column label="因子名称" align="center" prop="factorName" /> -->
        <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="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['scale:question:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['scale:question:remove']"></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="850px" append-to-body
      :close-on-click-modal="false">
      <el-form ref="SysScaleQuestionFormRef" :model="form" :rules="rules" label-width="120px">
        <el-card>
          <template #header>
            <div class="card-header">
              <span class="card-title">测评量表问题信息</span>
            </div>
          </template>
          <el-form-item label="问题序号" prop="questionOrder">
            <el-input v-model="form.questionOrder" placeholder="请输入问题序号" />
          </el-form-item>
          <el-form-item label="问题内容">
            <el-input v-model="form.questionContent" placeholder="请输入问题内容" />
          </el-form-item>
        </el-card>

        <el-card style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <div class="card-title">测评量表问题信息</div>
              <div>
                <el-button @click="addQuestion">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  增加
                </el-button>
              </div>
            </div>
          </template>
          <el-table :data="form.scaleAnswerList">
            <el-table-column type="index" label="序号" width="55" />
            <el-table-column prop="type" label="选项类型" width="100">
              <template #default="scope">
                <el-select v-model="scope.row.type" placeholder="请选择选项类型">
                  <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="answerOption" label="选项内容">
              <template #default="scope">
                <image-upload v-if="scope.row.type === 1" v-model="scope.row.answerOption" :limit="1" />
                <el-input v-else v-model="scope.row.answerOption" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column prop="score" label="分值" width="160">
              <template #default="scope">
                <el-input-number v-model="scope.row.score" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column prop="scoreType" label="得分类型" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.scoreType" placeholder="选填" />
              </template>
            </el-table-column>
            <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="Delete" @click="handleOptionDelete(scope.row)">删除</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </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>
  </div>
</template>

<script setup name="SysScaleQuestion" lang="ts">
import { onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { nanoid } from 'nanoid'
import { listSysScaleQuestion, getSysScaleQuestion, delSysScaleQuestion, addSysScaleQuestion, updateSysScaleQuestion } from '@/api/scale/SysScaleQuestion';
import { SysScaleQuestionVO, SysScaleQuestionQuery, SysScaleQuestionForm } from '@/api/scale/SysScaleQuestion/types';

import { listSysScaleFactor } from '@/api/scale/SysScaleFactor';
import { SysScaleFactorVO } from '@/api/scale/SysScaleFactor/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const scaleId = useRoute().params.scaleId;
const SysScaleQuestionList = ref<SysScaleQuestionVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

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

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

const typeOptions = [
  {
    label: '文字',
    value: 0
  },
  {
    label: '图片',
    value: 1
  }
]

const initFormData: SysScaleQuestionForm = {
  questionId: undefined,
  scaleId: scaleId,
  scaleTitle: undefined,
  questionOrder: undefined,
  questionContent: undefined,
  factorId: undefined,
  factorName: undefined,
  scaleAnswerList: []
}
const data = reactive<PageData<SysScaleQuestionForm, SysScaleQuestionQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    scaleId: scaleId,
    scaleTitle: undefined,
    questionOrder: undefined,
    questionContent: undefined,
    factorId: undefined,
    factorName: undefined,
    params: {
    }
  },
  rules: {
    questionId: [
      { required: true, message: "测评问题id不能为空", trigger: "blur" }
    ],
    scaleId: [
      { required: true, message: "所属测评量表id不能为空", trigger: "blur" }
    ],
    scaleTitle: [
      { required: true, message: "测评量表标题不能为空", trigger: "blur" }
    ],
    questionOrder: [
      { required: true, message: "问题序号不能为空", trigger: "blur" }
    ],
    questionContent: [
      { required: true, message: "问题内容不能为空", trigger: "blur" }
    ],
    factorId: [
      { required: true, message: "所属因子维度不能为空", trigger: "blur" }
    ],
    factorName: [
      { required: true, message: "因子名称不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询量问题内容列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSysScaleQuestion(queryParams.value);
  SysScaleQuestionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: SysScaleQuestionVO[]) => {
  ids.value = selection.map(item => item.questionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.scaleAnswerList = []
  dialog.visible = true;
  dialog.title = "添加量问题内容";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SysScaleQuestionVO) => {
  reset();
  const _questionId = row?.questionId || ids.value[0]
  const res = await getSysScaleQuestion(_questionId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改量问题内容";
}

function addQuestion() {
  form.value.scaleAnswerList.push({ answerId: nanoid(), answerOption: '', score: 0, type: 0, scoreType: '' })
}

function handleOptionDelete(row: any) {
  form.value.scaleAnswerList = form.value.scaleAnswerList.filter(item => item.answerId !== row.answerId)
}

/** 提交按钮 */
const submitForm = () => {
  SysScaleQuestionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.scaleAnswerList.forEach((item, index) => {
        if (item.answerId.length == 21) {
          item.answerId = '';
        }
        item.sort = index + 1
      })

      if (form.value.questionId) {
        await updateSysScaleQuestion(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSysScaleQuestion(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      reset();
      form.value.scaleAnswerList = []
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: SysScaleQuestionVO) => {
  await proxy?.$modal.confirm('是否确认删除量问题内容编号为"' + row?.questionContent + '"的数据项？').finally(() => loading.value = false);
  await delSysScaleQuestion({ questionId: row?.questionId, scaleId });
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('scale/SysScaleQuestion/export', {
    ...queryParams.value
  }, `SysScaleQuestion_${new Date().getTime()}.xlsx`)
}

const scaleFactorList = ref<SysScaleFactorVO[]>([]);
async function getScaleFactorList() {
  const res = await listSysScaleFactor({ scaleId })
  scaleFactorList.value = res.data
}

onMounted(() => {
  getList();

  getScaleFactorList()
});
</script>

<style lang="scss" scoped>
.card-title {
  font-size: 16px;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
}
</style>
