<template>
  <view class="ml-approval-select">
    <view class="ml-approval-select-header">
      <view class="ml-approval-select-header-title">审批流程</view>
    </view>
    <view class="ml-approval-select-body">
      <view class="ml-approval-select-list" v-for="(group, gIndex) in flowItems" :key="gIndex">
        <view class="ml-approval-select-flow-line"></view>
        <view class="ml-approval-select-item">
          <view class="ml-approval-select-item-title">{{ group.name }}</view>
        </view>
        <view class="ml-approval-select-users">
          <view class="ml-approval-select-user-item" v-for="(item, uIndex) in group.users" :key="uIndex">
            <image class="ml-approval-select-user-picture" v-if="item.faceImgUrl" :src="item.faceImgUrl" mode="scaleToFill"></image>
            <image class="ml-approval-select-user-picture" v-else src="https://csgc.saas.ddqrcode.com/applet/business/image/portrait2.png" mode="scaleToFill"></image>
            <view class="ml-approval-select-user-name">{{ item.name }}</view>
          </view>
          <view v-if="!rejectApproveJob" class="ml-approval-select-user-add" @click="openAddUser(group)">
            <view class="ml-approval-select-user-add-icon">
              <ml-icon name="add"></ml-icon>
            </view>
          </view>
        </view>
        <view v-if="group.copyRoles && group.copyRoles.length">
          <view class="ml-approval-select-item-title" v-if="!rejectApproveJob || (group.copyUsers)">抄送</view>
          <view class="ml-approval-select-users">
            <view class="ml-approval-select-user-item" v-for="(item, uIndex) in group.copyUsers" :key="uIndex">
              <image class="ml-approval-select-user-picture" src="https://csgc.saas.ddqrcode.com/applet/business/image/portrait2.png" mode="scaleToFill"></image>
              <view class="ml-approval-select-user-name">{{ item.name }}</view>
            </view>
            <view v-if="!rejectApproveJob" class="ml-approval-select-user-add" @click="openAddUser(group, true)">
              <view class="ml-approval-select-user-add-icon">
                <ml-icon name="add"></ml-icon>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <ml-picker-drawer v-model="showPopup" height="600rpx" showFooter @confirm="confirmEvent">
      <ml-list-menu-group type="checkbox" :checked.sync="selectedUserIds">
        <view v-for="(group, gIndex) in selectRoleGroups" :key="gIndex" :title="group.name">
          <view>{{ group.name }}</view>
          <ml-list-menu-item v-for="item in group.userList" :padding="false" :disabled="false" suffixIcon="none"
          :key="item.id"
          :value="item.id">
          <ml-row>
            <ml-col width="80rpx" shrink>
              <image class="ml-approval-picker-drawer-user-picture" src="https://csgc.saas.ddqrcode.com/applet/business/image/portrait2.png" mode="scaleToFill"></image>
            </ml-col>
            <ml-col verticalAlign="center">{{ item.name }}</ml-col>
          </ml-row>
        </ml-list-menu-item>
        </view>
      </ml-list-menu-group>
    </ml-picker-drawer>
  </view>
</template>

<script>
import globalStore from '../../../config/store'

