<template>
  <div style="margin-bottom:18px">
    <el-button @click="beginSubProcessSetting" size="small"
      >子流程触发配置</el-button
    >
    <el-dialog
      title="子流程触发配置"
      width="600px"
      append-to-body
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form
        v-if="mappingData"
        class="sub-mapping__form"
        :model="mappingData"
        v-form="{formItemAlign: 'left', inputsDisplay: 'block'}"
      >
        <ht-form-item label="数据策略">
          <ht-radio
            :options="[
              {key: 'share', value: '数据共用'},
              {key: 'mapping', value: '数据映射'}
            ]"
            v-model="mappingData.dataPolicy"
          />
        </ht-form-item>
        <ht-form-item v-if="!policyIsShare" label="触发类型">
          <ht-radio
            display-style="inline"
            :options="[
              {key: 'multiSameData', value: '多人发起同数据子流程'},
              {key: 'multiDiffData', value: '多人发起不同数据子流程'},
              {key: 'singleDiffData', value: '单人发起不同数据子流程'}
            ]"
            v-model="mappingData.triggerType"
          />
        </ht-form-item>
        <ht-form-item v-if="!(!policyIsShare && triggerIsMDD)" label="发起人">
          <el-button
            type="text"
            :disabled="
              (policyIsShare || (!policyIsShare && triggerIsSDD)) &&
                creatorUsers.length > 0
            "
            @click="beginCreatorUserSetting()"
            icon="el-icon-circle-plus-outline"
            >新增</el-button
          >
          <flow-node-user-condition
            ref="flowNodeUserCondition"
            @nodeUserConditionConfirm="creatorUserConditionConfirm"
          />
          <div class="sub-creator__panel">
            <draggable
              v-if="creatorUsers.length > 0"
              v-model="creatorUsers"
              class="creator-list__wrap"
              tag="ul"
              v-bind="dragOptions"
              handle=".sub-creator__handle"
              @start="isDragging = true"
              @end="isDragging = false"
            >
              <transition-group type="transition" name="flip-list">
                <li
                  v-for="creatorUser in creatorUsers"
                  :key="creatorUser.description"
                >
                  <ht-icon name="sort" class="sub-creator__handle" />
                  <p>
                    {{ creatorUser.description }}
                  </p>
                  <ht-icon
                    name="form"
                    @click="beginCreatorUserSetting(creatorUser)"
                  />
                  <ht-icon
                    name="close"
                    @click="removeCreatorUser(creatorUser)"
                  />
                </li>
              </transition-group>
            </draggable>
            <div v-else class="sub-creator__empty">
              尚未配置发起人，点击新增按钮进行配置。
            </div>
          </div>
        </ht-form-item>
        <ht-form-item v-if="!policyIsShare" label="分发映射">
          <mapping-dialog
            v-model="mappingData.distributeMapping"
            :creator-follow-data-key.sync="mappingData.creatorFollowDataKey"
            :trigger-type="mappingData.triggerType"
            :def-id="defId"
            :node-id="nodeId"
          />
        </ht-form-item>
        <ht-form-item v-if="!policyIsShare" label="回收映射">
          <mapping-dialog
            recovery
            v-model="mappingData.recoveryMapping"
            :trigger-type="mappingData.triggerType"
            :def-id="defId"
            :node-id="nodeId"
          />
        </ht-form-item>
      </el-form>
      <div v-else>正在加载</div>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="small" @click="handleDialogSure">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import flow from '@/api/flow.js'
const draggable = require('vuedraggable')
const FlowNodeUserCondition = () =>
  import('@/components/flow/FlowNodeUserCondition.vue')
const MappingDialog = () => import('@/components/mapping/MappingDialog.vue')

export default {
  name: 'SubProcessMapping',
  components: {
    draggable,
    FlowNodeUserCondition,
    MappingDialog
  },
  props: {
    defId: {
      type: String,
      required: true
    },
    nodeId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      mappingData: null,
      creatorUsers: [],
      currentCreatorUser: null,
      isDragging: false
    }
  },
  computed: {
    policyIsShare() {
      return this.mappingData && this.mappingData.dataPolicy == 'share'
    },
    triggerIsMDD() {
      return this.mappingData && this.mappingData.triggerType == 'multiDiffData'
    },
    triggerIsSDD() {
      return (
        this.mappingData && this.mappingData.triggerType == 'singleDiffData'
      )
    },
    dragOptions() {
      return {
        animation: 0,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost'
      }
    }
  },
  methods: {
    beginSubProcessSetting() {
      if (!this.defId || !this.nodeId) {
        this.$message.error('未获取到defId和nodeId，无法进行子流程触发配置。')
        return
      }
      flow.getSubProcessPlugin(this.defId, this.nodeId).then(resp => {
        const {data} = resp
        this.mappingData = data || {}
        this.dialogVisible = true
      })
    },
    handleClose() {
      this.currentCreatorUser = null
      this.dialogVisible = false
    },
    handleDialogSure() {
      const json = JSON.stringify(this.mappingData)
      flow.saveSubProcessPlugin(this.defId, this.nodeId, json).then(resp => {
        const {state} = resp.data
        if (state) {
          this.dialogVisible = false
        }
      })
    },
    beginCreatorUserSetting(creatorUser) {
      const conf = {nodeId: this.nodeId, nodeType: 'serviceTask'}
      if (creatorUser) {
        this.currentCreatorUser = creatorUser
        conf.userRule = creatorUser
      }
      this.$refs.flowNodeUserCondition.showDialog(conf)
    },
    creatorUserConditionConfirm(res) {
      if (res.calcs) {
        if (this.currentCreatorUser) {
          const index = this.creatorUsers.findIndex(
            item => this.currentCreatorUser === item
          )
          if (index > -1) {
            this.creatorUsers.splice(index, 1, res)
          }
          this.currentCreatorUser = null
        } else {
          this.creatorUsers.push(res)
        }
      }
    },
    removeCreatorUser(creatorUser) {
      this.creatorUsers.remove(creatorUser)
    }
  }
}
</script>
<style lang="scss" scoped>
.flip-list-move {
  transition: transform 0.5s;
}

.sub-mapping__form {
  .sub-creator__panel {
    border: 1px solid #dcdfe6;
    margin-left: -100px;
    padding: 10px;

    .sub-creator__empty {
      background-color: #f5f5f5;
      padding: 5px;
    }

    .creator-list__wrap {
      list-style: none;

      li {
        display: flex;
        align-items: center;
        background-color: #f5f5f5;
        margin-bottom: 10px;

        .sub-creator__handle {
          margin-left: 10px;
          cursor: move;
        }

        p {
          color: $--color-primary;
          width: calc(100% - 50px);
          margin-right: 10px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .fa-icon {
          margin-right: 10px;
        }
      }
    }
  }
}
</style>
