<template>
  <m-dialog
    ref="dialog"
    :title="itemData.entity ? '编辑' : '新增'"
    :option="{
      textSure: itemData.entity ? '保存' : '下一步'
    }"
    @sure="onSure"
  >
    <m-form ref="form" v-model="formQuery" :items="items" v-loading="loading"></m-form>

    <SalarySolutionRules ref="salarySolutionRulesRefs" append-to-body @refresh="onRefresh"></SalarySolutionRules>
  </m-dialog>
</template>

<script>
import {
  saveSolution,
  saveSolutionSimple,
  getSolutionDetails
} from '@/api/salary'
import SalarySolutionRules from './salarySolutionRules.vue'
import {
  getPostNameByOrganizationNo
// getOrganizationAtlasPostName
} from '@/api/system'
import { mapGetters } from 'vuex'
export default {
  name: 'salary-solution-edit',
  components: {
    SalarySolutionRules
  },
  data () {
    return {
      loading: false,
      formQuery: {
        title: null,
        tag: null,
        organizationNo: null,
        organizationName: null,
        postNames: [],
        rewriteType: 0
      },
      postNamesItems: [],
      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: {
            ref: 'organizationNo',
            filterable: true,
            clearable: true,
            placeholder: '请选择机构',
            options: this.organizationTree,
            showAllLevels: false,
            props: {
              emitPath: false,
              checkStrictly: true,
              value: 'organizationNo',
              label: 'organizationName',
              children: 'child'
            }
          },
          handles: {
            change: this.onchange
          },
          rules: [
            { required: true, message: '请选择绩效机构', trigger: 'change' }
          ]
        },
        {
          label: '绩效职务',
          prop: 'postNames',
          type: 'select',
          options: {
            placeholder: '请选择绩效职务',
            filterable: true,
            collapseTags: true,
            multiple: true,
            items: this.postNamesItems
          },
          rules: [
            { required: true, message: '请选择绩效职务', trigger: 'change' }
          ]
        }
      ]
    }
  },

  inject: ['env'],
  methods: {
    async open (item) {
      this.$refs.dialog.open()
      this.formQuery.title = item?.title ?? null
      this.formQuery.tag = item?.tag ?? null
      this.formQuery.organizationNo = item?.organizationNo ?? null
      this.formQuery.organizationName = item?.organizationName ?? null
      this.formQuery.postNames = []
      this.itemData = {}
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      if (!item) {
        return
      }
      this.itemData = {
        entity: {}
      }
      this.loading = true
      try {
        const { data } = await getSolutionDetails({
          performanceSolutionId: item.performanceSolutionId
        })
        this.itemData = data
        this.onchange(this.formQuery.organizationNo)
        this.formQuery.postNames = item.postNames
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    onRefresh () {
      this.$refs.dialog.close()
      this.$emit('refresh')
    },
    async onchange (organizationNo) {
      const nodes = this.$refs.form.$refs.organizationNo.getCheckedNodes()
      this.formQuery.organizationName = nodes[0].data.organizationName
      this.formQuery.postNames = []
      if (!organizationNo) {
        return
      }
      try {
        const { data } = await getPostNameByOrganizationNo({
          organizationNo
        })
        this.postNamesItems = (data && data.map(e => {
          return {
            label: e,
            value: e
          }
        })) || []
      } catch (error) {
        this.$message.error(error)
      }
    },
    onSure () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const query = {
            entity: {
              performanceSolutionId: this.itemData.entity?.performanceSolutionId,
              env: this.env,
              ...this.formQuery
            }
          }
          if (Object.keys(this.itemData).length === 0) {
            // 新增规则 下一步
            this.$refs.salarySolutionRulesRefs.open(query.entity)
            return
          }
          this.loading = true
          const submitApi = this.itemData.entity ? saveSolutionSimple : saveSolution
          try {
            await submitApi(query)
            this.$message.success('保存成功')
            this.$refs.dialog.close()
            this.$emit('refresh')
          } catch (error) {
            this.$message.error(error)
          } finally {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
