<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['his:answer:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['his:answer:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['his:answer:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:answer:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="answerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="问答名称" align="center" prop="questionName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['his:answer:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['his:answer:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改问答对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="问答名称" prop="questionName">
          <el-input v-model="form.questionName" placeholder="请输入内容" />
        </el-form-item>
        <div v-if="form.answers && form.answers.length == 0" class="empty-state">
          <div class="empty-state-icon">
            <i class="el-icon-document"></i>
          </div>
          <p>暂无问题，请点击下方按钮添加</p>
        </div>

        <div v-for="(answer, index) in form.answers" :key="index" class="answer-section">
          <div class="answer-section-header">
            <span class="answer-section-title">
              <span class="answer-section-number">{{ index + 1 }}</span>
              问题 {{ index + 1 }}
            </span>
            <div>
              <el-button 
                v-if="index !== 0" 
                type="danger" 
                size="mini" 
                icon="el-icon-delete"
                @click="delItem(answer, index)">
                删除问题
              </el-button>
            </div>
          </div>
          
          <el-row :gutter="15">
            <el-col :span="16">
              <el-form-item label="问题标题" :prop="`answers[${index}].title`" :rules="rules.title">
                <el-input v-model="answer.title" placeholder="请输入问题标题"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="选项配置">
            <div v-for="(option, optionIndex) in answer.options" :key="optionIndex" class="option-item">
              <div class="option-input">
                <el-input 
                  v-model="answer.options[optionIndex].name" 
                  :placeholder="`选项 ${optionIndex + 1}`">
                </el-input>
              </div>
              <div class="option-actions">
                <el-button 
                  v-if="optionIndex + 1 === answer.options.length"
                  type="primary" 
                  size="mini" 
                  icon="el-icon-plus"
                  circle
                  @click="addOption(index, optionIndex)">
                </el-button>
                <el-button 
                  v-if="optionIndex !== 0"
                  type="danger" 
                  size="mini" 
                  icon="el-icon-minus"
                  circle
                  @click="delOption(answer.options, optionIndex)">
                </el-button>
              </div>
            </div>
            <div class="option-tip">
              <span>提示：至少保留一个选项，点击 + 按钮添加更多选项</span>
            </div>
          </el-form-item>
        </div>
        
        <div class="add-section-btn">
          <el-button 
            type="primary" 
            icon="el-icon-plus"
            @click="addItem(form.answers.length)">
            添加问题
          </el-button>
        </div>
        
        <!-- <div v-for="(i, index) in form.answers" :key="index">
          <el-row>
            <el-col :span="8">
              <el-form-item label="标题" prop="title">
                <el-input v-model="i.title"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button style="margin: 5px;" v-if="index + 1 == form.answers.length"
                @click="addItem(form.answers.length)" type="primary" size="mini">+</el-button>
              <el-button style="margin: 5px;" v-if="index !== 0" type="danger" size="mini"
                @click="delItem(i, index)">-</el-button>
            </el-col>

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

<script>
import { listAnswer, getAnswer, delAnswer, addAnswer, updateAnswer, exportAnswer } from "@/api/his/answer";

export default {
  name: "Answer",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问答表格数据
      answerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jsonInfo: null,
      },
      form: {
            questionName: '',
            answers: [
              {
                title: '',
                options: [{name:'',value:0}]
              }
            ]
          },
          rules: {
            questionName: [
              { required: true, message: '请输入问答名称', trigger: 'blur' }
            ],
            title: [
              { required: true, message: '请输入问题标题', trigger: 'blur' }
            ]
          }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    addItem(length) {
          this.form.answers.push({
            title: '',
            options: [{name:'',value:0}]
          })
        },
        delItem(item, index) {
          if (this.form.answers.length > 1) {
            this.$confirm('确定要删除这个问题吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.form.answers.splice(index, 1)
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
          } else {
            this.$message.warning('至少保留一个问题')
          }
        },
        addOption(answerIndex, optionIndex) {
          this.form.answers[answerIndex].options.push({name:'',value:optionIndex + 1})
        },
        delOption(options, index) {
          if (options.length > 1) {
            this.$confirm('确定要删除这个选项吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              options.splice(index, 1)
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
          } else {
            this.$message.warning('至少保留一个选项')
          }
        },
    // addItem(length) {
    //   this.form.answers.push({
    //     title: '',
    //     options: [],
    //   })
    // },
    // delItem(item, index) {
    //   this.form.answers.splice(index, 1)
    // },
    // addItem1(length,n) {
    //   this.form.answers[n].options.push('')
    // },
    // delItem2(item, index) {
    //   this.form.answers.splice(index, 1)
    // },
    /** 查询问答列表 */
    getList() {
      this.loading = true;
      listAnswer(this.queryParams).then(response => {
        this.answerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        jsonInfo: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加问答";
      if (this.form.answers == null) {
        this.form = {
          answers: [{
            title: '',
            options: [{name:'',value:0}]
          }

          ]
        }
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAnswer(id).then(response => {
        this.form = response.data;
        if (this.form.answers == null) {
          this.form = {
            answers: [{
              title: '',
              options: [{name:'',value:0}]
            }

            ]
          }
        }
        this.form.questionName = response.data.questionName;
        this.form.id = response.data.id;
        this.open = true;
        this.title = "修改问答";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.answers) {
            this.form.jsonInfo = JSON.stringify(this.form.answers);
          }
          if (this.form.id != null) {
            updateAnswer(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAnswer(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除问答编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delAnswer(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有问答数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportAnswer(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => { });
    }
  }
};
</script>
<style>
    .form-container {
      max-width: 900px;
      margin: 30px auto;
      padding: 25px;
      background: #fff;
      border-radius: 10px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    }
    .form-header {
      margin-bottom: 25px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;
    }
    .form-header h2 {
      margin: 0;
      color: #303133;
      font-size: 22px;
    }
    .form-header p {
      margin: 8px 0 0;
      color: #606266;
      font-size: 14px;
    }
    .answer-section {
      margin: 25px 0;
      padding: 20px;
      border: 1px solid #e6e9f0;
      border-radius: 8px;
      background-color: #f9fafc;
      transition: all 0.3s ease;
    }
    .answer-section:hover {
      border-color: #c0c4cc;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }
    .answer-section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 12px;
      border-bottom: 1px dashed #dcdfe6;
    }
    .answer-section-title {
      font-weight: 600;
      color: #303133;
      font-size: 16px;
    }
    .answer-section-number {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 24px;
      background: #409EFF;
      color: white;
      border-radius: 50%;
      font-size: 12px;
      margin-right: 8px;
    }
    .option-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
    }
    .option-input {
      flex: 1;
    }
    .option-actions {
      margin-left: 10px;
      display: flex;
      gap: 5px;
    }
    .section-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
    .add-section-btn {
      margin-top: 15px;
      text-align: center;
    }
    .el-form-item {
      margin-bottom: 20px;
    }
    .el-col {
      padding-right: 15px;
    }
    .el-col:last-child {
      padding-right: 0;
    }
    .option-tip {
      margin-top: 10px;
      color: #909399;
      font-size: 12px;
    }
    .empty-state {
      text-align: center;
      padding: 30px;
      color: #909399;
    }
    .empty-state-icon {
      font-size: 48px;
      margin-bottom: 15px;
      color: #c0c4cc;
    }
  </style>

