<template>
  <div class="tab-content" id="PTtab-10" :key="'PTtab-10'" >
    <div>
      <div class="pagenamPT">
        <h3 class="pagename2 w100w">접속중인회원</h3>
      </div>
      <div class="PTsch">
        <select>
          <option value="memId" selected>아이디</option>
          <option value="memNick">닉네임</option>
          <option value="recommenderId">상위유저</option>
        </select>
        <input type="text" :placeholder="$t('front.search.emptySearch')" v-model="searchMemId"/>
        <a @click="getPartnerList(1)">
          <img src="@/assets/img/search.png" alt=""/>
        </a>
      </div>
      <div class="strTablescr">
         <div class="strTablePC">
            <table class="strTablePT">
              <colgroup>
                <col width="9%">
                <col width="9%">
                <col width="12%">
                <col width="12%">
                <col width="13%">
                <col width="16%">
              </colgroup>
              <thead>
                <tr>
                  <th>아이디</th>
                  <th>닉네임</th>
                  <th>보유금</th>
                  <th>보유포인트</th>
                  <th>로그인 일시</th>
                  <th>머니 관리</th>
                </tr>
              </thead>
              <tbody>
                <template v-if="loginMemList.length > 0">
                  <template v-for="(item) in loginMemList" :key="item.memId">
                    <tr>
                      <td>{{item.memId}}</td>
                      <td>{{item.memNick}}</td>
                      <td>{{thousand(item.cashAmt)}}</td>
                      <td>{{thousand(item.pointAmt)}}</td>
                      <td>{{item.loginDt}}</td>
                      <td class="poin">
                        <a class="btnRed btn2 btn3" @click="onOpenMoneyPopup(item)">지급/회수</a>
                      </td>
                    </tr>
                  </template>
                </template>

              </tbody>
            </table>
         </div>
         <div class="strTableM">
            <div class="strTablePTM">
               <ul>
                  <template v-if="loginMemList.length > 0">
                    <template v-for="(item) in loginMemList" :key="item.memId">
                        <li><em>아이디</em>{{item.memId}}</li>
                        <li><em>닉네임</em>{{item.memNick}}</li>
                        <li><em>보유금</em>{{thousand(item.cashAmt)}}</li>
                        <li><em>보유포인트</em>{{thousand(item.pointAmt)}}</li>
                        <li><em>로그인 일시</em>{{item.loginDt}}</li>
                        <li><em>머니관리</em>
                          <a class="bgr btn2 btn3" @click="onOpenMoneyPopup(item)">지급/회수</a>
                        </li>
                     </template>
                   </template>
               </ul>
            </div>
         </div>
      </div>
    </div>

    <div v-if="openMoneyMovePopup" class="moneyg">
      <a class="close" @click="onCloseMoneyPopup(moveTarget)"><img src="@/assets/img/icon_cancelB.svg" /></a>
      <h2>보유머니: <span>{{thousand(moveTarget.cashAmt)}}</span></h2>
      <input type="text" pattern="[0-9.,]+" :placeholder="$t('front.give.moneyInput')" v-model="moveTarget.inputCashAmt" @keyup="updateCashAmt(item, $event.target.value)" />
      <div class="mbtn">
        <a @click="setMoney(moveTarget, 10000)">1{{$t('front.cash.manwon')}}</a>
        <a @click="setMoney(moveTarget, 30000)">3{{$t('front.cash.manwon')}}</a>
        <a @click="setMoney(moveTarget, 50000)">5{{$t('front.cash.manwon')}}</a>
        <a @click="setMoney(moveTarget, 100000)">10{{$t('front.cash.manwon')}}</a>
      </div>
      <div class="mbtn">
        <a @click="setMoney(moveTarget, 30000)">3{{$t('front.cash.manwon')}}</a>
        <a @click="setMoney(moveTarget, 50000)">5{{$t('front.cash.manwon')}}</a>
        <a @click="setMoney(moveTarget, 100000)">10{{$t('front.cash.manwon')}}</a>
        <a @click="setMoney(moveTarget, 0)" style="background: #730000;">{{$t('front.cash.correct')}}</a>
      </div>
      <div class="submit">
        <a class="bgb btn2" @click="memCash('-3', moveTarget)">{{$t('front.give.give')}}</a>
        <a class="bgr btn2" @click="memCash('3', moveTarget)">{{$t('front.give.back')}}</a>
      </div>
    </div>
  </div>
</template>

<script>

import {
  getRetailMyMemList, partnerLevels, partnerMyMemIds, getRetailMyLoginMem
} from '@/api/retail'
import { thousand } from '@/libs/utils'
import { memCashInOut } from '@/api/give'
import { mapState } from 'vuex'
import { PARTNER_LEVEL_NAME } from '@/libs/constants'

