<template>
  <div class="tab-content" id="PTtab-7" :key="'PTtab-7'">
    <ul class="tablist">
      <li class="tabmenu" data-tab="moneytab_2" @click="currentTab = 'moneytab_2'" :class="{'current': currentTab == 'moneytab_2'}">하부머니 지급/회수 내역</li>
      <li class="tabmenu" data-tab="moneytab_1" @click="currentTab = 'moneytab_1'" :class="{'current': currentTab == 'moneytab_1'}">하부머니 지급/회수</li>
    </ul>
    <div id="moneytab_1" :key="'moneytab_1'" class="tab-content" v-if="currentTab == 'moneytab_1'">
      <!--div class="pagenamPT">
        <h3 class="pagename2">{{$t('front.give.title1')}}</h3>
      </div-->
      <div id="userMoney">
        <ul>
          <li>
            <h4>하부등급목록</h4>
            <select v-model="selectPartnerCode">
              <option value="" disabled selected>{{$t('front.give.bottomPatner')}}</option>
              <template v-for="item in partnerLevelList" v-bind:key="item.code">
                <option :value="item.code">{{item.codeName}}</option>
              </template>
            </select>
          </li>
          <li>
            <h4>하부등급목록</h4>
            <select v-model="selectMem" style="width: 200px">
              <option value="" disabled selected>{{$t('front.give.resultIDs')}}</option>
              <template v-for="member in myMemIdsList" v-bind:key="member.memId">
                <option :value="member">{{member.memId}}({{member.memNick}})</option>
              </template>
            </select>
          </li>
          <li class="w100w">
            <h4>대상 아이디 보유금</h4>
            <input type="text" :placeholder="$t('front.give.targetMoney')" v-model="selectMem.cashAmt" readonly class="w100w"/>
          </li>
          <li class="w100w">
            <h4>금액</h4>
            <input type="text" :placeholder="$t('front.give.moneyInput')" :value="formattedCashAmt" @input="cashAmt = parseFormattedValue($event.target.value)" class="w100w"/>
          </li>
          <li>
            <div class="btnWrap2">
              <a class="bgb" @click="memCash('-3')">{{$t('front.give.give')}}</a>
              <a class="bgr" @click="memCash('3')">{{$t('front.give.back')}}</a>
            </div>
          </li>
        </ul>
      </div>
      <div class="pagenamPT">
        <h3 class="pagename2">현재 접속중인 회원</h3>
      </div>
      <div>
        <div class="strTablescr">
          <div class="strTablePC">
              <table class="strTablePT">
                <colgroup>
                  <col width="10%">
                  <col width="10%">
                  <col width="10%">
                  <col width="10%">
                  <col width="10%">
                </colgroup>
                <thead>
                <tr>
<!--                  <th>IDX</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>23</td>-->
                        <td>{{item.memId}}</td>
                        <td>{{item.memNick}}</td>
                        <td>{{thousand(item.cashAmt)}}</td>
                        <td>{{dateFormatAll(item.loginDt)}}</td>
                        <td>{{thousand(item.totalLoginCount)}}</td>
