<template>
  <div class="app-container">
    <div class="app-header-top" style="width: 100%; float: right; margin-bottom: 10px">
      <div class="app-title">订单详情</div>
      <el-button
        type="primary"
        icon="el-icon-back"
        style="float: right"
        @click="backToList"
      >返回</el-button>
    </div>
    <el-card v-if="listLoading" class="box-card">
      <div class="refund-item">
        <el-row :gutter="24" class="box-row">
          <el-col :span="6"><b>下单时间：</b> {{ order.orderTime }}</el-col>
          <el-col
            :span="6"
          ><b>订单编号(ID)：</b> {{ order.orderNo + "(" + order.orderId + ")" }}</el-col>
          <el-col
            :span="4"
          ><b>订单状态：</b>
            <template
              v-if="
                ['11', '12', '13', '21', '22', '23', '31', '32', '33'].indexOf(
                  order.status
                ) >= 0
              "
            >
              <el-tag type="success" size="small">交易中</el-tag>
            </template>
            <template v-else>
              <el-tag :type="order.status * 1 === 6 ? 'info' : ''" size="small">{{
                order.status | orderStatusFilter
              }}</el-tag>
            </template>
          </el-col>
          <!-- <el-col :span="4"><b>订单类型：</b> {{ order.orderTime }}</el-col> -->
          <el-col :span="4"><b>订单来源：</b> 【采美】平台</el-col>
        </el-row>
        <el-row :gutter="24" class="box-row">
          <el-col
            :span="6"
          ><b>收款状态：</b>
            <el-tag
              v-if="order.receiptStatus * 1 === 1"
              type="danger"
              size="small"
            >待收款</el-tag>
            <el-tag
              v-if="order.receiptStatus * 1 === 2"
              type="warning"
              size="small"
            >部分收款</el-tag>
            <el-tag
              v-if="order.receiptStatus * 1 === 3"
              type="success"
              size="small"
            >已收款</el-tag>
          </el-col>
          <el-col
            :span="6"
          ><b>发货状态：</b>
            <el-tag
              v-if="order.sendOutStatus * 1 === 1"
              type="danger"
              size="small"
            >待发货</el-tag>
            <el-tag
              v-if="order.sendOutStatus * 1 === 2"
              type="warning"
              size="small"
            >部分发货</el-tag>
            <el-tag
              v-if="order.sendOutStatus * 1 === 3"
              type="success"
              size="small"
            >已发货</el-tag>
          </el-col>
          <el-col
            :span="4"
          ><b>付款状态：</b>
            <el-tag
              v-if="order.payStatus * 1 === 1"
              type="danger"
              size="small"
            >待付款</el-tag>
            <el-tag
              v-if="order.payStatus * 1 === 2"
              type="warning"
              size="small"
            >部分付款</el-tag>
            <el-tag
              v-if="order.payStatus * 1 === 3"
              type="success"
              size="small"
            >已付款</el-tag>
          </el-col>
          <el-col
            :span="4"
          ><b>退款状态：</b>
            <el-tag
              v-if="order.refundType * 1 === 1"
              type="warning"
              size="small"
            >部分退款</el-tag>
            <el-tag
              v-else-if="order.refundType * 1 === 2"
              type="danger"
              size="small"
            >已退款</el-tag>
            <el-tag v-else type="info" size="small">无退款</el-tag>
          </el-col>
          <!-- <el-col :span="4">
            <el-dropdown class="dropdown">
              <el-button type="primary" size="mini">
                功能<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="order.checkFlag === 1">
                  <div @click="handeleDropdown(6,order.orderId)"> 上传线下支付凭证</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="order.checkFlag === 1">
                  <div @click="handeleDialogFormVisible"> 确认收款金额</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="['11','12','21','22','31','32'].indexOf(order.status) !== -1">
                  <div @click="handeleDropdown(1,order.orderId)">发货</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="['4','5','12','13', '22', '23', '32', '33'].indexOf(order.status) !== -1">
                  <div @click="handeleDropdown(2,order.orderId)">发货记录</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="handeleDropdown(3,order.orderId)">收付款记录</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="handeleDropdown(4,order.orderId)">退款（退货）记录</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="handeleDropdown(5,order.orderId)">订单备注</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col> -->
        </el-row>
      </div>
      <div class="refund-item">
        <el-row v-if="order.bpOrderUserinfo" :gutter="24" class="box-row">
          <el-col
            v-if="order.bpOrderUserinfo"
            :span="6"
          ><b>机构：</b> {{ order.clubName }}</el-col>
        </el-row>
        <el-row v-if="order.bpOrderUserinfo" :gutter="24" class="box-row">
          <el-col
            :span="6"
          ><b>收货人：</b> {{ order.bpOrderUserinfo.shouHuoRen }}</el-col>
          <el-col :span="6"><b>手机：</b> {{ order.bpOrderUserinfo.mobile }}</el-col>
          <el-col
            :span="12"
          ><b>地址：</b>
            {{
              order.bpOrderUserinfo.province +
                " " +
                order.bpOrderUserinfo.city +
                " " +
                order.bpOrderUserinfo.town +
                " " +
                order.bpOrderUserinfo.address
            }}</el-col>
        </el-row>
        <el-row :gutter="24" class="box-row">
          <el-col
            :span="6"
          ><b>订单金额：</b> ¥{{ order.payTotalFee | toThousandFloatFilter }}</el-col>
          <el-col
            :span="6"
          ><b>应收金额：</b> ¥{{ order.payTotalFee | toThousandFloatFilter }}
          </el-col>
          <el-col
            :span="12"
          ><b>已收金额：</b>
            <template v-if="order.receiptStatus * 1 === 1">¥0.00</template>
            <template v-else>¥{{ receiptAmount | toThousandFloatFilter }}</template>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="24" class="box-row">
          <el-col :span="6"><b>退款金额(已完成)：</b> ¥{{ returnValue | toThousandFloatFilter }}
          </el-col>
        </el-row> -->
      </div>
      <div class="refund-item">
        <div
          v-for="shopOrder in order.newShopOrders"
          :key="shopOrder.shopOrderId"
          class="order-item"
        >
          <el-row :gutter="22" class="box-row">
            <el-col :span="6"><b>下单时间：</b> {{ shopOrder.orderTime }}</el-col>
            <el-col
              :span="6"
            ><b>子订单号(ID)：</b>
              {{ shopOrder.shopOrderNo + "(" + shopOrder.shopOrderId + ")" }}</el-col>
            <el-col
              :span="6"
            ><b>子订单金额：</b> ¥{{
              shopOrder.needPayAmount | toThousandFloatFilter
            }}</el-col>
            <el-col
              :span="6"
            ><b>运费：</b>
              <span>{{ shopOrder.postageInfo }}</span>
            </el-col>
            <el-col :span="4" class="function">
              <el-dropdown class="dropdown">
                <el-button type="primary" size="mini">
                  功能<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <!-- <el-dropdown-item v-if="order.checkFlag === 1">
                    <div @click="handeleDropdown(6,order.orderId)"> 上传线下支付凭证</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="order.checkFlag === 1">
                    <div @click="handeleDialogFormVisible"> 确认收款金额</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="['11','12','21','22','31','32'].indexOf(order.status) !== -1">
                    <div @click="handeleDropdown(1,order.orderId)">发货</div>
                  </el-dropdown-item> -->
                  <el-dropdown-item
                    v-if="shopOrder.sendOutStatus * 1 > 1"
                  >
                    <div @click="handeleDropdown(2, order.orderId, shopOrder.shopOrderId)">发货记录</div>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <div @click="handeleDropdown(3, order.orderId, shopOrder.shopOrderId)">收付款记录</div>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <div @click="handeleDropdown(4, order.orderId, shopOrder.shopOrderId)">退款（退货）记录</div>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <div @click="handeleDropdown(5, order.orderId, shopOrder.shopOrderId)">订单备注</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <el-row :gutter="22" class="box-row">
            <el-col
              :span="6"
            ><b>商品总额：</b> ¥{{
              shopOrder.productAmount | toThousandFloatFilter
            }}</el-col>
            <el-col
              :span="6"
            ><b>应付金额：</b> ¥{{
              shopOrder.shouldPayShopAmount | toThousandFloatFilter
            }}</el-col>
            <el-col
              :span="6"
            ><b>已付金额：</b> ¥{{
              shopOrder.payedShopAmount | toThousandFloatFilter
            }}</el-col>
            <el-col
              :span="6"
            ><b>待付金额：</b> ¥{{
              shopOrder.waitPayShop | toThousandFloatFilter
            }}</el-col>
          </el-row>
          <el-row :gutter="22" class="box-row">
            <el-col
              :span="6"
            ><b>收款状态：</b>
              <el-tag
                v-if="shopOrder.receiptStatus * 1 === 1"
                type="danger"
                size="small"
              >待付款</el-tag>
              <el-tag
                v-if="shopOrder.receiptStatus * 1 === 2"
                type="warning"
                size="small"
              >部分付款</el-tag>
              <el-tag
                v-if="shopOrder.receiptStatus * 1 === 3"
                type="success"
                size="small"
              >已付款</el-tag>
            </el-col>
            <el-col
              :span="6"
            ><b>付款状态：</b>
              <el-tag
                v-if="shopOrder.payStatus * 1 === 1"
                type="danger"
                size="small"
              >待付款</el-tag>
              <el-tag
                v-if="shopOrder.payStatus * 1 === 2"
                type="warning"
                size="small"
              >部分付款</el-tag>
              <el-tag
                v-if="shopOrder.payStatus * 1 === 3"
                type="success"
                size="small"
              >已付款</el-tag>
            </el-col>
            <el-col
              :span="6"
            ><b>发货状态：</b>
              <el-tag
                v-if="shopOrder.sendOutStatus * 1 === 1"
                type="danger"
                size="small"
              >待发货</el-tag>
              <el-tag
                v-if="shopOrder.sendOutStatus * 1 === 2"
                type="warning"
                size="small"
              >部分发货</el-tag>
              <el-tag
                v-if="shopOrder.sendOutStatus * 1 === 3"
                type="success"
                size="small"
              >已发货</el-tag>
            </el-col>
            <el-col
              :span="6"
            ><b>退款状态：</b>
              <el-tag
                v-if="shopOrder.orderStatusFlag * 1 === 1"
                type="info"
                size="small"
              >无退款</el-tag>
              <el-tag
                v-if="shopOrder.orderStatusFlag * 1 === 2"
                type="warning"
                size="small"
              >退款中</el-tag>
              <el-tag
                v-if="shopOrder.orderStatusFlag * 1 === 3"
                type="success"
                size="small"
              >已退款</el-tag>
            </el-col>
          </el-row>
          <el-row :gutter="22" class="box-row">
            <el-col
              :span="22"
            ><b>留言：</b> {{ shopOrder.note ? shopOrder.note : "无" }}</el-col>
          </el-row>
          <el-row :gutter="22" class="box-row">
            <el-col
              :span="22"
            ><b>供应商：</b>
              {{ shopOrder.shopName ? shopOrder.shopName : "无" }}</el-col>
          </el-row>
          <el-row :gutter="22">
            <el-table :data="shopOrder.newOrderProducts" border>
              <el-table-column label="商品图片" align="center" prop="productImage">
                <template slot-scope="{ row }">
                  <el-popover placement="top-start" title="" width="120" trigger="hover">
                    <img
                      :src="row.productImage"
                      alt=""
                      style="width: 100px; height: 100px"
                    >
                    <img
                      slot="reference"
                      :src="row.productImage"
                      alt=""
                      style="width: 50px; height: 50px"
                    >
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="商品名" align="center" prop="name" />
              <el-table-column label="规格" align="center" prop="unit" />
              <el-table-column label="数量" align="center" prop="num" width="60" />
              <el-table-column label="单价" align="center" prop="price">
                <template slot-scope="{ row }">
                  <span>¥{{ row.price | amountfilters }}</span>
                </template>
              </el-table-column>
              <el-table-column label="总价" align="center" prop="totalFee">
                <template slot-scope="{ row }">
                  <span>¥{{ row.totalFee | amountfilters }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="已发/已收"
                align="center"
                prop="returnedPurchaseProductNum"
              >
                <template slot-scope="{ row }">
                  <span>{{
                    `${row.sendOutNum ? row.sendOutNum : 0}/${
                      row.receivedNum ? row.receivedNum : 0
                    }`
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="退款(退货)中/已完成"
                align="center"
                prop="returnedPurchaseProductNum"
              >
                <template slot-scope="{ row }">
                  <span>{{ row.returningNum ? row.returningNum : 0 }} /
                    {{ row.returnedNum ? row.returnedNum : 0 }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>
      </div>
      <div class="refund-item">
        <template v-if="orderInvoice">
          <el-row :gutter="24" class="box-row">
            <el-col
              :span="6"
            ><b>发票信息：</b> {{ setInvoiceText(orderInvoice) }}</el-col>
          </el-row>
          <el-row :gutter="24" class="box-row">
            <el-col
              :span="6"
            ><b>发票抬头：</b>
              {{ orderInvoice.invoiceTitle ? orderInvoice.invoiceTitle : "无" }}</el-col>
            <el-col
              :span="6"
            ><b>单位税号：</b>
              {{
                orderInvoice.corporationTaxNum ? orderInvoice.corporationTaxNum : "无"
              }}</el-col>
            <el-col
              :span="8"
            ><b>注册地址：</b>
              {{
                orderInvoice.registeredAddress ? orderInvoice.registeredAddress : "无"
              }}</el-col>
          </el-row>
          <el-row :gutter="24" class="box-row">
            <el-col
              :span="6"
            ><b>注册电话：</b>
              {{
                orderInvoice.registeredPhone ? orderInvoice.registeredPhone : "无"
              }}</el-col>
            <el-col
              :span="6"
            ><b>开户银行：</b>
              {{ orderInvoice.openBank ? orderInvoice.openBank : "无" }}</el-col>
            <el-col
              :span="8"
            ><b>银行账号：</b>
              {{ orderInvoice.bankAccountNo ? orderInvoice.bankAccountNo : "无" }}</el-col>
          </el-row>
        </template>
        <template v-else>
          <el-row :gutter="24" class="box-row">
            <el-col :span="24"><b>发票信息：</b> 不开发票</el-col>
          </el-row>
        </template>
      </div>
      <div v-if="voucher.length > 0" class="refund-item">
        <h1 style="font-size: 14px; color: #409eff">线下支付凭证：</h1>
        <el-row v-for="(vouch, index) in voucher" :key="index" style="padding: 5px 0">
          <p class="refund-item-p">{{ vouch.addTime }}</p>
          <div class="refund-item-imgs">
            <div
              v-for="(imgage, imgIndex) in vouch.images"
              :key="imgIndex"
              class="item-image"
            >
              <a :href="imgage" target="_blank" rel="noopener noreferrer">
                <img :src="imgage" alt="">
              </a>
            </div>
          </div>
          <p v-if="vouch.remarks" class="refund-item-p">备注：{{ vouch.remarks }}</p>
        </el-row>
      </div>
      <el-dialog title="更改收款状态" :visible.sync="dialogFormVisible" width="600px">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="chengeOrder"
          label-position="right"
          label-width="150px"
        >
          <el-row :gutter="24" class="box-row" style="margin-bottom: 40px">
            <el-col
              :span="8"
            ><b>应收金额：</b> ￥{{ order.payTotalFee | amountfilters }}</el-col>
            <el-col
              :span="8"
            ><b>已收金额：</b>￥{{ receiptAmount | amountfilters }}</el-col>
            <el-col
              :span="8"
            ><b>未收金额：</b> ￥{{
              (order.payTotalFee - receiptAmount) | amountfilters
            }}</el-col>
          </el-row>
          <el-form-item label="订单本次收款金额:" prop="amount" :rules="rules.amount">
            <el-input v-model="chengeOrder.amount" style="width: 200px">
              <template slot="prepend">￥</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="disabled"
            @click="handleChangOrder"
          >确定</el-button>
        </div>
      </el-dialog>
      <Remarks
        dialog-title="订单备注信息"
        :is-visible.sync="dialogRemarksVisible"
        :order-id="dialogRemarksorderId"
        :remark-list="dialogRemarkList"
      />
    </el-card>
  </div>
</template>

<script>
import { getDetail, getRemarks, orderCheckReceipt } from '@/api/order'
import Remarks from './components/remarks'
export default {
  components: { Remarks },
  filters: {
    invoiceFilters(value) {
      const map = {
        0: '不开发票',
        1: '普通发票',
        2: '增值税发票'
      }
      return map[value]
    }
  },
  data() {
    const picValidator = (rule, value, callback) => {
      if (!this.chengeOrder.amount) {
        callback(new Error('请输入本次收款金额'))
      } else if (
        this.chengeOrder.amount >
        this.SubtrAount(this.order.payTotalFee, this.receiptAmount) * 1
      ) {
        callback(new Error('本次收款金额不能大于未收金额'))
      } else {
        callback()
      }
    }
    return {
      activeIndex: '2',
      order: null,
      receiptAmount: 0,
      returnValue: 0,
      returnedPurchaseFee: 0,
      bpClauses: null,
      dialogRemarkList: [],
      dialogRemarksVisible: false,
      dialogRemarksorderId: 0,
      dialogFormVisible: false,
      chengeOrder: {
        orderId: this.$route.query.orderId * 1,
        amount: null
      },
      orderInvoice: {},
      voucher: [],
      rules: {
        amount: [{ required: true, validator: picValidator, trigger: 'blur' }]
      },
      listLoading: false
    }
  },
  computed: {
    orderId: function() {
      return this.$route.query.orderId * 1
    },
    disabled() {
      return !(this.chengeOrder.amount > 0)
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getDetail({ id: this.orderId })
        .then((response) => {
          this.order = response.data.order
          this.bpClauses = response.data.bpClauses
          this.receiptAmount = response.data.receiptAmount
          this.returnValue = response.data.returnValue
          this.returnedPurchaseFee = response.data.returnedPurchaseFee
          this.orderInvoice = this.order.orderInvoice
          this.voucher = response.data.voucher
          this.listLoading = true
        })
        .catch(() => {
          this.listLoading = true
        })
    },
    // 设置发票文案
    setInvoiceText(data) {
      const map = {
        0: '个人',
        1: '单位'
      }
      let invoiceText = ''
      switch (data.type * 1) {
        case 0:
          invoiceText = `不开发票`
          break
        case 1:
          invoiceText = `普票-${map[data.invoiceTitleType * 1]}`
          break
        case 2:
          invoiceText = `专票`
          break
      }
      return invoiceText
    },
    RemarksOrder: function(id) {
      getRemarks(id).then((response) => {
        this.dialogRemarkList = response.data
      })
      this.dialogRemarksorderId = id
      this.dialogRemarksVisible = true
    },
    handeleDialogFormVisible() {
      this.dialogFormVisible = true
    },
    handeleDropdown(type, orderId, shopOrderId) {
      switch (type) {
        case 1: // 发货
          this.$router.push({ path: '/order/deliver', query: { orderId: orderId }})
          break
        case 2: // 发货记录
          this.$router.push({
            path: '/order/deliver-record',
            query: { orderId: orderId, shopOrderId }
          })
          break
        case 3: // 收付款记录
          this.$router.push({
            path: '/finance/remit-record',
            query: { orderId: orderId, shopOrderId }
          })
          break
        case 4: // 退款（退货）记录
          this.$router.push({
            path: '/finance/refund-record',
            query: { orderId: orderId, shopOrderId }
          })
          break
        case 5: // 订单备注
          this.$router.push({
            path: '/order/order-remarks',
            query: { orderId: orderId, shopOrderId }
          })
          break
        case 6: // 上传线下支付凭证
          this.$router.push({ path: '/order/pay-remarks', query: { orderId: orderId }})
          break
      }
    },
    async handleChangOrder() {
      // 确认本次收款金额
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.orderCheckReceipt()
        } else {
          return false
        }
      })
    },
    async orderCheckReceipt() {
      try {
        await orderCheckReceipt(this.chengeOrder)
        this.$message.success('操作成功')
        this.dialogFormVisible = false
        this.fetchData()
      } catch (error) {
        console.log('error', error)
      }
    },
    SubtrAount(arg1, arg2) {
      var r1, r2, m, n
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      m = Math.pow(10, Math.max(r1, r2))
      n = r1 >= r2 ? r1 : r2
      return ((arg1 * m - arg2 * m) / m).toFixed(n)
    },
    backToList() {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.$nextTick(() => {
          this.$router.replace({
            path: '/order/list'
          })
        })
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-row {
  position: relative;
}
.function {
  position: absolute;
  right: 0;
  width: auto;
}
.app-title {
  float: left;
  line-height: 36px;
  font-size: 18px;
  font-weight: bold;
  color: #999999;
}
.box-card {
  margin-top: 20px;
  font-size: 14px;
}
.box-row {
  padding: 10px 0;
}
.box-row .dropdown {
  margin-top: -10px;
}
.refund-item {
  padding: 10px 0;
  border-bottom: 1px dashed #e4e7ed;
}
.refund-item-p {
  width: 100%;
  line-height: 18px;
  font-size: 14px;
  color: #666666;
  float: left;
}
.refund-item-imgs {
  width: 100%;
  height: auto;
  margin: 5px 0;
}
.refund-item-imgs .item-image {
  width: 148px;
  height: 148px;
  margin-right: 10px;
  border: 1px dashed #e1e1e1;
  float: left;
}
.refund-item-imgs .item-image a {
  width: 148px;
  height: 148px;
  display: block;
}
.refund-item-imgs .item-image a img {
  width: 148px;
  height: 148px;
  display: block;
}
.order-item {
  background: #f7f7f7;
  padding: 10px 20px;
  box-sizing: border-box;
  border-radius: 5px;
  margin-bottom: 10px;
}
.product-row {
  padding: 10px 0;
  background: #ebeef5;
  border-top: 1px dashed #dcdfe6;
}
.op-item {
  padding: 5px 0;
}
</style>
