<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="应收应付" prop="settlementType">
        <el-select v-model="queryParams.settlementType" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.jy_settlement_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租户" prop="tenantId">
        <el-select v-model="queryParams.tenantId" placeholder="请选择租户" clearable filterable>
          <el-option v-for="item in tenantOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="结算年月" prop="settleYearMonth">
        <el-date-picker
          v-model="queryParams.settleYearMonth"
          type="month"
          value-format="yyyy-MM"
          placeholder="选择年月"
          clearable
        />
      </el-form-item>
      <el-form-item label="是否结算" prop="settleStatus">
        <el-select v-model="queryParams.settleStatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.jy_purchase_settle_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleBatchExportPdf"
          v-hasPermi="['jysystem:feeSettlement:exportPdf']"
        >批量导出PDF</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleBatchExportExcel"
          v-hasPermi="['jysystem:feeSettlement:exportExcel']"
        >批量导出Excel</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jysystem:feeSettlement:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="settlementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="结算单号" align="center" prop="settlementNo" width="200" show-overflow-tooltip />
      <el-table-column label="应收应付" align="center" prop="settlementType" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.jy_settlement_type" :value="scope.row.settlementType" />
        </template>
      </el-table-column>
      <el-table-column label="租户" align="center" prop="tenantName" min-width="140" show-overflow-tooltip />
      <el-table-column label="结算年月" align="center" prop="settleYearMonth" width="90" />
      <el-table-column label="制单日期" align="center" prop="settleDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.settleDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合计金额" align="center" prop="totalAmount" width="100">
        <template slot-scope="scope">
          <span>{{ formatAmount(scope.row.totalAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否已结算" align="center" prop="settleStatus" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.jy_purchase_settle_status" :value="scope.row.settleStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="320" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['jysystem:feeSettlement:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleExportPdf(scope.row)"
            v-hasPermi="['jysystem:feeSettlement:exportPdf']"
          >导出PDF</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleExportExcel(scope.row)"
            v-hasPermi="['jysystem:feeSettlement:exportExcel']"
          >导出Excel</el-button>
          <el-button
            v-if="scope.row.settleStatus === '0'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleSettle(scope.row)"
            v-hasPermi="['jysystem:feeSettlement:settle']"
          >已结算</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-dialog title="费用结算单详情" :visible.sync="detailOpen" width="960px" append-to-body>
      <el-descriptions v-if="detail" :column="3" border size="small" class="mb16">
        <el-descriptions-item label="结算单号">{{ detail.settlementNo }}</el-descriptions-item>
        <el-descriptions-item label="类型">
          <dict-tag :options="dict.type.jy_settlement_type" :value="detail.settlementType" />
        </el-descriptions-item>
        <el-descriptions-item label="租户">{{ detail.tenantName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="结算年月">{{ detail.settleYearMonth }}</el-descriptions-item>
        <el-descriptions-item label="制单日期">{{ parseTime(detail.settleDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="合计">{{ formatAmount(detail.totalAmount) }}</el-descriptions-item>
      </el-descriptions>
      <el-table v-if="detail && detail.itemList" :data="detail.itemList" size="small" border>
        <el-table-column type="expand" width="48">
          <template slot-scope="props">
            <el-table :data="props.row.logisticsList || []" size="mini" border>
              <el-table-column label="状态日志ID" prop="statusLogId" width="140" align="center" />
              <el-table-column label="物流费用" prop="logisticsFee" width="120" align="center">
                <template slot-scope="scope">{{ formatAmount(scope.row.logisticsFee) }}</template>
              </el-table-column>
            </el-table>
            <div v-if="!(props.row.logisticsList && props.row.logisticsList.length)" class="detail-empty-tip">无物流明细</div>
          </template>
        </el-table-column>
        <el-table-column label="订单号" prop="orderNo" min-width="160" show-overflow-tooltip />
        <el-table-column label="镜片价格" prop="lensPrice" width="100" align="center">
          <template slot-scope="scope">{{ formatAmount(scope.row.lensPrice) }}</template>
        </el-table-column>
        <el-table-column label="渐进多焦点价格" prop="progressivePrice" width="130" align="center">
          <template slot-scope="scope">{{ formatAmount(scope.row.progressivePrice) }}</template>
        </el-table-column>
        <el-table-column label="物流价格" prop="logisticsPrice" width="130" align="center">
          <template slot-scope="scope">
            {{ formatAmount(scope.row.logisticsPrice) }}
            <span v-if="scope.row.logisticsCount">（{{ scope.row.logisticsCount }}条）</span>
          </template>
        </el-table-column>
        <el-table-column label="合计" prop="totalAmount" width="100" align="center">
          <template slot-scope="scope">{{ formatAmount(scope.row.totalAmount) }}</template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="detail"
          type="primary"
          icon="el-icon-download"
          @click="handleExportPdf(detail)"
          v-hasPermi="['jysystem:feeSettlement:exportPdf']"
        >导出PDF</el-button>
        <el-button
          v-if="detail"
          type="success"
          icon="el-icon-download"
          @click="handleExportExcel(detail)"
          v-hasPermi="['jysystem:feeSettlement:exportExcel']"
        >导出Excel</el-button>
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFeeSettlement, getFeeSettlement, delFeeSettlement, settleFeeSettlement } from '@/api/jysystem/feeSettlement'
import { listTenant } from '@/api/jysystem/tenant'

export default {
  name: 'FeeSettlement',
  dicts: ['jy_settlement_type', 'jy_purchase_settle_status'],
  data() {
    return {
      loading: false,
      showSearch: true,
      ids: [],
      multiple: true,
      total: 0,
      settlementList: [],
      tenantOptions: [],
      selectedRows: [],
      detailOpen: false,
      detail: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        settlementType: undefined,
        tenantId: undefined,
        settleYearMonth: undefined,
        settleStatus: undefined
      }
    }
  },
  created() {
    this.getList()
    this.loadTenants()
  },
  methods: {
    getList() {
      this.loading = true
      listFeeSettlement(this.queryParams).then(response => {
        this.settlementList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    loadTenants() {
      listTenant({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.tenantOptions = response.rows || []
      })
    },
    formatAmount(value) {
      if (value == null || value === '') return '-'
      const num = Number(value)
      return Number.isNaN(num) ? value : num.toFixed(2)
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selectedRows = selection
      this.multiple = !selection.length
    },
    handleDetail(row) {
      getFeeSettlement(row.id).then(response => {
        this.detail = response.data
        this.detailOpen = true
      })
    },
    handleSettle(row) {
      this.$modal.confirm(`确认将结算单【${row.settlementNo}】标记为已结算？`).then(() => {
        return settleFeeSettlement(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(() => {})
    },
    handleExportPdf(row) {
      if (!row || !row.id) {
        return
      }
      const fileName = (row.settlementNo || 'fee-settlement') + '.pdf'
      this.download('jysystem/feeSettlement/exportPdf/' + row.id, {}, fileName)
    },
    handleExportExcel(row) {
      if (!row || !row.id) {
        return
      }
      const fileName = (row.settlementNo || 'fee-settlement') + '.xlsx'
      this.download('jysystem/feeSettlement/exportExcel/' + row.id, {}, fileName)
    },
    handleBatchExportPdf() {
      if (!this.ids.length) {
        this.$modal.msgWarning('请先选择要导出的结算单')
        return
      }
      const fileName = this.buildBatchFileName('pdf')
      this.download('jysystem/feeSettlement/exportPdf/batch/' + this.ids.join(','), {}, fileName)
    },
    handleBatchExportExcel() {
      if (!this.ids.length) {
        this.$modal.msgWarning('请先选择要导出的结算单')
        return
      }
      const fileName = this.buildBatchFileName('excel')
      this.download('jysystem/feeSettlement/exportExcel/batch/' + this.ids.join(','), {}, fileName)
    },
    buildBatchFileName(type) {
      if (this.ids.length === 1) {
        const row = this.selectedRows[0] || {}
        const baseName = row.settlementNo || 'fee-settlement'
        return type === 'pdf' ? `${baseName}.pdf` : `${baseName}.xlsx`
      }
      return `fee-settlements-${new Date().getTime()}.zip`
    },
    handleDelete(row) {
      const ids = row && row.id ? row.id : this.ids
      this.$modal.confirm('删除结算单将恢复关联订单物流费用的未结算状态，是否继续？').then(() => {
        return delFeeSettlement(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.mb16 {
  margin-bottom: 16px;
}
.detail-empty-tip {
  padding: 8px 0;
  color: #909399;
  font-size: 12px;
}
</style>
