<template>
  <el-form ref="setting"
           :inline="false"
           :model="form"
           :rules="rules"
           class="y-factor-configuration"
           label-position="right"
           label-width="120px">

    <slot></slot>
    <el-row>
      <el-col :span="8">
        <el-form-item :label="form.code+' 因子名称'" prop="title">
          <el-input v-model="form.title"
                    clearable
                    placeholder="请输入因子名称"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item label="因子说明" prop="explain">
          <el-input v-model="form.explain"
                    clearable
                    type="textarea"
                    placeholder="请输入因子说明"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="项目绑定" required>
      <el-button size="mini" type="success" @click="openQuestion">点击选择</el-button>
      <span style="color: green">
        （已选择 {{ form.values.length }}  题）
      </span>
      <span v-if="form.values.some(code => !questionList.some(item => item.code == code))"
            style="padding: 0;margin: 0;color: red;line-height: 15px;">
         检测到已绑定题项数量与当前配置不匹配，请重新进行项目绑定</span>
    </el-form-item>

    <el-row>
      <el-col :span="8">
        <el-form-item ref="originalScoreQl" label="原始分" prop="originalScoreQl">
          <el-input v-model="form.originalScoreQl" clearable placeholder="请输入原始分公式">
            <template slot="suffix">
              <a href="javascript:;" style="position: absolute;right: -80px;width: 70px;color: #6268f6;"
                 @click="form.originalScoreQl=form.code">使用默认</a>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col>
        <el-form-item class="y-input" label="标准分">
          <el-radio-group v-model="form.standardScoreType" size="mini"
                          @change="(val)=>val==2&&form.factorCallType=='STANDARD'?form.factorCallType='':''">
            <el-radio label="1">有</el-radio>
            <el-radio label="2">无</el-radio>
          </el-radio-group>

        </el-form-item>
        <el-form-item v-if="form.standardScoreType==1" ref="standardScoreQl" class="y-input" label-width="20px"
                      prop="standardScoreQl">
          <el-input v-model="form.standardScoreQl"
                    clearable
                    placeholder="请输入因子标准分公式"/>
        </el-form-item>
      </el-col>

      <el-col :lg="16" :md="16" :sm="16" :xl="16" :xs="24">
        <el-form-item class="y-input" label="因子均分">
          <el-radio-group v-model="form.factorAverageScoreType"
                          @change="(val)=>val==2&&form.factorCallType=='AVERAGE'?form.factorCallType='':''">
            <el-radio label="1">有</el-radio>
            <el-radio label="2">无</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.factorAverageScoreType==1" ref="factorAverageScoreQl" class="y-input" label-width="20px"
                      prop="factorAverageScoreQl">
          <el-input v-model="form.factorAverageScoreQl" clearable placeholder="请输入因子均分公式"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item class="y-input" label="因子区间">
          <el-radio-group v-model="form.factorIntervalType">
            <el-radio label="1">有</el-radio>
            <el-radio label="2">无</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.factorIntervalType==1" class="y-input" label="得分来源" label-width="90px"
                      prop="factorCallType">
          <el-radio-group v-model="form.factorCallType">
            <el-radio label="ORIGINAL">原始分</el-radio>
            <el-radio :disabled="form.standardScoreType==2" label="STANDARD">标准分</el-radio>
            <el-radio :disabled="form.factorAverageScoreType==2" label="AVERAGE">平均分</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <div v-if="form.factorIntervalType==2">
      <el-row>
        <el-col :span="8">
          <el-form-item label="评测结果" prop="conclusion">
            <el-input v-model="form.conclusion" size="mini" type="textarea" placeholder="请输入评测结果"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="评测建议" prop="suggest">
            <el-input v-model="form.suggest" size="mini" type="textarea" placeholder="请输入评测建议"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="症状表现" prop="symptom">
            <el-input v-model="form.symptom" size="mini" type="textarea" placeholder="请输入症状表现"/>
          </el-form-item>
        </el-col>
      </el-row>
    </div>

    <!--  因子区间结论配置   -->
    <div v-else-if="form.factorIntervalType==1" class="y-range-conclusion">
      <score-interval-evaluation
          ref="fie"
          :data.sync="form.rules"/>
    </div>

    <!--  选择项目   -->
    <el-dialog
        :modal="false"
        :modal-append-to-body="false"
        :visible.sync="open"
        title="项目绑定"
        width="760px"
    >
      <question
          ref="question"
          :data.sync="form.values"
          :questionList="questionList"
          :show="open"
          height="450px"
          width="100%"
      />
    </el-dialog>
  </el-form>
</template>

<script>
import Question from './question'

import { validExec, validFactor, validTotal } from './exec'
import ScoreIntervalEvaluation from './scoreIntervalEvaluation'
import tool from '../../tool'
import { scrollToView } from '../../../static/js/tool/xy.tool.valid'
import { exec } from './exec2'

