<template>
  <div style="padding:0 30px;">
    <el-steps
      :active="activeIndex"
      finish-status="success"
      simple
      style="margin-top: 0px; margin-bottom:15px;"
    >
      <el-step title="基本信息"></el-step>
      <el-step title="编辑细则"></el-step>
    </el-steps>
    <el-form
      v-loading="loading"
      ref="detailForm"
      :status-icon="!editMode"
      :model="detailData"
      :rules="rules"
      @submit.native.prevent
    >
      <div class="grid-content bg-purple ruleDetailForm">
        <div style=" background-color: #fff; height: 300px;">
          <el-row type="card">
            <el-col :span="24" v-show="activeIndex==0" label="基本信息" name="first">
              <div style="padding:30px; padding-top:30px;">
                <el-form-item
                  label="积分分类"
                  prop="category_id"
                  :required="true"
                  :label-width="formLabelWidth"
                >
                  <el-cascader
                    v-model="detailData.category_id"
                    clearable
                    :options="categoryTree"
                    change-on-select
                    style="width:100%;"
                  ></el-cascader>
                </el-form-item>
                <el-form-item
                  label="规则名称"
                  prop="name"
                  :label-width="formLabelWidth"
                >
                  <el-input v-model="detailData.name" ref="inputName" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="类型" :required="true" :label-width="formLabelWidth">
                  <el-select v-model="detailData.type" placeholder="请选择规则类型">
                    <el-option label="常规加分" :value="0"></el-option>
                    <el-option label="固定加分" :value="1"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="备注" prop="remark" :label-width="formLabelWidth" v-show="false">
                  <el-input
                    v-model="detailData.remark"
                    ref="inputName"
                    placeholder="输入备注（最多100字）"
                    :maxlength="100"
                    auto-complete="off"
                    type="textarea"
                    :rows="5"
                    resize="none"
                    style="margin-top:5px;"
                  ></el-input>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="24" v-show="activeIndex==1" label="细则" name="second">
              <el-card class="box-card panel-card-box" shadow="never">
                <div slot="header" class="clearfix">
                  <span>积分细则（{{detailData.items.length}}条）</span>
                  <el-button
                    style="float: right; padding: 3px 0"
                    type="text"
                    @click="addNewItemTemplate"
                  >添加细则</el-button>
                </div>
                <el-scrollbar
                  wrap-class="column-wrapper scrollable-items-container"
                  :native="false"
                  style="height: 300px;"
                >
                  <div style="padding:20px 30px; padding-top:0">
                    <el-form-item
                      v-for="(item, key) in detailData.items"
                      :key="item.id"
                      :prop="'items.' + key"
                      :rules="itemRules"
                      style="margin-bottom:0;"
                    >
                      <el-card shadow="hover" class="rule_box_card">
                        <div class="card-frame" style="margin-top:5px; padding:1px;">
                          <!-- <el-form-item :rules="{required: true, message: '请输入细则内容', trigger: 'blur'}"> -->


                          <div style="padding:0 15px;">
                            <el-input
                              style="border-radius: 0;"
                              v-model="item.content"
                              auto-complete="off"
                              :prop="'itemContent.'+ key"
                              type="textarea"
                              :autosize="{ minRows: 2, maxRows: 4}"
                              :maxlength="80"
                              placeholder="请输入细则内容（最多80字）"
                            ></el-input></div>
                          <!-- </el-form-item> -->


                          <div style="margin-top:10px; padding:0 15px;">
                            <el-switch
                              v-show="detailData.type == 0"
                              class="gap-right-15"
                              v-model="item.is_range"
                              :prop="'itemRange.'+key"
                              active-text="范围"
                              inactive-text="固定"
                            ></el-switch>
                            <el-input-number
                              class="gap-right-8"
                              v-model="item.value_1"
                              size="small"
                              :min="0"
                              :max="99999"
                            ></el-input-number>
                            <span class="gap-right-8" v-show="item.is_range">-</span>
                            <el-input-number
                              v-model="item.value_2"
                              size="small"
                              :min="item.value_1"
                              :max="99999"
                              v-show="item.is_range"
                            ></el-input-number>
                          </div>
                          <div style="margin-top:10px; padding:0 15px; padding-bottom:10px;">
                            <el-switch
                              class="gap-right-15"
                              v-model="item.is_negative"
                              active-text="扣分"
                              inactive-text="奖分"
                              active-color="#FF6161"
                              inactive-color="#11B65B"
                            ></el-switch>
                            <el-radio-group v-model="item.point_type" size="small">
                              <el-radio
                                v-show="settings.point_set.indexOf('a') >= 0"
                                v-for="(option, index) in pointTypes"
                                :label="option.value"
                                :key="index"
                                border
                              >{{ option.label }}</el-radio>
                            </el-radio-group>

                            <el-button
                              style="float:right;"
                              icon="el-icon-delete"
                              type="text"
                              :disabled="detailData.items.length < 2"
                              @click="confirmDelete(key)"
                            >删除</el-button>
                          </div>
                        </div>
                      </el-card>
                    </el-form-item>
                  </div>
                </el-scrollbar>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
    <div style="clear: both;"></div>
    <div slot="footer" class="dialog-footer" style="text-align: center; margin-top:15px;">
      <el-button @click="cancelHandle">取 消</el-button>
      <el-button v-show="activeIndex>0" @click="activeIndexPrev">上一步</el-button>
      <el-button type="primary" v-show="activeIndex<1" @click="activeIndexNext">下一步</el-button>

      <el-button
        type="primary"
        v-show="activeIndex==1"
        :loading="submitLoading"
        @click="submitForm('detailForm')"
      >保 存</el-button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    const validateName = (rule, value, callback) => {
      const validValue = value
        ? value.replace(/\s/g, '').replace(/&nbsp;/gi, '')
        : value
      if (!validValue) {
        return callback(new Error('请填写积分规则名称'))
      } else {
        callback()
      }
    }
    // let contentDetail = (rule,value,callback) =>{
    //   console.log('value---------?//')
    //   console.log(value)
    // }
    let validateItem = (rule, value, callback) => {
      if (this.activeIndex == 0) {
        callback()
        return;
      }
      if (!value || value.length == 0) {
        return callback(new Error('请填写积分细则内容'))
      }
      const itemContent = value.content
        ? value.content.replace(/\s/g, '').replace(/&nbsp;/gi, '')
        : null
      if (!itemContent) {
        return callback(new Error('请填写积分细则内容'))
      }
      const valueLeft = value.value_1
      if (isNaN(valueLeft) || parseInt(valueLeft) == 0) {
        return callback(new Error('请填写有效的积分数值'))
      }
      const isRange = value.is_range
      if (isRange) {
        const valueRight = value.value_2
        if (isNaN(valueRight) || parseInt(valueRight) == 0) {
          return callback(new Error('请填写有效的积分数值'))
        }
        if (parseInt(valueLeft) == parseInt(valueRight)) {
          return callback(new Error('请填写不同的范围分值界限'))
        }
      }
      callback()
    };
    const validateCategory = (rule, value, callback) => {
      if (!value || value.length == 0) {
        return callback(new Error('请选择积分分类'))
      } else {
        callback()
      }
    }
    let isEditMode = this.$route.params.targetId > 0;
    const template = {
      id: -1,
      content: '',
      is_range: false,
      is_negative: false,
      value_1: 0,
      value_2: 0,
      point_type: 0
    }
    return {
      settings: this.$store.getters.system_setting,
      activeIndex: 0,
      loading: false,
      tabs_active: 'first',
      profile: this.$store.getters.user_info,
      activeName2: 'overall',
      activeName: 'Rules',
      editMode: isEditMode,
      formLabelWidth: '90px',
      pointTypes: [],
      itemTemplate: template,
      submitLoading: false,
      detailData: {
        name: '',
        remark: '',
        category_id: [],
        type: 1,
        items: [template]
      },
      categoryTree: [],
      rules: {
        name: [{ required: true , validator: validateName, trigger: 'blur' }],
        category_id: [{ validator: validateCategory, trigger: 'change' }]
      },
      itemRules: {
        validator: validateItem,
      }
      // itemRules:{
      //   itemContent:[{required:true ,validator: contentDetail, trigger: "blur" }],
      //   itemRange:[{required:true ,validator: validateItem, trigger: "change"}]
      // }
    }
  },
  methods: {
    activeIndexPrev() {
      this.activeIndex--
    },
    activeIndexNext() {
      var form = this.$refs['detailForm']
      var self = this
      form.validate(valid => {
        if (!valid) {
          return false
        } else {
          this.activeIndex++
        }
      })
    },
    loadPointType: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_point_types')
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.pointTypes = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 获取积分分类列表
    loadCategory: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_integral_category_list_cascaded',{site_id: this.profile.site_id})
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.categoryTree = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 获取用户数据
    loadRuleDetail: function(ruleId) {
      this.loading = true
      let params = {
        id: ruleId
      }
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_rule_info',params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            let jsonData = response.data
            try {
              const detailData = self.processDetailData(jsonData)
              self.detailData.name = detailData.name
              detailData.remark = detailData.remark == 'null' ? '':detailData.remark
              self.detailData.remark = detailData.remark
              self.detailData.type = detailData.type
              self.detailData.category_id = detailData.category_id
              self.detailData.items = detailData.items
              self.detailData.id = detailData.id
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    processDetailData: function(object) {
      // 所属分类转换成插件需要的数组格式
      const pathStr = object.category_id.toString()
      object.category_id = pathStr.split(',').map(Number)
      let items = object.items
      for (let index = 0; index < items.length; index++) {
        const item = items[index]
        item.is_range = item.is_range == 1;
        item.is_negative = item.is_negative == 1;
      }
      return object
    },
    discardBack: function() {},
    submitForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendSaveRequest()
          }
        } else {
          // console.log('验证未通过');
          return false
        }
      })
    },
    sendSaveRequest: function() {
      var formData = {}
      this.submitLoading = true
      var dataObj = this.detailData
      for (const item in dataObj) {
        if (item == 'category_id') {
          var length = dataObj[item].length
          formData[item] = length == 0 ? 0 : dataObj[item][length - 1]
        } else {
          // if (!dataObj[item]) {  备注修改为空时，不能上传备注为空的值
          //   continue;
          // }
          formData[item] = dataObj[item]
        }
      }
      formData['site_id'] = this.profile.site_id
      formData['items'] = JSON.stringify(this.detailData.items)
      let url = '/integral.php/ajax_request_common/';
      url += this.editMode ? 'update_integral_rule' : 'add_integral_rule';
      var self = this
      this.$http('post',url,formData,'','',
        {transformRequest: [
          data => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(
                encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
              )
            }
            return paramArray.join('&')
          }
        ]},
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      )
        .then(function(response) {
          var message = '';
          var status = 0
          if (response.status == 200) {
            self.submitLoading = false
            var data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            let actionName = self.editMode ? '编辑积分规则' : '新增积分规则';
            switch (status) {
              case 1:
                self.activeIndex = 0
                message = actionName + '成功';
                break
              case -1:
                message = '表单参数错误';
                break
              case -2:
                message = data.info ? data.info : actionName + '失败';
                self.$refs[data.target_field].focus()
                self.$refs[data.target_field].$parent.clearValidate()
                break;
              default:
                message = data.info ? data.info : actionName + '失败';
            }
          } else {
            message = '服务器出现问题';
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.formClear()
            self.$parent.$parent.loadRuleList()
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    formClear() {
      const self = this
      self.$refs['detailForm'].resetFields()
      self.detailData.items = [
        {
          id: -1,
          content: '',
          is_range: false,
          is_negative: false,
          value_1: 0,
          value_2: 0,
          point_type: 0
        }
      ]
      delete self.detailData.id
      self.$parent.$parent.RuleDetailDialogVisible = false
      this.loadCategory()
    },
    cancelHandle() {
      this.formClear()
      this.activeIndex = 0
      this.$parent.$parent.RuleDetailDialogVisible = false
    },
    addNewItemTemplate: function() {
      this.itemTemplate.id = this.itemTemplate.id || -1
      let item = {}
      for (const key in this.itemTemplate) {
        item[key] = this.itemTemplate[key]
      }
      const itemList = this.detailData.items
      // itemList.push(item)
      itemList.unshift(item)
      this.itemTemplate.id--
    },
    confirmDelete: function(index) {
      this.$confirm('确定要删除此条细则吗?', '删除积分细则', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeItem(index)
        })
        .catch(() => {
          // console.log('已取消删除');
        })
    },
    removeItem: function(index) {
      const itemList = this.detailData.items
      if (itemList.length > index) {
        itemList.splice(index, 1)
      }
    }
  },
  watch:{
    'detailData.type':function (val, old) {
      /*
      itemTemplate: template,
      submitLoading: false,
      detailData: {
        name: '',
        remark: '',
        category_id: [],
        type: 0,
        items: [template]
      },
       */
      if(val == 1){
        this.itemTemplate.is_range = false
        for(let i in this.detailData.items){
          this.detailData.items[i].is_range = false
        }
      }
    }
  },
  created() {
    this.loadPointType()
    this.loadCategory()
    if (this.$route.params.targetId > 0) {
      this.loadRuleDetail(this.$route.params.targetId)
    }
  }
}
</script>
<style scoped>
.ruleDetailForm .el-scrollbar__wrap {
  overflow-x: hidden;
}
.ruleDetailForm .el-scrollbar__wrap .el-textarea__inner {
}
.panel-card-box .rule_box_card {
  margin-top: 15px;
  margin-bottom: 0 !important;
}
.panel-card-box .rule_box_card .el-card__body {
  padding: 10px 15px;
  background-color: #fff;
}
.panel-card-box .el-card__body {
  background-color: #fafafa;
  padding: 0;
}

.textSelect .el-cascader__label {
  padding-left: 0;
}
.textSelect .el-input__suffix {
  display: none;
}
.textSelect .el-cascader.is-disabled .el-cascader__label {
  color: #333;
}
.textSelect .el-input.is-disabled .el-input__inner {
  background-color: rgba(5, 250, 12, 0);
  border-color: rgba(228, 231, 237, 0);
  color: #000000;
  cursor: not-allowed;
}

</style>
