<template>
    <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="门店名称" prop="orgName">
        <el-input v-model="queryParams.orgName" placeholder="请输入门店名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.settlement_status_type" :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" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
        <el-table v-loading="loading" fit highlight-current-row border stripe :data="billList" @selection-change="handleSelectionChange">
            <el-table-column label="门店名称" align="center" prop="orgName" width="130px" />
            <el-table-column label="账单标题" align="center" prop="title" width="100px" />
            <el-table-column label="开始时间" align="center" prop="beginTime" width="100px" />
            <el-table-column label="结束时间" align="center" prop="endTime" width="100px" />
            <el-table-column label="清算状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.settlement_status_type" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="会员剩余金额" align="center" prop="memberBalance" width="100px" />
            <el-table-column label="应付押金" align="center" prop="payableDeposit" width="100px" />
            <el-table-column label="已付押金" align="center" prop="paidDeposit" width="130px" />
            <el-table-column label="福利金额" align="center" prop="welfareAmount" width="130px" />
            <el-table-column label="福利押金" align="center" prop="welfareDeposit" width="150px" />
            <el-table-column label="卡密押金" align="center" prop="cardPasswordDeposit" width="100px" />
            <el-table-column label="未开卡卡密金额" align="center" prop="unopenedCardPasswordAmount" width="140px" />
            <el-table-column label="已付卡密押金" align="center" prop="paidCardPasswordDeposit" width="130px" />
            <el-table-column label="已付福利押金" align="center" prop="paidWelfareDeposit" width="100px" />
      <el-table-column label="支付宝/微信" align="center" prop="alipayAndWechatAmount" width="130px">
        <template slot-scope="scope">
          <el-tag size="mini" type="success">微信实收：¥{{ scope.row.wechatAmount || '0' }}</el-tag>
          <el-tag size="mini" type="warning">支付宝实收：¥{{ scope.row.alipayAmount || '0' }}</el-tag>
        </template> 
      </el-table-column>
            <el-table-column label="原材料备用金" align="center" prop="materialImprestAmount" width="100px" />
      <el-table-column label="原材料剩余金额" align="center" prop="materialImprestRemainAmount" width="120px" />
            <el-table-column label="系统维护费" align="center" prop="systemMaintenanceAmount" width="100px" />
            <el-table-column label="洗衣费" align="center" prop="washClothAmount" width="100px" />
            <el-table-column label="快递费" align="center" prop="expressAmount" width="100px" />
            <el-table-column label="跨店结算金" align="center" prop="crossStoreSettlementAmount" width="100px" />
            <!-- <el-table-column label="超额订货金额" align="center" prop="overOrderingAmount" width="100px" /> -->
            <el-table-column label="结算金额" align="center" prop="settlementAmount" width="100px" />
                        <el-table-column label="备注" align="center" prop="remark" width="120px" >
                <template slot-scope="scope">
                    {{ scope.row.remark || "--" }}
                </template>
                </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
                <template slot-scope="scope">
                    <el-button type="text" @click="getDetail(scope.row)">详情</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="title" :visible.sync="open" width="80%" append-to-body v-if="settlementManageStore">
      <el-row :gutter="20">
        <!-- 基本信息 -->
        <el-col :span="24">
          <el-card class="box-card">
            <div slot="header">
              <span>基本信息</span>
            </div>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="门店名称">{{ sysStore && sysStore.name || '--' }}</el-descriptions-item>
              <el-descriptions-item label="开始时间">{{ settlementManageStore && settlementManageStore.beginTime || '--' }}</el-descriptions-item>
              <el-descriptions-item label="结束时间">{{ settlementManageStore && settlementManageStore.endTime || '--' }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>

        <!-- 收支明细 -->
        <el-col :span="24">
          <el-card class="box-card">
            <div slot="header">
              <span>收支明细</span>
            </div>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="微信到账">{{ settlementManageStore.wechatAmount}}</el-descriptions-item>
              <el-descriptions-item label="微信实收">{{settlementManageStore.wechatArriveAmount }}</el-descriptions-item>
              <el-descriptions-item label="支付宝到账">{{ settlementManageStore.alipayAmount }}</el-descriptions-item>
              <el-descriptions-item label="支付宝实收">{{ settlementManageStore.alipayArriveAmount  }}</el-descriptions-item>
            </el-descriptions>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="会员剩余金额">
                <el-input-number v-model="settlementManageStore.memberBalance" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-statistic title="微信实收" :value="settlementManageStore.wechatArriveAmount" :precision="2">
                  <template slot="suffix">元</template>
                </el-statistic>
              </el-col>
              <el-col :span="8">
                <el-statistic title="支付宝实收" :value="settlementManageStore.alipayArriveAmount" :precision="2">
                  <template slot="suffix">元</template>
                </el-statistic>
              </el-col>
            </el-row>
          </el-card>
        </el-col>

        <!-- 押金信息 -->
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header">
              <span>押金信息</span>
              <el-tooltip content="押金 = 会员剩余金额 * 费率" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </div>
            <el-form ref="depositForm" :model="form" label-width="120px">
              <el-form-item label="会员剩余金额">
                <el-input-number v-model="settlementManageStore.memberBalance" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="应付押金">
                <el-input-number v-model="settlementManageStore.payableDeposit" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="收取押金" prop="settlePaidDeposit">
                <el-input-number v-model="form.settlePaidDeposit" :disabled="getCanEdit" :precision="2" :controls="false" style="width: 180px" @change="handleAmountChange"></el-input-number>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 福利信息 -->
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header">
              <span>福利信息</span>
              <el-tooltip content="福利押金 = 福利金额 * 费率" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </div>
            <el-form ref="welfareForm" :model="form" label-width="120px">
              <el-form-item label="福利金额">
                <el-input-number v-model="settlementManageStore.welfareAmount" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="应付福利押金">
                <el-input-number v-model="settlementManageStore.welfareDeposit" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="收取福利押金" prop="settleWelfareDeposit">
                <el-input-number v-model="form.settleWelfareDeposit" :disabled="getCanEdit" :precision="2" :controls="false" style="width: 180px" @change="handleAmountChange"></el-input-number>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 卡密信息 -->
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header">
              <span>卡密信息</span>
              <el-tooltip content="卡密押金 = 未开卡卡密金额 * 费率" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </div>
            <el-form ref="cardForm" :model="form" label-width="120px">
              <el-form-item label="未开卡卡密金额">
                <el-input-number v-model="settlementManageStore.unopenedCardPasswordAmount" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="应付卡密押金">
                <el-input-number v-model="settlementManageStore.cardPasswordDeposit" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="收取卡密押金" prop="settleGetCardPasswordDeposit">
                <el-input-number v-model="form.settleGetCardPasswordDeposit" :disabled="getCanEdit" :precision="2" :controls="false" style="width: 180px" @change="handleAmountChange"></el-input-number>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 卡密信息 -->
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header">
              <span>异店信息</span>
              <el-tooltip content="跨店结算金=(本店卡:洗衣*费率-异店卡:洗衣*费率)+(本店卡:零售*费率-异店卡:零售*费率)+(本店卡:app*费率-异店卡:app*费率)+(本店卡:第三方*费率-异店卡:第三方*费率)+(本店卡:运费*费率-异店卡:运费*费率)" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </div>
            <el-form ref="cardForm" :model="form" label-width="120px">
              <el-form-item label="本店卡异店消费金额">
                <el-input-number v-model="settlementManageStore.otherStoreAmount" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="异店卡本店消费金额">
                <el-input-number v-model="settlementManageStore.otherCardAmount" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="跨店结算金">
                <el-input-number v-model="settlementManageStore.crossStoreSettlementAmount" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 其他费用 -->
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header">
              <span>其他费用</span>
            </div>
            <el-form ref="otherForm" :model="form" label-width="120px">
              <el-form-item label="原材料备用金">
                <el-input-number v-model="settlementManageStore.materialImprestAmount" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="收取材料费" prop="settleMaterialImprestAmount">
                <el-input-number v-model="form.settleMaterialImprestAmount" :disabled="getCanEdit" :precision="2" :controls="false" style="width: 180px" @change="handleAmountChange"></el-input-number>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 结算金额 -->
        <el-col :span="24">
          <el-card class="box-card">
            <div slot="header">
              <span>结算金额</span>
              <el-tooltip content="结算金额 = 支付宝/微信 - 收取押金 - 收取福利押金 - 收取卡密押金 - 收取材料费 - 系统维护费 - 洗衣费 - 顺丰快递费 - 跨店结算金 - 超额订货金额" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </div>
            <el-form ref="settlementForm" :model="form" label-width="120px">
              <el-form-item label="实际结算金额" prop="realSettlementAmount">
                <el-input-number v-model="form.realSettlementAmount" :disabled="true" :precision="2" :controls="false" style="width: 180px"></el-input-number>
              </el-form-item>
              <el-form-item label="清算备注" prop="settleRemark">
                <el-input type="textarea" v-model="form.settleRemark" :rows="3" :disabled="getCanEdit" style="width: 100%"></el-input>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!getCanEdit">确认结算</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
    </div>
</template>

<script>
import { getRate, delRate } from '@/api/settlement/rate'
import { allOrg } from '@/api/system/store'
import { listStoreSettlement, getInfoByStore, submitStoreSettlement } from '@/api/settlement/bill'

export default {
    name: 'BillSettlementStore',
    dicts: ['settlement_status_type'],
    data() {
        return {
            monthTime: '',
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 结算费率表格数据
            billList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                title: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
        settlePaidDeposit: [
          { required: true, message: '请输入收取余额押金', trigger: 'blur' },
          { type: 'number', message: '收取余额押金必须为数字', trigger: 'blur' }
        ],
        settleWelfareDeposit: [
          { required: true, message: '请输入收取福利押金', trigger: 'blur' },
          { type: 'number', message: '收取福利押金必须为数字', trigger: 'blur' }
        ],
        settleGetCardPasswordDeposit: [
          { required: true, message: '请输入收取卡密押金', trigger: 'blur' },
          { type: 'number', message: '收取卡密押金必须为数字', trigger: 'blur' }
        ],
        settleMaterialImprestAmount: [
          { required: true, message: '请输入收取材料费', trigger: 'blur' },
          { type: 'number', message: '收取材料费必须为数字', trigger: 'blur' }
        ],
        realSettlementAmount: [
          { required: true, message: '请输入实际结算金额', trigger: 'blur' },
          { type: 'number', message: '实际结算金额必须为数字', trigger: 'blur' }
        ],
        settleRemark: [
          { required: true, message: '请输入清算备注', trigger: 'blur' }
        ]
            },
            orgList: [],
            storeList: [],
            settlementManageStore: null,
            sysSettlementRate: null,
            sysStore: null
        }
    },
    created() {
        this.billId = this.$route.params.billId
        this.queryParams.billId = this.billId
        allOrg().then((res) => {
            this.orgList = res.data
            this.orgList.forEach((org) => {
                if (org.sourceType == '02') {
                    this.storeList.push(org)
                }
            })
        })
        this.getList()
    },
    computed: {
        getCheckName() {
            if (this.settlementManageStore.dataCheck == null) {
                return '--'
            }
            if (this.settlementManageStore.dataCheck == '1') {
                return '符合'
            }
            if (this.settlementManageStore.dataCheck == '2') {
                return '不符合'
            }
            if (this.settlementManageStore.dataCheck == '0') {
                return '未检测'
            }
        },
        getCanEdit() {
            return this.settlementManageStore.status == '1'
        }
    },
    methods: {
        getDetail(row) {
            this.reset()
            const id = row.id
            getInfoByStore(id).then((response) => {
                this.settlementManageStore = response.data.settlementManageStore
                this.sysSettlementRate = response.data.sysSettlementRate
                this.sysStore = response.data.sysStore
                this.open = true
                this.title = '门店结算费率详情信息'
                this.handleSettleAmount(this.settlementManageStore.id)
            })
        },
        handleSettleAmount(id) {
            this.initSettlementForm()
        },
        restartCountSettlementAmount() {
            this.calculateSettlementAmount()
        },
        /** 查询结算费率列表 */
        getList() {
            this.loading = true
            // this.queryParams.monthTime = this.monthTime
            listStoreSettlement(this.queryParams).then((response) => {
                this.billList = response.data.records
                this.total = response.data.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                settleId: null, //门店结算Id
                settleGetCardPasswordDeposit: null, //清算收取卡密押金
                settleSettlementAmount: null, //清算结算金额
                settleMaterialImprestAmount: null, //清算原材料备用金（材料费）
                settleWelfareDeposit: null, //清算福利金额
                settlePaidDeposit: null, //清算已付押金
                realSettlementAmount: null, //实际结算金额
                settleRemark: null //清算备注
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.monthTime = null
            this.queryParams.monthTime = null
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加结算费率'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getRate(id).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '修改结算费率'
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$confirm('是否确认结算？')
                .then(() => {
                    this.$refs['form'].validate((valid) => {
                        if (valid) {
                            this.restartCountSettlementAmount()
                            submitStoreSettlement(this.form).then((response) => {
                                this.$modal.msgSuccess('提交成功')
                                this.open = false
                                this.getList()
                            })
                        }
                    })
                })
        .catch(() => { })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal
                .confirm('是否确认删除结算费率编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delRate(ids)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
        .catch(() => { })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'mapi/settlement/rate/export',
                {
                    ...this.queryParams
                },
                `rate_${new Date().getTime()}.xlsx`
            )
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
        .then(() => { })
        .catch(() => { })
        },
        /**
         * 处理金额变化,重新计算结算金额
         */
        handleAmountChange() {
            this.calculateSettlementAmount()
        },

        /**
         * 计算实际结算金额
         */
        calculateSettlementAmount() {
            const baseAmount = (this.settlementManageStore.alipayArriveAmount + this.settlementManageStore.wechatArriveAmount)
            
            const result = baseAmount * 1000000 -
                this.form.settlePaidDeposit * 1000000 -
                this.form.settleWelfareDeposit * 1000000 -
                this.form.settleGetCardPasswordDeposit * 1000000 -
                this.form.settleMaterialImprestAmount * 1000000 -
                this.settlementManageStore.systemMaintenanceAmount * 1000000 -
                this.settlementManageStore.washClothAmount * 1000000 -
                this.settlementManageStore.sfExpressAmount * 1000000 -
                this.settlementManageStore.crossStoreSettlementAmount * 1000000 -
                this.settlementManageStore.overOrderingAmount * 1000000

            this.form.realSettlementAmount = Number((result / 1000000).toFixed(2))
        },

        /**
         * 初始化结算表单数据
         */
        initSettlementForm() {
            if (this.settlementManageStore.status === '1') {
                // 已结算状态,展示历史数据
                this.form = {
                    settleRemark: this.settlementManageStore.settleRemark,
                    settleGetCardPasswordDeposit: this.settlementManageStore.settleGetCardPasswordDeposit,
                    settleWelfareDeposit: this.settlementManageStore.settleWelfareDeposit,
                    settlePaidDeposit: this.settlementManageStore.settlePaidDeposit,
                    settleMaterialImprestAmount: this.settlementManageStore.settleMaterialImprestAmount,
                    realSettlementAmount: this.settlementManageStore.settleSettlementAmount
                }
            } else {
                // 未结算状态,计算初始值
                this.form = {
                    settleId: this.settlementManageStore.id,
                    settleGetCardPasswordDeposit: this.settlementManageStore.cardPasswordDeposit - this.settlementManageStore.paidCardPasswordDeposit,
                    settleWelfareDeposit: this.settlementManageStore.welfareDeposit - this.settlementManageStore.paidWelfareDeposit,
                    settlePaidDeposit: this.settlementManageStore.payableDeposit - this.settlementManageStore.paidDeposit,
                    settleMaterialImprestAmount: this.settlementManageStore.materialImprestAmount,
                    settleRemark: ''
                }
                this.calculateSettlementAmount()
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
  
  .el-card__header {
    padding: 10px 20px;
    font-weight: bold;
    
    .el-icon-question {
      margin-left: 5px;
      color: #909399;
      cursor: help;
    }
  }
}

.el-statistic {
  text-align: center;
  
  .el-statistic__title {
    font-size: 14px;
    color: #606266;
  }
  
  .el-statistic__content {
    color: #409EFF;
    font-size: 20px;
    font-weight: bold;
  }
}

.el-input-number {
  width: 180px !important;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}
</style>
