<template>
  <van-popup
    v-model="relatedInformationDialog"
    round
    :close-on-click-overlay="false"
    append-to-body
    @close="closeDailog"
    safe-area-inset-bottom
    position="bottom"
    class="dialog__min-height"
  >
    <van-nav-bar
      title="选择目标节点"
      left-text="取消"
      right-text="确定"
      @click-left="
        () => {
          relatedInformationDialog = false
        }
      "
      @click-right="confirm"
    />
    <div v-if="!selectConfig.jumpType" v-form>
      <div v-for="(item, index) in selectConfig.afterNodes" :key="index">
        <van-field
          :label="item.nodeName"
          readonly
          input-align="right"
          class="contentButton"
        >
          <template #input>
            <ht-user-selector-input
              v-if="selectConfig.choiceExcutor != 'candidate'"
              v-model="item.selectUsers"
              :config="{ id: 'selectConfig.afterNodes[' + index + '].id' }"
            ></ht-user-selector-input>
            <ht-select
              v-if="selectConfig.choiceExcutor == 'candidate'"
              v-model="item.selectUserIds"
              :options="item.excutorList"
              clearable
              multiple
              :props="{ key: 'id', value: 'name' }"
            ></ht-select>
          </template>
        </van-field>
      </div>
    </div>
    <div v-if="selectConfig.jumpType" v-form>
      <van-search
        v-model="value"
        shape="square"
        placeholder="搜索"
        @input="searchClick"
      />

      <div class="selectConten more-select node-user-list">
        <van-radio-group v-model="selectNodeId" ref="checkboxGroup">
          <div
            v-for="(item, i) of searchList"
            :key="i"
            :class="{
              'user-item': item.nodeType != 'end' && selectConfig.choiceExcutor,
            }"
          >
            <van-radio
              :name="item.nodeId"
              class="node-radio"
              :class="{ 'end-node': item.nodeType === 'end' }"
            >
              {{ item.nodeName }}
            </van-radio>
            <van-field
              v-if="item.nodeType != 'end' && selectConfig.choiceExcutor"
              label="选择处理人"
              readonly
              input-align="right"
              class="contentButton"
            >
              <template #input>
                <ht-user-selector-input
                  v-model="item.selectUsers"
                  :config="{ id: 'searchList[' + i + '].id' }"
                  v-if="selectConfig.choiceExcutor != 'candidate'"
                  :append-to-body="true"
                ></ht-user-selector-input>
                <ht-select
                  v-if="selectConfig.choiceExcutor == 'candidate'"
                  v-model="item.selectUserIds"
                  :options="item.excutorList"
                  clearable
                  multiple
                  :props="{ key: 'id', value: 'name' }"
                ></ht-select>
              </template>
            </van-field>
            <!-- <van-divider v-if="i + 1 !== selectConfig.afterNodes.length" /> -->
          </div>
        </van-radio-group>
      </div>
    </div>
  </van-popup>
</template>

