<template>
  <div class="order-base-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="2">
        <el-button icon="el-icon-check" type="primary" @click="exportCsv">
          {{ __('导出') }}
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="22">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.order_id"
              clearable
              :placeholder="__('请输入订单编号')"
              style="width: 160px"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.order_title"
              clearable
              :placeholder="__('订单标题')"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model.trim="queryForm.buyer_user_id"
              clearable
              filterable
              :loading="userLoading"
              :placeholder="__('买家昵称')"
              remote
              :remote-method="getUserInfoList"
              reserve-keyword
              style="width: 120px"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.user_id"
                :label="item.user_nickname"
                :value="item.user_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="queryForm.order_state_id"
              clearable
              filterable
              :placeholder="__('请选择状态')"
              style="width: 120px"
            >
              <el-option
                v-for="item in optionsStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="queryForm.store_is_selfsupport"
              clearable
              filterable
              :placeholder="__('店铺类型')"
              style="width: 120px"
            >
              <el-option
                v-for="item in optionsStores"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="block">
              <el-date-picker
                v-model="queryForm.order_date"
                :placeholder="__('订单日期')"
                type="date"
                value-format="yyyy-MM-dd"
              >
                >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              {{ __('查询') }}
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="table"
      v-loading="listLoading"
      border
      :data="list"
      :height="tableConfig.height"
      @selection-change="setSelectRows"
    >
      <el-table-column align="center" show-overflow-tooltip type="selection" />
      <el-table-column
        align="center"
        fixed="left"
        :label="__('订单编号')"
        show-overflow-tooltip
        width="140"
      >
        <template #default="{ row }">
          <span v-if="row.return_flag">
            <el-link style="color: red" @click="handleEdit(row)">
              {{ row.order_id }}
            </el-link>
          </span>
          <span v-if="!row.return_flag">
            <el-link type="primary" @click="handleEdit(row)">
              {{ row.order_id }}
            </el-link>
          </span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :formatter="formatTime"
        :label="__('下单时间')"
        prop="order_time"
        show-overflow-tooltip
        width="160"
      />
      <el-table-column
        v-if="false"
        align="center"
        :label="__('转单状态')"
        prop="has_supplier_trans"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-button
            v-if="row.has_supplier_trans"
            type="info"
            @click="changeState(row.has_supplier_trans)"
          >
            转单
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('支付金额')"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ row.currency_symbol_left }}{{ row.order_payment_amount }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('积分')"
        prop="order_resource_ext1"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('运费')"
        prop="order_shipping_fee"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('平台佣金')"
        prop="order_commission_fee"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('佣金退款')"
        prop="order_commission_fee_refund"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('退款额度')"
        prop="order_refund_amount"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('卖家店铺编号')"
        prop="store_id"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :label="__('卖家店铺名称')"
        prop="store_name"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :label="__('买家编号')"
        prop="buyer_user_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('买家姓名')"
        prop="buyer_user_name"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :formatter="formatStateId"
        :label="__('订单状态')"
        prop="order_state_id"
        show-overflow-tooltip
        width="110"
      />
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <item ref="item" />
    <add ref="add" @fetch-data="fetchData" />
    <Return ref="Return" />
  </div>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { renderTime } from '@/utils/date'
  import {
    exportFile,
    getBaseList,
    review,
    reviewFinance,
    reviewPicking,
    reviewShipping,
  } from '@/api/order/base'
  import { getAccounts, getList } from '@/api/user/base'
  import Item from './components/OnlineOrderItem'
  import add from './components/OrderBaseEdit'
  import Return from './components/OrderReturnList'

  export default {
    name: 'OrderBase',
    components: { Item, add, Return },
    data() {
      return {
        tableConfig: {
          height: window.innerHeight - 220 - 90,
        },
        userLoading: false,
        list: [],
        userOptions: [],
        optionsStores: [
          {
            value: 1,
            label: this.__('自营'),
          },
          {
            value: 0,
            label: this.__('加盟'),
          },
        ],
        optionsStatus: [
          {
            value: 2010,
            label: this.__('等待买家付款'),
          },
          {
            value: 2011,
            label: this.__('待订单审核'),
          },
          {
            value: 2013,
            label: this.__('待财务审核'),
          },
          {
            value: 2020,
            label: this.__('等待卖家配货'),
          },
          {
            value: 2030,
            label: this.__('等待卖家发货'),
          },
          {
            value: 2040,
            label: this.__('等待买家确认收货'),
          },
          {
            value: 2050,
            label: this.__('买家已签收'),
          },
          {
            value: 2060,
            label: this.__('交易成功'),
          },
          {
            value: 2070,
            label: this.__('交易关闭'),
          },
        ],
        value: '',
        listLoading: false,
        loading: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNum: 1,
          pageSize: 20,
        },
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      formatTime(row) {
        return renderTime(row.order_time)
      },
      handleAdd() {
        this.$refs['add'].showEdit()
      },
      handleReturnTable(row) {
        this.$refs['Return'].showTable(row)
      },
      handleEdit(row) {
        this.$refs['item'].showEdit(row)
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      formatPaid(row) {
        return row.order_is_paid === 3010
          ? this.__('未付款')
          : row.order_is_paid === 3011
          ? this.__('付款待审核')
          : row.order_is_paid === 3012
          ? this.__('部分付款')
          : this.__('已付款')
      },
      formatReceived(row) {
        return row.order_is_received === 0
          ? this.__('未收货')
          : this.__('已收货')
      },
      formatPrint(row) {
        return row.order_express_print === 0
          ? this.__('未打印')
          : this.__('已打印')
      },
      formatFlag(row) {
        return row.return_flag ? this.__('是') : this.__('否')
      },
      formatReview(row) {
        return row.order_is_review === 0 ? this.__('未审核') : this.__('已审核')
      },
      foematShipped(row) {
        return row.order_is_shipped === 3030
          ? this.__('未发货')
          : row.order_is_shipped === 3031
          ? this.__('已发货')
          : this.__('部分发货')
      },
      formatOut(row) {
        return row.order_is_out === 3020
          ? this.__('未出库')
          : row.order_is_out === 3021
          ? this.__('部分出库通过')
          : this.__('已出库')
      },
      formatStateId(row) {
        const obj = this.optionsStatus.find(
          (item) => item.value === row.order_state_id
        )
        return obj ? obj.label : ''
      },

      __,
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },

      async review() {
        let order_id = this.selectRows.map((item) => item.order_id)
        const { msg, status } = await review({
          order_ids: order_id.toString(),
          order_is_review: 1,
        })
        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
        this.fetchData()
      },
      async reviewFinance() {
        let order_id = this.selectRows.map((item) => item.order_id)
        const { msg, status } = await reviewFinance({
          order_ids: order_id.toString(),
          order_finance_review: 1,
        })
        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
        this.fetchData()
      },

      async reviewShipping() {
        let order_id = this.selectRows.map((item) => item.order_id)
        const { msg, status } = await reviewShipping({
          order_ids: order_id.toString(),
          order_state_id: 2030,
        })
        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
        this.fetchData()
      },
      async reviewPicking() {
        let order_id = this.selectRows.map((item) => item.order_id)
        const { msg, status } = await reviewPicking({
          order_ids: order_id.toString(),
          order_is_out: 1,
        })
        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await getBaseList(this.queryForm)
        this.list = data.items
        this.total = data.records
        this.listLoading = false
      },
      async getUserInfoList(user_nickname) {
        if (user_nickname.trim() !== '') {
          this.userLoading = true
          const { data } = await getAccounts({ user_nickname })
          this.userOptions = data
          this.userLoading = false
        } else {
          this.userOptions = []
        }
      },
      exportCsv() {
        const rows = this.$refs.table.selection
        if (!rows || rows.length <= 0) {
          this.$baseMessage('没有选中的数据！', 'error')
          return
        }
        let order_ids = rows.map((item) => item.order_id)
        exportFile({ order_ids: order_ids.toString() }).then((data) => {
          const blob = new Blob([data])
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = decodeURIComponent('订单数据.csv') //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
      },
    },
  }
</script>