export default {
  name: 'onlineMemberList',
  computed: {
    ...mapState([
      'userData',
      'gameCount',
      'commonCodeByOrder',
      'commonCodeByCode'
    ]),
    partnerLevelName () {
      console.log(this.item.partnerLevel)
      return PARTNER_LEVEL_NAME[this.item.partnerLevel]
    },
    formattedCashAmt () {
      if (!this.cashAmt) return ''
      return this.cashAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
  },
  data () {
    return {
      searchType: 'N',
      searchPartnerLevel: '',
      partnerLevelList: [],
      partnerList: [],
      partnerLevelObject: null,
      summaryNew: null,
      searchMemId: '',
      cashAmt: '',
      selectMem: {
        cashAmt: ''
      },
      list: [],
      isProcessing: false,
      moveTarget: null,
      loginMemList: [],
      openMoneyMovePopup: false
    }
  },
  async created () {
    this.emitter.emit('Loading', true)
    this.getPartnerLevels()
    this.getPartnerList(1)
    await this.getLoginMember()
    this.emitter.emit('Loading', false)
  },
  watch: {
    selectPartnerCode () {
      if (this.selectPartnerCode) {
        this.selectMem.cashAmt = ''
        this.getMyMemIds()
      }
    },
    selectMem () {
      if (this.selectMem) {
        this.selectMem.cashAmt = thousand(this.selectMem.cashAmt)
      }
    }
  },
  methods: {
    thousand,
    async getLoginMember () {
      const res = await getRetailMyLoginMem()
      console.log('getRetailMyLoginMem : ', res)
      const result = res.data
      if (result.resultCode === '0') {
        this.loginMemList = result.data.loginMemList
      }
    },
    onOpenMoneyPopup (value) {
      this.moveTarget = value
      this.moveTarget.inputCashAmt = ''
      this.openMoneyMovePopup = true
    },
    onCloseMoneyPopup (value) {
      this.moveTarget = null
      this.openMoneyMovePopup = false
    },
    parseFormattedValue (value) {
      return value.replace(/,/g, '')
    },
    getMyMemIds () {
      const params = {
        code: this.selectPartnerCode,
        masterCode: 'partner'
      }
      partnerMyMemIds(params).then(res => {
        const result = res.data
        if (result.resultCode === '0') {
          this.myMemIdsList = result.data.memIds
        }
      })
    },
    getPartnerList (page) {
      this.emitter.emit('Loading', true)
      if (!page) {
        page = this.pageInfo.page
      }
      const params = {
        searchMemId: this.searchMemId,
        page: page,
        partnerLevel: this.searchPartnerLevel,
        searchType: this.searchType,
        count_per_list: 40
      }
      console.log('[REQ]getRetailMyMemList : ', params)
      getRetailMyMemList(params).then(res => {
        console.log('[RES]getRetailMyMemList : ', res.data)
        this.emitter.emit('Loading', false)
        const result = res.data
        if (result.resultCode === '0') {
          console.log(result.list)
          this.partnerList = result.data.list

          this.partnerList.forEach(item => {
            item.inputCashAmt = ''
          })

          if (result.data.pageInfo) {
            this.pageInfo = result.data.pageInfo
          }
        }
      })
    },
    getPartnerLevels () {
      partnerLevels({}).then(res => {
        const result = res.data
        if (result.resultCode === '0') {
          console.log('partnerLevel : ', result.data)
          this.partnerLevelList = result.data.list
          this.newPartnerLevel = result.data.list[0]

          const partnerObj = {}
          for (let i = 0; i < this.partnerLevelList.length; i++) {
            const item = this.partnerLevelList[i]
            const code = item.code
            const codeName = item.codeName

            if (!partnerObj[code]) {
              partnerObj[code] = codeName
            }
          }

          this.partnerLevelObject = partnerObj
        }
      })
    },
    async memCash (type, item) {
      const memId = item.memId
      const cashStr = item.inputCashAmt
      console.log(item)
      if (!cashStr) {
        await this.onAlert('warningart', 'front.give.moneyInput')
        return false
      }

      if (!memId) {
        await this.onAlert('warningart', '회원 아이디를 선택해주세요.')
        return false
      }

      if (!this.isProcessing) {
        const cash = Number(cashStr.replace(/,/g, ''))
        this.isProcessing = true

        const params = {
          memId: memId
        }
        if (type === '-3') {
          params.inAmt = cash
        } else {
          params.outAmt = cash
        }

        const message = this.$t('front.cash.moneyMoveConfirm', { memNick: memId, cashAmt: cashStr, type: type === '-3' ? '지급' : '회수' })

        const confirm = await this.onConfirm(message)
        if (confirm) {
          this.emitter.emit('Loading', true)
          memCashInOut(params, type).then(async response => {
            const result = response.data
            console.log(result)
            this.emitter.emit('Loading', false)
            if (result.resultCode === '0') {
              if (type === '-3') {
                await this.onCheck('지급 완료')
              } else {
                await this.onCheck('회수 완료')
              }
              item.inputCashAmt = ''
              this.onCloseMoneyPopup(this.moveTarget)
              await this.getLoginMember()
            } else {
              await this.onAlert('warningart', result.resultMessage)
            }
            this.isProcessing = false
          })
        } else {
          this.isProcessing = false
        }
      }
    },
    updateCashAmt (item, value) {
      const parts = item.inputCashAmt.split('.')
      const v = parts[0].replace(/\D/g, '')
      const dec = parts[1]
      let n = new Intl.NumberFormat('en-EN').format(v)
      n = dec !== undefined ? n + '.' + dec : n
      if (v === '0' || v === '') {
        item.inputCashAmt = ''
      } else {
        item.inputCashAmt = n
      }
    },
    setMoney (item, value) {
      const currentMoney = Number(item.inputCashAmt.replace(/,/g, ''))
      console.log(currentMoney)
      if (value === 0) {
        item.inputCashAmt = (value).toString()
      } else {
        item.inputCashAmt = (currentMoney + value).toString()
      }
      this.updateCashAmt(item)
    }
  }
}
</script>
<style scoped src="@/styles/striNew.css"></style>
