<template>
  <m-dialog title="审批配置" ref="dialog" @sure="onSure">
    <el-form ref="form" inline :model="formValues" label-width="70px" >
      <el-form-item label="工作流">
        <el-tag>{{ item.workFlowTmplate?.name }}</el-tag>
      </el-form-item>
      <el-form-item label="工作流">
        <m-card shadow="never">
          <m-card
            v-for="(item, index) in formValues.items"
            :key="item.key"
            class="mb-5 cardBox"
          >
            <el-form-item label="处理对象" :prop="`items.${index}.handleType`">
              <el-select v-model="item.handleType" placeholder="请选择处理对象" @change="onChange(item)">
                <el-option label="指定人" value="0"></el-option>
                <el-option label="指定部室岗位" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="处理方" :prop="`items.${index}.handleValue`" :rules="{ required: true, message: '请选择处理方', trigger: 'change' }">
              <el-cascader
                v-model="item.handleValue"
                :ref="`cascader_${index}`"
                placeholder="请选择处理方"
                :show-all-levels="false"
                :options="options[item.handleType]"
                :props="{
                  emitPath: false,
                  value: 'id',
                  label: 'title',
                  children: 'child'
                }"
                @change="onChangeCascader(item, `cascader_${index}`)"
              ></el-cascader>
            </el-form-item>
            <div class="button-group">
              <m-button :disabled="index === 0" icon="el-icon-top" circle size="mini" @click="onUp(index)"></m-button>
              <m-button :disabled="index === formValues.items.length - 1" icon="el-icon-bottom" circle size="mini" @click="onDown(index)"></m-button>
              <m-button type="danger" icon="el-icon-delete" circle size="mini" @click="onDelete(index)"></m-button>
            </div>
          </m-card>
          <div class="text-center">
            <el-button type="orange" @click="onAdd" icon="el-icon-plus">新增一条记录</el-button>
          </div>
        </m-card>
      </el-form-item>
    </el-form>
  </m-dialog>
</template>

<script>
import {
  saveWorkflow
} from '@/api/workflow'
import {
  getOrganizationAtlasAll
} from '@/api/system'
import { mapGetters } from 'vuex'
import { cloneDeep } from 'lodash'
export default {
  name: 'workflowApproved',
  data () {
    return {
      key: 0,
      formValues: {
        items: [
          {
            key: 0,
            handleType: '0',
            handleValue: null,
            handleValueData: {}
          }
        ]
      },
      item: {},
      options: []
    }
  },
  computed: {
    ...mapGetters(['organizationTree']),
    personOrganizationTree () {
      return cloneDeep(this.organizationTree)
    },
    postOrganizationTree () {
      return cloneDeep(this.organizationTree)
    }
  },
  methods: {
    async open (item) {
      this.item = item
      this.$refs.dialog.open()
      this.loading = true
      if (item.workFlowTmplateItems.length > 0) {
        this.formValues.items = item.workFlowTmplateItems.map((e, index) => {
          return {
            handleType: e.handleType,
            handleValue: e.handleType === '0' ? e.handleValue.userId : e.handleValue.postName,
            handleValueData: e.handleValue, // 回显
            key: index
          }
        })
      }
      this.key = item.workFlowTmplateItems.length + 1
      try {
        const { data: person } = await getOrganizationAtlasAll({ type: 0 })
        this.options.push(person)
        const { data: post } = await getOrganizationAtlasAll({ type: 1 })
        this.options.push(post)
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    onAdd () {
      this.key++
      this.formValues.items.push({
        key: this.key,
        handleType: '0',
        handleValue: null,
        handleValueData: {}
      })
    },
    // 向上移动一位
    onUp (index) {
      if (index === 0) return
      const temp = this.formValues.items[index]
      this.formValues.items.splice(index, 1)
      this.formValues.items.splice(index - 1, 0, temp)
    },
    // 向下移动一位
    onDown (index) {
      if (index === this.formValues.items.length - 1) return
      const temp = this.formValues.items[index]
      this.formValues.items.splice(index, 1)
      this.formValues.items.splice(index + 1, 0, temp)
    },
    // 删除
    onDelete (index) {
      this.formValues.items.splice(index, 1)
    },
    // 情况选项
    onChange (item) {
      item.handleValue = null
    },
    // 提交参数格式化
    onChangeCascader (item, ref) {
      if (item.handleType === '0') {
        item.handleValueData = {
          userId: item.handleValue
        }
        return
      }
      const node = this.$refs[ref][0].getCheckedNodes()[0]
      item.handleValueData = {
        organizationNo: node.parent.value,
        postName: node.value
      }
    },
    onSure () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        try {
          await saveWorkflow({
            workFlowTmplateItems: this.formValues.items.map((e, index) => {
              return {
                handleType: e.handleType,
                handleValue: e.handleValueData,
                sort: index
              }
            }),
            workFlowTmplate: {
              workFlowTmplateId: this.item.workFlowTmplate.workFlowTmplateId
            }
          })
          this.$message.success('保存成功')
          this.$refs.dialog.close()
        } catch (error) {
          this.$message.error(error)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.cardBox {
  position: relative;
  overflow: visible;
  .button-group {
    position: absolute;
    right: 10px;
    top: -20px;
  }
}
</style>