export default {
  name: 'MlApprovalSelect',
  props: {
    value: Array,
    code: String,
    rejectApproveJob: String
  },
  data () {
    return {
      flowItems: [],
      approvalData: {
        flowHandlers: [],
        module: null,
        flowSettingCode: null,
        enableFlag: false
      },
      showPopup: false,
      isAllChecked: false,
      isAllIndeterminate: false,
      checkList: [],
      dataList: [],
      selectFlowItem: null,
      selectedUserIds: [],
      isCopyUser: false
    }
  },
  computed: {
    selectRoleGroups () {
      if (this.selectFlowItem) {
        return (this.selectFlowItem.roleList || []).filter(item => item.id).map(item => {
          const userList = (item.userList || []).map(user => ({ ...user, id: `${user.id}_${item.id}` }))
          return {
            ...item,
            userList
          }
        })
      }
      return []
    },
    selectedUserList () {
      const allUser = []
      this.selectRoleGroups.forEach(element => {
        (element?.userList || []).forEach(ele => {
          allUser.push(ele)
        })
      })
      return allUser.filter(item => this.selectedUserIds.indexOf(item.id) > -1)
    }
  },
  watch: {
    code () {
      this.loadFlow()
    }
  },
  created () {
    this.approvalData.module = this.code
    this.approvalData.flowSettingCode = this.code
    this.loadFlow()
  },
  methods: {
    updateModel () {
      this.$emit('input', this.approvalData)
    },
    async updateFlowItems () {
      await this.$nextTick()
      if (!this.rejectApproveJob) {
        return
      }
      if (globalStore.approval && globalStore.approval.select) {
        const updateMethod = globalStore.approval.select.updateFlowItems
        if (updateMethod) {
          Promise.resolve(updateMethod({
            sysApproveJobId: this.rejectApproveJob,
            flowItems: [...this.flowItems]
          })).then(res => {
            this.flowItems = res
            console.log('updateMethod====', res)
          })
        }
      }
    },
    async loadFlow () {
      await this.$nextTick()
      if (!this.code) {
        return
      }
      if (globalStore.approval && globalStore.approval.select) {
        const loadFlowMethod = globalStore.approval.select.loadFlow
        if (loadFlowMethod) {
          Promise.resolve(loadFlowMethod({
            code: this.code
          })).then(res => {
            this.approvalData.enableFlag = res.enableFlag
            this.approvalData.flowSettingCode = res.flowSettingCode
            this.approvalData.module = res.module
            this.flowItems = res.flowItems
            this.updateFlowItems()
            this.updateModel()
          })
        }
      }
    },
    openAddUser (group, isCopy = false) {
      this.isCopyUser = isCopy
      this.selectFlowItem = group
      // 返选已选中项
      this.selectedUserIds = ((isCopy ? this.selectFlowItem?.copyUsers : this.selectFlowItem?.users) || []).map(item => item.id)
      this.showPopup = true
    },
    mergeMemberIdsByRoleId (list) {
      const userList = []
      const roleIds = []
      list.forEach(item => {
        const [memberId, roleId] = item.id?.split('_')
        const index = roleIds.indexOf(roleId)
        if (index > -1) {
          userList[index].memberIds += `,${memberId}`
        } else {
          roleIds.push(roleId)
          userList.push({
            memberIds: memberId,
            memberNames: item.name,
            roleId: roleId
          })
        }
      })
      return userList
    },
    updateFlowHandlers () {
      const flowHandlers = this.flowItems.map(item => {
        return {
          copierList: this.mergeMemberIdsByRoleId(item.copyUsers || []),
          flowItemSettingId: item.id,
          userList: this.mergeMemberIdsByRoleId(item.users || [])
        }
      })
      this.approvalData.flowHandlers = flowHandlers
    },
    confirmEvent () {
      if (this.isCopyUser) {
        this.selectFlowItem.copyUsers = this.selectedUserList
      } else {
        this.selectFlowItem.users = this.selectedUserList
      }
      console.log(this.flowItems)
      this.showPopup = false
      this.selectedUserIds = []
      this.updateFlowHandlers()
      this.updateModel()
    }
  }
}
</script>

<style lang="scss">
.ml-approval-select {
  background: #ffffff;
  padding: 20rpx;
  border-radius: $ml-border-radius;
  font-size: 30rpx;
  .ml-approval-select-header-title {
    font-weight: 700;
    line-height: 60rpx;
  }
  .ml-approval-select-list {
    position: relative;
    padding-bottom: $ml-border-radius;
    .ml-approval-select-flow-line {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      width: 4rpx;
      background: #D9D9D9;
      &::before {
        content: "";
        position: absolute;
        top: 12rpx;
        left: -10rpx;
        width: 24rpx;
        height: 24rpx;
        border-radius: 50%;
        background: #D9D9D9;
      }
    }
    &:first-child {
      .ml-approval-select-flow-line {
        top: 12rpx;
        &::before {
          top: 0;
        }
      }
    }
    &:last-child {
      .ml-approval-select-flow-line {
        height: 30rpx;
      }
    }
  }
  .ml-approval-select-item-title {
    padding-left: 40rpx;
    line-height: 60rpx;
    font-size: 28rpx;
  }
  .ml-approval-select-users {
    display: flex;
    flex-direction: row;
    padding-left: 40rpx;
  }
  .ml-approval-select-user-item {
    display: flex;
    flex-direction: column;
    padding: 10rpx;
    text-align: center;
    width: 140rpx;
    .ml-approval-select-user-picture {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin: 0 auto;
    }
    .ml-approval-select-user-name {
      display: inline-block;
      vertical-align: middle;
      max-width: 150rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 10rpx;
      font-size: 24rpx;
      color: rgba(0, 0, 0, 0.85);
    }
  }
  .ml-approval-select-user-add {
    display: flex;
    flex-direction: column;
    padding: 10rpx;
    text-align: center;
    .ml-approval-select-user-add-icon {
      width: 80rpx;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 50%;
      font-size: 40rpx;
      color: $ml-theme-primary-color;
      background: #DAE6FF;
      overflow: hidden;
    }
  }
}
.ml-approval-picker-drawer-user-picture {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
}
</style>
