<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="sysOrigins"
        :placeholder="$t('pages.purchaseOrders.filter.system')"
        style="width: 200px"
        class="filter-item"
        multiple
        collapse-tags
      >
        <el-option
          v-for="item in permissionsSysOrigins"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;">
            <sys-origin-icon
              :icon="item.value"
              :desc="item.value"
            /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>
      <el-select
        v-model="listQuery.platform"
        :placeholder="$t('pages.purchaseOrders.filter.sourcePlatform')"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in originPlatforms"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.status"
        :placeholder="$t('pages.purchaseOrders.filter.status')"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in localizedOrderStatus"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <div class="filter-item">
        <account-input
          v-model="listQuery.userId"
          :sys-origin="
            sysOrigins && sysOrigins.length === 1 ? sysOrigins[0] : ''
          "
          :placeholder="$t('pages.purchaseOrders.filter.userId')"
        />
      </div>
      <div class="filter-item">
        <el-input
          v-model.trim="listQuery.orderId"
          :placeholder="$t('pages.purchaseOrders.filter.orderId')"
          style="width: 200px;"
        />
      </div>
      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          :range-separator="$t('pages.purchaseOrders.filter.to')"
          :start-placeholder="$t('pages.purchaseOrders.filter.startDate')"
          :end-placeholder="$t('pages.purchaseOrders.filter.endDate')"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        {{ $t('pages.purchaseOrders.action.search') }}
      </el-button>
      <el-button
        v-if="buttonPermissions.includes('user:table:purchasing:export')"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="exprotOrder"
      >
        {{ $t('pages.purchaseOrders.action.export') }}
      </el-button>
    </div>
    <el-alert v-show="isShowUserTotal" type="success" :closable="false">
      <span
        style="font-size: .25rem; color: #54c988;"
      >{{ $t('pages.purchaseOrders.summary.userTotalRecharge', { total: userTotal }) }}</span>
    </el-alert>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column type="index" width="50" label="No" />
      <el-table-column prop="orderPurchase.evn" :label="$t('pages.purchaseOrders.table.environment')" align="center" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.orderPurchase.evn === 'PROD'" type="success">{{
            scope.row.orderPurchase.evn
          }}</el-tag>
          <el-tag v-else-if="scope.row.orderPurchase.evn === 'TEST'" type="warning">{{
            scope.row.orderPurchase.evn
          }}</el-tag>
          <el-tag v-else type="danger">{{ scope.row.orderPurchase.evn }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="platform"
        :label="$t('pages.purchaseOrders.table.platformChannel')"
        min-width="120"
        align="center"
      >
        <template slot-scope="scope">
          <el-row>
            <el-col :span="8">
              <sys-origin-icon
                :icon="scope.row.orderPurchase.sysOrigin"
                :desc="scope.row.orderPurchase.sysOrigin"
              />
            </el-col>
            <el-col :span="8">
              <platform-svg-icon :icon="scope.row.orderPurchase.platform" />
            </el-col>
            <el-col :span="8">
              <platform-svg-icon :icon="scope.row.orderPurchase.payPlatform" />
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="expandTypeName" label="事件" align="center" min-width="80" /> -->
      <el-table-column :label="$t('pages.purchaseOrders.table.buyer')" align="center" min-width="200">
        <template slot-scope="scope">
          <div>
            <user-table-exhibit
              :size="scope.row.friendBaseInfo ? 'mini' : 'small'"
              :user-profile="scope.row.userBaseInfo"
              :query-details="true"
            />
          </div>
          <div v-if="scope.row.friendBaseInfo" class="attached">
            <user-table-exhibit
              size="mini"
              :user-profile="scope.row.friendBaseInfo"
              :query-details="true"
              :tag-name="$t('pages.purchaseOrders.word.friend')"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.purchaseOrders.table.amount')" align="center" min-width="80">
        <template slot-scope="scope">
          <div>{{ scope.row.orderPurchase.unitPrice }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderPurchase.productDescription"
        :label="$t('pages.purchaseOrders.table.description')"
        align="center"
        min-width="200"
      />

      <el-table-column
        prop="statusName"
        :label="$t('pages.purchaseOrders.table.status')"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.orderPurchase.status === 'REIMBURSE'" type="danger">{{
            getOrderStatusName(scope.row.orderPurchase.status, scope.row.statusName)
          }}</el-tag>
          <el-tag v-else type="success">{{ getOrderStatusName(scope.row.orderPurchase.status, scope.row.statusName) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderPurchase.orderId"
        :label="$t('pages.purchaseOrders.table.thirdPartyId')"
        align="center"
        min-width="200"
      />
      <el-table-column
        prop="orderPurchase.purchaseDateMs"
        :label="$t('pages.purchaseOrders.table.purchaseTime')"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <div>{{ $t('pages.purchaseOrders.word.purchase') }}: {{ scope.row.orderPurchase.purchaseDateMs | dateFormat }}</div>
          <div>{{ $t('pages.purchaseOrders.word.update') }}: {{ scope.row.orderPurchase.updateTime | dateFormat }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('pages.purchaseOrders.table.actions')" align="center" width="80">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="clickQueryDetails(scope.row)"
          >{{ $t('pages.purchaseOrders.action.details') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <user-deatils-drawer
      v-if="userDeatilsDrawerVisible"
      :user-id="thatSelectedUserId"
      @close="userDeatilsDrawerVisible = false"
    />

    <in-app-purchase-details
      v-if="inAppPurchaseDetailsVisible"
      :order-id="thisRow.id"
      @close="inAppPurchaseDetailsVisible = false"
    />

    <el-drawer
      :title="$t('pages.purchaseOrders.export.title')"
      :visible="exportConditionVisible"
      :before-close="exportConditionClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div class="exprot-select">
        <div class="drawer-form">
          <el-form
            ref="exportQuery"
            :rules="exportQueryRules"
            :model="exportQuery"
            label-position="left"
            label-width="70px"
          >
            <el-form-item :label="$t('pages.purchaseOrders.filter.system')" prop="sysOrigins">
              <el-select
                v-model="exportQuery.sysOrigins"
                :placeholder="$t('pages.purchaseOrders.filter.system')"
                class="filter-item"
                multiple
                collapse-tags
                style="width: 100%;"
              >
                <el-option
                  v-for="item in permissionsSysOrigins"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left;">
                    <sys-origin-icon
                      :icon="item.value"
                      :desc="item.value"
                    /></span>
                  <span style="float: left;margin-left:10px">{{
                    item.label
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('pages.purchaseOrders.export.month')" prop="monthDate">
              <el-date-picker
                v-model="exportQuery.monthDate"
                type="month"
                value-format="yyyyMM"
                :placeholder="$t('pages.purchaseOrders.export.selectMonth')"
                style="width: 100%;"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button @click="exportConditionClose()">{{ $t('pages.purchaseOrders.action.close') }}</el-button>
          <el-button
            type="primary"
            :disabled="exportLoading"
            :loading="exportLoading"
            @click="exportConditionSubmit()"
          >{{ $t('pages.purchaseOrders.action.export') }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getPurchaseTable,
  getBuyTotalByUserId,
  exportPurchaseConsumeTable
} from '@/api/purchase'
import { originPlatforms } from '@/constant/origin'
import Pagination from '@/components/Pagination'
import PlatformSvgIcon from '@/components/PlatformSvgIcon'
import { orderStatus } from '@/constant/type'
import { pickerOptions } from '@/constant/el-const'
import { mapGetters } from 'vuex'
import InAppPurchaseDetails from '@/components/data/InAppPurchaseDetails'

export default {
  components: { Pagination, PlatformSvgIcon, InAppPurchaseDetails },
  data() {
    const commonRules = [
      {
        required: true,
        message: this.$t('pages.purchaseOrders.validation.requiredField'),
        trigger: 'blur'
      }
    ]
    return {
      exportLoading: false,
      exportQuery: {
        monthDate: '',
        sysOrigins: ''
      },
      exportQueryRules: {
        monthDate: commonRules,
        sysOrigins: commonRules
      },
      exportConditionVisible: false,
      inAppPurchaseDetailsVisible: false,
      searchDisabled: false,
      pickerOptions,
      orderStatus,
      userDeatilsDrawerVisible: false,
      thatSelectedUserId: '',
      originPlatforms,
      isShowUserTotal: false,
      userTotal: 0,
      list: [],
      total: 0,
      rangeDate: [],
      listQuery: {
        cursor: 1,
        limit: 20,
        userId: '',
        platform: '',
        startTime: '',
        endTime: '',
        status: '',
        sysOrigin: '',
        orderId: ''
      },
      sysOrigins: [],
      listLoading: true,
      clickUserId: '',
      thisRow: {}
    }
  },
  computed: {
    ...mapGetters([
      'permissionsSysOriginPlatforms',
      'permissionsSysOriginPlatformAlls',
      'buttonPermissions'
    ]),
    permissionsSysOrigins() {
      const that = this
      if (
        !that.permissionsSysOriginPlatformAlls ||
        that.permissionsSysOriginPlatformAlls.length <= 0
      ) {
        return []
      }

      if (
        !that.permissionsSysOriginPlatforms ||
        that.permissionsSysOriginPlatforms.length <= 0
      ) {
        return []
      }
      return (
        that.permissionsSysOriginPlatformAlls.filter(item =>
          that.permissionsSysOriginPlatforms.some(permissions =>
            item.value.startsWith(permissions.value)
          )
        ) || []
      )
    },
    localizedOrderStatus() {
      return this.orderStatus.map(item => ({
        ...item,
        name: this.getOrderStatusName(item.value, item.name)
      }))
    }
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0]
          this.listQuery.endTime = newVal[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOrigins[0]
    if (!querySystem) {
      return
    }
    that.sysOrigins.push(querySystem.value)
    that.renderData()
  },
  methods: {
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.list = []
        that.listQuery.cursor = 1
      }
      that.listLoading = true
      that.listQuery.sysOrigin =
        that.sysOrigins.length > 0
          ? that.sysOrigins.join(',')
          : that.permissionsSysOrigins.map(item => item.value).join(',')
      getPurchaseTable(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
      that.isShowUserTotal = false
      if (that.listQuery.userId) {
        getBuyTotalByUserId(that.listQuery.userId).then(res => {
          const { body } = res
          that.userTotal = body
          that.isShowUserTotal = true
        })
      }
    },
    handleSearch() {
      this.renderData(true)
    },
    queryUserDetails(id) {
      this.userDeatilsDrawerVisible = true
      this.thatSelectedUserId = id
    },
    clickQueryDetails(row) {
      this.inAppPurchaseDetailsVisible = true
      this.thisRow = row
    },
    exportConditionClose() {
      if (this.exportLoading) {
        this.$opsMessage.warn(this.$t('pages.purchaseOrders.message.exporting'))
        return
      }
      this.exportConditionVisible = false
    },
    exprotOrder() {
      this.exportQuery.sysOrigins = this.listQuery.sysOrigins
      this.exportConditionVisible = true
    },
    exportConditionSubmit() {
      const that = this
      that.$refs.exportQuery.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        that.exportLoading = true
        exportPurchaseConsumeTable(
          that.exportQuery,
          `Export Order ${that.exportQuery.monthDate}`
        )
          .then(res => {
            that.exportLoading = false
            that.exportConditionVisible = false
          })
          .catch(er => {
            that.exportLoading = false
            this.$opsMessage.fail(this.$t('pages.purchaseOrders.message.downloadFailed'))
          })
      })
    },
    getOrderStatusName(status, fallback) {
      const key = `pages.purchaseOrders.orderStatus.${status}`
      const text = this.$t(key)
      return text === key ? fallback : text
    }
  }
}
</script>
