<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <!-- <el-form-item label="电话号码" prop="phone">
				<el-input v-model="ruleForm.phone" placeholder="请输入电话号码"></el-input>
			</el-form-item> -->
      <el-form-item label="步骤编号" prop="step">
        <el-input-number v-model="ruleForm.step" :min="1" label="描述文字"/>
      </el-form-item>
      <el-form-item label="步骤内容" prop="content">
        <!-- <el-input type="textarea" autosize v-model="ruleForm.content" placeholder="请输入内容"></el-input> -->
        <el-input v-model="ruleForm.content" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
      <el-form-item label="有无选项" prop="optiontype">
        <el-select v-model="ruleForm.optiontype" placeholder="请选择选项" @change="selectChange">
          <el-option label="无" value="0"/>
          <el-option label="系统字典" value="1"/>
          <el-option label="手输选项" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item v-if="ruleForm.optiontype==1" label="字典code" prop="dictionarycode">
        <el-select v-model="ruleForm.dictionarycode" clearable placeholder="请选择">
          <el-option v-for="items in dictionaryData" :key="items.dictionarycode" :label="items.dictionaryname" :value="items.dictionarycode">
            <span style="float: left">{{ items.dictionaryname }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ items.dictionarycode }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <div v-if="ruleForm.optiontype==2">
        <el-form-item
          v-for="(domain, index) in ruleForm.domains"
          :label="'选项' + index"
          :key="index"
          :prop="'domains.' + index + '.value'"
          :rules="{
            required: true, message: '自定义选项不能为空', trigger: 'blur'
          }"
          label-width="100px"
        >
          <el-input v-model="domain.value" style="margin-right:20px; width:85%"/><el-button @click.prevent="removeDomain(domain)">删除</el-button>
        </el-form-item>

      </div>

      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button v-if="ruleForm.optiontype==2" @click="addDomain">新增选项</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getDetailes, addLineChat, editLineChat, getDictionary } from '@/api/onLineChat/lineChatManage'
import { validateTel } from '@/utils/validate'
import { filterContent } from '@/utils'

const validateTelRule = (rule, value, callback) => {
  if (!validateTel(value)) {
    callback(new Error('请输入有效的电话号码!'))
  } else {
    callback()
  }
}

export default {
  name: 'AddOrEditLineChat',
  props: {
    rowid: {
      type: String,
      default: ''
    },
    layerid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      ruleForm: {
        id: '',
        // phone: '',
        step: '',
        content: '',
        optiontype: '',
        dictionarycode: '',
        domains: []
      },
      rules: {
        phone: [{
          required: true,
          trigger: 'blur',
          validator: validateTelRule
        }],
        step: [
          { required: true, message: '请输入步骤编号', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请填写内容', trigger: 'blur' }
        ],
        optiontype: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        dictionarycode: [
          { required: true, message: '请选择字典code', trigger: 'change' }
        ],
        rangTimes: [{
          required: true,
          message: '请设置时间段!',
          trigger: 'blur'
        }]
      },
      loading: false,
      dictionaryData: []
    }
  },
  created() {
    this.getDictionaryData().then(() => {
      if (this.rowid) {
        this.ruleForm.id = this.rowid
        console.log(this.rowid)
        this.getDetail(this.rowid)
      }
    })
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const optionArr = []
          for (const i of this.ruleForm.domains) {
            optionArr.push(i.value)
          }
          const datas = {
            id: this.ruleForm.id,
            step: this.ruleForm.step,
            content: this.ruleForm.content,
            optiontype: this.ruleForm.optiontype,
            options: optionArr,
            dictionarycode: this.ruleForm.dictionarycode

          }
          // 添加
          if (!this.rowid) {
            addLineChat(datas).then(response => {
              this.loading = false
              if (response.state.toLowerCase() === 'success') {
                this.$parent.$layer.close(this.layerid)
                this.$parent.getList() // 重新加载父级数据
                this.$message.success('恭喜你，回复步骤信息添加成功!')
              }
            }).catch(() => {
              this.loading = false
            })
            return
          }
          // 编辑
          editLineChat(datas).then(response => {
            this.loading = false
            if (response.state.toLowerCase() === 'success') {
              this.$parent.$layer.close(this.layerid)
              this.$parent.getList() // 重新加载父级数据
              this.$message.success('恭喜你，回复步骤信息编辑成功!')
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.$message.error('请输入有效的必填项信息!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    // 获取详情
    getDetail(rid) {
      getDetailes(rid).then(response => {
        if (response.state.toLowerCase() === 'success') {
          const res = response.data
          this.ruleForm.step = res.step
          this.ruleForm.content = res.content
          this.ruleForm.optiontype = String(res.optiontype)
          // this.ruleForm.des = res.describe;
          // this.ruleForm.dictionarycode=res.dictionarycode
          this.ruleForm.dictionarycode = res.dictionarycode
          for (const y of res.options) {
            this.ruleForm.domains.push({
              value: y
            })
          }
        }
      })
    },
    // 获取字典下拉数据
    getDictionaryData() {
      return new Promise(resolve => {
        getDictionary().then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.dictionaryData = response.data
          }
        })
        resolve()
      })
    },
    addDomain() {
      this.ruleForm.domains.push({
        value: ''
      })
    },
    removeDomain(item) {
      var index = this.ruleForm.domains.indexOf(item)
      if (index !== -1) {
        this.ruleForm.domains.splice(index, 1)
      }
    },
    selectChange(val) {
      if (val === 2) {
        this.$message({
          showClose: true,
          message: '点击新增选项按钮，进行新增选项！'
        })
      } else {
        this.ruleForm.domains = [{ value: '' }]
        // console.log( this.ruleForm.domains)
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.date_picker{
		width: 100%;
	}
	div.date_picker input.el-range-input{
		width: 46%;
	}
</style>
