<template>
  <el-dialog
    :visible.sync="visible"
    v-bind="modalOptions"
    append-to-body
  >
    <div>
      <div style="display: flex;justify-content: flex-end;padding: 0 0 10px;">
        <!-- v-if="formData.relatedOrders[orderSn] && formData.relatedOrders[orderSn].some(i => i.cerePayLog.Sub_Acc_Stcd === '01')" -->
        <el-button
          v-if="formData.relatedOrders[orderSn] &&
            (formData.relatedOrders[orderSn].some(i => ['0', '3'].includes(i.cerePayLog.hsbSplitState)) || formData.relatedOrders[orderSn].some(i => i.cerePayLog.Sub_Acc_Stcd === '01'))"
          type="danger" size="medium"
          @click="handleConfirmSn()"
        >
          三方订单确认
        </el-button>
      </div>
      <div>
        <el-table
          v-loading="!formData.relatedOrders[orderSn]" height="60vh" element-loading-text="暂无关联订单数据"
          :data="formData.relatedOrders[orderSn]"
          v-bind="{ stripe: true, size: 'small', border: true, fit: true, highlightCurrentRow: true }"
        >
          <el-table-column align="center" min-width="80" prop="orderId" label="订单ID" />
          <el-table-column align="center" min-width="120" label="分账处理状态" prop="cerePayLog.hsbSplitState">
            <template slot-scope="{ row }">
              <span v-if="row.cerePayLog.hsbSplitState === '0'">未分账</span>
              <span v-else-if="row.cerePayLog.hsbSplitState === '1'">分账中</span>
              <span v-else-if="row.cerePayLog.hsbSplitState === '2'">已分账</span>
              <span v-else-if="row.cerePayLog.hsbSplitState === '3'">分账失败</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="center" min-width="100" prop="cerePayLog.transactionId" label="三方交易流水号" show-overflow-tooltip />
          <el-table-column align="center" min-width="120" label="分账指令发送状态" prop="cerePayLog.Sub_Acc_Stcd">
            <template slot-scope="{ row }">
              <span v-if="row.cerePayLog.Sub_Acc_Stcd === '00'">成功</span>
              <span v-else-if="row.cerePayLog.Sub_Acc_Stcd === '01'">失败</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="center" min-width="100" prop="cerePayLog.Err_Inf" label="错误信息" show-overflow-tooltip />
          <el-table-column label="操作" width="140" fixed="right" class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <el-button
                v-if="row.cerePayLog.Clrglist && row.cerePayLog.Clrglist.length"
                type="warning" size="mini" @click="$refs.ClearingDetails && $refs.ClearingDetails.handleOpen(row.cerePayLog)"
              >
                清算明细列表
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 清算明细 -->
      <ClearingDetails ref="ClearingDetails" />
    </div>
  </el-dialog>
</template>

<script>
import ClearingDetails from './ClearingDetails'
import { getWithdrawalHsbOrderDistribution, updateWithdrawalTryConfirmSn } from '@/api/withdrawal'

export default {
  name: 'LedgerInformation',
  components: {
    ClearingDetails
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '1100px',
        title: '查看惠市宝订单的分账信息'
      },
      visible: false,
      formData: {
        withdrawalId: '',
        relatedSettlement: [],
        relatedOrders: {},
        relatedPresenterVoucherLogs: {},
        relatedCommissionLogs: {},
        relatedBuyerUsers: []
      },
      orderSn: '' // 结算编号
    }
  },
  methods: {
    handleClose() {
      this.visible = false
    },
    async initList() {
      this.formData.relatedOrders[this.orderSn] = this.formData.relatedOrders[this.orderSn].map((item) => {
        item.cerePayLog = Object.assign({
          id: '',
          shopId: '',
          orderFormid: '',
          outTradeNo: '',
          transactionId: '', // 支付订单三方编号。三方交易流水号
          outRefundNo: '',
          totalFee: '',
          refundFee: '',
          userId: '',
          state: '',
          remark: '',
          paymentMode: '',
          after: '',
          createTime: '',
          extInfo: '',
          hsbSplitState: '',
          hsbHandlingFee: ''
        }, item.cerePayLog || {}, {
          Clrglist: [],
          Sign_Inf: '',
          Rsp_Inf: '',
          Svc_Rsp_Cd: '',
          Svc_Rsp_St: '',
          Py_Trn_No: '',
          Sub_Acc_Stcd: '', // 该笔订单的分账处理状态 00-分账处理成功(分账处理成功，会有部分商家因收款账号异常导致分账失败) 01-分账处理失败
          Ittparty_Tms: '',
          Ittparty_Jrnl_No: '',
          Err_Inf: '' // 错误信息。分账处理状态为01时有值
        })
        return item
      })
      const loading = this.$loading({ text: '加载中' })
      try {
        for (let index = 0; index < this.formData.relatedOrders[this.orderSn].length; index++) {
          if (['1', '2'].includes(this.formData.relatedOrders[this.orderSn][index].cerePayLog.hsbSplitState)) {
            await getWithdrawalHsbOrderDistribution({
              transactionId: this.formData.relatedOrders[this.orderSn][index].cerePayLog.transactionId
            }).then((res) => {
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Clrglist = res.data.Clrglist || []
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Sign_Inf = res.data.Sign_Inf
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Rsp_Inf = res.data.Rsp_Inf
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Svc_Rsp_Cd = res.data.Svc_Rsp_Cd
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Svc_Rsp_St = res.data.Svc_Rsp_St
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Py_Trn_No = res.data.Py_Trn_No
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Sub_Acc_Stcd = res.data.Sub_Acc_Stcd
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Ittparty_Tms = res.data.Ittparty_Tms
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Ittparty_Jrnl_No = res.data.Ittparty_Jrnl_No
              this.formData.relatedOrders[this.orderSn][index].cerePayLog.Err_Inf = res.data.Err_Inf
            })
          }
        }
        console.log(this.formData.relatedOrders[this.orderSn])
      } finally {
        loading.close()
      }
    },
    handleOpen(params = {}, orderSn) {
      this.formData = Object.assign(this.$options.data().formData, JSON.parse(JSON.stringify(params)))
      this.orderSn = orderSn
      this.initList()
      if (params.withdrawalId) {
        // this.getInfo(params.withdrawalId)
      }
      this.visible = true
    },
    async getInfo(id) {
      const loading = this.$loading({ text: '加载中' })
      try {
        const res = await xxx({ id })
        this.formData = Object.assign(this.$options.data().formData, res.data, {
          withdrawalId: res.data.withdrawalId || ''
        })
      } finally {
        loading.close()
      }
    },

    handleConfirmSn() {
      this.$confirm('确定尝试三方订单确认？', '确认收货')
        .then(async () => {
          await updateWithdrawalTryConfirmSn({ settlementSn: this.orderSn })
          this.$message({ message: '操作成功！', type: 'success' })
          this.$emit('success')
          this.visible = false
        })
        .catch(() => { })
    }
  }
}
</script>

<style lang="scss" scoped>
.small-padding {
	.cell {
		padding-left: 5px;
		padding-right: 5px;
	}
}

.fixed-width {
	.el-button--mini {
		padding: 7px 10px;
	}
}
</style>