<!--                        <td>-->
<!--                          <a class="bgb btn">{{$t('front.give.give')}}</a>-->
<!--                          <a class="bgr btn">{{$t('front.give.back')}}</a>-->
<!--                        </td>-->
                      </tr>
                    </template>
                  </template>
                  <template v-else>
                    <tr>
                      <td colspan="6">현재 접속 중인 회원이 없습니다.</td>
                    </tr>
                  </template>
                </tbody>
              </table>
          </div>
          <div class="strTableM">
              <div class="strTablePTM">
                <template v-if="loginMemList.length > 0">
                    <template v-for="(item) in loginMemList" :key="item.memId">
                      <ul>
                        <li><em>아이디</em>{{item.memId}}</li>
                        <li><em>닉네임</em>{{item.memNick}}</li>
                        <li><em>보유금</em>{{thousand(item.cashAmt)}}</li>
                        <li><em>로그인 시간</em>{{dateFormatAll(item.loginDt)}}</li>
                        <li><em>로그인 횟수</em>{{thousand(item.totalLoginCount)}}</li>
                      </ul>
                    </template>
                  </template>
                  <template v-else>
                  <ul>
                      <li class="nodata">내역 없음</li>
                  </ul>
                </template>
              </div>
          </div>
        </div>

        <pagination v-if="pageInfo"
                    :pageNum="pageInfo.page"
                    :pageSize="pageInfo.count_per_list"
                    :totalCount="pageInfo.tatal_list_count"
                    :className="'partnerPaging'"
                    @goToPage="loadData"
        />
      </div>
    </div>
    <div id="moneytab_2" :key="'moneytab_2'" class="tab-content" v-if="currentTab == 'moneytab_2'">
      <!--div class="pagenamew">
        <h3 class="pagename2">{{$t('front.give.title2')}}</h3>
      </div-->
      <div class="datesearchPT">
        <p>{{$t('front.give.date')}}:
          <input type="date" :value="searchForm.startDate" @change="onChangeStartDate"/>
          <span>~</span>
          <input type="date" :value="searchForm.endDate" @change="onChangeEndDate" class="mobile_margin"/>
        </p>
        <ul>
          <li>
            받은 아이디: <input type="text" v-model="searchForm.botMemId"/>
          </li>
          <li>
            성공처리여부:
            <select v-model="searchForm.cashStatus" class="w183">
              <option :value="''">{{$t('front.gameCategory.all')}}</option>
              <option :value="'1'">{{$t('front.give.ok')}}</option>
              <option :value="'-1'">{{$t('front.give.fail')}}</option>
            </select>
          </li>
          <li>
            종류:
            <select v-model="searchForm.cashType" class="w183">
              <option :value="''">{{$t('front.gameCategory.all')}}</option>
              <option :value="'-3'">{{$t('front.give.give')}}</option>
              <option :value="'3'">{{$t('front.give.back')}}</option>
            </select>
          </li>
          <li>
            <a @click="loadData(1)">
              <img src="@/assets/img/search.png" alt=""/>
            </a>
          </li>
        </ul>
      </div>
      <div class="datesearchM moveM">
        <ul>
          <li>
            <em>{{$t('front.give.date')}}</em>:
            <input type="date" :value="searchForm.startDate" @change="onChangeStartDate" class="mobiledate"/>
            <span>~</span>
            <input type="date" :value="searchForm.endDate" @change="onChangeEndDate" class="mobile_margin mobiledate"/>
          </li>
          <li>
            <em>받은 아이디</em>: <input type="text" v-model="searchForm.botMemId" class="w183"/>
          </li>
          <li>
            <em>성공처리여부</em>:
            <select v-model="searchForm.cashStatus" class="w183">
              <option :value="''">{{$t('front.gameCategory.all')}}</option>
              <option :value="'1'">{{$t('front.give.ok')}}</option>
              <option :value="'-1'">{{$t('front.give.fail')}}</option>
            </select>
          </li>
          <li>
            <em>종류</em>:
            <select v-model="searchForm.cashType" class="w183">
              <option :value="''">{{$t('front.gameCategory.all')}}</option>
              <option :value="'-3'">{{$t('front.give.give')}}</option>
              <option :value="'3'">{{$t('front.give.back')}}</option>
            </select>
          </li>
          <li class="PTsch">
            <a @click="loadData(1)">
              <img src="@/assets/img/search.png" alt=""/>
            </a>
          </li>
        </ul>
      </div>
      <div class="strTableWrap">
        <div class="subMemWrap">
          <!-- <p class="p10"></p> -->
          <ul class="subPT_1">
            <!-- <li>
              <a>
                <span class="box" :class="userData.partnerLevel">{{partnerLevelName(userData.partnerLevel)}}</span>
                {{userData.memId}}
              </a>
            </li> -->
            <h3>하부 파트너 목록<a @click="idlist=!idlist">i</a><span v-if="idlist" @click="idlist=!idlist">아이디 클릭시 목록 출력</span></h3>
            <li v-for="(item1) in partnerList" :key="item1.memId" :class="{'morebar':item1.open}">
              <span class="arr" v-if="item1.cnt" :class="[item1.partnerLevel, {'moreOn':item1.open}]" @click="listOpen(item1.memId, 'sub', item1)"></span>
              <span class="arr normal" v-if="!item1.cnt"></span>
              <a :class="[item1.partnerLevel, { 'active': selectedLi === item1.memId }]" @click="getMyPartnerList(item1.memId, 'sub', item1)">
                <span class="box" :class="item1.partnerLevel">본사</span>
                {{item1.memId}}
              </a>

              <ul class="subPT_2" v-show="item1.open && item1.children">
                <li v-for="item2 in item1.children" :key="item2.memId" :class="{'morebar':item2.open}">
                  <span class="arr" v-if="item2.cnt" :class="[item2.partnerLevel, {'moreOn':item2.open}]" @click="listOpen(item2.memId, 'sub', item2)"></span>
                  <span class="arr normal" v-if="!item2.cnt"></span>
                  <a :class="[item2.partnerLevel, { 'active': selectedLi === item2.memId }]" @click="getMyPartnerList(item2.memId, 'sub', item2)">
                    <span class="box" :class="item2.partnerLevel">부본</span>
                    {{item2.memId}}
                  </a>

                  <ul class="subPT_3" v-show="item2.open && item2.children">
                    <li v-for="item3 in item2.children" :key="item3.memId" :class="{'morebar':item3.open}">
                      <span class="arr" v-if="item3.cnt" :class="[item3.partnerLevel, {'moreOn':item3.open}]" @click="listOpen(item3.memId, 'sub', item3)"></span>
                      <span class="arr normal" v-if="!item3.cnt"></span>
                      <a :class="[item3.partnerLevel, { 'active': selectedLi === item3.memId }]" @click="getMyPartnerList(item3.memId, 'sub', item3)">
                        <span class="box" :class="item3.partnerLevel">{{partnerLevelName(item3.partnerLevel)}}</span>
                        {{item3.memId}}
                      </a>

                      <ul class="subPT_4" v-show="item3.open && item3.children">
                        <li v-for="item4 in item3.children" :key="item4.memId" :class="{'morebar':item4.open}">
                          <span class="arr" v-if="item4.cnt" :class="[item4.partnerLevel, {'moreOn':item4.open}]" @click="listOpen(item4.memId, 'sub', item4)"></span>
                          <span class="arr normal" v-if="!item4.cnt"></span>
                          <a :class="[item4.partnerLevel, { 'active': selectedLi === item4.memId }]" @click="getMyPartnerList(item4.memId, 'sub', item4)">
                            <span class="box" :class="item4.partnerLevel">{{partnerLevelName(item4.partnerLevel)}}</span>
                            {{item4.memId}}
                          </a>
                        </li>
                      </ul>
                    </li>
                  </ul>
                </li>
              </ul>
            </li>
          </ul>
        </div>
        <div class="strTablescr">
          <div class="strTablePC">
            <table class="strTablePT">
              <colgroup>
                <col width="10%">
                <col width="10%">
                <col width="10%">
                <col width="10%">
                <col width="10%">
                <col width="10%">
                <col width="10%">
                <col width="10%">
                <col width="10%">
                <col width="10%">
              </colgroup>
              <thead>
              <tr>
                <th>IDX</th>
                <th>받은아이디</th>
                <th>닉네임</th>
                <th>내용</th>
                <th>전송금액</th>
                <th>처리 후 캐시</th>
                <th>내 보유 캐시</th>
                <th>전송일시</th>
                <th>처리 여부</th>
                <th>비고</th>
              </tr>
              </thead>
              <tbody>
                <template v-if="list.length > 0">
                  <template v-for="(item, index) in list" v-bind:key="item.cashIdx">
                    <tr>
                      <td>{{((pageInfo.page-1) * 10) +  (index + 1)}}</td>
                      <td>{{item.botMemId}}</td>
                      <td>{{item.botMemNick}}</td>
                      <td class="blc" v-if="item.cashType === '-3'">{{$t('front.give.give')}}</td>
                      <td class="rdc" v-else>회수</td>
                      <td :class="{'rdc': item.cashType ==='3', 'blc':item.cashType ==='-3'}">{{thousand(item.cashAmt)}}</td>
                      <td>{{thousand(item.aftCashAmt)}}</td>
                      <td>{{thousand(item.preCashAmt)}}</td>
                      <td>{{dateFormatAll(item.regDate)}}</td>
                      <td class="blc" v-if="item.cashStatus === '1'">O</td>
                      <td class="rdc" v-else>X</td>
                      <td>{{item.memo}}</td>
                    </tr>
                  </template>
                </template>
              </tbody>
            </table>
          </div>
          <div class="strTableM">
              <div class="strTablePTM">
                <template v-if="list.length > 0">
                    <template v-for="(item, index) in list" v-bind:key="item.cashIdx">
                      <ul>
                        <li><em>IDX</em>{{((pageInfo.page-1) * 10) +  (index + 1)}}</li>
                        <li><em>받은아이디</em>{{item.botMemId}}</li>
                        <li><em>닉네임</em>{{item.botMemNick}}</li>
                        <li class="blc" v-if="item.cashType === '-3'"><em>내용</em>{{$t('front.give.give')}}</li>
                        <li class="rdc" v-else><em>내용</em>회수</li>
                        <li :class="{'rdc': item.cashType ==='3', 'blc':item.cashType ==='-3'}"><em>전송금액</em>{{thousand(item.cashAmt)}}</li>
                        <li><em>처리 후 캐시</em>{{thousand(item.aftCashAmt)}}</li>
                        <li><em>내 보유 캐시</em>{{thousand(item.preCashAmt)}}</li>
                        <li><em>전송일시</em>{{dateFormatAll(item.regDate)}}</li>
                        <li class="blc" v-if="item.cashStatus === '1'"><em>처리 여부</em>O</li>
                        <li class="rdc" v-else><em>처리 여부</em>X</li>
                        <li><em>비고</em>{{item.memo}}</li>
                      </ul>
                    </template>
                  </template>
                  <template v-else>
                  <ul>
                      <li class="nodata">내역 없음</li>
                  </ul>
                </template>
              </div>
          </div>
        </div>
      </div>
      <pagination v-if="pageInfo && currentTab === 'moneytab_2'"
                  :pageNum="pageInfo.page"
                  :pageSize="pageInfo.count_per_list"
                  :totalCount="pageInfo.tatal_list_count"
                  :className="'partnerPaging'"
                  @goToPage="loadData"
      />
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/ui/Pagination.vue'
import { getCashSendList, memCashInOut } from '@/api/give'
import { getDateStr, getSubDaysDate, thousand } from '@/libs/utils'
import { getRetailMyLoginMem, partnerLevels, partnerMyMemIds, retailMyPartnerDirectList } from '@/api/retail'
import { PARTNER_LEVEL_NAME } from '@/libs/constants'
import { mapState } from 'vuex'

