<template>
  <div class="form-inline">
    <label class="control-label">{{ node.name }}({{ node.nodeId }})</label>
    <el-button type="primary" size="mini" @click="editTaskReminder"
      >设置</el-button
    >
    <br />
    <label
      v-if="!confList || confList.length == 0"
      class="control-label"
      style="color: #dd6161"
      >尚未配置自动触发新流程</label
    >
    <div v-if="confList && confList.length > 0">
      <label
        style="display: block; text-align: left"
        class="control-label"
        v-for="taskReminder in confList"
        :key="taskReminder.name"
        >{{ taskReminder.name }}</label
      >
      <div class="control-label" style="text-align: right">
        查看更多信息请编辑
      </div>
      <br />
    </div>
    <el-dialog
      width="68%"
      top="8vh"
      :title="'触发新流程设置(' + node.name + ')'"
      :visible="dialogVisibleSetting"
      :before-close="close"
      :close-on-click-modal="false"
      append-to-body
    >
      <div style="width: 100%; height: 550px;min-width:880px">
        <div
          ref="flowNodeSetting"
          @scroll="handlerScroll()"
          class="flow-node-setting"
        >
          <el-form
            v-model="reminder"
            data-vv-scope="settingSave"
            v-form
            class="elForm"
          >
            <table
              class="form-table flow-form-table"
              cellspacing="0"
              cellpadding="0"
              border="0"
            >
              <tbody>
                <tr>
                  <th width="110px" class="is-required">名称:</th>
                  <td>
                    <el-input
                      v-model="reminder.name"
                      placeholder="请输入配置名称"
                      style="width:400px"
                    />
                  </td>
                </tr>
                <tr>
                  <th
                    width="110px"
                    class="is-required"
                    v-if="node.nodeType != 'START' && node.nodeType != 'END'"
                  >
                    触发动作:
                  </th>
                  <td v-if="node.nodeType != 'START' && node.nodeType != 'END'">
                    <el-radio v-model="reminder.triggerAction" label="agree"
                      >同意</el-radio
                    >
                    <el-radio v-model="reminder.triggerAction" label="reject"
                      >驳回</el-radio
                    >
                    <el-radio v-model="reminder.triggerAction" label="oppose"
                      >反对</el-radio
                    >
                  </td>
                </tr>

                <tr>
                  <th width="110px" class="is-required">选择流程:</th>
                  <td>
                    <div>
                      <el-input
                        v-model="reminder.defName"
                        placeholder="选择触发的新流程"
                        validate="required"
                        :readonly="true"
                        disabled
                        style="width:300px"
                      />
                      <el-button
                        type="primary"
                        @click="selectDef"
                        style="margin-left:8px !important"
                        >选择流程
                      </el-button>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th width="110px" class="is-required">触发类型:</th>
                  <td>
                    <el-radio-group
                      v-model="reminder.triggerType"
                      @change="handleOldDefVar()"
                    >
                      <el-radio label="1">按发起人</el-radio>
                      <el-radio label="2">按表单对象</el-radio>
                    </el-radio-group>
                  </td>
                </tr>

                <tr v-if="reminder.triggerType == '2'">
                  <th width="110px" class="is-required">触发对象:</th>
                  <td>
                    <div>
                      <ht-select
                        v-model="curSelectEntity"
                        :options="boEntityList"
                        :validate="{required: true}"
                        @change="handleEntityChange()"
                        style="width:250px"
                      />
                    </div>
                  </td>
                  <th width="110px">触发时机:</th>
                  <td>
                    <el-radio-group
                      v-model="reminder.triggerTiming"
                      @change="initCondition()"
                    >
                      <el-radio label="1">直接触发</el-radio>
                      <el-radio label="2">按规则触发</el-radio>
                    </el-radio-group>
                  </td>
                </tr>
                <tr v-if="reminder.triggerTiming == '2'">
                  <th width="110px">规则设置:</th>
                  <td colspan="3">
                    <div>
                      <span>{{ reminder.condition.conditionDes }}</span
                      >&nbsp;
                      <el-button
                        type="text"
                        size="mini"
                        icon="el-icon-setting"
                        @click="openConditionDialog()"
                        >设置规则</el-button
                      >
                    </div>
                  </td>
                </tr>
                <tr>
                  <th width="150px" class="is-required th_notes">
                    <el-tooltip effect="dark" placement="right"
                      ><div slot="content">
                        ①可不选，不选则取节点完成时的审批人作为发起人<br />
                        ②所选用户拥有该流程启动权限方可触发<br />
                      </div>
                      <i class="icon-notes"></i>:
                    </el-tooltip>
                    <label style="margin-left:25px">流程发起人:</label>
                  </th>
                  <td colspan="3">
                    <div
                      v-if="reminder.triggerType == '1'"
                      @click="addUserCondition"
                    >
                      <el-input
                        v-model="reminder.userRule.description"
                        autosize
                        type="textarea"
                        placeholder="设置流程发起人"
                        validate="required"
                        :readonly="true"
                        style="width:300px"
                      />
                    </div>
                    <ht-user-selector-input
                      v-else
                      :appendToBody="true"
                      v-model="reminder.startName"
                      :config="{account: 'reminder.startAccount'}"
                      class="flow-selector-input"
                    />
                  </td>
                </tr>

                <tr>
                  <th width="110px" style="    display: flex;">
                    对应字段:
                  </th>
                  <td colspan="3" style="padding: 15px">
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-plus"
                      @click="addFormVarConf()"
                      >添加</el-button
                    >
                    <div class="table-wrap">
                      <div class="table-header">
                        <div
                          class="header-item"
                          v-for="item in tableHeader"
                          :key="item.key"
                        >
                          {{ item.value }}
                        </div>
                      </div>
                      <div class="table-content">
                        <ul
                          class="row"
                          v-for="(userRule, userIndex) in reminder.formVarConf"
                          :key="userIndex"
                        >
                          <li class="col flex-column">
                            <div class="col-item-box">
                              <span>选择主流程表：</span>
                              <FlowVarSelector
                                v-show="false"
                                type="3"
                                :varData="flowVarWithOutSub"
                                v-model="userRule.oldVar"
                                @node-click="handleClickNode"
                                @getData="getData"
                                style="width:33%;display:none"
                              />
                              <el-select
                                v-model="userRule.oldTable"
                                placeholder="请选择表"
                                :popper-append-to-body="false"
                                @change="
                                  change($event, 1, userIndex, `oldDisabled`)
                                "
                                style="    margin-right: 10px;"
                              >
                                <el-option
                                  v-for="item in optionsOld.filter(
                                    it => it.name !== '扩展变量'
                                  )"
                                  :key="item.id"
                                  :label="item.desc"
                                  :value="item.id"
                                  :disabled="
                                    selectedOldTableList.includes(item.id)
                                  "
                                >
                                </el-option>
                              </el-select>
                            </div>
                            <div class="col-item-box">
                              <span>选择触发流程表：</span>
                              <FlowVarSelector
                                v-show="false"
                                type="3"
                                v-if="defVarMap[reminder.defKey]"
                                :varData="defVarMap[reminder.defKey]"
                                :isNewFlow="true"
                                :isSubOrSunTable="isSubOrSunTable"
                                v-model="userRule.newVar"
                                @getData="getData"
                                style="width:33%;display:none"
                              />
                              <el-select
                                v-model="userRule.newTable"
                                placeholder="请选择表"
                                :disabled="userRule.oldNewTable"
                                :popper-append-to-body="false"
                                @change="
                                  change($event, 3, userIndex, `oldNewField`)
                                "
                                style="    margin-right: 10px;"
                              >
                                <el-option
                                  v-for="item in userRule.optionsNew &&
                                    userRule.optionsNew.filter(
                                      it => it.name !== '扩展变量'
                                    )"
                                  :key="item.id"
                                  :label="item.desc"
                                  :value="item.id"
                                  :disabled="
                                    selectedNewTableList.includes(item.id)
                                  "
                                >
                                </el-option>
                              </el-select>
                            </div>
                          </li>
                          <li class="col two-column">
                            <div
                              class="col-field-item"
                              v-for="(it, idx) in userRule.fieldList"
                              :key="idx"
                            >
                              <el-select
                                v-model="it.oldField"
                                :disabled="userRule.oldDisabled"
                                :popper-append-to-body="false"
                                placeholder="请选择流程字段"
                                @change="
                                  change(
                                    $event,
                                    2,
                                    userIndex,
                                    `oldNewTable`,
                                    idx
                                  )
                                "
                              >
                                <el-option
                                  v-for="item in userRule.oldFieldOptions"
                                  :key="item.id"
                                  :label="item.desc"
                                  :value="item.id"
                                  :disabled="oldFieldList.includes(item.id)"
                                >
                                </el-option>
                              </el-select>
                              <el-select
                                v-model="it.newField"
                                style="margin-left:20px"
                                placeholder="请选择流程字段"
                                :popper-append-to-body="false"
                                :disabled="userRule.oldNewField"
                                @change="change($event, 4, userIndex, '', idx)"
                              >
                                <el-option
                                  v-for="item in userRule.newFieldOptions"
                                  :key="item.id"
                                  :label="item.desc"
                                  :value="item.id"
                                  :disabled="newFieldList.includes(item.id)"
                                >
                                </el-option>
                              </el-select>
                              <el-button
                                style="margin-left:10px !important"
                                size="small"
                                icon="el-icon-delete"
                                type="text"
                                v-show="userRule.fieldList.length > 1"
                                @click="handleDel(userIndex, idx)"
                              ></el-button>
                            </div>
                          </li>
                          <li class="col last-col">
                            <el-button
                              size="small"
                              icon="el-icon-plus"
                              @click="handleAdd(userIndex)"
                            ></el-button>
                            <el-button
                              size="small"
                              icon="el-icon-delete"
                              @click="deleteItem(userIndex)"
                            ></el-button>
                          </li>
                        </ul>
                      </div>
                    </div>
                    <!-- <table
                      class="table table-bordered var-conf-table"
                      style="width: 100%;margin-top: 15px;"
                    >
                      <thead> 
                        <tr>
                          <th width="45%">
                            主流程字段
                          </th>

                          <th width="45%">新流程字段</th>
                          <th width="10%">操作</th>
                        </tr>
                      </thead>
                      <tr
                        v-for="(userRule, userIndex) in reminder.formVarConf"
                        :key="userIndex"
                      >
                        <td>
                          <FlowVarSelector
                            v-show="false"
                            type="3"
                            :varData="flowVarWithOutSub"
                            v-model="userRule.oldVar"
                            @node-click="handleClickNode"
                            @getData="getData"
                            style="width:33%;display:none"
                          />
                          <el-select
                            v-model="userRule.oldTable"
                            placeholder="请选择表"
                            @change="
                              change($event, 1, userIndex, `oldDisabled`)
                            "
                            style="    margin-right: 10px;"
                          >
                            <el-option
                              v-for="item in optionsOld"
                              :key="item.id"
                              :label="item.desc"
                              :value="item.id"
                            >
                            </el-option>
                          </el-select>
                          <el-select
                            v-model="userRule.oldField"
                            :disabled="userRule.oldDisabled"
                            placeholder="请选择流程字段"
                            @change="
                              change($event, 2, userIndex, `oldNewTable`)
                            "
                          >
                            <el-option
                              v-for="item in optionsFilter[
                                `oldFieldOptions_${userIndex}`
                              ]"
                              :key="item.id"
                              :label="item.desc"
                              :value="item.id"
                            >
                            </el-option>
                          </el-select>
                        </td>
                        <td>
                          <FlowVarSelector
                            v-show="false"
                            type="3"
                            v-if="defVarMap[reminder.defKey]"
                            :varData="defVarMap[reminder.defKey]"
                            :isNewFlow="true"
                            :isSubOrSunTable="isSubOrSunTable"
                            v-model="userRule.newVar"
                            @getData="getData"
                            style="width:33%;display:none"
                          />
                          <el-select
                            v-model="userRule.newTable"
                            placeholder="请选择表"
                            :disabled="userRule.oldNewTable"
                            @change="
                              change($event, 3, userIndex, `oldNewField`)
                            "
                            style="    margin-right: 10px;"
                          >
                            <el-option
                              v-for="item in optionsFilter[
                                `optionsNew_${userIndex}`
                              ]"
                              :key="item.id"
                              :label="item.desc"
                              :value="item.id"
                            >
                            </el-option>
                          </el-select>
                          <el-select
                            v-model="userRule.newField"
                            placeholder="请选择流程字段"
                            :disabled="userRule.oldNewField"
                            @change="change($event, 4, userIndex)"
                          >
                            <el-option
                              v-for="item in optionsFilter[
                                `newFieldOptions_${userIndex}`
                              ]"
                              :key="item.id"
                              :label="item.desc"
                              :value="item.id"
                            >
                            </el-option>
                          </el-select>
                        </td>
                        <td>
                          <el-button
                            size="mini"
                            type="text"
                            @click="deleteItem(userIndex)"
                            >删除</el-button
                          >
                        </td>
                      </tr>
                    </table> -->
                  </td>
                </tr>
              </tbody>
            </table>
          </el-form>
        </div>
      </div>
      <div slot="footer" style="margin-bottom: 10px">
        <el-button type="default" @click="close">关闭</el-button>
        <el-button type="primary" plain @click="clear">清空</el-button>
        <el-button type="primary" @click="addRemind">保存</el-button>
      </div>
    </el-dialog>
    <!-- 人员配置选择器 -->
    <FlowNodeUserCondition
      @nodeUserConditionConfirm="nodeUserConditionConfirm"
      ref="flowNodeUserCondition"
    />
    <FlowConditionBuildDialog
      @onConfirmWithData="conditionDialogConfirm"
      ref="flowConditionBuildDialog"
    />
    <eip-flow-dialog
      ref="eipFlowDialog"
      name="eipFlowDialog"
      @onConfirm="handleDialogSure"
      :single="true"
      append-to-body
    />
  </div>
