<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select v-model="listQuery.sortId" placeholder="请选择问题类别" clearable class="filter-item" style="width: 200px;">
        <el-option v-for="item in sortList" :key="item.id" :label="item.sort" :value="item.id">
        </el-option>
      </el-select>

      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入问题题目" v-model="listQuery.ask">
      </el-input>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column type="index" label="序号" header-align="center" align="center">
      </el-table-column>

      <el-table-column align="center" min-width="120px" label="问题类别" prop="sort">
      </el-table-column>

      <el-table-column align="center" min-width="180px" label="问题题目" prop="ask">
      </el-table-column>

      <el-table-column align="center" min-width="180px" label="问题答案" prop="answer">
      </el-table-column>

      <!--<el-table-column align="center" min-width="80px" label="是否启用" prop="enabled">-->
      <!--<template slot-scope="scope">-->
      <!--<el-tag :type="scope.row.enabled ? 'success' : 'error' ">{{ scope.row.enabled ? '启用' : '不启用' }}</el-tag>-->
      <!--</template>-->
      <!--</el-table-column>-->

      <el-table-column align="center" label="操作" width="240px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="small"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="问题类别" prop="sortId">
          <el-select v-model="dataForm.sortId" placeholder="请选择">
            <el-option
              v-for="item in sortList"
              :key="item.id"
              :label="item.sort"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题题目" prop="ask">
          <el-input v-model="dataForm.ask"></el-input>
        </el-form-item>
        <!--<el-form-item label="问题答案" prop="answer">-->
          <!--<el-input v-model="dataForm.answer"></el-input>-->
        <!--</el-form-item>-->

        <el-form-item :key="index" v-for="(item,index) in dataForm.answers" :label="'答案 '+(index+1)" :prop="answers" >
          <el-row :gutter="20">
            <el-col :span="17">
              <div class="grid-content bg-purple">
                <el-input v-model="item['answer']"></el-input>
              </div>
            </el-col>
            <el-col :span="3">
              <div class="grid-content bg-purple">
                <el-checkbox v-model="item['right']" label="答案" border @change="chooseAnswer(index)"></el-checkbox>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!--<el-form-item label="关联新闻" prop="newsId">-->
        <!--<el-select v-model="dataForm.newsId" filterable placeholder="请选择" style="width: 350px;">-->
        <!--<el-option v-for="item in displayList" :label="item.title" :value="item.id" :key="item.id">-->
        <!--</el-option>-->
        <!--</el-select>-->
        <!--</el-form-item>-->

        <!--<el-form-item label="是否启用" prop="enabled">-->
        <!--<el-select v-model="dataForm.enabled" placeholder="请选择">-->
        <!--<el-option label="启用" :value="true">-->
        <!--</el-option>-->
        <!--<el-option label="不启用" :value="false">-->
        <!--</el-option>-->
        <!--</el-select>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 200px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
</style>

<script>
  import { listQuestionDetail, createQuestionDetail, readQuestionDetail, updateQuestionDetail, deleteQuestionDetail } from '@/api/questionDetail'
  import { listQuestionSort } from '@/api/questionSort'
  import waves from '@/directive/waves' // 水波纹指令

  export default {
    name: 'questionDetail',
    directives: {
      waves
    },
    data() {
      return {
        list: undefined,
        total: undefined,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          sortId:undefined,
          ask:undefined,
          answer:undefined,
        },
        dataForm: {
          id: undefined,
          sortId:undefined,
          sort:undefined,
          ask:undefined,
          answer:undefined,
          answers:[{
            "answer":undefined,
            "right":false
          }, {
            "answer":undefined,
            "right":false
          }, {
            "answer":undefined,
            "right":false
          }, {
            "answer":undefined,
            "right":true
          }],
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          sortId: [{ required: true, message: '请选择问题类别', trigger: 'blur' }],
          ask:[{ required: true, message: '请填写问题题目', trigger: 'blur' }],
          answer:[{ required: true, message: '请填写问题答案', trigger: 'blur' }],
        },
        displayList: [],
        sortList:[],//存放问题种类
      }
    },

    created() {
      this.getList()

      listQuestionSort({
        page: 1,
        limit: 20,
      }).then(response => {
       for(let i = 0; i< (response.data.data.items).length; i++){
         this.sortList.push(response.data.data.items[i]);
       }
        //this.displayList = response.data.data.items
      }).catch(() => {
        this.sortList = []
      })
    },
    methods: {
      getList() {
        this.listLoading = true
        listQuestionDetail(this.listQuery).then(response => {
          this.list = response.data.data.items
          for(let i=0;i<this.list.length;i++){
            this.list[i]['answers'] = JSON.parse(this.list[i].answer);
          }
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          sortId:undefined,
          sort:undefined,
          ask:undefined,
          answer:undefined,
          answers:[{
            "answer":undefined,
            "right":false
          }, {
            "answer":undefined,
            "right":false
          }, {
            "answer":undefined,
            "right":false
          }, {
            "answer":undefined,
            "right":true
          }],
        }
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      uploadUrl(item) {
        const formData = new FormData()
        formData.append('file', item.file)
        createStorage(formData).then(res => {
          this.dataForm.url = res.data.data.url
        }).catch(() => {
          this.$message.error('上传失败，请重新上传')
        })
      },
      createData() {
        this.dataForm.answer = JSON.stringify(this.dataForm.answers);
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            for(let i = 0;i<this.dataForm.answers.length;i++){
              if(this.dataForm.answers[i]['answer']==null || this.dataForm.answers[i]['answer'].replace(/(^\s*)|(\s*$)/g, "")==""){
                this.$notify({
                  title: '警告',
                  message: '答案 '+(i+1)+' 内容不能为空',
                  type: 'warning',
                  duration: 2000
                })
                return false;
              }
            }
            createQuestionDetail(this.dataForm).then(response => {
              response.data.data['answers'] = JSON.parse(response.data.data.answer);
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.dataForm.answer = JSON.stringify(this.dataForm.answers);
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            for(let i = 0;i<this.dataForm.answers.length;i++){
              if(this.dataForm.answers[i]['answer']==null || this.dataForm.answers[i]['answer'].replace(/(^\s*)|(\s*$)/g, "")==""){
                this.$notify({
                  title: '警告',
                  message: '答案 '+(i+1)+' 内容不能为空',
                  type: 'warning',
                  duration: 2000
                })
                return false;
              }
            }
            updateQuestionDetail(this.dataForm).then(res => {
              this.dataForm.sort = res.data.data.sort;//赋值分类名称
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {

        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteQuestionDetail(row).then(response => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
        }).catch(() => {

        })

      },
      chooseAnswer(index){//选择答案
        if(this.dataForm.answers!=null){
          for(let i = 0;i<this.dataForm.answers.length;i++){
            i == index?this.dataForm.answers[i]['right']=true:this.dataForm.answers[i]['right']=false;
          }
        }
      },

    }
  }
</script>
<style>
  .ad-avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .ad-avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .ad-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .ad-avatar {
    display: block;
  }
</style>
