<template>
  <el-collapse v-model="activeNames" accordion>
    <el-collapse-item
      :title="customPresetHintMessage || '预设节点信息（折叠不作处理）'"
      name="1"
    >
      <div v-for="(item, index) of newPresetList" :key="index">
        <el-form-item prop="flow" :label="`➤ 节点${index + 1}`">
          <el-select
            v-model="item.name"
            @change="changePreset($event, null, index)"
          >
            <el-option
              v-for="items in item.option"
              :key="items.nodeId"
              :label="items.nodeName"
              :value="items.nodeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="item.name != 'endEvent'" prop="user" label="办理人">
          <SelectUser
            ref="selectUser"
            :showUser="true"
            :showTooltip="showTooltip"
            :nextUser="item.nextUser"
            :radioList="item.radioList"
            :multiple="item.multiple"
            :isCustomUser="item.isCustomUser"
            :options="item.options"
            :presetEdit="item.presetEdit"
            :selectUserList="item.selectUserList"
            @change="changePresetUser($event, index)"
            :types="['employee', 'persongroup']"
            :params="item.params"
          />
        </el-form-item>
      </div>
    </el-collapse-item>
  </el-collapse>
</template>

<script>
import { getNodeInfo, getPresetCustomInfo } from 'eoss-ui/src/config/api';
import SelectUser from '../selectUser.vue';
import util from 'eoss-ui/src/utils/util';
export default {
  name: 'CustomPreset',
  components: {
    [SelectUser.name]: SelectUser
  },
  data() {
    return {
      activeNames: '1',
      newProcessDefinitionId: '',
      newPresetList: []
    };
  },
  props: {
    presetList: {
      type: Array,
      default: () => []
    },
    processDefinitionId: {
      type: String,
      default: ''
    },
    showTooltip: { type: Boolean, default: true },
    customPresetHintMessage: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    nextNode: {
      type: String,
      default: ''
    }
  },
  watch: {
    activeNames(val) {
      this.$emit('changeActiveNames', val);
      this.$emit('change-active-names', val);
    },
    processDefinitionId: {
      handler(val) {
        this.newProcessDefinitionId = val;
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    changePreset(nodeId, processDefinitionId, index) {
      this.newPresetList.splice(index + 1);

      if (nodeId === 'endEvent' || nodeId == 1) {
        this.newPresetList[index].options = [];
        this.newPresetList[index].selectUserList = [];
        this.newPresetList[index].params = {};
        this.newPresetList[index].radioList = [];
        this.newPresetList[index].nextUser = [];
        return;
      }
      this.$emit('loadingStart');
      this.$emit('loading-start');
      this.show = false;
      this.getPresetFlowInfo(nodeId, processDefinitionId);
      // return
      this.getNodeInfos(nodeId, processDefinitionId, index);
    },
    getNodeInfos(nodeId, processDefinitionId, index) {
      let params = {
        processDefinitionId: processDefinitionId
          ? processDefinitionId
          : this.newProcessDefinitionId,
        nextNodeId: nodeId,
        businessId: this.id
      };
      util
        .ajax({ url: getNodeInfo, params })
        .then((res) => {
          const {
            status,
            message,
            data: { nextUserList, nodeExtAttr }
          } = res;
          if (status === 'success') {
            let info = this.newPresetList[index];
            const { multiple, params } = this.isMultiple(
              nodeExtAttr.userSelectionType
            );
            info.isCustomUser = nodeExtAttr.isCustomUser;
            info.multiple = multiple;
            info.params = params;
            info.nextUser = [];
            info.options = [];
            info.selectUserList = [];
            info.presetEdit = 0;
            info.presetEdit = nodeExtAttr.presetEdit;
            info.isDefSelectedObj = nodeExtAttr.isDefSelectedObj;
            nextUserList.map((item) => {
              if (info.multiple && info.isDefSelectedObj == 1) {
                info.nextUser.push(item.userId);
                info.selectUserList.push({
                  showname: item.username,
                  showid: item.userId
                });
              }
              info.options.push({
                showname: item.username,
                showid: item.userId
              });
            });
            if (
              !info.multiple &&
              nextUserList.length > 0 &&
              info.isDefSelectedObj == 1
            ) {
              info.nextUser = nextUserList[0].userId;
              info.selectUserList.push({
                showname: nextUserList[0].username,
                showid: nextUserList[0].userId
              });
            }

            if (!info.multiple && info.isDefSelectedObj != 1)
              info.nextUser = '';

            info.radioList = info.options;
            this.changeSelectData();
          } else {
            this.$message.error(message || '系统错误，请联系管理员！');
          }
          this.$emit('loadingEnd');
          this.$emit('loading-end');
          nodeId &&
            setTimeout(() => {
              this.$refs.selectUser[index].changeInfo(
                this.newPresetList[index]
              );
            }, 500);
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    isMultiple(val, choiceOrgId, choiceDeptId, pOrgId) {
      let multiple = false;
      let params = {};
      if (val == 2 || val == 4 || val == 6 || val == 16) {
        multiple = true;
      }
      if (val == 1 || val == 2 || val == 5) {
        params.filid = util.getStorage('orgId');
        params.only_filid = true;
        if (choiceOrgId) {
          params.filid = choiceOrgId;
        }
      }
      if (val == 5 || val == 6) {
        params.filid = util.getStorage('orgId');
        params.mydeptid = util.getStorage('depId');
        if (choiceDeptId) {
          params.mydeptid = choiceDeptId;
        }
        if (choiceOrgId) {
          params.filid = choiceOrgId;
        }
      }
      if (val == 15 || val == 16) {
        params.filid = util.getStorage('orgId');
        if (pOrgId) {
          params.filid = pOrgId;
        }
      }
      return { multiple, params };
    },
    getPresetFlowInfo(nodeId, processDefinitionId, isNoStart) {
      isNoStart && (this.newPresetList = []);
      let params = {
        url: getPresetCustomInfo,
        data: {
          nodeId: nodeId,
          processDefinitionId: processDefinitionId
            ? processDefinitionId
            : this.newProcessDefinitionId
        },
        method: 'post'
      };
      util
        .ajax(params)
        .then((res) => {
          const { status, data } = res;
          if (status === 'success') {
            let list = [
              {
                nodeName: '请选择',
                nodeId: '1',
                value: '',
                options: [],
                multiple: false,
                selectUserList: [],
                isCustomUser: 1,
                params: {},
                radioList: []
              }
            ];
            for (let key in data) {
              list.push({
                nodeName: data[key],
                nodeId: key,
                options: [],
                multiple: false,
                selectUserList: [],
                isCustomUser: 1,
                params: {},
                radioList: []
              });
              if (key === 'endEvent') {
                list.splice(0, 1);
              }
            }
            let lastName = '';
            if (this.newPresetList.length == 0) {
              lastName = this.nextNode;
            } else {
              lastName = this.newPresetList[this.newPresetList.length - 1].name;
            }
            this.newPresetList.push({
              name: '',
              value: '',
              option: list,
              lastName,
              sequence: this.newPresetList.length + 1 + ''
            });
            if (
              this.newPresetList[this.newPresetList.length - 1].option[0]
                .nodeId === 'endEvent'
            ) {
              this.newPresetList[this.newPresetList.length - 1].name =
                'endEvent';
            }
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    changePresetUser(val, index) {
      const { nextUser, options } = val;
      this.newPresetList[index].nextUser = nextUser;
      this.newPresetList[index].selectUserList = options;
      this.changeSelectData();
    },
    changeSelectData() {
      let customPresetUserJson = [];
      this.newPresetList.map((item) => {
        customPresetUserJson.push({
          name: item.name,
          lastName: item.lastName,
          value:
            item.name != 'endEvent'
              ? item.multiple
                ? item.nextUser.join(',')
                : item.nextUser
              : '',
          sequence: item.sequence
        });
      });
      this.$emit('changeCustom', customPresetUserJson);
      this.$emit('change-custom', customPresetUserJson);
    }
  }
};
</script>

<style></style>