<script>
  import { mapState } from 'vuex'
  import { Dialog } from 'vant'
  import {
    getAfterJumpNodesByDefId,
    savaTaskComplete,
    startProcess,
  } from '@/api/process'
  import { validObject } from '@/utils'

  export default {
    name: 'TaskSelectDestination',
    props: ['taskId', 'defId', 'instId', 'leaderId', 'currentAlias'],
    data() {
      return {
        relatedInformationDialog: false,
        selectNodeId: '',
        files: '',
        zfiles: '',
        opinion: '',
        selectConfig: {},
        value: '',
        searchList: [],
        jumpNodes: {},
        form: {
          fullname: '',
          id: '',
        },
        jumpType: '',
        formData: {},
        startParams: {},
        isAgree: false,
      }
    },
    computed: {
      ...mapState('process', ['bpmTask', 'curNodeDef']),
      ...mapState({
        curOrgPost: (state) => state.user.postCharge,
      }),
    },
    mounted() {
      this.startParams = {}
      this.setJumpType()
    },
    methods: {
      //鼠标点击页面其他其他位置不关闭弹框
      showDailog(startParams, files, opinion) {
        this.isAgree = startParams.isAgree
        this.startParams = startParams
        this.files = files
        this.opinion = opinion
        const params = {
          taskId: this.taskId || '',
          data: startParams.data || startParams,
          alias: this.currentAlias,
          defId: this.defId || '',
          instId: this.instId || '',
        }
        this.relatedInformationDialog = true
        getAfterJumpNodesByDefId(params).then((res) => {
          this.jumpNodes = res
          this.selectConfig = res
          if (startParams.selectedNodeAndUser) {
            const userIdsMap = startParams.selectedNodeAndUser.nodeUsers.reduce(
              (pre, cur) => {
                pre[cur.nodeId] = cur.selectUserIds
                return pre
              },
              {}
            )
            if (startParams.selectedNodeAndUser.selectNodeId) {
              this.$set(
                this,
                'searchList',
                startParams.selectedNodeAndUser.searchList
              )
            } else {
              this.selectConfig.afterNodes = this.selectConfig.afterNodes.map(
                (item) => {
                  return {
                    ...item,
                    selectUserIds: userIdsMap[item.nodeId] || '',
                  }
                }
              )
              this.setSelectConfigVal()
              this.$set(this, 'searchList', this.selectConfig.afterNodes)
            }
          } else {
            this.setSelectConfigVal()
            this.$set(this, 'searchList', this.selectConfig.afterNodes)
          }
        })
      },
      closeDailog() {
        this.relatedInformationDialog = false
      },
      //搜索
      searchClick() {
        this.searchList = []
        if (this.value) {
          this.selectConfig.afterNodes.forEach((item) => {
            if (item.nodeName.indexOf(this.value) > -1) {
              this.searchList.push(item)
            }
          })
        } else this.searchList = this.selectConfig.afterNodes
      },
      getNodeProperties() {
        let currentNodeProperties = {}
        const nodeProperties = (this.curNodeDef || {}).nodeProperties
        if (nodeProperties && nodeProperties.length) {
          const { nodeProperties, localProperties } = this.curNodeDef
          currentNodeProperties = nodeProperties[0] || localProperties
        }
        return currentNodeProperties
      },
      setJumpType() {
        this.jumpType = this.getNodeProperties()?.jumpType
      },
      getValueByKey(array, key) {
        let value = ''
        if (array && array.length > 0) {
          value = array.map((it) => it[key]).join(',')
        }
        return value
      },
      setSelectConfigVal() {
        if (this.isFree) {
          this.selectConfig = {
            ...this.selectConfig,
            jumpType: this.jumpType,
            choiceExcutor: this.jumpType,
          }
        }
        const { afterNodes } = this.selectConfig
        if (afterNodes?.length === 1) {
          this.selectNodeId = afterNodes[0].nodeId
        }
        // 如果是自由选择，默认带出候选人，然后在再基于候选人进行调整（删减或增加）
        if (
          afterNodes?.length > 0 &&
          this.selectConfig.choiceExcutor &&
          this.selectConfig.choiceExcutor != 'candidate'
        ) {
          this.selectConfig.afterNodes = afterNodes.map((item) => {
            return {
              ...item,
              selectUsers: this.getValueByKey(item.excutorList, 'name'),
              id: this.getValueByKey(item.excutorList, 'id'),
            }
          })
        }
      },
      confirm() {
        if (this.isAgree) {
          const currentSelectNode = this.selectConfig.afterNodes.find(
            (item) => item.nodeId === this.selectNodeId
          )
          const selectNodeName = currentSelectNode
            ? currentSelectNode.nodeName
            : ''
          this.$emit('confirm', {
            selectNodeId: this.selectNodeId,
            nodeUsers: this.getNodeUserList() || [],
            selectNodeName,
            selectConfig: this.selectConfig,
            searchList: this.searchList,
          })
          this.closeDailog()
        } else {
          this.handleSubmit()
        }
      },
      handleSubmit() {
        if (this.taskId) {
          Dialog.confirm({
            title: '提示',
            overlayClass: 'overlay',
            message: '确认办理此任务?',
            closeOnClickModal: false,
            beforeClose: (action, done) => {
              if (action === 'confirm') {
                const data = this.getSubmitData()
                //删除多余参数
                if (data.hasOwnProperty('proInstId')) {
                  delete data.proInstId
                }
                if (data.hasOwnProperty('defId')) {
                  delete data.defId
                }
                if (data.hasOwnProperty('isSendNodeUsers')) {
                  delete data.isSendNodeUsers
                }
                if (data.hasOwnProperty('startOrgId')) {
                  delete data.startOrgId
                }
                if (data.hasOwnProperty('businessKey')) {
                  delete data.businessKey
                }
                if (data.hasOwnProperty('sysCode')) {
                  delete data.sysCode
                }
                savaTaskComplete(data).then((res) => {
                  if (!res.state)
                    return this.$notify({
                      type: 'danger',
                      message: res.message,
                    })
                  this.$notify({ type: 'success', message: res.message })
                  done()
                  this.$router.push({
                    path: '/matter/myTask',
                    query: {
                      type: 'done',
                      tabActiveName: 'done',
                    },
                  })
                })
              } else {
                done()
              }
            },
          }).then(() => {})
        } else {
          this.handleStartProcess()
        }
      },
      handleStartProcess() {
        const data = {
          ...this.getSubmitData(),
          supportMobile: 1,
          defId: this.defId
        }
        //删除多余参数
        if (data.hasOwnProperty('actionName')) {
          delete data.actionName
        }
        if (data.hasOwnProperty('zfiles')) {
          delete data.zfiles
        }
        if (data.hasOwnProperty('jumpType')) {
          delete data.jumpType
        }
        if (data.hasOwnProperty('files')) {
          delete data.files
        }
        if (data.hasOwnProperty('opinion')) {
          delete data.opinion
        }
        this.loading = true
        startProcess(data)
          .then((res) => {
            this.$notify({ type: 'success', message: res.message })
            if (JSON.stringify(this.$route.query) == '{}') {
              this.$router.go(-1)
            } else {
              this.$router.push('/matter/myTask')
            }
          })
          .finally(() => {
            this.loading = false
          })
      },
      //获取点击审批按钮时需要提交的共同数据
      getSubmitCommonData() {
        let formType = ''
        if (this.formType) {
          formType = this.formType.toLowerCase()
        }
        const formData = {
          formType: formType,
          businessKey: this.data?.businessKey || '',
          sysCode: this.data?.sysCode || '',
          vars: this.data?.vars || '',
          data:
            formType === 'inner'
              ? Base64.encode(JSON.stringify(this.data))
              : '',
        }
        const data = {
          taskId: this.taskId,
          actionName: this.alias,
          destination: '',
          zfiles: '',
          jumpType: '',
          agentLeaderId: this.leaderId,
          files: JSON.stringify(this.files),
          ...validObject(formData),
        }
        return data
      },
      getSubmitData() {
        //审批意见回填
        let data = {
          ...this.getSubmitCommonData(),
          formType: this.data?.businessKey ? 'frame' : 'inner',
          proInstId: this.instId || '',
          opinion: this.opinion,
          agentLeaderId: this.leaderId || 0,
          isSendNodeUsers: '1',
          destination: this.selectNodeId,
          ...this.getEffectiveValue(),
        }
        if (this.jumpType) {
          data.jumpType = this.jumpType === 'select' ? 'select' : 'free'
        }
        if (this.startParams.data) {
          data.data = Base64.encode(JSON.stringify(this.startParams.data))
        }
        return data
      },
      getEffectiveValue() {
        const currentUrgentConfig = this.$storage.get('urgentStateValue')
        const data = {
          urgentStateValue: currentUrgentConfig || '',
          nodeUsers: JSON.stringify(this.getNodeUserList()),
          startOrgId: this.curOrgPost?.org?.id,
        }
        return validObject(data)
      },
      getNodeUserList() {
        let nodeUsers = []
        if (this.selectConfig?.choiceExcutor === 'candidate') {
          nodeUsers = this.getCandidateList()
        } else {
          nodeUsers = this.getNodeUsers()
        }
        return nodeUsers.length > 0 ? nodeUsers : ''
      },
      getCandidateList() {
        let candidateList = []
        this.selectConfig?.afterNodes?.map((item) => {
          if (item.selectUserIds?.length > 0) {
            const excutorList = item.excutorList
            const selectUsers = excutorList?.filter((it) => {
              return item.selectUserIds.includes(it.id)
            })
            candidateList.push({
              nodeId: item.nodeId,
              executors: selectUsers,
              selectUserIds: item.selectUserIds,
            })
          }
        })
        return candidateList
      },
      getNodeUsers() {
        let nodeUsers = []
        this.selectConfig?.afterNodes?.map((node) => {
          const currentSelectedUserList = node.selectUsers?.split(',')
          const selectedUserIds = node.id?.split(',')
          if (currentSelectedUserList?.length > 0) {
            const selectUsers = currentSelectedUserList?.map((user, index) => {
              return {
                id: selectedUserIds[index],
                name: user,
                type: 'user',
              }
            })
            nodeUsers.push({
              nodeId: node.nodeId,
              executors: selectUsers,
              selectUserIds: node.id,
            })
          }
        })
        return nodeUsers
      },
      clearNodeOrUser() {
        this.selectNodeId = ''
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/styles/matterButton.scss';
  .van-radio {
    font-size: 14px;
    padding: 0 12px;
  }
  .selectConten {
    padding: 12px 0 16px;
  }
  .more-select {
    ::v-deep .van-field__label {
      margin-left: 22px;
    }
    ::v-deep .van-cell {
      &::after {
        border: none;
      }
    }
  }
  .node-user-list {
    .node-radio {
      height: 48px;
      line-height: 48px;
      border-bottom: 1px solid #f6f6f6;
    }
    .end-node,
    .user-item {
      border-bottom: 10px solid #f6f6f6;
    }
    .user-item {
      &:last-child {
        border-bottom: none;
      }
    }
  }
</style>
