<template>
  <div id="root">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="form-ruleForm">
      <el-form-item label="收费组名称" prop="billName">
        <el-input v-model="ruleForm.billName"/>
      </el-form-item>
      <el-form-item label="收费组说明" prop="billExplain">
        <el-input v-model="ruleForm.billExplain"/>
      </el-form-item>
      <el-form-item label="截止时间" prop="endDate">
        <el-date-picker
          v-model="ruleForm.endDate"
          type="date"
          placeholder="选择日期"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Index',
  data() {
    return {
      ruleForm: {
        id: '', // 收费项ID
        billName: '', // 收费项名称
        billExplain: '', // 缴费项说明
        endDate: '' // 截止时间
      },
      rules: {
        billName: [
          { required: true, message: '请输入收费项名称', trigger: 'blur' }
        ],
        billExplain: [
          { required: true, message: '请选择缴费项说明', trigger: 'blur' }
        ],
        endDate: [
          { type: 'date', required: true, message: '请选择截止时间', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.ruleForm.id = this.$route.query.id
    this.getBillByIdInfo()
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch('UpdateBillNameAndBillExplainAndEndDate', this.ruleForm).then(res => {
            const code = res.code
            if (code === '0') {
              this.$message.success(res.message)
              this.$router.push({ name: 'bill-info', query: { id: this.ruleForm.id }})
              return
            }
            this.$message.error(res.message)
          }).catch(() => {
            console.log('UpdateBillNameAndBillExplainAndEndDate error')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) { // 重置
      this.$refs[formName].resetFields()
    },
    getBillByIdInfo() { // 根据 id 查询 缴费项信息
      this.$store.dispatch('GetBillByIdInfo', this.ruleForm.id).then(res => {
        const resData = res.data
        this.ruleForm.billName = resData.billName
        this.ruleForm.billExplain = resData.billExplain
        this.ruleForm.endDate = resData.endDate
      }).catch(() => {
        console.log('GetBillByIdInfo error')
      })
    }
  }
}
</script>

<style scoped>
#root {
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 500px;
}
</style>
