<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <!-- #ifndef MP-WEIXIN -->
      <wk-nav-bar
        title="团队成员"
        :refresh-prev="refreshPrevPage">
        <template v-if="!showEdit">
          <button class="button white-btn" @click="handleToEdit">
            <text class="wk wk-edit edit-icon" />
          </button>
          <button class="button white-btn" @click="handleAdd">
            <text class="wk wk-plus plus-icon" />
          </button>
        </template>
        <template v-else>
          <button class="button white-btn" @click="handleSave">
            保存
          </button>
        </template>
      </wk-nav-bar>
      <!-- #endif -->
      <!-- #ifdef MP-WEIXIN -->
      <wk-nav-bar
        :command-list="commandList"
        :refresh-prev="refreshPrevPage"
        title="团队成员"
        theme="white"
        class="nav-bar"
        @command="handleCommand" />
      <!-- #endif -->

      <view class="container">
        <view v-if="teamList.length > 0" class="list">
          <view v-for="(item, index) in teamList" :key="index" class="list-item">
            <view class="content">
              <view class="info">
                <wk-avatar :name="item.realname" :avatar="item.img" class="avatar" />
                <view class="info-content">
                  <view class="box">
                    <text class="name">
                      {{ item.realname }}
                    </text>
                    <text
                      v-if="!showEdit || Number(item.power) === 3"
                      class="role">
                      {{ getRoleText(item.power) }}
                    </text>
                    <text
                      v-else
                      class="control"
                      @click="handleDelete(index)">
                      &times;
                    </text>
                  </view>
                  <view class="box">
                    <text class="position">
                      {{ item.name }}
                    </text>
                  </view>
                </view>
              </view>
              <view class="permission" @click="handleEdit(item)">
                <view class="label">
                  权限
                </view>
                <view class="text">
                  {{ getPowerText(item.power) }}
                  <text class="wk wk-arrow-right icon" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- #ifdef MP-WEIXIN -->
      <view v-if="showEdit" class="footer-btn-group">
        <button class="button" @click="handleSave">
          保存
        </button>
      </view>
      <!-- #endif -->
    </view>

    <uni-popup ref="popup">
      <view v-if="showEditPop" class="pop-wrapper">
        <view
          v-for="(item, index) in popOptions"
          :key="index"
          class="pop-item"
          @click.stop="handleSelectOptions(item)">
          {{ item.label }}
        </view>
      </view>
      <uni-popup-dialog
        v-else
        :content="dialogMsg"
        type="warning"
        @confirm="handleDialogConfirm" />
    </uni-popup>
  </view>
</template>

