<style lang="less">
	@import "@/styles/table-common.less";
	@import "./logiticsCompany.less";
</style>
<template>
	<div class="search">
		<Card>
			<Row>
				<Form ref="searchForm" :model="searchForm" inline :label-width="100">
					<FormItem label="选择时间" prop="settlementDate">
						<DatePicker @on-change="changeDate" type="date" placeholder="请选择时间" style="width: 200px" />
					</FormItem>
					<FormItem style="margin-left: -35px" class="br">
						<Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
					</FormItem>
				</Form>
			</Row>
			<Row align="middle" justify="space-between" class="operation">
				<div>
					<Button @click="oneSettlement" icon="md-folder-open" :loading="settlementLoading" :disabled="settlementLoading">结算</Button>
				</div>
			</Row>
			<Alert show-icon v-show="openTip">
				已选择
				<span class="select-count">{{ selectList.length }}</span> 项
				<a class="select-clear" @click="clearSelectAll">清空</a>
			</Alert>
			<Table :loading="loading" border :columns="columns" :data="data"
				@on-selection-change="allSelect" ref="table"></Table>
			<Row type="flex" justify="end" class="page">
				<Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize"
					@on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10, 20, 50]"
					size="small" show-total show-elevator show-sizer></Page>
			</Row>
			<Modal title="商家结算明细" v-model="detailVisible" :mask-closable="false" :width="1500">
				<Table :loading="detailLoading" border :columns="detailColumns" :data="detailData"></Table>
				<div slot="footer">
					<Button type="text" @click="detailVisible = false">关闭</Button>
				</div>
			</Modal>
			<Modal title="订单详情" v-model="orderDetailVisible" :mask-closable="false" :scrollabele="true" :width="1000">
				<logistics-address v-if="orderDetailVisible" @closePage="closeOrderDetail" ref="orderDetailDialog"></logistics-address>
				<div slot="footer" v-show="orderDetailVisible">
					<Button type="text" @click="orderDetailVisible = false">关闭</Button>
				</div>
			</Modal>
		</Card>
	</div>
</template>

