<template>
  <m-card shadow="never">
    <div>
      <div class="d-flex mb-3">
        <div class="boxLabel">参数配置</div>
        <div class="boxContent">
          <m-table
            ref="tableRefs"
            shadow="naver"
            clearHeader
            :items="items"
            row-key="index"
            :headers="[
              { type: 'expand', prop: 'expandProp' },
              { label: '参数', prop: 'name' },
              { label: '参数类型', prop: 'valueCategory' },
              { label: '操作', prop: 'actions' }
            ]"
            @expand-change="onExpandChange"
          >
            <template #expandProp="{ row, $index }">
              <SalarySolutionRulesEditParam :ref="`salarySolutionRulesEditParamRefs${$index}`" @assign="onAssign(row, $event)"></SalarySolutionRulesEditParam>
            </template>
            <div class="text-center mt-3">
              <m-button icon="el-icon-plus" type="orange" size="small" @click="onAdd">添加参数</m-button>
            </div>
            <template #valueCategory="{ row }">
              {{ DICT_CATEGORY.find(item => item.value === row.valueCategory)?.label }}
            </template>
            <template #actions="scope">
              <m-button size="small" text type="danger" @click="onDelete(scope)">移除</m-button>
            </template>
          </m-table>
        </div>
      </div>
      <div class="d-flex">
        <div class="boxLabel">计算公式</div>
        <div class="boxContent">
          <m-card shadow="never">
            <Toolbar
              style="border-bottom: 1px solid #eee"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
                style="height: 250px; overflow-y: hidden;"
                v-model="formulaData"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
            />
          </m-card>
        </div>
      </div>
    </div>
  </m-card>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import SalarySolutionRulesEditParam from './salarySandboxRulesEditParam.vue'
import {
  DICT_CATEGORY
} from '../solution/utils/Dict'
export default {
  name: 'salarySandboxRulesEdit',
  components: { Editor, Toolbar, SalarySolutionRulesEditParam },
  props: {
    item: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      DICT_CATEGORY,
      editor: null,
      formulaData: '',
      toolbarConfig: {
        toolbarKeys: [
          'headerSelect',
          // 分割线
          '|',
          'bold',
          'italic'
        ]
      },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
      items: []
    }
  },
  beforeDestroy () {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onAssign (row, obj) {
      Object.assign(row, obj)
    },
    onCreated (editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onAdd () {
      const item = {
        index: this.items.length,
        name: null,
        valueCategory: 0
      }
      this.items.push(item)
      const ref = this.$refs.tableRefs.getRefs()
      ref.toggleRowExpansion(item)
    },
    onDelete (scope) {
      this.$confirm('确定要移除改组参数吗？', '提示').then(e => {
        this.items.splice(scope.$index, 1)
      }).catch(_ => {})
    },
    valid () {
      return new Promise((resolve, reject) => {
        const check = this.items.every(e => {
          if (!this.$refs[`salarySolutionRulesEditParamRefs${e.index}`]) {
            return true
          }
          return this.$refs[`salarySolutionRulesEditParamRefs${e.index}`].valid()
        })
        if (!check) {
          reject(this.item)
        } else {
          resolve(this.getValue())
        }
      })
    },
    onExpandChange (row, expandedRows) {
      const open = expandedRows.find(e => e.index === row.index)
      if (!open) {
        return
      }
      this.$nextTick(() => {
        this.$refs[`salarySolutionRulesEditParamRefs${row.index}`].setValue(row)
      })
    },
    setValue (data) {
      this.items = data.calculateConfigurations.map((e, index) => {
        return {
          index,
          ...e
        }
      })
      this.$nextTick(() => {
        this.formulaData = data.calculateFormulas.length ? data.calculateFormulas[0].content : ''
      })
    },
    getValue () {
      const calculateConfigurations = this.items.map(e => {
        if (!this.$refs[`salarySolutionRulesEditParamRefs${e.index}`]) {
          const { index, ...obj } = e
          return obj
        }
        return this.$refs[`salarySolutionRulesEditParamRefs${e.index}`].getValue()
      })
      return {
        category: this.item.title,
        calculateConfigurations,
        calculateFormulas: [
          {
            category: this.item.title,
            content: this.formulaData
          }
        ]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tree-node__content {
  height: 40px;
}
.boxLabel {
  width: 80px;
  text-align: right;
  padding-right: 20px;
  box-sizing: border-box;
}
.boxContent {
  flex: 1;
}
</style>
