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

<script>
import {
  saveSolution,
  getSolutionDetails
} from '@/api/salary'
import { mapGetters } from 'vuex'
export default {
  name: 'salary-solution-edit',
  data () {
    return {
      loading: false,
      formQuery: {
        title: null,
        tag: null
      },
      itemData: {}
    }
  },
  computed: {
    ...mapGetters(['organizationTree']),
    items () {
      return [
        {
          label: '方案名称',
          prop: 'title',
          type: 'input',
          rules: [
            { required: true, message: '请输入方案名称', trigger: 'blur' }
          ],
          options: {
            placeholder: '请输入方案名称'
          }
        },
        {
          label: '方案描述',
          prop: 'tag',
          type: 'input',
          options: {
            placeholder: '请输入方案描述'
          }
        },
        {
          label: '绩效机构',
          prop: 'organizationNo',
          type: 'cascader',
          options: {
            clearable: true,
            placeholder: '请选择机构',
            options: this.organizationTree,
            showAllLevels: false,
            props: {
              checkStrictly: true,
              // emitPath: false,
              value: 'organizationNo',
              label: 'organizationName',
              children: 'child'
            }
          }
        }
      ]
    }
  },
  methods: {
    async open (item) {
      this.$refs.dialog.open()
      if (item) {
        this.formQuery.title = item.title
        this.formQuery.tag = item.tag
        this.loading = true
        try {
          const { data } = await getSolutionDetails({
            performanceSolutionId: item.performanceSolutionId
          })
          this.itemData = data
        } catch (error) {
          this.$message.error(error)
        } finally {
          this.loading = false
        }
      } else {
        this.formQuery.title = null
        this.formQuery.tag = null
        this.itemData = {}
      }
    },
    onSure () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const query = {
            entity: {
              performanceSolutionId: this.itemData.entity?.performanceSolutionId,
              ...this.formQuery
            },
            calculateConfigurations: this.itemData.calculateConfigurations ?? []
          }
          try {
            await saveSolution(query)
            this.$refs.dialog.close()
            this.$emit('refresh')
            this.$message.success('保存成功')
          } catch (error) {
            this.$message.error(error)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