</template>

<script>
import req from '@/request.js'
import {mapState, mapActions} from 'vuex'
import {Message} from 'element-ui'
const eipScriptDialog = () => import('@/components/dialog/EipScriptDialog.vue')
const FlowNodeUserCondition = () =>
  import('@/components/flow/FlowNodeUserCondition.vue')
const eipFlowDialog = () => import('@/components/dialog/EipFlowDialog.vue')
const FlowVarSelector = () => import('@/components/flow/FlowVarSelector.vue')
import FlowConditionBuildDialog from '@/components/flow/FlowConditionBuildDialog.vue'

export default {
  name: 'FlowStartConf',
  components: {
    eipScriptDialog,
    FlowNodeUserCondition,
    eipFlowDialog,
    FlowVarSelector,
    FlowConditionBuildDialog
  },
  props: {
    //任务节点信息
    node: {
      type: Object,
      required: true
    },
    //流程配置信息
    defConfigData: {
      type: Object,
      required: true
    },
    //所有的自动触发新流程的配置
    confList: {
      type: Array,
      required: true
    },
    flowVar: {
      type: Array,
      required: false
    }
  },

  data() {
    return {
      dialogVisibleSetting: false, //是否显示设置节点新流程触发设置侧边栏
      reminder: {
        name: '',
        triggerAction: 'agree',
        userRule: {description: ''},
        defName: '',
        defKey: '',
        formVarConf: [],
        isAdd: true,
        startName: '',
        startAccount: '',
        triggerEntity: '',
        condition: {}
      },
      isSave: false, //判断是否可以保存
      confListCopy: [], //复制一份最开始的新流程触发设置配置的信息
      defVarMap: {},
      boEntityList: [],
      flowVarWithOutSub: [],
      curSelectEntity: '',
      isSubOrSunTable: false,
      optionsOld: [],
      optionsNew: [],
      newFieldOptions: [],
      oldFieldOptions: [],
      //被选的
      newFieldList: [],
      oldFieldList: [],
      //
      optionsFilter: {},
      tableHeader: [
        {
          key: 'selectTable',
          value: '所选表'
        },
        {
          key: 'mainFlowField',
          value: '主流程字段'
        },
        {
          key: 'newFlowField',
          value: '触发流程字段'
        },
        {
          key: 'operate',
          value: '操作'
        }
      ],
      selectedOldTableList: [],
      selectedNewTableList: [],
   
    }
  },
  watch: {
    'reminder.defKey': function(n, o) {
      if (n && !this.defVarMap[n]) {
        this.getNewDefVar()
      }
    },
    confList: {
      handler(val) {},
      immediate: true,
      deep: true
    }
  },
  methods: {
    handlerScroll() {
      this.scrollBol = true
      let target = this.$refs.flowNodeSetting.querySelectorAll(
        '.el-select-dropdown'
      )
      for (let item of target) {
        item.style.display = 'none'
      }
    },
    //监听父子滚动
    handleDel(index, idx) {
      this.reminder.formVarConf[index].fieldList.splice(idx, 1)
      this.setSelectedIds()
    },
    handleAdd(index) {
      this.reminder.formVarConf[index].fieldList.push({
        oldTable: '',
        oldField: '',
        newTable: '',
        newField: ''
      })
    },
    //typeDiff 1主 2子
    getData(list, Bol) {
      let data = _.cloneDeep(list)
      let options = []
      let optionsField = []

      data.forEach(item => {
        if (item.children && item.children.length) {
          item.children.forEach(zhubItem => {
            if (zhubItem.children && zhubItem.children.length) {
              zhubItem.children.forEach(ziItem => {
                if (ziItem.children && ziItem.children.length) {
                  ziItem.children.forEach(sunItem => {
                    if (sunItem.children && sunItem.children.length) {
                    } else {
                      ziItem.typeDiff = 2
                      options.push(ziItem)
                      sunItem.typeDiff = 2
                      optionsField.push(sunItem)
                    }
                  })
                } else {
                  zhubItem.typeDiff = 1
                  options.push(zhubItem)
                  ziItem.typeDiff = 1
                  optionsField.push(ziItem)
                }
              })
            } else {
              item.typeDiff = 1
              options.push(item)
              zhubItem.typeDiff = 1
              optionsField.push(zhubItem)
            }
          })
        }
      })
      options = this.filterList(options)
      optionsField = this.filterList(optionsField)
      if (Bol) {
        this.optionsNew = options
        this.newFieldOptions = optionsField
      } else {
        this.optionsOld = options
        this.oldFieldOptions = optionsField
      }
    },
    filterList(data) {
      let map = new Map()
      for (let item of data) {
        map.set(item.id, item)
      }
      data = [...map.values()]
      return data
    },
    change($event, type, index, disabled, idx) {
      let that = this

      // if (this.oldFieldList.includes($event)) {
      //   this.$message.warning('该流程字段已被选择')

      //   this.$nextTick(() => {
      //     that.reminder.formVarConf[index].oldField = ''
      //   })
      //   return
      // }
      // if (this.newFieldList.includes($event)) {
      //   this.$message.warning('该流程字段已被选择')
      //   this.$nextTick(() => {
      //     that.reminder.formVarConf[index].newField = ''
      //   })
      //   return
      // }
      if ([1, 2, 3].includes(type)) {
        that.reminder.formVarConf[index][disabled] = false
      }
      if (type == 1) {
        that.reminder.formVarConf[index].oldField = ''
        that.reminder.formVarConf[index].newTable = ''
        that.reminder.formVarConf[index].newField = ''
        this.filterListOptions($event, index, 'oldFieldOptions')
        this.filterListOptions($event, index, 'optionsNew')
        this.filterListOptions($event, index, 'newFieldOptions')
        const selectTable = that.optionsOld.find(it => it.id === $event)
        const currentNewTableList = that.optionsNew.filter(
          item => item.typeDiff === selectTable.typeDiff
        )
        const currentFieldList = that.oldFieldOptions.filter(
          item =>
            item.path === selectTable.path ||
            (item.typeDiff == selectTable.typeDiff && !item.path)
        )
        that.$set(
          that.reminder.formVarConf[index],
          'oldFieldOptions',
          currentFieldList
        )
        that.$set(
          that.reminder.formVarConf[index],
          'optionsNew',
          currentNewTableList
        )
      }
      if (type == 2) {
        // that.reminder.formVarConf[index].newTable = ''
        // that.reminder.formVarConf[index].newField = ''
        // userRule.oldVar
        this.addDataList($event, 'oldVar', index, 'oldFieldOptions', idx)
      }
      if (type == 3) {
        that.reminder.formVarConf[index].newField = ''
        const selectTable = that.optionsNew.find(it => it.id === $event)
        const currentFieldList = that.newFieldOptions.filter(
          it =>
            it.path === selectTable.path ||
            (it.typeDiff == selectTable.typeDiff && !it.path)
        )
        that.$set(
          that.reminder.formVarConf[index],
          'newFieldOptions',
          currentFieldList
        )
      }
      if (type == 4) {
        // userRule.newVar
        this.addDataList($event, 'newVar', index, 'newFieldOptions', idx)
      }
      this.oldFieldList = []
      this.newFieldList = []
      const oldFieldList = []
      const newFieldList = []
      this.selectedOldTableList = []
      this.selectedNewTableList = []
      this.reminder.formVarConf.forEach(item => {
        if (item.oldTable) {
          this.selectedOldTableList.push(item.oldTable)
        }
        if (item.newTable) {
          this.selectedNewTableList.push(item.newTable)
        }
        if (item.fieldList && item.fieldList.length) {
          oldFieldList.push(item.fieldList.map(it => it.oldField))
          newFieldList.push(item.fieldList.map(it => it.newField))
        }
      })
      this.oldFieldList = oldFieldList.flat().filter(Boolean)
      this.newFieldList = newFieldList.flat().filter(Boolean)
      that.reminder = Object.assign({}, that.reminder)
    },
    //合成传参
    addDataList(even, name, index, opName, idx) {
      this.optionsFilter[`${opName}_${index}`].forEach(item => {
        if (item.id == even) {
          this.reminder.formVarConf[index].fieldList[idx][name] =
            // this.reminder.formVarConf[index][name] =
            item.desc +
            '【' +
            item.path +
            '.' +
            item.name +
            '】-' +
            item.dataType
          this.reminder.formVarConf[index].fieldList[
            idx
          ].oldTable = this.reminder.formVarConf[index].oldTable
          this.reminder.formVarConf[index].fieldList[
            idx
          ].newTable = this.reminder.formVarConf[index].newTable
        }
      })
    },
    //过滤选项
    filterListOptions(event, index, name) {
      this.optionsOld.forEach(item => {
        if (item.id == event) {
          if (item.typeDiff) {
            this.optionsFilter[`${name}_${index}`] = this[name].filter(i => {
              return i.typeDiff == item.typeDiff
            })
          }
        }
      })
    },
    //删除
    deleteItem(userIndex) {
      this.reminder.formVarConf.splice(userIndex, 1)
      this.reminder = Object.assign({}, this.reminder)
      this.setSelectedIds()
    },
    updateOptions() {},
    handleClickNode(data, node) {
      this.isSubOrSunTable = data.path && data.path.split('.').length > 1
    },
    handleClickNewFlowNode() {},
    initCondition() {
      this.reminder.condition = {
        conditionString: '',
        conditionDes: '',
        conditionObj: ''
      }
    },
    // 当触发对象发生变化时。计算旧流程的可选变量
    handleOldDefVar(remainVarCinf) {
      if (!remainVarCinf) {
        this.reminder.formVarConf = []
        this.selectedOldTableList = []
        this.selectedNewTableList = []
        this.newFieldList = []
        this.oldFieldList = []
      }
      let pathArr = []
      if (this.reminder.triggerType == '2') {
        pathArr = this.reminder.triggerEntity.split('.')
      }
      this.flowVarWithOutSub = JSON.parse(JSON.stringify(this.flowVar))
      //只保留主表字段
      if (!this.flowVarWithOutSub || this.flowVarWithOutSub.length <= 0) {
        return
      }
      this.flowVarWithOutSub[0].children.forEach(mainEnt => {
        if (mainEnt.childre == undefined || mainEnt.childre.length == 0) {
          return
        }
        for (let index = mainEnt.children.length - 1; index > 0; index--) {
          const mainEntFiled = mainEnt.children[index]
          // 主表字段有children的表名为子表
          if (mainEntFiled.children) {
            // pathArr.length < 3 表示所选的是主表，则移除掉子表。  或者选了子表，移除掉非所选则子表
            if (
              pathArr.length < 3 ||
              (pathArr.length > 2 && pathArr[2] != 'sub_' + mainEntFiled.name)
            ) {
              mainEnt.children.splice(index, 1)
            } else {
              // 选择的触发对象是子表的，遍历子表移除孙表 或者选了孙表，移除非所选孙表
              for (let i = mainEntFiled.children.length - 1; i > 0; i--) {
                const subFiled = mainEntFiled.children[i]
                if (
                  subFiled.children &&
                  (pathArr.length == 3 ||
                    (pathArr.length > 3 &&
                      pathArr[3] != 'sub_' + subFiled.name))
                ) {
                  mainEntFiled.children.splice(i, 1)
                }
              }
            }
          }
        }
      })
    },
    handleEntityChange() {
      if (this.reminder.condition.conditionObj) {
        this.$confirm('修改触发对象会清空触发规则, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.reminder.triggerEntity = this.curSelectEntity
            this.reminder.condition = {}
            this.handleOldDefVar()
          })
          .catch(() => {
            this.curSelectEntity = this.reminder.triggerEntity
          })
      } else {
        this.reminder.triggerEntity = this.curSelectEntity
        this.handleOldDefVar()
      }
    },
    openConditionDialog() {
      if (!this.reminder.triggerEntity) {
        this.$message.warning('请先选择触发对象')
        return
      }
      let boVar = {}
      this.boEntityList.forEach(bo => {
        if (bo.key == this.reminder.triggerEntity) {
          bo = bo.entity
          bo.path = bo.name
          if (bo.children) {
            for (let index = bo.children.length - 1; index > 0; index--) {
              const filed = bo.children[index]
              filed.path = bo.name
              if (filed.children) {
                bo.children.splice(index, 1)
              }
            }
          }
          boVar = bo
        }
      })
      let varArray = [
        {name: 'curUserId', desc: '当前用户ID', comment: '当前用户ID'},
        {name: 'curUserAccount', desc: '当前用户账号', comment: '当前用户账号'},
        {name: 'curUserName', desc: '当前用户姓名', comment: '当前用户姓名'}
      ]
      let param = {
        boVar: [
          {name: '表单变量', children: [boVar]},
          {name: '流程变量', isFlow: true, children: varArray}
        ]
      }

      if (this.reminder.condition.conditionObj) {
        param.conditionObj = JSON.parse(this.reminder.condition.conditionObj)
      }
      this.$refs.flowConditionBuildDialog.showDialog(param)
    },
    conditionDialogConfirm(data) {
      this.reminder.condition = data
    },
    getNewDefVar() {
      let me_ = this
      req
        .post(window.context.bpmModel + '/flow/node/v1/varTree', {
          flowKey: this.reminder.defKey,
          nodeId: this.node.nodeId,
          includeBpmConstants: false,
          removeSub: false,
          bpmForm: true
        })
        .then(response => {
          if (
            response &&
            response.data[0] &&
            response.data[0].children &&
            response.data[0].children.length > 1
          ) {
            this.reminder.defName = ''
            this.reminder.defKey = ''
            return this.$message.warning(
              '当前选择流程绑定的是多实体表单，请选择单实体表单流程'
            )
          }
          me_.$set(me_.defVarMap, me_.reminder.defKey, response.data || [])
        })
    },
    handleDialogSure(data) {
      if (
        (data && data.length > 0 && this.reminder.defKey == data[0].defKey) ||
        !this.reminder.defKey
      ) {
        this.reminder.defName = data[0].name
        this.reminder.defKey = data[0].defKey
        return
      }
      this.$confirm(`更换流程将会清空对应字段的配置,是否确定更换?`).then(() => {
        if (data && data.length > 0) {
          this.reminder.defName = data[0].name
          this.reminder.defKey = data[0].defKey
        } else {
          this.reminder.defName = ''
          this.reminder.defKey = ''
        }
        this.reminder.formVarConf = []
        this.selectedOldTableList = []
        this.selectedNewTableList = []
        this.newFieldList = []
        this.oldFieldList = []
      })
    },
    selectDef() {
      this.$refs.eipFlowDialog.showDialog()
    },
    addFormVarConf() {
      if (!this.reminder.defKey) {
        Message.warning('要先选择要触发的流程才能配置对应字段')
        return
      }
      if (this.reminder.triggerType == '2' && !this.reminder.triggerEntity) {
        Message.warning('要先选择触发对象才能配置对应字段')
        return
      }
      this.reminder.formVarConf.push({
        oldDisabled: true,
        oldNewTable: true,
        oldNewField: true,
        oldTable: '',
        oldField: '',
        newTable: '',
        newField: '',
        fieldList: [
          {
            oldDisabled: true,
            oldNewTable: true,
            oldNewField: true,
            oldTable: '',
            oldField: '',
            newTable: '',
            newField: ''
          }
        ]
      })
      this.reminder = Object.assign({}, this.reminder)
    },
    nodeUserConditionConfirm(res) {
      this.reminder.userRule = res
    },
    //添加人员配置（办结抄送）
    addUserCondition() {
      let conf = {}
      if (
        this.reminder &&
        this.reminder.userRule &&
        this.reminder.userRule.description
      ) {
        conf.userRule = JSON.parse(JSON.stringify(this.reminder.userRule))
      }
      conf = {...conf, ...{nodeType: '', nodeId: '', defId: this.defId}}
      this.$refs.flowNodeUserCondition.showDialog(conf)
    },
    setSelectedIds() {
      const oldFieldList = []
      const newFieldList = []
      this.selectedOldTableList = this.reminder.formVarConf.map(item => {
        if (item.fieldList && item.fieldList.length) {
          oldFieldList.push(item.fieldList.map(it => it.oldField))
          newFieldList.push(item.fieldList.map(it => it.newField))
        }
        return item.oldTable
      })
      this.selectedNewTableList = this.reminder.formVarConf.map(
        item => item.newTable
      )
      this.oldFieldList = oldFieldList.flat().filter(Boolean)
      this.newFieldList = newFieldList.flat().filter(Boolean)
    },
    //编辑触发新流程设置
    editTaskReminder() {
      if (
        !this.defConfigData.nodeSetData.bpmDefSetting.globalForm ||
        !this.defConfigData.nodeSetData.bpmDefSetting.globalForm.formValue
      ) {
        this.$message.warning('请先设置全局表单')
        return
      }
      this.confListCopy = JSON.parse(JSON.stringify(this.confList))

      this.confListCopy.forEach(conf => {
        const formVarConf = conf.formVarConf && JSON.parse(conf.formVarConf)
        conf.formVarConf =
          formVarConf && formVarConf[0]
            ? JSON.parse(formVarConf[0].formVarConf)
            : []
        conf.userRule = conf.userRule ? JSON.parse(conf.userRule) : {}
        conf.condition = conf.condition ? JSON.parse(conf.condition) : {}
        conf.triggerType = conf.triggerType ? conf.triggerType : '1'
      })
      if (this.confListCopy.length > 0) {
        this.$set(this, 'reminder', this.confListCopy[0])

        this.curSelectEntity = this.reminder.triggerEntity
        if (
          this.reminder &&
          this.reminder.formVarConf &&
          this.reminder.formVarConf[0] &&
          this.reminder.formVarConf[0].optionsFilter
        ) {
          this.optionsFilter = this.reminder.formVarConf[0].optionsFilter
        }
        this.setSelectedIds()
        this.handleOldDefVar(true)
      } else {
        this.restConf()
      }
      this.handleOldDefVar(true)
      this.boEntityList = []
      // if (!this.flowVar[0]) {
      //   return
      // }
      if (this.flowVar) {
        if (this.flowVar.length) {
          this.flowVar[0].children.forEach(mainEnt => {
            if (mainEnt.children) {
              this.boEntityList.push({
                key: mainEnt.path + '.' + mainEnt.name,
                value: mainEnt.desc + '(' + mainEnt.name + ')——主表',
                entity: mainEnt
              })
              mainEnt.children.forEach(mainEntFiled => {
                if (mainEntFiled.children) {
                  this.boEntityList.push({
                    key:
                      mainEnt.path +
                      '.' +
                      mainEnt.name +
                      '.sub_' +
                      mainEntFiled.name,
                    value:
                      mainEntFiled.desc + '(' + mainEntFiled.name + ')——子表',
                    entity: mainEntFiled
                  })
                }
              })
            }
          })
        }
        if (this.boEntityList.length > 0) {
          this.isSave = true
          this.dialogVisibleSetting = true
        }
      }
      if (this.boEntityList.length == 0) {
        req
          .get(
            window.context.form +
              '/form/form/v1/getBoJsonByFormKey?formkey=' +
              this.defConfigData.nodeSetData.bpmDefSetting.globalForm.formValue
          )
          .then(response => {
            let data = response.data[0]
            if (data) {
              this.boEntityList.push({
                key: data.path + '.' + data.name,
                value: data.desc + '(' + data.name + ')——主表',
                entity: data
              })
            }
            if (data.children) {
              data.children.forEach(mainEnt => {
                if (mainEnt.children) {
                  this.boEntityList.push({
                    key: data.path + '.' + data.name + '.sub_' + mainEnt.name,
                    value: mainEnt.desc + '(' + mainEnt.name + ')——子表',
                    entity: mainEnt
                  })
                }
              })
            }

            this.isSave = true
            this.dialogVisibleSetting = true
          })
      }
    },
    //列表某一条数据时触发
    orgRowClick(row, column, event) {
      if (column.label != '操作') {
        row.formVarConf = row.formVarConf || []
        row.userRule = row.userRule || {description: ''}
        row.startDef = row.startDef || {}
        this.reminder = row
        this.isSave = true
      }
    },
    //保存新流程触发设置
    saveRemind(isSaveOption) {
      const this_ = this
      //判断是否有新增的数据
      if (!this_.isSave) {
        Message.warning('请先新增新流程触发设置信息再保存')
        return
      } else {
        let saveConf = JSON.parse(JSON.stringify(this_.confListCopy))

        // if (this.reminder.formVarConf && this.reminder.formVarConf[0]) {
        //   this.reminder.formVarConf[0].optionsFilter = this.optionsFilter
        // }

        //校验是否有必填字段没有填写
        // for (let x = 0; x < saveConf.length; x++) {
        saveConf = [{...this.reminder}]
        const currentFormVarConf = this.reminder.formVarConf
          .map(item => item.fieldList)
          .flat()

        for (let x = 0; x < saveConf.length; x++) {
          if (this.validateData(saveConf[x])) {
            if (currentFormVarConf.length > 0) {
              this_.$message({
                showClose: true,
                message:
                  '列表第' +
                  (x + 1) +
                  '行有字段未通过校验，请正确填写表单内容。',
                type: 'warning'
              })
              return
            }
          }
          saveConf[x].formVarConf = JSON.stringify(
            this.getCurrentFormVarConfig(saveConf[x].formVarConf)
          )
          saveConf[x].userRule = JSON.stringify(saveConf[x].userRule)
          saveConf[x].condition = JSON.stringify(saveConf[x].condition)
        }

        let remindersCopyJson = JSON.stringify(saveConf) //转json字符串
        req
          .post(
            '${bpmModel}/flow/plugins/v1/startNewFlowSave?defId=' +
              this_.node.defId +
              '&nodeId=' +
              this_.node.nodeId,
            remindersCopyJson
          )
          .then(function(data) {
            data = data.data
            if (data.state) {
              if (isSaveOption) {
                Message.success('保存成功！')
              } else {
                Message.success('清除成功！')
              }
              this_.$emit('update:confList', saveConf) //子组件更新父组件的值
              this_.restConf()
              if (isSaveOption) {
                this_.dialogVisibleSetting = false
              }
            } else {
              Message.error('新流程触发设置保存出现异常：' + data.message)
            }
          })
      }
    },
    getCurrentFormVarConfig(data) {
      let newData = data && data.map(item => item.fieldList).flat()
      if (newData && newData[0]) {
        newData[0].formVarConf = JSON.stringify(this.reminder.formVarConf)
      }
      return newData
    },
    validateData(data) {
      //新增数据
      let errMsg = []
      if (!data.name) {
        errMsg.push('名称')
      }
      if (!data.defKey) {
        errMsg.push('新流程')
      }
      if (data.triggerType == '2' && !data.triggerEntity) {
        errMsg.push('触发对象')
      }

      if (
        (data.triggerType == '1' &&
          (!data.userRule || !data.userRule.description)) ||
        (data.triggerType == '2' && !data.startAccount)
      ) {
        //errMsg.push('流程发起人');
      }
      return errMsg.join(',')
    },
    //新增新流程触发设置
    addRemind() {
      if (this.validateData(this.reminder)) {
        Message.warning(this.validateData(this.reminder) + '不能为空')
        return
      }
      this.isSave = true
      delete this.reminder.isAdd

      this.confListCopy = []
      this.confListCopy.push(this.reminder) //新增新流程触发设置基本信息、消息设置

      if (this.reminder.formVarConf) {
        const currentFormVarConf = this.reminder.formVarConf
          .map(item => item.fieldList)
          .flat()
        for (let index = 0; index < currentFormVarConf.length; index++) {
          const conf = currentFormVarConf[index]
          if (!conf.oldVar || !conf.newVar) {
            this.$message({
              showClose: true,
              message: '对应字段第' + (index + 1) + '行不完整',
              type: 'warning'
            })
            return
          }
          if (
            conf.newVar.split('】-')[conf.newVar.split('】-').length - 1] !=
            conf.oldVar.split('】-')[conf.oldVar.split('】-').length - 1]
          ) {
            this.$message({
              showClose: true,
              message: '对应字段第' + (index + 1) + '行字段类型必须一致',
              type: 'warning'
            })
            return
          }
        }
      }
      this.saveRemind(true)
    },
    clear() {
      this.$confirm(`是否确定清空该节点已有配置?`).then(() => {
        this.confListCopy = []
        this.restConf()
        this.saveRemind(false)
        this.oldFieldList = []
        this.newFieldList = []
        this.selectedOldTableList = []
        this.selectedNewTableList = []
      })
    },
    //关闭设置节点新流程触发设置列弹框
    close() {
      this.dialogVisibleSetting = false
    },
    //删除新流程触发设置
    deleteSetting(list, index) {
      list.splice(index, 1)
      this.isSave = true
      this.restConf()
    },
    //初始化设置
    restConf() {
      let rest = {
        name: '',
        triggerAction: 'agree',
        triggerType: '1',
        userRule: {description: ''},
        defName: '',
        defKey: '',
        formVarConf: [],
        isAdd: true,
        startName: '',
        startAccount: '',
        triggerEntity: '',
        condition: {}
      }
      this.curSelectEntity = ''
      this.$set(this, 'reminder', rest)
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  }
}
</script>

