<template>
  <div class="parameter-setting-container">
    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item v-for="(subject, index) in subjectInfos" :key="index" :name="index + ''">
        <template slot="title">
          <span class="collapse-title">{{ subject.name }}</span>
        </template>
        <div v-if="showTools" class="flex-row top-btn">
          <el-button type="primary" size="mini" @click="addParam(subject, index)">新增</el-button>
        </div>
        <el-table
          :header-cell-style="{ background: '#F6F7FB', color: '#606266' }"
          :data="subject.options"
          border
          style="width: 100%;"
        >
          <el-table-column prop="name" label="名称" min-width="3">
            <template slot-scope="scope">
              {{ scope.row.name }}
              <template v-if="scope.row.remaks && scope.row.remaks.length > 0">
                {{ scope.row.remaks }}
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="编码" min-width="1" />
          <el-table-column prop="value" label="值" min-width="2" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" placeholder="请输入参数值" @change="editParam(scope.row)"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      append-to-body
    >
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="160px">
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入参数名称"></el-input>
        </el-form-item>
        <el-form-item label="参数编码" prop="name">
          <el-input v-model="form.code" placeholder="请输入参数编码（确认后不可更改）"></el-input>
        </el-form-item>
        <el-form-item label="值" prop="name">
          <el-input v-model="form.value" placeholder="请输入参数值"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addParamFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: "ReportMgr",
  data() {
    return {
      activeNames: [],
      subjectInfos: [],
      loading: false,
      uId: '',
      institutionNo: '',

      dialogTitle: '',
      dialogVisible: false,
      targetSubject: {},
      targetIndex: -1,
      form: {
        id: null, // 数据ID
        taskId: '', // 认知任务ID
        code: '', // 参数编码
        name: '', // 参数名称
        value: '', // 参数值
        remarks: '' // 备注
      },
      rules: {
        name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入参数编码', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请输入参数值', trigger: 'blur' }
        ]
      },

      showTools: false
    }
  },
  mounted() {
    this.showTools = process.env.NODE_ENV === 'development'
    this.loadData()
  },
  methods: {
    handleChange(val) {
      val.forEach((item) => {
        this.$http.get(
            `/taskParam/getByTaskId?taskId=${this.subjectInfos[Number(item)].id}`,
            {},
            (msg) => {
              this.subjectInfos[Number(item)].options = msg.data
              console.log('this.subjectInfos[Number(item)].options: ', this.subjectInfos[Number(item)].options)
            }
        )
      })
    },

    // 加载数据
    loadData() {
      this.loading = true
      this.$http.get(
          `subjectInfo/getCognizeListByName?categoryEname=CALL&scaleName=&pageNum=1&pageSize=100`,
          {},
          (msg) => {
            console.log(msg,'msg')
            this.subjectInfos = msg.data.data.filter((item) => ['空间定向任务', '精神运动警觉度测试', '时间知觉能力测试', '多目标追踪', '决策倾向测试'].includes(item.name)).map((item) => {
              return {
                id: item.no,
                name: item.name,
                isOpen: false,
                options: []
              }
            })
            console.log('')
            console.log('-----------------http start-------------------')
            console.log('this.subjectInfos: ', this.subjectInfos)
            console.log('-----------------http end-------------------')
            console.log('')
            setTimeout(() => {
              this.loading = false
            }, 350)
          }, (err) => {
            console.log(err)
            this.loading = false
          }
      )
    },

    /**
     * 新增参数
     * @param subject 当前 subjectInfos
     * @param index 当前索引
     */
    addParam(subject, index) {
      this.form = {
        id: null, // 数据ID
        taskId: subject.id, // 认知任务ID
        code: '', // 参数编码
        name: '', // 参数名称
        value: '', // 参数值
        remaks: '' // 备注
      }
      this.targetIndex = index
      this.dialogTitle = `${subject.name} 参数设置`
      this.dialogVisible = true
    },

    addParamFn() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$http.post(
              '/taskParam/save',
              this.form,
              () => {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.subjectInfos[this.targetIndex].options.push(this.form)
              },
              (err) => {
                this.$message.error('添加失败, ' + err.msg)
              }
          )
        }
      })
    },

    editParam(row) {
      console.log(row,'row')
      let params = {
        code:row.code,
        id:row.id,
        name:row.name,
        taskId:row.taskId,
        value:row.value
      }
      let valid = true;
      if (row.code == 'TTC_Target_Count' || row.code =='SOA_Target_Count') {
        console.log('TTC_Target_Count')
        const items = row.value.split(",");
        for (const item of items) {
          if (Number(item) > 5) {
            valid = false;
            break;
          }
        }
      }
      if (valid) {
        this.$http.post(
            '/taskParam/update',
            params,
            () => {
              console.log('修改成功!~')
              this.$message.success('修改成功')
            },
            (err) => {
              this.$message.error('修改失败, ' + err.msg)
            }
        )
      } else {
        console.log("字符串中有项大于 5");
        this.$message.error('修改失败，目标数量最大值不能超过5')
      }

    }
  }
}
</script>

<style lang="scss" scoped>
.parameter-setting-container {
  width: calc(100% - 50px);
  height: calc(100% - 50px);
  padding: 15px 25px;
  border-radius: 8px;
  overflow: auto;
  background-color: white;

  .collapse-title {
    font-size: 0.08rem;
    color: #007EFF;
  }

  .top-btn {
    margin-bottom: 8px;
  }
}
</style>
