<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="settlementNo">
          <template slot="label">{{ tmT("querySettlementNo") }}</template>
          <el-input
            v-model="queryParams.settlementNo"
            :placeholder="tmT('querySettlementNoPh')"
            clearable
            style="width: 180px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="orderNo">
          <template slot="label">{{ tmT("queryOrderNo") }}</template>
          <el-input
            v-model="queryParams.orderNo"
            :placeholder="tmT('queryOrderNoPh')"
            clearable
            style="width: 180px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ tmCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ tmCommon("reset") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <el-table-column :label="tmT('colSettlementNo')" prop="settlementNo" align="center" min-width="130" :show-overflow-tooltip="true" />
        <el-table-column :label="tmT('colCreateTime')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime) : dash }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colOrderNo')" prop="orderNo" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="tmT('colSupplier')" prop="supplierName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="tmT('colTotalHeads')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.totalHeads }}{{ tmT("unitHead") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colTotalAmount')" align="center" width="120">
          <template slot-scope="scope">
            <span>{{ formatAmount(scope.row.totalAmount) }}{{ tmT("unitYuan") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colServiceFee')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ formatAmount(scope.row.serviceFeeAmount) }}{{ tmT("unitYuan") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colPayableAmount')" align="center" width="130">
          <template slot-scope="scope">
            <span>{{ formatAmount(scope.row.payableAmount) }}{{ tmT("unitYuan") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colSettlementStatus')" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="isPending(scope.row) ? 'warning' : 'success'" size="small">{{ settlementStatusLabel(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colSettleVoucher')" align="center" width="90">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.settleVoucherUrl"
              :src="mediaUrl(scope.row.settleVoucherUrl)"
              :preview-src-list="[mediaUrl(scope.row.settleVoucherUrl)]"
              fit="cover"
              class="settle-list-voucher"
            />
            <span v-else>{{ dash }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colSettleFinishTime')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.settleFinishTime || dash }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmCommon('colOp')" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="isPending(scope.row)"
              v-hasPermi="['tradeMarket:supplierSettlement:settle']"
              type="text"
              size="mini"
              @click="openCompleteSettle(scope.row)"
            >{{ tmT("btnCompleteSettle") }}</el-button>
            <el-button
              v-if="isCompleted(scope.row)"
              v-hasPermi="['tradeMarket:supplierSettlement:query']"
              type="text"
              size="mini"
              @click="handlePrint(scope.row)"
            >{{ tmT("btnPrintVoucher") }}</el-button>
            <el-button v-hasPermi="['tradeMarket:supplierSettlement:query']" type="text" size="mini" @click="handleView(scope.row)">{{ tmCommon("view") }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 完成结算 -->
    <el-dialog :title="tmT('dialogCompleteSettle')" :visible.sync="settleOpen" width="520px" append-to-body @close="cancelSettle">
      <el-form ref="settleFormRef" :model="settleForm" label-width="120px">
        <el-form-item prop="settleVoucherPath" :rules="settleFormRules.settleVoucherPath">
          <template slot="label">{{ tmT("formSettleVoucher") }}</template>
          <el-upload
            class="settle-voucher-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            accept=".jpg,.jpeg,.png"
            :before-upload="beforeVoucherUpload"
            :on-success="handleVoucherUploadSuccess"
            :on-error="handleUploadHttpError"
          >
            <img v-if="settleForm.settleVoucherUrl" :src="mediaUrl(settleForm.settleVoucherUrl)" class="settle-voucher-preview">
            <i v-else class="el-icon-plus settle-voucher-icon" />
          </el-upload>
          <div class="el-upload__tip">{{ tmT("tipSettleVoucher") }}</div>
          <el-button v-if="settleForm.settleVoucherPath" type="text" size="mini" @click="clearSettleVoucher">{{ tmCommon("delete") }}</el-button>
        </el-form-item>
        <div class="form-tip">{{ tmT("tipCompleteSettle") }}</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCompleteSettle">{{ tmCommon("ok") }}</el-button>
        <el-button @click="cancelSettle">{{ tmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog :title="tmCommon('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form label-width="140px" size="small">
        <el-form-item :label="tmT('colSettlementNo')"><span>{{ viewRow.settlementNo }}</span></el-form-item>
        <el-form-item :label="tmT('colCreateTime')"><span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : dash }}</span></el-form-item>
        <el-form-item :label="tmT('colOrderNo')"><span>{{ viewRow.orderNo }}</span></el-form-item>
        <el-form-item :label="tmT('colSupplier')"><span>{{ viewRow.supplierName }}</span></el-form-item>
        <el-form-item :label="tmT('colTotalHeads')"><span>{{ viewRow.totalHeads }}{{ tmT("unitHead") }}</span></el-form-item>
        <el-form-item :label="tmT('colTotalAmount')"><span>{{ formatAmount(viewRow.totalAmount) }}{{ tmT("unitYuan") }}</span></el-form-item>
        <el-form-item :label="tmT('formFeeSnapshot')"><span>{{ feeSnapshotText(viewRow) }}</span></el-form-item>
        <el-form-item :label="tmT('colServiceFee')"><span>{{ formatAmount(viewRow.serviceFeeAmount) }}{{ tmT("unitYuan") }}</span></el-form-item>
        <el-form-item :label="tmT('colPayableAmount')"><span>{{ formatAmount(viewRow.payableAmount) }}{{ tmT("unitYuan") }}</span></el-form-item>
        <el-form-item :label="tmT('colSettlementStatus')">
          <el-tag :type="isPending(viewRow) ? 'warning' : 'success'" size="small">{{ settlementStatusLabel(viewRow) }}</el-tag>
        </el-form-item>
        <el-form-item :label="tmT('formSettleVoucher')">
          <el-image
            v-if="viewRow.settleVoucherUrl"
            :src="mediaUrl(viewRow.settleVoucherUrl)"
            :preview-src-list="[mediaUrl(viewRow.settleVoucherUrl)]"
            fit="cover"
            class="settle-view-voucher"
          />
          <span v-else>{{ dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('colSettleFinishTime')"><span>{{ viewRow.settleFinishTime || dash }}</span></el-form-item>
        <el-form-item :label="tmT('viewCreateBy')"><span>{{ viewRow.createBy || dash }}</span></el-form-item>
        <el-form-item :label="tmT('viewCreateTime')"><span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : dash }}</span></el-form-item>
        <el-form-item :label="tmT('viewUpdateBy')"><span>{{ viewRow.updateBy || dash }}</span></el-form-item>
        <el-form-item :label="tmT('viewUpdateTime')"><span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : dash }}</span></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="isPending(viewRow)"
          v-hasPermi="['tradeMarket:supplierSettlement:settle']"
          type="primary"
          plain
          @click="openCompleteSettleFromView"
        >{{ tmT("btnCompleteSettle") }}</el-button>
        <el-button
          v-if="isCompleted(viewRow)"
          v-hasPermi="['tradeMarket:supplierSettlement:query']"
          type="primary"
          plain
          @click="handlePrint(viewRow)"
        >{{ tmT("btnPrintVoucher") }}</el-button>
        <el-button @click="viewOpen = false">{{ tmCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import { parseTime } from "@/utils/ruoyi"
import tradeMarketLocaleMixin from "@/mixins/tradeMarketLocaleMixin"
import {
  listSupplierSettlement,
  getSupplierSettlement,
  completeSupplierSettlement
} from "@/api/tradeMarket/supplierSettlement"

const SETTLEMENT_STATUS_PENDING = "0"
const SETTLEMENT_STATUS_COMPLETED = "1"
const FEE_METHOD_PER_HEAD = 2
const FEE_METHOD_BY_AMOUNT = 3
const PHOTO_EXTS = ["jpg", "jpeg", "png"]
const MAX_PHOTO_MB = 10

export default {
  name: "TradeMarketSupplierSettlement",
  mixins: [tradeMarketLocaleMixin],
  data() {
    return {
      tmNs: "supplierSettlement",
      loading: false,
      viewOpen: false,
      settleOpen: false,
      viewRow: {},
      total: 0,
      tableList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        settlementNo: undefined,
        orderNo: undefined
      },
      settleForm: {
        id: undefined,
        settleVoucherUrl: undefined,
        settleVoucherPath: undefined
      }
    }
  },
  computed: {
    dash() {
      return this.$t("tradeMarket.status.dash")
    },
    uploadAction() {
      return process.env.VUE_APP_BASE_API + "/common/upload"
    },
    uploadHeaders() {
      return { Authorization: "Bearer " + getToken() }
    },
    settleFormRules() {
      return {
        settleVoucherPath: [{ validator: this.validateSettleVoucher, trigger: "change" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    parseTime,
    isPending(row) {
      return row && row.settlementStatus === SETTLEMENT_STATUS_PENDING
    },
    isCompleted(row) {
      return row && row.settlementStatus === SETTLEMENT_STATUS_COMPLETED
    },
    settlementStatusLabel(row) {
      if (row && row.settlementStatusName) {
        return row.settlementStatusName
      }
      return this.isCompleted(row) ? this.tmT("statusCompleted") : this.tmT("statusPending")
    },
    formatAmount(val) {
      if (val == null || val === "") {
        return "0.00"
      }
      const n = Number(val)
      if (isNaN(n)) {
        return String(val)
      }
      return n.toFixed(2)
    },
    mediaUrl(url) {
      if (!url) {
        return ""
      }
      if (/^https?:\/\//i.test(url)) {
        return url
      }
      return process.env.VUE_APP_BASE_API + url
    },
    feeSnapshotText(row) {
      if (!row || row.feeMethod == null) {
        return this.dash
      }
      const name = row.feeMethodName || this.dash
      if (row.feeMethod === FEE_METHOD_PER_HEAD && row.feeStandard != null) {
        return `${name}：${this.formatAmount(row.feeStandard)}${this.tmT("unitYuanPerHead")}`
      }
      if (row.feeMethod === FEE_METHOD_BY_AMOUNT) {
        const tx = row.transactionFeeRate != null ? row.transactionFeeRate : this.dash
        const mg = row.managementFeeRate != null ? row.managementFeeRate : this.dash
        return `${name}：${this.tmT("labelTransactionRate")}${tx}% ${this.tmT("labelManagementRate")}${mg}%`
      }
      return name
    },
    validateSettleVoucher(rule, value, callback) {
      if (!this.settleForm.settleVoucherPath) {
        callback(new Error(this.tmT("ruleSettleVoucher")))
        return
      }
      callback()
    },
    extOf(fileName) {
      if (!fileName || fileName.lastIndexOf(".") < 0) {
        return ""
      }
      return fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase()
    },
    beforeVoucherUpload(file) {
      const ext = this.extOf(file.name)
      if (!PHOTO_EXTS.includes(ext)) {
        this.$modal.msgError(this.tmT("errPhotoFmt"))
        return false
      }
      if (file.size / 1024 / 1024 > MAX_PHOTO_MB) {
        this.$modal.msgError(this.tmT("errPhotoMb"))
        return false
      }
      return true
    },
    handleVoucherUploadSuccess(res) {
      if (res.code === 200) {
        this.settleForm.settleVoucherUrl = res.url
        this.settleForm.settleVoucherPath = res.fileName
        this.$nextTick(() => {
          if (this.$refs.settleFormRef) {
            this.$refs.settleFormRef.validateField("settleVoucherPath")
          }
        })
      } else {
        this.$modal.msgError(res.msg || this.tmT("errPhotoFmt"))
      }
    },
    clearSettleVoucher() {
      this.settleForm.settleVoucherUrl = undefined
      this.settleForm.settleVoucherPath = undefined
    },
    handleUploadHttpError() {
      this.$modal.msgError(this.tmT("errPhotoFmt"))
    },
    getList() {
      this.loading = true
      listSupplierSettlement(this.queryParams)
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total != null ? res.total : 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.settlementNo = undefined
      this.queryParams.orderNo = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleView(row) {
      getSupplierSettlement(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    openCompleteSettle(row) {
      this.settleForm = {
        id: row.id,
        settleVoucherUrl: undefined,
        settleVoucherPath: undefined
      }
      this.settleOpen = true
      this.$nextTick(() => {
        if (this.$refs.settleFormRef) {
          this.$refs.settleFormRef.clearValidate()
        }
      })
    },
    openCompleteSettleFromView() {
      this.viewOpen = false
      this.openCompleteSettle(this.viewRow)
    },
    cancelSettle() {
      this.settleOpen = false
      this.settleForm = { id: undefined, settleVoucherUrl: undefined, settleVoucherPath: undefined }
    },
    submitCompleteSettle() {
      this.$refs.settleFormRef.validate((valid) => {
        if (!valid) {
          return
        }
        completeSupplierSettlement({
          id: this.settleForm.id,
          settleVoucherUrl: this.settleForm.settleVoucherUrl,
          settleVoucherPath: this.settleForm.settleVoucherPath
        }).then(() => {
          this.$modal.msgSuccess(this.tmT("msgSettleOk"))
          this.settleOpen = false
          this.getList()
        })
      })
    },
    handlePrint(row) {
      getSupplierSettlement(row.id).then((res) => {
        const data = res.data || {}
        if (!this.isCompleted(data)) {
          this.$modal.msgWarning(this.tmT("ruleVoucherCompletedOnly"))
          return
        }
        this.openPrintWindow(data)
      })
    },
    openPrintWindow(row) {
      const title = this.tmT("printVoucherTitle")
      const voucherHtml = row.settleVoucherUrl
        ? `<p><strong>${this.tmT("formSettleVoucher")}：</strong><br/><img src="${this.mediaUrl(row.settleVoucherUrl)}" style="max-width:320px;margin-top:8px;" /></p>`
        : ""
      const html = `<!DOCTYPE html><html><head><meta charset="utf-8"/><title>${title}</title>
        <style>body{font-family:sans-serif;padding:24px;font-size:14px;} h2{text-align:center;}</style></head><body>
        <h2>${title}</h2>
        <p>${this.tmT("colSettlementNo")}：${row.settlementNo || ""}</p>
        <p>${this.tmT("colOrderNo")}：${row.orderNo || ""}</p>
        <p>${this.tmT("colSupplier")}：${row.supplierName || ""}</p>
        <p>${this.tmT("colTotalHeads")}：${row.totalHeads || 0}${this.tmT("unitHead")}</p>
        <p>${this.tmT("colTotalAmount")}：${this.formatAmount(row.totalAmount)}${this.tmT("unitYuan")}</p>
        <p>${this.tmT("formFeeSnapshot")}：${this.feeSnapshotText(row)}</p>
        <p>${this.tmT("colServiceFee")}：${this.formatAmount(row.serviceFeeAmount)}${this.tmT("unitYuan")}</p>
        <p>${this.tmT("colPayableAmount")}：${this.formatAmount(row.payableAmount)}${this.tmT("unitYuan")}</p>
        <p>${this.tmT("colSettlementStatus")}：${this.settlementStatusLabel(row)}</p>
        <p>${this.tmT("colCreateTime")}：${row.createTime ? parseTime(row.createTime) : ""}</p>
        <p>${this.tmT("colSettleFinishTime")}：${row.settleFinishTime || ""}</p>
        ${voucherHtml}
        </body></html>`
      const win = window.open("", "_blank")
      if (!win) {
        this.$modal.msgError(this.tmT("errPrintBlocked"))
        return
      }
      win.document.write(html)
      win.document.close()
      win.focus()
      win.print()
    }
  }
}
</script>

<style scoped lang="scss">
.form-tip {
  color: #909399;
  font-size: 12px;
  margin: 0 0 8px 120px;
}
.settle-list-voucher {
  width: 48px;
  height: 48px;
  border-radius: 4px;
}
.settle-view-voucher {
  width: 120px;
  height: 120px;
  border-radius: 4px;
}
.settle-voucher-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  overflow: hidden;
}
.settle-voucher-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.settle-voucher-preview {
  width: 120px;
  height: 120px;
  object-fit: cover;
  display: block;
}
.settle-voucher-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>
