<template>
  <span :class="$style.wapper">
    <sd-value-picker
      :render="renderList"
      :modal-props="{ class: $style.userpicker }"
      v-bind="$props"
      option-value="code"
      :single-column="false"
      @change="change"
    >
      <template v-slot="scope">
        <SdPickerUsersByGroup
          title="按部门"
          icon="apartment"
          v-bind="scope"
          :render="renderList"
          :root-node="rootNode"
          :hierarchical="hierarchical"
          :secret-level="secretLevel"
        />
        <SdPickerUsersByUsergroup
          ref="SdPickerUsersByUsergroup"
          title="个人群组"
          icon="user"
          v-bind="scope"
          :render="renderList"
          :secret-level="secretLevel"
        />
        <SdPickerUsersByDepgroup
          title="部门群组"
          icon="apartment"
          v-bind="scope"
          :render="renderList"
          :root-node="rootNode"
          :hierarchical="hierarchical"
          :secret-level="secretLevel"
        />
        <sd-picker-source-list
          v-if="webflow.flowData"
          title="流程参与人"
          icon="user"
          :load-list-data="() => participant()"
          v-bind="scope"
          :show-search="false"
        />
        <SdPickerUsersByCommon title="常用的" icon="user" v-bind="scope" />
      </template>
      <template v-slot:targetListHeader="{ targetKeys, targetValues }">
        <a-button type="link" icon="save" title="保存群组" @click="userGroupClick(targetValues)" />
      </template>
      <a-icon v-if="!readOnly" slot="suffixIcon" type="user" />
    </sd-value-picker>
    <a-modal
      ok-text="保存"
      cancel-text="退出"
      :mask="true"
      destroy-tooltip-on-hide
      :visible="confirm.confirmvisible"
      @ok="saveconfirm"
      @cancel="cancelconfirm"
    >
      <a-form-model ref="ruleForm" :model="confirm.form" :rules="confirm.rules">
        <a-form-model-item ref="groupName" label="群组名称" prop="groupName">
          <a-input v-model="confirm.form.groupName" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </span>
</template>

