<template>
  <div :class="$style.query">
    <a-card :class="$style.top">
      <div :class="$style.search">
        <sd-select
          v-model="hierarchy"
          :options="hierarchyOptions"
          :class="$style.select"
          @change="hierarchyChange"
        />
        <a-select v-model="type" :options="options" :class="$style.middle" @change="typeChange" />
        <div :class="[$style.picker, $style.middle]">
          <sd-role-picker
            v-if="type === 'Role'"
            :key="key"
            v-model="codeData"
            :disabled-keys="roleDiskeys"
            single
            :belonged-org-id="hierarchy[0].id"
          />
          <sd-user-picker v-else v-model="codeData" hierarchical single :root-node="rootNode" />
        </div>
        <a-button type="primary" :loading="btnLoading" @click="submit">查询</a-button>
      </div>
      <div :class="[$style.search, $style.check]">
        <span>
          <span :class="$style.label">筛选范围:</span>
          <a-checkbox-group
            v-model="userType"
            :options="userTypeOptions"
            @change="userTypeChange"
          />
        </span>
        <span v-if="type === 'Role'">
          <span :class="$style.label">筛选类型:</span>
          <a-checkbox-group
            v-model="screenType"
            :options="screenTypeOptions"
            @change="screenTypeChange"
          />
        </span>
      </div>
    </a-card>
    <a-card :class="$style.bottom">
      <a-empty v-if="!expressions.length" />
      <sd-data-table
        v-else
        ref="datatable"
        data-url="api/framework/v1/flow-operator/list"
        :columns="columns"
        :actions="actions"
        :row-key="'id'"
        :show-selection="(record) => record.batchModify"
        :filter-expressions="expressions"
        @rowClick="rowClick"
      >
      </sd-data-table>
    </a-card>
    <a-modal v-model="visible" title="批量修改参与者" destroy-on-close :width="700" @ok="handleOk">
      <SdParticipantForm @change="participantChange" />
    </a-modal>
    <SdFlowamendStatus ref="amendStatus" @ok="finishAmend" />
  </div>
</template>