export default {
  name: 'factor-setting',
  components: { ScoreIntervalEvaluation, Question },
  inject: ['getToken', 'getSetting'],
  provide () {
    return {
      getToken: () => this.getToken(),
      getSetting: () =>  this.getSetting(),
    }
  },
  props: {
    questionList: [Array, Object],
    data: [Object],
    index: [Number],
    maxIndex: [Number],
  },
  data () {
    return {
      open: false,
      factorIndexList: [],
      form: {},

      rules: {
        title: [
          { required: true, message: '因子名称不能为空', trigger: 'blur' },
        ],
        originalScoreQl: [
          { required: true, message: '原始分不能为空', trigger: 'blur' },
          { required: true, message: '请检测运算符号', trigger: 'blur', pattern: /^[0-9\-\+\*\/\.()\$\s]+$/gm },
          // {
          //   validator: (rule, value, callback) => validExec(value, callback, this.factorIndexList, validFactor),
          //   trigger: 'blur'
          // },
          {
            validator: (rule, value, callback) => {
              let message = exec(value, this.factorIndexList, [{ reg: `总分`, msg: '’总分‘未知函数' }])
              typeof message == 'boolean' && message ? callback() : callback(new Error(message))
            },
            trigger: 'blur'
          }
        ],
        standardScoreQl: [
          { required: false, message: '标准分不能为空', trigger: 'blur' },
          // { required: false, message: '请检测运算符号', trigger: 'blur', pattern: /^[0-9\-\+\*\/\.()\$\s]+$/gm },
          // {
          //   validator: (rule, value, callback) => validExec(value, callback, this.factorIndexList, validFactor),
          //   trigger: 'blur'
          // }
          {
            validator: (rule, value, callback) => {
              let message = exec(value, this.factorIndexList, [{ reg: `总分`, msg: '’总分‘未知函数' }])
              typeof message == 'boolean' && message ? callback() : callback(new Error(message))
            },
            trigger: 'blur'
          }
        ],
        factorAverageScoreQl: [
          { required: false, message: '因子分不能为空', trigger: 'blur' },
          // { required: false, message: '请检测运算符号', trigger: 'blur', pattern: /^[0-9\-\+\*\/\.()\$\s]+$/gm },
          // {
          //   validator: (rule, value, callback) => validExec(value, callback, this.factorIndexList, validFactor),
          //   trigger: 'blur'
          // }
          {
            validator: (rule, value, callback) => {
              let message = exec(value, this.factorIndexList, [{ reg: `总分`, msg: '’总分‘未知函数' }])
              typeof message == 'boolean' && message ? callback() : callback(new Error(message))
            },
            trigger: 'blur'
          }
        ],
        factorCallType: [
          { required: true, message: '因子分不能为空', trigger: 'blur,change' },
        ]
      }
    }
  },
  watch: {
    index: {
      handler (index) {
        this.form.code = `$${index + 1}`
      },
      immediate: true,
    },
    form: {
      handler (data) {
        if (data != this.data) {
          console.log('因子变化', this.index, data)
        }
        this.$emit('update', data)
      },
      deep: true,
      immediate: false
    },
    data: {
      handler (data) {
        // 合并因子配置数据 默认配置
        if (data) {
          this.form = Object.assign(
              {
                // 因子名称
                title: '',
                // 因子说明、因子解释
                explain: '',
                // 原始分-计算公式
                originalScoreQl: '',
                // 标准分
                standardScoreType: '2',
                // 标准分-计算公式
                standardScoreQl: '',
                // 因子平均分
                factorAverageScoreType: '2',
                // 因子平均分-计算公式
                factorAverageScoreQl: '',
                // 因子区间
                factorIntervalType: '2',
                // 因子区间 得分来源  ORIGINAL、STANDARD、AVERAGE
                factorCallType: 'ORIGINAL',
                // 因子区间配置
                rules: [],
                // 测评结果
                conclusion: '',
                // 测评建议
                suggest: '',
                // 症状表现
                symptom: '',

                // 旧版本 因子题项逗号分隔列表
                value: '',
                // 旧版本 因子题项数组列表
                values: []
              },
              data,
              {
                code: `$${this.index + 1}`
              })
        } else if (data != this.form) {
          this.form = data
        }
        console.log('初始化因子数据：$', this.index, data, this.form)
      }
      ,
      deep: true,
      immediate: true,
    },
// 当前索引集合 唯一校验
    maxIndex: {
      handler (num) {
        this.factorIndexList = tool.range.rangeNumer(1, num, false)
      }
      ,
      immediate: true,
    }
  },
  created () {
  },
  mounted () {
    if (!this.form.uid) {
      this.form.uid = this.$tool.random.snowflakeId()
    }
  },
  methods: {
    // init (data) {
    //   this.form = data
    // },
    openQuestion () {
      this.open = true
    },
    form_validate () {
      let is_bool = true
      console.log('获取', this.form.factorIntervalType)
      // 验证当前因子配置
      this.$refs['setting'].validate((valid) => {
        console.log('因子分设置：', valid)
        if (!valid) {
          is_bool = false
          // 验证移动 具体到form-item
          // scrollToView(this, obj)
          this.$refs['setting'].$el.scrollIntoView({
            //滚动到指定节点
            block: 'center', //值有start,center,end，nearest，当前显示在视图区域中间
            behavior: 'smooth', //值有auto、instant,smooth，缓动动画（当前是慢速的）
          })
          setTimeout(() => {
            this.$message.error('请检查因子配置')
          }, 200)
        } else if (this.form.factorIntervalType == 1 && !this.$refs['fie'].form_validate()) {
          is_bool = false
          setTimeout(() => {
            this.$message.error('请检查因子区间配置')
          }, 200)
        }
      })
      return is_bool
    },
  }
}
</script>
<style scoped>
.y-factor-configuration {
  padding: 25px 0;
  /* min-width: 1500px; */
}

.y-range-conclusion {
}

.y-input {
  display: inline-block;
}

.y-input .el-input {
  width: 250px
}


hr {
  margin: 50px 0;
}

</style>
