<template>
  <div>
    <sd-value-picker
      :render="renderList"
      :modal-props="{ class: $style.userpicker }"
      v-bind="$props"
      option-value="code"
      :single-column="$props.single"
      v-on="$listeners"
      @change="change"
    >
      <template v-slot="scope">
        <AuditPickerUsersByGroup
          title="按机构"
          icon="apartment"
          v-bind="scope"
          :render="renderList"
          :root-node="rootNode"
          :hierarchical="hierarchical"
          :secret-level="secretLevel"
        />
        <sd-picker-source-list
          title="常用的"
          icon="user"
          :load-list-data="() => recentUser()"
          v-bind="scope"
          :show-search="false"
        />
      </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>
  </div>
</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 '../../../../../../src/common/services/storage-service'
import pickerMixin from './picker-mixin'
import AuditPickerUsersByGroup from './audit-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/audit-user-picker-import'
let saveValues
export default {
  name: 'AuditUserPicker',
  components: {
    ...components,
    AuditPickerUsersByGroup,
    // SdPickerUsersByUsergroup,
    // SdPickerUsersByDepgroup,
  },
  mixins: [pickerMixin],
  metaInfo: {
    title: 'AuditUsersPicker',
  },
  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/xcoa-mobile/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,
            }
          })
        })
        .catch(() => {
          Message.error('获取流程参与人失败')
          return []
        })
    },
    recentUser() {
      // const recents = JSON.parse(sdLocalStorage.getItem('recentUser') || '[]')
      // // 有密级且有常用人时，调用接口按密级过滤
      // if (this.secretLevel && recents.length > 0) {
      //   return axios
      //     .post(`api/xcoa-mobile/v1/user-manager/filter_user_by_securityl`, {
      //       sourceSecurityL: this.secretLevel,
      //       targetUser: recents.map((item) => item.code),
      //     })
      //     .then((res) => recents.filter((item) => (res.data || []).includes(item.code)))
      //     .catch(() => [])
      // } else {
      //   return Promise.resolve(recents)
      // }
      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))
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.userpicker {
  :global(.ant-tabs-tabpane):nth-child(1) {
    margin-left: 270px;
  }
  :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;
}
</style>
