<template>
  <sd-value-picker
    v-bind="pickerMixinProps"
    :modal-props="{
      class: [$style.entrustAdd, { [$style.noApp]: !appsList.length }],
      visible: modalVisible,
    }"
    @change="handleData"
    @cancel="handleCancel"
  >
    <template v-slot="scope">
      <a-card :class="$style.pickerSource">
        <div :class="$style.content">
          <div v-if="appsList.length" :class="$style.header">
            <sd-select
              v-model="selectApp"
              :options="appsList"
              option-label="appName"
              option-value="appCode"
              :class="$style.select"
              @change="appChange"
            />
          </div>
          <sd-picker-source-tree
            ref="treePicker"
            :key="key"
            :load-tree-data="[loadTreeData, loadGroupTreeData, loadModuleTreeData][mode]"
            v-bind="scope"
            :render="(item, direction) => renderItem(item, direction)"
            v-on="$listeners"
          />
        </div>

        <div :class="$style.bottom">
          <a-radio-group v-model="trustDirect">
            <a-radio :value="1">不委托</a-radio>
            <a-radio :value="0">委托</a-radio>
          </a-radio-group>
          <sd-user-picker
            v-show="trustDirect !== 1"
            v-model="trustUser"
            single
            :disabled-keys="disabledUserKeys"
            :class="$style.select"
          />
        </div>
      </a-card>
    </template>
  </sd-value-picker>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import { Message } from 'ant-design-vue'
import AddressBook from '@/addressbook/group-user-service'
import pickerMixin from '@/common/components/sd-picker/picker-mixin'
import businesstypeService from '@/business-type/businesstype-service'
import EntrustService from '../entrust-service'
import components from './_import-components/sd-entrust-add-import'

export default {
  name: 'SdEntrustAdd',
  metaInfo: {
    title: 'SdEntrustAdd',
  },
  components,
  mixins: [pickerMixin],
  props: {
    mode: {
      type: Number,
      default: 0,
    },
    trustor: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      trustDirect: 0,
      selectedData: [],
      trustUser: [],
      selectApp: [],
      modalVisible: true,
      appsList: [],
      key: 0,
    }
  },
  computed: {
    disabledUserKeys() {
      return [getUserInfo().account, this.trustor]
    },
  },
  created() {
    this.getAppsList()
  },
  methods: {
    getAppsList() {
      EntrustService.getApps().then((res) => {
        this.appsList = res.data
        if (this.appsList.length) this.selectApp.push(this.appsList[0])
        this.key++
      })
    },
    appChange(value) {
      this.key++
    },
    loadTreeData(parentCatId = '', parent) {
      // 获取流程树
      if (parent?.expandable === false) {
        return EntrustService.getFlowStep({
          id: parentCatId,
          appCode: this.selectApp[0]?.appCode || '',
        }).then((res) => {
          return res.data.map((item) => {
            return {
              id: item.stepId,
              flowId: item.flowId,
              name: item.name,
              checkable: true,
              isLeaf: true,
              parentFlowName: parent?.name,
              trustModeName: '流程环节',
              trustMode: 'flow-step',
            }
          })
        })
      } else {
        return EntrustService.getFlowsList({
          listFlow: true,
          parentCatId,
          appCode: this.selectApp[0]?.appCode || '',
        })
          .then((res) => {
            if (res.data) {
              return res.data.map((item, index) => {
                return {
                  id: item.id,
                  name: item.text,
                  checkable: !item.expandable,
                  isLeaf: false,
                  expandable: item.expandable,
                  trustModeName: '流程整体',
                  trustMode: 'flow',
                }
              })
            }
          })
          .catch((err) => {
            Message.error(err.response?.data?.errors || '获取失败')
          })
      }
    },
    loadGroupTreeData(id) {
      if (!id) {
        const expandedKey = this.defaultExpandedKeys
        return AddressBook.getGroupTree({
          expandedKey,
          rootNode: this.rootNode,
          hierarchical: this.hierarchical,
          levPath: true,
          trustModeName: '申请部门',
          trustMode: 'department',
        })
      } else {
        return AddressBook.getChildNodes(id, {
          type: 'G',
          isContainSub: false,
          hierarchical: this.hierarchical,
          levPath: true,
        }).then((res) => {
          return res.map((item) => {
            item.checkable = true
            item.trustModeName = '申请部门'
            item.trustMode = 'department'
            return item
          })
        })
      }
    },
    loadModuleTreeData(id, originalValue) {
      let params = {}
      if (id) {
        params = { appId: originalValue.props?.appId, parentId: id }
      }
      params.appCode = this.selectApp[0]?.appCode || ''
      return businesstypeService.getYwlxTree(params).then((res) => {
        return (res.data || []).map((item) => {
          return {
            id: item.id,
            name: item.text,
            checkable: item.props?.isChoice === 'true',
            isLeaf: item.leaf,
            props: item.props,
            trustModeName: '模块',
            trustMode: 'businessType',
          }
        })
      })
    },
    renderItem(item, direction) {
      return <span title={item.name}>{item.name.split('/').pop()}</span>
    },
    handleData(selectedData) {
      let params = selectedData
      if (!this.trustUser.length && this.trustDirect !== 1) {
        Message.warn('请选择委托人')
        return
      }
      if (selectedData.length) {
        params = selectedData.map((item) => {
          return {
            businessCode: this.selectApp[0]?.appCode || '',
            businessName: this.selectApp[0]?.appName || '',
            trusteeName: this.trustUser.length ? this.trustUser[0].name : null,
            trustee: this.trustUser.length ? this.trustUser[0].code : null,
            trustMode: item.trustMode,
            trustModeName: item.trustModeName,
            trustObjectId: item.trustMode === 'flow-step' ? item.flowId : item.id,
            trustObjectExt: item.trustMode === 'flow-step' ? item.id : null,
            trustObjectName:
              item.text ||
              item.name +
                (this.mode === 0 && item.parentFlowName ? `(${item.parentFlowName})` : ''),
            trustDirect: this.trustDirect,
            key: item.id + new Date().getTime(),
          }
        })
      }
      this.modalVisible = false
      this.$emit('change', params)
    },
    handleCancel() {
      this.modalVisible = false
      this.$emit('change')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.entrust-add {
  :global(.ant-modal-body) {
    display: table;
    width: 100%;
    min-height: 630px;
    > div {
      position: relative;
      top: 30px;
      .picker-source {
        position: absolute;
        width: 100%;
        :global .ant-card-body {
          padding: 0;
        }
        .content {
          width: 100%;
          height: 457px;
          overflow: auto;
        }
        .header {
          position: absolute;
          top: -84px;
          .select {
            margin-bottom: 10px;
          }
        }
        .bottom {
          position: absolute;
          bottom: -60px;
          display: flex;
          align-items: center;
          width: 600px;
          height: 40px;
        }
      }
    }

    .select {
      display: inline-block;
      width: 200px;
      :global(.ant-select) {
        width: 100%;
      }
    }
  }
}
.no-app {
  :global(.ant-modal-body) {
    min-height: 600px;
    > div {
      position: relative;
      top: 0;
    }
  }
}
</style>