<style lang="scss" scoped>
div >>> .el-dialog__body {
  padding: 10px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.div_list {
  height: 30px;
  background: #e2e2e2;
  line-height: 30px;
  font-weight: bold;
  padding-left: 10px;
  margin-bottom: 10px;
}
>>> label.el-checkbox {
  margin: 5px 10px 0 0;
}
.ht {
  width: 300px;
}
.form-inline {
  float: left;
  width: 100%;
}
.left-label {
  width: 18%;
  float: left;
}
.control-label {
  word-break: break-all;
  text-align: right;
  color: #545252;
  font-size: 12px;
  padding: 0px 10px !important;
  font-weight: bold;
  line-height: 35px;
}
div >>> .box-card {
  margin-bottom: 20px;
}

div >>> .box-card .clearfix {
  padding-top: 20px;
}

div >>> .el-button {
  margin-right: 10px;
  margin-left: 0px !important;
}

.table {
  border-bottom: 1px solid #e7eaec;
  border-right: 1px solid #e7eaec;
}

.var-conf-table th,
.var-conf-table td {
  border-top: 1px solid #e7eaec;
  border-left: 1px solid #e7eaec;
  line-height: 1.4em;
  padding: 4px;
  vertical-align: middle;
  text-align: center;
}

.var-conf-table > thead > tr > th,
.var-conf-table > tbody > tr > th {
  background: #fafafa;
  height: 30px;
}

.table {
  border-bottom: 1px solid #e7eaec;
  border-right: 1px solid #e7eaec;
  border-collapse: collapse;
}
.flow-selector-input {
  width: 400px;

  ::v-deep {
    .inputs {
      width: 400px !important;
    }
    .el-select__tags {
      max-height: 190px !important;
      overflow: auto;
    }
    .el-select {
      max-height: 200px;
      overflow: hidden;
    }
    .el-input__inner {
      max-height: 200px;
    }
    .el-tag--info {
      color: #0080fe;
    }
    .el-tag__close {
      background: rgba(0, 128, 254, 0.1);
      border-radius: 50%;
      color: #0080fe;
      font-weight: bold;
    }
  }
}
.flow-node-setting {
  width: 96%;
  float: left;
  height: 100%;
  overflow: auto;
  .flow-form-table {
    & > tbody > tr,
    & > tbody > tr > td,
    & > tbody > tr > th {
      border: none;
    }
  }
  .form-table > tbody > tr > th,
  .form-table > tbody > tr > td,
  .form-table > tfoot > tr > td,
  .form-table > thead > tr > th {
    white-space: nowrap;
    padding: 15px;
    // vertical-align: text-top;
  }
}
.elForm {
  tbody > tr > th {
    color: #888888;
    text-align: left !important;
  }

  ::v-deep {
    .el-tooltip {
      margin-left: 4px;
    }
  }
  .icon-notes {
    position: absolute;
    left: 8px;
    top: 24px;
  }
}
.th_notes {
  position: relative;
  &::before {
    position: absolute;
    left: 30px;
  }
}
.is-plain {
  background: #fff;
}
.table-wrap {
  display: grid;
  .table-header {
    display: flex;

    height: 40px;
    background: #fafafa;
    border: 1px solid #e7eaec;
    .header-item {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex: 1;

      border-right: 1px solid #e7eaec;
      color: #333;
      font-weight: bold;
      &:last-child {
        border-right: none;
      }
    }
  }
  .table-content {
    .row {
      display: flex;
      border: 1px solid #e7eaec;
      border-top: none;
      .col {
        padding: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex: 1;
        border-right: 1px solid #e7eaec;
        &:last-child {
          border-right: none;
        }
      }
      .two-column {
        flex: 2;
        flex-direction: column;
        .col-field-item {
          margin-bottom: 10px;
        }
      }
      .flex-column {
        flex-direction: column;
        padding-right: 0;
        .col-item-box {
          display: flex;
          flex-direction: column;
          span {
            padding-bottom: 8px;
          }
          &:last-child {
            padding-top: 16px;
          }
        }
      }
      .last-col {
        padding-left: 0;
      }
    }
  }
}
</style>
