<template>
  <m-dialog ref="dialog" :title="itemData.subsidy ? '编辑' : '新增'" @sure="onSure">
    <m-form ref="form" v-model="formQuery" :items="items" v-loading="loading"></m-form>
  </m-dialog>
</template>

<script>
import {
  saveWelfare,
  getWelfareDetail
} from '@/api/welfare'
export default {
  name: 'welfare-edit',
  data () {
    return {
      loading: false,
      formQuery: {
        subsidyName: null,
        subsidyTag: null
      },
      items: [
        {
          label: '福利名称',
          prop: 'subsidyName',
          type: 'input',
          rules: [
            { required: true, message: '请输入福利名称', trigger: 'blur' }
          ],
          options: {
            placeholder: '请输入福利名称'
          }
        },
        {
          label: '福利描述',
          prop: 'subsidyTag',
          type: 'input',
          options: {
            placeholder: '请输入福利名称'
          }
        }
      ],
      itemData: {}
    }
  },
  methods: {
    async open (item) {
      this.$refs.dialog.open()
      if (item) {
        this.formQuery.subsidyName = item.subsidyName
        this.formQuery.subsidyTag = item.subsidyTag
        this.loading = true
        try {
          const { data } = await getWelfareDetail({
            subsidyId: item.subsidyId
          })
          this.itemData = data
        } catch (error) {
          this.$message.error(error)
        } finally {
          this.loading = false
        }
      } else {
        this.formQuery.subsidyName = null
        this.formQuery.subsidyTag = null
        this.itemData = {}
      }
    },
    onSure () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const query = {
            subsidy: {
              subsidyId: this.itemData.subsidy?.subsidyId,
              ...this.formQuery
            },
            subsidyItems: this.itemData.subsidyItems ?? []
          }
          try {
            await saveWelfare(query)
            this.$refs.dialog.close()
            this.$emit('refresh')
            this.$message.success('保存成功')
          } catch (error) {
            this.$message.error(error)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
