<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="sysOrigins"
        placeholder="系统"
        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="来源平台"
        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="状态"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in orderStatus"
          :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="用户ID"
        />
      </div>
      <div class="filter-item">
        <el-input
          v-model.trim="listQuery.orderId"
          placeholder="订单id"
          style="width: 200px;"
        />
      </div>
      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        v-if="buttonPermissions.includes('user:table:purchasing:export')"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="exprotOrder"
      >
        导出
      </el-button>
    </div>
    <el-alert v-show="isShowUserTotal" type="success" :closable="false">
      <span
        style="font-size: .25rem; color: #54c988;"
      >该用户总充值: {{ 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="环境" 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="平台渠道"
        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="购买人" 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="朋友"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="金额" 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="描述"
        align="center"
        min-width="200"
      />

      <el-table-column
        prop="statusName"
        label="状态"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.orderPurchase.status === 'REIMBURSE'" type="danger">{{
            scope.row.statusName
          }}</el-tag>
          <el-tag v-else type="success">{{ scope.row.statusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderPurchase.orderId"
        label="第三方ID"
        align="center"
        min-width="200"
      />
      <el-table-column
        prop="orderPurchase.purchaseDateMs"
        label="购买时间"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <div>购买: {{ scope.row.orderPurchase.purchaseDateMs | dateFormat }}</div>
          <div>修改: {{ scope.row.orderPurchase.updateTime | dateFormat }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="50">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="clickQueryDetails(scope.row)"
          >详情</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="导出条件"
      :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="系统" prop="sysOrigins">
              <el-select
                v-model="exportQuery.sysOrigins"
                placeholder="系统"
                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="月份" prop="monthDate">
              <el-date-picker
                v-model="exportQuery.monthDate"
                type="month"
                value-format="yyyyMM"
                placeholder="选择月"
                style="width: 100%;"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button @click="exportConditionClose()">关闭</el-button>
          <el-button
            type="primary"
            :disabled="exportLoading"
            :loading="exportLoading"
            @click="exportConditionSubmit()"
          >导出</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: '必填字段不可为空', 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)
          )
        ) || []
      )
    }
  },
  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('正在执行导出, 请稍等~')
        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('下载失败！')
          })
      })
    }
  }
}
</script>