<script>
import { sdLocalStorage } from '@/common/services/storage-service'
import loginService from '@/login/login-service'
import SdFlowamendStatus from '@/flowamend-tools/sd-flowamend-status.vue'
import SdParticipantForm from '@/flowamend-tools/sd-participant-form.vue'
import TableActionTypes from '@/common/services/table-action-types'
import { message } from 'ant-design-vue'
import storeMixin from '@/common/store-mixin'
import components from './_import-components/sd-flowplayer-query-import'
const columns = [
  {
    dataIndex: 'flowName',
    title: '流程',
    defaultSortOrder: 'asc',
    sdClickable: true,
  },
  {
    dataIndex: 'stepName',
    title: '环节',
  },
  {
    dataIndex: 'stepId',
    sdHidden: true,
    defaultSortOrder: 'asc',
  },
  {
    dataIndex: 'operatorName',
    title: '候选参与者',
  },
  {
    dataIndex: 'defaultOperatorName',
    title: '默认参与者',
  },
]
export default {
  name: 'SdFlowplayerQuery',
  metaInfo: {
    title: '流程参与者查询',
  },
  components: { SdParticipantForm, SdFlowamendStatus, ...components },
  mixins: [storeMixin],
  data() {
    return {
      columns,
      type: 'Role',
      visible: false,
      codeData: [],
      options: [
        { label: '角色', value: 'Role' },
        { label: '人员', value: 'User' },
      ],
      userType: ['operator', 'defaultOperator'],
      screenType: ['Role', 'Function'],
      userTypeOptions: [
        { label: '候选参与者', value: 'operator', disabled: false },
        { label: '默认参与者', value: 'defaultOperator', disabled: false },
      ],
      screenTypeOptions: [
        { label: '角色', value: 'Role', disabled: false },
        { label: '策略接口', value: 'Function', disabled: false },
      ],
      expressions: [],
      btnLoading: false,
      hierarchy: [],
      roleDiskeys: [
        'ADMINISTRATOR',
        'SUB_ADMIN',
        'SECURITYADMINISTRATOR',
        'SUB_SECURITY_ADMIN',
        'SECURITYAUDITOR',
        'ANONYMOUS',
        'USER',
      ],
      selectedData: [],
      form: {},
      actions: [
        {
          label: '批量修改',
          id: 'revise',
          type: TableActionTypes.batch,
          permission: null,
          callback: (keys, records) => {
            this.visible = true
            this.selectedData = records
          },
        },
      ],
      key: 0,
    }
  },
  computed: {
    hierarchyOptions() {
      return (this.userInfo.belongedOrgIds || []).map((item) => ({
        id: item.id,
        name: item.text,
        title: item.text,
      }))
    },
    rootNode() {
      let node = {}
      if (this.hierarchy.length) {
        node = { code: this.hierarchy[0].id, name: this.hierarchy[0].title }
      }
      return node
    },
  },
  created() {
    if (this.hierarchyOptions[0]) {
      this.hierarchy = [{ ...this.hierarchyOptions[0] }]
    }
  },
  methods: {
    handleOk() {
      const params = this.selectedData.reduce(
        (res, item) => {
          const findItem = res.find((r) => r.flowId === item.flowId)
          findItem.elements.push(item.stepId)
          return res
        },
        this.selectedData
          .map((item) => {
            return {
              flowId: item.flowId,
              flowName: item.flowName,
              elements: [],
              propInfo: {},
            }
          })
          .filter((s, i, arr) => i === arr.findIndex((a) => a.flowId === s.flowId))
      )
      params.forEach((p) => {
        p.type = 1
        if (this.form.participants) {
          p.propInfo.participants = this.form.participants
        }
        if (this.form.defaultParticipants) {
          p.propInfo.props = {
            defaultParticipants: JSON.stringify(this.form.defaultParticipants),
            defaultParticipantsStrategy: 'range',
          }
        }
      })
      this.$refs.amendStatus.paramsList = params
      this.$refs.amendStatus.open()
    },
    finishAmend() {
      this.visible = false
      this.$refs.datatable.refresh()
    },
    hierarchyChange() {
      this.key++
    },
    typeChange() {
      this.codeData = []
    },
    userTypeChange(value) {
      this.userTypeOptions.forEach((item) => {
        item.disabled = value.includes(item.value) && value.length === 1
      })
    },
    screenTypeChange(value) {
      this.screenTypeOptions.forEach((item) => {
        item.disabled = value.includes(item.value) && value.length === 1
      })
    },
    submit() {
      if (!this.codeData.length)
        return message.warn(`请选择${this.type === 'Role' ? '角色' : '人员'}`)
      this.btnLoading = true
      const baseExpressions = this.userType.map((item) => {
        return {
          expressionsValue: [
            {
              name: item + 'Type',
              op: 'eq',
              stringValue: this.type,
              dataType: 'str',
            },
            {
              name: item + 'Code',
              op: 'eq',
              stringValue: this.codeData[0].code,
              dataType: 'str',
            },
          ].concat(
            this.screenType.length === 1
              ? [
                  {
                    name:
                      item === 'operator' ? 'originalOperatorType' : 'originalDefaultOperatorType',
                    op: 'eq',
                    stringValue: this.screenType[0],
                    dataType: 'str',
                  },
                ]
              : []
          ),
        }
      })
      const expressionsValue =
        this.userType.length === 1
          ? baseExpressions.map((item) => item.expressionsValue)[0]
          : [
              {
                dataType: 'exps',
                op: 'or',
                expressionsValue: baseExpressions.map((item) => {
                  return {
                    dataType: 'exps',
                    op: 'and',
                    expressionsValue: item.expressionsValue,
                  }
                }),
              },
            ]
      this.expressions = [
        ...[
          {
            name: 'belongedOrgId',
            op: 'eq',
            longValue: this.hierarchy[0].id,
            dataType: 'long',
          },
        ],
        ...expressionsValue,
      ]
      this.btnLoading = false
    },
    rowClick(record) {
      loginService.updateAccessToken().then((accessToken) => {
        const sysManageUrl = JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').weSysManage
          ?.sysManageUrl
        const url = `api/ssologin?destUrl=${sysManageUrl}/user/flowNew/userDesigner.jsp%3FdirectModifyFlowId=${
          record.flowId
        }&token=${accessToken.replace('Bearer ', '')}`
        const newWindow = window.open(url, '_blank')
        newWindow.opener = null
      })
    },
    participantChange(form) {
      this.form = form
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.query {
  display: flex;
  flex-direction: column;
  height: 100%;
  .top {
    margin-bottom: 20px;
    .search {
      display: flex;
      align-items: center;
      justify-content: space-around;
      width: 30%;
      margin: 0 auto 10px auto;
      .picker {
        min-width: 220px;
        :global .ant-select {
          width: 100%;
        }
      }
      .middle {
        margin: 0 10px;
      }
      &.check {
        width: 35%;
        .label {
          margin-right: 10px;
        }
      }
    }
  }
  .bottom {
    flex: 1;
  }
}
.border {
  width: 70%;
  padding: 10px;
  margin: 0 auto 20px;
  border: 1px solid #ccc;
  .label {
    margin: 10px;
    font-weight: bold;
  }
}
</style>
