<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-select
        v-model="sysOrigins"
        placeholder="系统"
        style="width: 200px"
        class="filter-item"
        multiple
        collapse-tags
        @change="changeSysorigin"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :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.factoryPlatform"
        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 statusList"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.receiptType"
        placeholder="订单类型"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in receiptTypes"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <div class="filter-item">
        <account-input
          v-model="listQuery.acceptUserId"
          :sys-origin="
            sysOrigins && sysOrigins.length === 1 ? sysOrigins[0] : ''
          "
          placeholder="用户ID"
        />
      </div>
      <div class="filter-item">
        <el-input
          v-model.trim="listQuery.id"
          placeholder="App订单ID"
          style="width: 200px;"
        />
      </div>
      <div class="filter-item">
        <el-input
          v-model.trim="listQuery.orderId"
          placeholder="第三方订单ID"
          style="width: 200px;"
        />
      </div>
      <div class="filter-item">
        <el-input
          v-model.trim="listQuery.trackId"
          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-select
        v-model="listQuery.countryCode"
        placeholder="地区"
        clearable
        style="width:150px;"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in regions"
          :key="index"
          :label="item.regionName"
          :value="item.regionCode"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>
    </div>

    <!-- 总信息 -->
    <el-alert type="warning" :closable="false">
      <strong
        >当前查询到订单总数为:{{
          total.totalOrderCount || "-"
        }}、订单总金额为:{{ total.totalAmountUsd || "-" }}</strong
      >
    </el-alert>
    <!-- 表单 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column
        prop="details.env"
        label="环境"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.details.env === 'PROD'" type="success">{{
            scope.row.details.env
          }}</el-tag>
          <el-tag v-else-if="scope.row.details.env === 'TEST'" type="warning">{{
            scope.row.details.env
          }}</el-tag>
          <el-tag v-else type="danger">{{ scope.row.details.env }}</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.details.sysOrigin"
                :desc="scope.row.details.sysOrigin"
              />
            </el-col>
            <el-col :span="8">
              <platform-svg-icon :icon="scope.row.details.factory.platform" />
            </el-col>
            <el-col :span="8">
              <platform-svg-icon
                :icon="scope.row.details.factory.factoryCode"
              />
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        prop="details.factory.factoryChannelCode"
        label="渠道"
        align="center"
        min-width="100"
      />
      <el-table-column label="购买人" align="left" min-width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.createNickname">
            <div>{{ scope.row.createNickname }}</div>
            <div v-if="scope.row.acceptUserProfile" class="attached">
              <user-table-exhibit
                size="mini"
                :user-profile="scope.row.acceptUserProfile"
                :query-details="true"
              />
            </div>
          </div>
          <div v-else-if="scope.row.createUserProfile">
            <div>
              <user-table-exhibit
                size="mini"
                :user-profile="scope.row.createUserProfile"
                :query-details="true"
              />
            </div>
            <div v-if="scope.row.acceptUserProfile" class="attached">
              <user-table-exhibit
                size="mini"
                :user-profile="scope.row.acceptUserProfile"
                :query-details="true"
                tag-name="朋友"
              />
            </div>
          </div>
          <div v-else>
            <user-table-exhibit
              size="small"
              :user-profile="scope.row.acceptUserProfile"
              :query-details="true"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="金额(USD)" align="center" min-width="80">
        <template slot-scope="scope">
          <div>{{ scope.row.details.amountUsd }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="details.productDescriptor"
        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="statusMap[scope.row.details.status]"
            :type="statusMap[scope.row.details.status].tagType"
            >{{ statusMap[scope.row.details.status].lable }}</el-tag
          >
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="details.orderId"
        label="第三方ID"
        align="center"
        min-width="200"
      />
      <el-table-column
        prop="details.purchaseDateMs"
        label="购买时间"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <div>购买: {{ scope.row.details.purchaseDateMs | dateFormat }}</div>
          <div>修改: {{ scope.row.details.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>

    <div v-if="listQuery.lastId" class="load-more">
      <span v-if="notData">已加载全部</span>
      <el-button
        v-else
        size="mini"
        :disabled="loadMoreLoading"
        :loading="loadMoreLoading"
        @click="clickLoadMore"
        >加载更多</el-button
      >
    </div>

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

<script>
import {
  regionAssistConfigTable,
  updateRegionAssistConfig,
  addRegionAssistConfig,
  deleteRegionAssistConfig,
  regionConfigTable
} from "@/api/sys";
import { listInAppPurchase, getOrderAmount } from "@/api/purchase";
import { pickerOptions } from "@/constant/el-const";
import { sysOriginPlatforms } from "@/constant/origin";
import { mapGetters } from "vuex";
import PlatformSvgIcon from "@/components/PlatformSvgIcon";
import { originPlatforms } from "@/constant/origin";
import InAppPurchaseDetails from "@/components/data/InAppPurchaseDetails";

export default {
  components: { PlatformSvgIcon, InAppPurchaseDetails },
  data() {
    return {
      thisRow: {},
      inAppPurchaseDetailsVisible: false,
      originPlatforms,
      gameRedPacketDetailsDrawerVisible: false,
      thatRow: {},
      sysOriginPlatforms,
      gameRedPacketReceivingUsers: false,
      roomDeatilsDrawerVisible: false,
      thatSelectedUserId: "",
      pickerOptions,
      list: [],
      notData: false,
      loadMoreLoading: false,
      checkList: [],
      total: {},
      sysOrigins: [],
      regions: [], //地区列表
      listQuery: {
        limit: 20,
        acceptUserId: "",
        factoryPlatform: "",
        startTime: "",
        endTime: "",
        status: "",
        sysOrigin: "",
        id: "",
        orderId: "",
        lastId: "",
        receiptType: "",
        trackId: "",
        countryCode: "" // 地区码
      },
      listLoading: false,
      rangeDate: "",
      redPacketId: "",
      searchLoading: false,
      searchDisabled: false,
      receiptTypes: [
        { name: "付款", value: "PAYMENT" },
        { name: "收款", value: "RECEIPT" }
      ],
      statusList: [
        { name: "创建付款", value: "CREATE" },
        { name: "支付成功", value: "SUCCESS" },
        { name: "支付失败", value: "FAIL" },
        { name: "取消支付", value: "CANCEL" },
        { name: "交易被挂起", value: "HANG" },
        { name: "退款", value: "REFUND" }
      ],
      statusMap: {
        CREATE: {
          tagType: "",
          lable: "创建付款"
        },
        SUCCESS: {
          tagType: "success",
          lable: "支付成功"
        },
        FAIL: {
          tagType: "danger",
          lable: "支付失败"
        },
        CANCEL: {
          tagType: "info",
          lable: "取消支付"
        },
        HANG: {
          tagType: "warning",
          lable: "交易被挂起"
        },
        REFUND: {
          tagType: "danger",
          lable: "退款"
        }
      }
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"]),
    sysOriginStr() {
      return !this.sysOrigins || this.sysOrigins.length === 0
        ? this.permissionsSysOriginPlatforms.map(item => item.value).join(",")
        : this.sysOrigins.join(",");
    }
  },

  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;
    this.listRegion();
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    that.sysOrigins.push(querySystem.value);
    that.renderData(true, true);
  },
  methods: {
    // 获取地区列表
    listRegion() {
      const that = this;
      regionConfigTable({ sysOrigin: "ATYOU" })
        .then(res => {
          that.regions = res.body || [];
        })
        .catch(er => {});
    },
    renderData(isReset, isLoading) {
      const that = this;
      if (!that.sysOriginStr) {
        return;
      }

      that.listQuery.sysOrigins = that.sysOriginStr;

      if (isReset === true) {
        that.list = [];
        that.listQuery.lastId = "";
      }
      that.listLoading = isLoading;
      listInAppPurchase(that.listQuery)
        .then(res => {
          that.listLoading = false;
          that.loadMoreLoading = false;
          const { body } = res;
          const list = body || [];
          that.notData = list.length <= 0;
          if (!that.notData) {
            that.list = that.list.concat(list);
            that.listQuery.lastId = that.list[that.list.length - 1].details.id;
          }
        })
        .catch(er => {
          that.listLoading = false;
          that.loadMoreLoading = false;
        });
      getOrderAmount(that.listQuery).then(res => {
        const { body } = res;
        that.total = body || {};
      });
    },
    handleSearch() {
      this.searchLoading = true;
      this.renderData(true, true);
    },
    clickQueryDetails(row) {
      this.inAppPurchaseDetailsVisible = true;
      this.thisRow = row;
    },
    changeSysorigin(val) {
      if (!val || val.length === 0) {
        this.sysOrigins = this.permissionsSysOriginPlatforms.map(
          item => item.value
        );
        this.listRegion();
      }
    },
    queryRoomDetails(row) {
      this.thatRow = row;
      this.roomDeatilsDrawerVisible = true;
    },
    getReceiveUsersLength(row) {
      return row.receiveUsers ? row.receiveUsers.length : 0;
    },
    clickLoadMore() {
      const that = this;
      that.loadMoreLoading = true;
      that.renderData();
    }
  }
};
</script>
<style scoped lang="scss">
.room-avatar {
  position: relative;
  width: 50px;
  height: 50px;
  margin: auto;
  flex-shrink: 0;
  .flag-icon {
    position: absolute;
    bottom: 0px;
  }
}

.room-name {
  width: 100%;
  text-align: left;
  padding-left: 10px;
}

.load-more {
  padding: 20px;
  text-align: center;
}
.content {
  overflow: auto;
  padding: 10px 0px;
}
</style>