<script>
  import {
    GetMembers as CustomerGet,
    DeleteMembers as CustomerDelete,
    UpdateMembers as CustomerUpdate
  } from 'API/crm/customer'
  import {
    GetMembers as BusinessGet,
    DeleteMembers as BusinessDelete,
    UpdateMembers as BusinessUpdate
  } from 'API/crm/business'
  import {
    GetMembers as ContractGet,
    DeleteMembers as ContractDelete,
    UpdateMembers as ContractUpdate
  } from 'API/crm/contract'

  export default {
    name: 'GroupIndex',
    data() {
      return {
        id: null,
        type: null,
        routerQuery: {},

        teamList: [],
        deleteList: [],
        editItem: null,

        showEdit: false,
        showEditPop: false,
        dialogMsg: '',
        popType: null,

        popOptions: [
          {label: '只读', value: 1},
          {label: '读写', value: 2}
        ],
        apiMap: {
          customer: {
            get: CustomerGet,
            delete: CustomerDelete,
            update: CustomerUpdate,
            fields: 'id'
          },
          business: {
            get: BusinessGet,
            delete: BusinessDelete,
            update: BusinessUpdate,
            fields: 'id'
          },
          contract: {
            get: ContractGet,
            delete: ContractDelete,
            update: ContractUpdate,
            fields: 'id'
          }
        },

        commandList: [
          {
            label: '编辑',
            imgIcon: 'update',
            auth: '',
            value: 'update'
          },
          {
            label: '新增成员',
            icon: 'wk-plus',
            auth: '',
            value: 'add'
          },
        ],

        refreshPage: false, // 刷新页面标志
        refreshPrevPage: false
      }
    },
    onLoad(options) {
      this.routerQuery = options
      this.id = options.id
      this.type = options.type
      if (this.apiMap.hasOwnProperty(this.type)) {
        this.getTeamList()
      }
    },
    onShow() {
      if (this.refreshPage) {
        this.$nextTick(() => {
          this.refreshPage = false
          this.refreshPrevPage = true
          this.getTeamList()
        })
      }
    },
    onBackPress(evt) {
      if (evt.from === 'backbutton' && this.refreshPrevPage) {
        this.$refreshAndToPrev(this)
        return true // 返回值为 true 时，表示不执行默认的返回
      }
      return false
    },
    methods: {
      getPowerText(power) {
        return {
          1: '只读',
          2: '读写',
          3: '负责人权限'
        }[power]
      },
      getRoleText(power) {
        // 3 负责人 1 2 普通员工
        if (Number(power) === 3) return '负责人'
        return '普通员工'
      },

      getTeamList() {
        this.deleteList = []
        this.apiMap[this.type].get({
          id: this.id,
        }).then(res => {
          console.log('teamList: ', res)
          this.teamList = res
        })
      },

      handleCommand(command) {
        if (command.value === 'update') {
          this.handleToEdit()
        } else {
          this.handleAdd()
        }
      },

      handleAdd() {
        this.$Router.navigateTo({
          url: '/pages_crm/group/add',
          query: this.routerQuery
        })
      },

      /**
       * 点击删除
       */
      handleDelete(index) {
        this.deleteList.push(this.teamList[index].userId)
        this.deleteList = [...new Set(this.deleteList)]
        this.teamList.splice(index, 1)
      },

      handleToEdit() {
        this.showEdit = !this.showEdit
      },

      handleEdit(item) {
        if (Number(item.power) === 3) {
          this.$toast('不允许编辑负责人')
          return
        }
        this.showEditPop = true
        this.editItem = item
        this.$refs.popup.open()
      },

      handleSelectOptions(opt) {
        this.dialogMsg = '确定要修改权限吗？'
        this.showEditPop = false
        this.editItem.powerValue = opt.value
        this.popType = 'update'
      },

      handleSave() {
        if (this.deleteList.length === 0) {
          this.showEdit = !this.showEdit
          this.deleteList = []
          return
        }
        this.dialogMsg = '确定要保存更改吗？'
        this.showEditPop = false
        this.popType = 'save'
        this.$refs.popup.open()
      },

      handleDialogConfirm(next) {
        switch (this.popType) {
        case 'update':
          this.apiMap[this.type].update({
            ids: [this.id],
            memberIds: [this.editItem.userId],
            power: this.editItem.powerValue
          }).then(response => {
            this.$toast('修改成功')
            this.showEdit = false
            this.refreshPrevPage = true
            this.getTeamList()
          }).catch()
          this.editItem = null
          break
        case 'save':
          this.showEdit = !this.showEdit
          this.apiMap[this.type].delete({
            ids: [this.id],
            memberIds: this.deleteList
          }).then(response => {
            this.deleteList = []
            this.$toast('删除成功')
            this.refreshPrevPage = true
            this.getTeamList()
          }).catch()
          break
        }
        next()
      }
    }
  }
</script>

<style scoped lang="scss">
.edit-icon {
  font-weight: bold;
}
.edit-icon, .plus-icon {
  font-size: 36rpx;
  line-height: 1;
}

.container {
  width: 100%;
  flex: 1;
  overflow: auto;
  padding-bottom: 20rpx;
  margin-top: 20rpx;

  .list {
    width: 100%;
    background-color: white;
    .list-item {
      border-bottom: 1rpx solid $border-color;
      display: flex;
      .content {
        flex: 1;
        padding-right: 30rpx;
        .info {
          @include left;
          .avatar {
            width: 70rpx;
            height: 70rpx;
            border-radius: 50%;
            margin: 0 26rpx 0 30rpx;
          }
          .info-content {
            flex: 1;
            border-bottom: 1rpx solid $border-color;
            padding: 28rpx 0 26rpx 0;
            .box {
              @include left;
              .name {
                flex: 1;
                font-size: 32rpx;
                color: $dark;
              }
              .role {
                font-size: 26rpx;
                color: $light;
              }
              .control {
                font-size: 42rpx;
                color: #FF6767;
                line-height: 1;
              }
              .position {
                font-size: 26rpx;
                color: $light;
                line-height: 2;
              }
            }
          }
        }

        .permission {
          height: 80rpx;
          font-size: 26rpx;
          color: $gray;
          margin-left: 126rpx;
          @include left;
          .label {
            flex: 1;
          }
          .text {
            line-height: 1;
            @include left;
            .icon {
              font-size: 24rpx;
              color: $light;
              margin-left: 26rpx;
            }
          }
        }
      }

      &:last-child {
        border-bottom: 0 none;
      }
    }
  }
}
</style>