<script>
	import {
		getBillList,
		getBillDetailList,
		settlementConfirm
	} from "@/api/app";
	import logisticsAddress from "@/views/sys/order-manage/logisticsAddress";
	export default {
		name: "logiticsCompany",
		components: {
			logisticsAddress,
		},
		data() {
			return {
				dictData: [{
					title: "全部",
					value: ""
				}, {
					title: "待确认",
					value: 0
				}, {
					title: "待结算",
					value: 1
				}, {
					title: "已打款",
					value: 2
				}],
				openTip: true,
				loading: true,
				reading: false,
				drop: false,
				selectList: [],
				settledShopIds: [],
				searchForm: {
					regionId:JSON.parse(this.getStore("user")).departmentId,
					settlementDate:'',
					status: 0,
					pageNumber: 1,
					pageSize: 10
				},
				form: {},
				columns: [{
						type: "selection",
						width: 60,
						align: "center",
						fixed: "left",
					},
					{
						type: "index",
						width: 60,
						align: "center",
						fixed: "left",
					},
					{
						title: "账单周期",
						key: "billTime",
						width: 120,
					},
					{
						title: "店铺名称",
						key: "shopName",
						minWidth: 160,
					},
					{
						title: "记录数",
						key: "recordCount",
						width: 90,
					},
					{
						title: "正向记录",
						key: "positiveCount",
						width: 90,
					},
					{
						title: "扣款记录",
						key: "negativeCount",
						width: 90,
					},
					{
						title: "结算基数",
						key: "totalBaseAmount",
						width: 110,
					},
					{
						title: "正向结算",
						key: "positiveSettlementAmount",
						width: 110,
					},
					{
						title: "退款/售后扣款",
						key: "negativeSettlementAmount",
						width: 130,
					},
					{
						title: "平台抽佣",
						key: "totalCommissionAmount",
						width: 110,
					},
					{
						title: "应结算金额",
						key: "totalSettlementAmount",
						width: 120,
					},
					{
						title: "操作",
						key: "action",
						width: 200,
						align: "center",
						fixed: "right",
						render: (h, params) => {
							return h("div", [
								h(
									"a", {
										on: {
											click: () => {
												this.stationBinding(params.row);
											},
										},
									},
									"详情"
								)
							]);
						},
					},
				],
				detailColumns: [
					{ title: "订单号", key: "orderNumber", minWidth: 140 },
					{ title: "订单ID", key: "orderId", minWidth: 170 },
					{ title: "类型", key: "type", width: 100, render: (h, params) => h("span", params.row.type == 2 ? "退款/售后扣款" : "正常结算") },
					{ title: "结算基数", key: "baseAmount", width: 110 },
					{ title: "抽佣比例%", key: "commissionRate", width: 110 },
					{ title: "平台抽佣", key: "commissionAmount", width: 110 },
					{ title: "商家结算", key: "settlementAmount", width: 110 },
					{ title: "退款/售后ID", key: "refundId", minWidth: 170 },
					{ title: "生成时间", key: "createTime", minWidth: 170, render: (h, params) => h("span", this.formatDateTime(params.row.createTime)) },
					{ title: "支付时间", key: "payTime", minWidth: 170, render: (h, params) => h("span", this.formatDateTime(params.row.payTime)) },
					{
						title: "操作",
						key: "action",
						width: 100,
						align: "center",
						fixed: "right",
						render: (h, params) => h("a", { on: { click: () => this.showOrderDetail(params.row) } }, "查看详情")
					}
				],
				data: [],
				detailData: [],
				total: 0,
				Visiable: false,
				detailVisible: false,
				orderDetailVisible: false,
				detailLoading: false,
				settlementLoading: false,
			};
		},
		methods: {
			init() {
				this.searchForm.settlementDate = this.getTime()
				this.getDataList();
			},
			changeDate(v){
				this.searchForm.settlementDate = v
				this.settledShopIds = []
			},
			handleSearch() {
				this.searchForm.pageNumber = 1;
				this.getDataList();
			},
			formatDateTime(isoString) {
				if (!isoString) return ''
				const date = new Date(isoString)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hours = String(date.getHours()).padStart(2, '0')
				const minutes = String(date.getMinutes()).padStart(2, '0')
				const seconds = String(date.getSeconds()).padStart(2, '0')
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
			},
			getTime() {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			allSelect(v){
				this.selectList = v
			},
			oneSettlement(){
				if (this.settlementLoading) return
				if (this.selectList.length === 0) {
					this.$Message.warning("请选择要结算的商家");
					return
				}
				const isCurrentPageEmpty = this.selectList.length >= this.data.length && this.searchForm.pageNumber > 1
				let data = {
					shopIds:[],
					settlementDate:this.searchForm.settlementDate,
					regionId:JSON.parse(this.getStore("user")).departmentId
				}
				for(let i=0;i<this.selectList.length;i++){
					data.shopIds.push(this.selectList[i].shopId)
				}
				this.settlementLoading = true
				settlementConfirm(data).then((res) => {
					if (res.success) {
						this.$Message.success("结算成功");
						this.settledShopIds = this.settledShopIds.concat(data.shopIds).filter((shopId, index, list) => list.indexOf(shopId) === index);
						this.clearSelectAll();
						this.selectList = [];
						if (isCurrentPageEmpty) {
							this.searchForm.pageNumber -= 1;
							this.getDataList();
						} else {
							this.data = this.data.filter(item => this.settledShopIds.indexOf(item.shopId) === -1);
							this.total = Math.max(this.total - data.shopIds.length, 0);
						}
					}
				}).finally(() => {
					this.settlementLoading = false
				});
			},
			clearSelectAll(){
				this.$refs.table.selectAll(false);
			},
			getDataList() {
				// 多条件搜索用户列表
				this.loading = true;
				getBillList(this.searchForm).then((res) => {
					this.loading = false;
					if (res.success) {
						const records = (res.result && res.result.records) || res.result || []
						const total = (res.result && res.result.total) || records.length
						const hasSettledRecords = records.some(item => this.settledShopIds.indexOf(item.shopId) !== -1)
						this.data = records.filter(item => this.settledShopIds.indexOf(item.shopId) === -1)
						this.total = hasSettledRecords ? Math.max(total - this.settledShopIds.length, 0) : total
					}
				});
			},
			changePage(v) {
				this.searchForm.pageNumber = v;
				this.getDataList();
			},
			changePageSize(v) {
				this.searchForm.pageNumber = 1;
				this.searchForm.pageSize = v;
				this.getDataList();
			},
			stationBinding(row) {
				this.detailVisible = true
				this.detailLoading = true
				getBillDetailList({
					regionId: this.searchForm.regionId,
					settlementDate: this.searchForm.settlementDate,
					shopId: row.shopId,
					status: 0
				}).then((res) => {
					this.detailLoading = false
					if (res.success) {
						this.detailData = res.result || []
					}
				}).catch(() => {
					this.detailLoading = false
				})
			},
			closeOrderDetail(){
				this.orderDetailVisible = false;
			},
			showOrderDetail(row) {
				let data = {
					id: row.orderId,
					shopId: row.shopId || "",
					status: "",
				};
				this.orderDetailVisible = true;
				this.$nextTick(() => {
					this.$refs.orderDetailDialog.initRecharge(data);
				});
			}
		},
		mounted() {
			this.init();
		},
	};
</script>