<script>
import AddressBook from '@/addressbook/group-user-service'
import PageService from '@/common/services/page-service'
import axios from '@/common/services/axios-instance'
import { Modal, Message } from 'ant-design-vue'
import sdUserinfoCard from '@/common/components/sd-user-item/sd-userinfo-card'
import { sdLocalStorage } from '../services/storage-service'
import pickerMixin from './sd-picker/picker-mixin'
import SdPickerUsersByCommon from './sd-picker/sd-picker-users-by-common.vue'
import SdPickerUsersByGroup from './sd-picker/sd-picker-users-by-group.vue'
import SdPickerUsersByUsergroup from './sd-picker/sd-picker-users-by-usergroup.vue'
import SdPickerUsersByDepgroup from './sd-picker/sd-picker-users-by-depgroup.vue'
import components from './_import-components/sd-user-picker-import'
let saveValues
export default {
  name: 'SdUserPicker',
  components: {
    ...components,
    SdPickerUsersByGroup,
    SdPickerUsersByUsergroup,
    SdPickerUsersByDepgroup,
    SdPickerUsersByCommon,
  },
  mixins: [pickerMixin],
  metaInfo: {
    title: 'SdUsersPicker',
  },
  props: {
    rootNode: {
      type: [Object, Array],
      default: undefined,
    },
    /**
     * 当开启分级授权时，是否过滤掉启用分级授权的子公司，true时过滤,false时不过滤
     *
     */
    hierarchical: {
      type: Boolean,
      default: undefined,
    },
    /**
     * 密级，开启等分保功能后，可按密级过滤人员
     * @since 0.17
     */
    secretLevel: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      confirm: {
        confirmvisible: false,
        pageflowId: '',
        pagePath: '',
        groupData: [],
        form: {
          groupName: '',
        },
        rules: {
          groupName: [{ required: true, message: '请输入群组名称', trigger: ['change', 'blur'] }],
        },
      },
    }
  },
  inject: {
    webflow: { default: () => ({}) },
  },
  methods: {
    // 获取流程参与人
    participant() {
      const params = {}
      if (this.secretLevel) {
        params.securityLevel = this.secretLevel
      }
      return axios
        .get(
          `api/framework/v1/user-manager/instance/${this.webflow.FlowData?.instId || 0}/processors`,
          {
            params,
          }
        )
        .then((res) => {
          return (res.data || []).map((item) => {
            return {
              id: item.id,
              code: item.props.account,
              name: item.text,
              props: item.props,
              type: item.props?.type?.startsWith('G') ? 'Group' : 'User',
            }
          })
        })
        .catch(() => {
          Message.error('获取流程参与人失败')
          return []
        })
    },
    renderList(item) {
      return [
        <span class={this.$style.label}>{item.name}</span>,
        <sdUserinfoCard account={item.code} />,
      ]
    },
    // 打开保存个人组
    userGroupClick(targetValues) {
      if (targetValues.length < 1) {
        Message.warning('请选择人员')
        return
      }
      saveValues = targetValues
      this.confirm.form.groupName = ''
      PageService.get({}, 'personal/usergroup/personalUserGroup').then((res) => {
        if (res.status === 200) {
          this.confirm.groupData = res.data
          this.confirm.confirmvisible = true
        }
      })
    },
    // 关闭组
    cancelconfirm() {
      this.confirm.confirmvisible = false
    },
    // 保存个人组
    saveconfirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const groupName = this.confirm.form.groupName
          // 检查群组名是否存在
          AddressBook.checkExistGroupByName(groupName).then((res) => {
            if (res.data === true) {
              Message.warn('已存在群组名[' + groupName + '],请重新输入！')
              return false
            } else {
              const resJson = this.confirm.groupData
              resJson.pageFormData.pageFieldInfos.forEach((item) => {
                if (item.name === 'groupName') {
                  item.value = this.confirm.form.groupName
                }
                if (item.name === 'members') {
                  item.value = JSON.stringify(saveValues)
                }
              })
              const params = {
                eventId: 'save',
                inputs: resJson.pageFormData.pageFieldInfos.map((v) => ({
                  name: v.name,
                  value: v.value,
                })),
                pageFlowId: resJson.attrs.pageflowId,
                pagePath: resJson.attrs.pagePath,
              }
              PageService.save(params)
                .then((res) => {
                  Message.success('保存成功')
                  this.confirm.confirmvisible = false
                  this.$refs.SdPickerUsersByUsergroup?.updateTree()
                })
                .catch((err) => {
                  Modal.error({
                    title: '保存失败',
                    content: err.response?.data?.message?.split(':')[1] || '保存失败',
                  })
                })
            }
          })
        } else {
          return false
        }
      })
    },
    change(users) {
      // 常用选择人
      let recentUser = JSON.parse(sdLocalStorage.getItem('recentUser') || '[]')
      users.forEach((item) => {
        if (!recentUser.find((user) => user.code === item.code)) {
          recentUser.unshift(item)
        }
      })
      recentUser = recentUser.slice(0, 100)
      sdLocalStorage.setItem('recentUser', JSON.stringify(recentUser))
      this.$emit(
        'change',
        users?.map((item) => {
          return {
            name: item.name,
            code: item.code,
            type: item.type,
          }
        })
      )
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.userpicker {
  :global(.ant-tabs-tabpane):nth-child(1) {
    margin-left: 370px;
  }
  :global(.ant-tabs-tabpane):nth-child(2) {
    margin-left: 270px;
  }
  :global(.ant-tabs-tabpane):nth-child(3) {
    margin-left: 270px;
    :global(.ant-transfer-list):first-child {
      top: 250px;
      height: 250px;
    }
    :global(.source-list-header_sd-value-picker_common) button {
      top: 250px;
    }
  }
  :global(.ant-transfer-list-body-customize-wrapper) {
    > div {
      height: 100%;
    }
  }
  div[mask='true'] {
    display: inline-block;
  }
  a {
    display: none;
  }
  :global(.ant-transfer-list-content-item:not(.ant-transfer-list-content-item-disabled):hover) {
    a {
      display: inline;
    }
  }
  :global(.ant-tabs-left-content) {
    height: 500px;
  }
}
.label {
  display: inline-block;
  width: calc(100% - 42px);
  min-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: top;
}
.wapper {
  width: 100%;
}
</style>