export default {
  name: 'PartnerMoneyMove',
  components: { Pagination },
  data () {
    return {
      currentTab: 'moneytab_2',
      model: {},
      selectMemId: '',
      selectMem: {
        cashAmt: ''
      },
      cashAmt: '',
      list: [],
      searchForm: {
        topMemId: '',
        cashType: '',
        cashStatus: '',
        botMemId: '',
        startDate: getDateStr(getSubDaysDate(new Date(), 7)),
        endDate: getDateStr(new Date(), 'yyyy-MM-dd')
      },
      partnerLevelList: [],
      partnerList: [],
      selectPartnerCode: '',
      myMemIdsList: [],
      isProcessing: false,
      loginMemList: [],
      selectedLi: null,
      idlist: false
    }
  },
  watch: {
    selectPartnerCode () {
      if (this.selectPartnerCode) {
        this.selectMem.cashAmt = ''
        this.getMyMemIds()
      } else {
        this.selectMem = {}
        this.selectMem.cashAmt = ''
      }
    },
    selectMem () {
      if (this.selectMem) {
        this.selectMem.cashAmt = thousand(this.selectMem.cashAmt)
      }
    }
  },
  computed: {
    ...mapState([
      'userData'
    ]),
    formattedCashAmt () {
      if (!this.cashAmt) return ''
      return this.cashAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
  },
  async created () {
    this.getPartnerLevels()
    await this.getLoginMember()
    this.getMyPartnerList(this.userData.memId)
    this.loadData()
  },
  methods: {
    thousand,
    partnerLevelName (partnerLevel) {
      return PARTNER_LEVEL_NAME[partnerLevel]
    },
    async getLoginMember () {
      const res = await getRetailMyLoginMem()
      console.log(res)
      const result = res.data
      if (result.resultCode === '0') {
        this.loginMemList = result.data.loginMemList
      }
    },
    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
        }
      })
    },
    listOpen (memId, type, item) {
      this.emitter.emit('Loading', true)
      const params = {
        memId: memId
      }
      this.searchMemId = memId
      retailMyPartnerDirectList(params).then(res => {
        const result = res.data
        if (result.resultCode === '0') {
          const list = result.data.list
          if (type === 'sub') {
            item.children = list
            item.open = !item.open
          } else {
            this.partnerList = list
          }
        }
        this.emitter.emit('Loading', false)
      })
    },
    getMyPartnerList (memId, type, item) {
      this.emitter.emit('Loading', true)
      const params = {
        memId: memId
      }
      this.searchMemId = memId

      console.log('[REQ]retailMyPartnerDirectList : ', params)
      retailMyPartnerDirectList(params).then(res => {
        console.log('[RES]retailMyPartnerDirectList : ', res.data)
        const result = res.data
        if (result.resultCode === '0') {
          const list = result.data.list
          if (type === 'sub') {
            item.children = list

            if (this.selectedLi === memId) {
              this.selectedLi = memId
            } else {
              this.selectedLi = memId
            }

            this.loadData(1)
          } else {
            this.partnerList = list
          }
        }
        this.emitter.emit('Loading', false)
      })
    },
    getPartnerLevels () {
      partnerLevels({}).then(res => {
        const result = res.data
        if (result.resultCode === '0') {
          this.partnerLevelList = result.data.list
        }
      })
    },
    onChangeStartDate (event) {
      const startDate = event.target.value
      this.searchForm.startDate = startDate
    },
    onChangeEndDate (event) {
      const endDate = event.target.value
      this.searchForm.endDate = endDate
    },
    loadData (page) {
      if (!page) {
        page = this.pageInfo.page
      }
      if (this.selectedLi) {
        this.searchForm.topMemId = this.selectedLi
      }
      const form = JSON.parse(JSON.stringify(this.searchForm))
      form.startDate += ' 00:00:00'
      form.endDate += ' 23:59:59'
      // form.page = page

      const params = {
        ...form,
        page: page,
        count_per_list: 40
      }
      this.emitter.emit('Loading', true)
      console.log('getCashSendList : ', params)
      getCashSendList(params).then(response => {
        this.emitter.emit('Loading', false)
        console.log('getCashSendList : ', response)
        const result = response.data
        if (result.resultCode === '0') {
          this.list = result.data.list
          if (result.data.pageInfo) {
            this.pageInfo = result.data.pageInfo
          }
        }
      })
    },
    async memCash (type) {
      if (!this.cashAmt) {
        await this.onAlert('warningart', 'front.give.moneyInput')
        return false
      }

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

      if (!this.isProcessing) {
        this.isProcessing = true

        const params = {
          memId: this.selectMem.memId
        }
        if (type === '-3') {
          params.inAmt = this.cashAmt
          if (Number(this.cashAmt) > Number(this.userData.cashAmt)) {
            await this.onAlert('warningart', '보유금보다 지급 금액이 큽니다.')
            this.isProcessing = false
            return false
          }
        } else {
          params.outAmt = this.cashAmt
          if (Number(this.cashAmt) > Number(this.selectMem.cashAmt)) {
            await this.onAlert('warningart', '보유금보다 회수 금액이 큽니다.')
            this.isProcessing = false
            return false
          }
        }

        const message = this.$t('front.cash.moneyMoveConfirm', { memNick: this.selectMem.memNick, cashAmt: thousand(this.cashAmt), 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
            this.emitter.emit('Loading', false)
            if (result.resultCode === '0') {
              if (type === '-3') {
                this.onCheck('지급 완료')
              } else {
                this.onCheck('회수 완료')
              }

              this.selectPartnerCode = ''
              this.cashAmt = ''
              this.loadData()
            } else {
              await this.onAlert('warningart', result.resultMessage)
            }
            this.isProcessing = false
          })
        } else {
          this.isProcessing = false
        }
      }
    }
  }
}
</script>
<style scoped src="@/styles/striNew.css"></style>
<style scoped>
.datesearchPT input[type="date"]::-webkit-calendar-picker-indicator{/*background: url(../../../assets/img/PTcalender.svg);display: block;background-repeat: no-repeat;background-size: contain;*/}
.strTablescr {width: 100%;}

@media (max-width: 1000px) {
  .strTablescr {width: 100%;}
  .strTablePTM ul {padding: 0;}
  .strTablePTM ul li:nth-child(4) {
    width: 100%;
  }
}
</style>
