<template>
    <a-card class="container">
        <div class="info">
            <a-row :gutter="[16, 16]">
                <a-col :span="4" class="padding_8">
                    <div class="title">
                        协议单位
                    </div>
                    <div class="value">
                        {{ agreementUnitInfo.customerName }}
                        <a-tag color="cyan">
                            {{ agreementUnitInfo.accountStatus_dictText }}
                        </a-tag>
                    </div>
                </a-col>
                <a-col :span="3" class="padding_8">
                    <div class="title">
                        客户类型
                    </div>
                    <div class="value">
                        {{ agreementUnitInfo.customerType_dictText }}
                    </div>
                </a-col>
                <a-col :span="3" class="padding_8">
                    <div class="title">
                        消费
                    </div>
                    <div class="value">
                        {{ accountModel.consume }}
                    </div>
                </a-col>
                <a-col :span="3" class="padding_8">
                    <div class="title">
                        收款
                    </div>
                    <div class="value">
                        {{ accountModel.payment }}
                    </div>
                </a-col>
                <a-col :span="3" class="padding_8">
                    <div class="title">
                        记账额度
                    </div>
                    <div class="value">
                        {{ agreementUnitInfo.bookkeeping == null || agreementUnitInfo.bookkeeping ==
                            0 ? '无限制' : agreementUnitInfo.bookkeeping }}
                    </div>
                </a-col>
                <a-col :span="4" class="padding_8">
                    <div class="title">
                        已用额度
                    </div>
                    <div class="value">
                        {{ accountModel.used }}
                    </div>
                </a-col>
                <a-col :span="4" class="bak_red padding_8 border_radius_10">
                    <div class="title" style="color: white;">
                        剩余额度
                    </div>
                    <div class="value" style="color: white; font-weight: 600;">
                        {{ (agreementUnitInfo.bookkeeping == null || agreementUnitInfo.bookkeeping == 0 ? '--.--' :
                            (agreementUnitInfo.bookkeeping - accountModel.used)) }}
                    </div>
                </a-col>
            </a-row>
        </div>
        <div class="oper">
            <div class="oper-wrapper">
                <div class="oper-item" v-if="settleType != 2">
                    <a-button @click="handleClick(1)">
                        <a-icon type="file" />
                        商品消费
                    </a-button>
                </div>
                <div class="oper-item" v-if="settleType != 2">
                    <a-button @click="handleClick(2)">
                        <a-icon type="file" />
                        入账
                    </a-button>
                </div>
                <div class="oper-item" v-if="settleType == 1">
                    <a-button @click="handleClick(3)">
                        <a-icon type="file" />
                        转账
                    </a-button>
                </div>
                <div class="oper-item" v-if="settleType == 1">
                    <a-button @click="handleClick(4)">
                        <a-icon type="file" />
                        结算
                    </a-button>
                </div>
                <div class="oper-item" v-if="settleType == 1">
                    <a-button @click="handleClick(5)">
                        <a-icon type="file" />
                        冲账
                    </a-button>
                </div>
            </div>
            <div class="kajimi">
                <a-radio-group button-style="solid" v-model="settleType" @change="onTypeChange">
                    <a-radio-button :value="0">
                        全部
                    </a-radio-button>
                    <a-radio-button :value="1">
                        未结算
                    </a-radio-button>
                    <a-radio-button :value="2">
                        已结算
                    </a-radio-button>
                </a-radio-group>
                <span style="display: inline-block; margin-left: 10px;">
                    <a-range-picker v-model="rangeValue" @change="onRangeChange" :format="dateFormat" />
                </span>
                <span style="display: inline-block; margin-left: 10px;">
                    <a-button @click="searchQuery" icon="search">
                        查询
                    </a-button>
                </span>
                <span style="display: block; margin-left: 10px;">
                    <a-tag color="orange">
                        <pre style="margin: 0;">消费：￥300    收款：￥0    余额：￥-300</pre>
                    </a-tag>
                </span>
            </div>
        </div>
        <div class="cotent" style="margin-top: 20px;">
            <a-table
                    ref="table"
                    size="middle"
                    :scroll="{x:true}"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="ipagination"
                    :loading="loading"
                    :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                    class="j-table-force-nowrap"
                    @change="handleTableChange">

                <template slot="projectNameSlot" slot-scope="text, record">
                    <span v-if="record.type == 3">
<!--                        <a-tag color="green" @click="handleCommodityRecord(record)">-->
<!--                            {{record.projectName}}-->
<!--                        </a-tag>-->
                        <a-button class="project_name" @click="handleCommodityRecord(record)">
                          {{record.categoryId_dictText}}
                        </a-button>
                    </span>
                    <span v-else>
                        <span v-if="record.categoryId != null && record.categoryId.toString().length >0 ">
                            {{record.categoryId_dictText}}
                        </span>
                        <span v-else>
                            {{record.projectName}}
                        </span>
                    </span>
                </template>
                <template slot="orderNoSlot" slot-scope="text, record">
                    <a style="color: #4172db">{{record.orderNo}}</a>
                </template>
                <template slot="saleSlot" slot-scope="text, record">
                    <span v-if="record.type == 1 || record.type == 2">
                        -
                    </span>
                    <span v-else>
                        <a-tag color="green"  v-if="record.payPrice >= 0">
                            {{record.payPrice}}
                        </a-tag>
                        <a-tag color="red" v-else>
                            {{record.payPrice}}
                        </a-tag>
                    </span>
                </template>
                <template slot="paymentSlot" slot-scope="text, record">
                    <span v-if="record.type == 1 || record.type == 2">
                        <a-tag color="green" v-if="record.type == 1">
                            {{record.payPrice}}
                        </a-tag>
                        <a-tag color="red" v-else>
                            {{record.payPrice}}
                        </a-tag>
                    </span>
                    <span v-else>
                        -
                    </span>
                </template>
                <template slot="statusSlot" slot-scope="text, record">
                    <a-tag v-if="record.status == 2" color="green">已结算</a-tag>
                    <a-tag v-else color="red">未结算</a-tag>
                </template>
                <template slot="remarksSlot" slot-scope="text,record">
                    <a-input v-model="record.remarks" placeholder="" @blur="handleAccountRemarks(record)"></a-input>
                </template>
                <span slot="action" slot-scope="text, record">
                    <a-popconfirm v-if="record.status == 2" title="确定撤销结算吗?" @confirm="() => handleRevoke(record)">
                      <a>撤销</a>
                    </a-popconfirm>
                    <span v-else>
                        <a v-if="record.type == 3" @click="handleGoodsReturn(record)">退货</a>
                    </span>
                </span>
            </a-table>
        </div>

        <goods-consume-modal ref="goodsConsumeForm" @ok="modalFormOk" :agreementModel="agreementUnitInfo"></goods-consume-modal>
        <account-enter-modal ref="accountEnterForm" @ok="modalFormOk" :agreementModel="agreementUnitInfo"></account-enter-modal>
        <account-reverse-entry-modal :maxMoney="parseFloat(accountModel.consume)" ref="accountReverseEnterForm" :agreementModel="agreementUnitInfo" @ok="modalFormOk"></account-reverse-entry-modal>
        <account-transfer-modal :maxMoney="parseFloat(accountModel.consume)" ref="accountTransferForm" :agreementModel="agreementUnitInfo" @ok="modalFormOk"></account-transfer-modal>
        <settlement-modal ref="settlementForm" :agreementModel="agreementUnitInfo" @ok="modalFormOk"></settlement-modal>
        <commodity-record-modal ref="commodityRecordForm" @ok="modalFormOk"></commodity-record-modal>
        <commodity-return-modal ref="commodityReturnForm" @ok="modalFormOk"></commodity-return-modal>
    </a-card>
</template>

<script>
import moment from 'moment';
import { httpAction, getAction } from "@/api/manage";
import GoodsConsumeModal from './account/goodsConsumeModal'
import AccountEnterModal from './account/accountEnterModal'
import AccountReverseEntryModal from './account/accountReverseEntryModal'
import AccountTransferModal from './account/accountTransferModal'
import SettlementModal from './account/settlementModal'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CommodityRecordModal from './account/commodityRecordModal'
import CommodityReturnModal from './account/commodityReturnModal'

export default {
    name: 'agreementAccount',
    mixins:[JeecgListMixin, mixinDevice],
    components: { CommodityReturnModal, CommodityRecordModal, SettlementModal, AccountTransferModal, AccountReverseEntryModal, AccountEnterModal, GoodsConsumeModal },
    data() {
        var my_date = new Date();
        var first_date = new Date(my_date.getFullYear(), my_date.getMonth(), 1);
        var last_date = new Date(my_date.getFullYear(), my_date.getMonth() + 1, 0);
        return {
            settleType: 1,
            dateFormat: 'YYYY-MM-DD',
            rangeValue: [moment(first_date), moment(last_date)],
            agreementUnitInfo: {},
            accountModel: {
                consume: '0',
                payment: '0',
            },
            // 表头
            columns: [
                {
                    title:'项目名称',
                    align:"center",
                    dataIndex: 'projectName',
                    scopedSlots: { customRender: 'projectNameSlot' }
                },
                {
                    title:'订单号',
                    align:"center",
                    dataIndex: 'orderNo',
                    scopedSlots: { customRender: 'orderNoSlot' }
                },
                {
                    title:'客人信息',
                    align:"center",
                    dataIndex: 'guest'
                },
                {
                    title:'付款方式',
                    align:"center",
                    dataIndex: 'payType_dictText',
                    customRender: function (text) {
                        return !text?"-":text
                    },
                },
                {
                    title:'消费',
                    align:"center",
                    scopedSlots: { customRender: 'saleSlot' }
                },
                {
                    title:'付款',
                    align:"center",
                    scopedSlots: { customRender: 'paymentSlot' }
                },
                {
                    title:'状态',
                    align:"center",
                    dataIndex: 'status',
                    scopedSlots: { customRender: 'statusSlot' }
                },
                {
                    title:'备注',
                    width: 200,
                    align:"center",
                    dataIndex: 'remarks',
                    scopedSlots: { customRender: 'remarksSlot' }
                },
                {
                    title:'操作员',
                    align:"center",
                    dataIndex: 'createBy'
                },
                {
                    title:'操作时间',
                    align:"center",
                    dataIndex: 'createdTime',
                    customRender:function (text) {
                        return !text?"":(text.length>10?text.substr(0,10):text)
                    }
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align:"center",
                    fixed:"right",
                    width:147,
                    scopedSlots: { customRender: 'action' }
                }
            ],
            url: {
                list: "/business/busAgreementOrderFee/list",
                baseList: "/business/busAgreementOrderFee/list",
                delete: "/business/busAgreementOrderFee/delete",
                deleteBatch: "/business/busAgreementOrderFee/deleteBatch",
                exportXlsUrl: "/business/busAgreementOrderFee/exportXls",
                importExcelUrl: "business/busAgreementOrderFee/importExcel",
                revoke: "/business/busAgreementOrderFee/revoke",
                editRemarks: "/business/busAgreementOrderFee/editRemarks",
                queryAgreementAccount: "/business/busAgreementOrderFee/queryAgreementAccount",//获取协议单位消费、收款信息
            },
            queryParam: {
                startTime: first_date.format('yyyy-MM-dd'),
                endTime: last_date.format('yyyy-MM-dd'),
            },
        }
    },
    activated() {
        var agreementUnitInfo = JSON.parse(localStorage.getItem("agreementUnitInfo"));
        this.agreementUnitInfo = Object.assign({}, agreementUnitInfo);
        this.url.list = this.url.list +"?status=1&agreementUnitId="+this.agreementUnitInfo.id;
        this.loadData(1);
        this.$forceUpdate()
    },
    created() {
        var agreementUnitInfo = JSON.parse(localStorage.getItem("agreementUnitInfo"));
        this.agreementUnitInfo = Object.assign({}, agreementUnitInfo);

        this.getAccount();
        // this.accountModel = Object.assign({}, {});
    },
    methods: {
        moment,
        onRangeChange(date, dateString) {
            console.log(date)
            console.log(dateString)
            if (dateString[0]=="" || dateString[1]=="") {
                return
            }
            this.queryParam = {
                startTime: dateString[0],
                endTime: dateString[1],
            }
            if (this.settleType == 1 || this.settleType == 2){
                this.url.list = this.url.baseList +"?status="+this.settleType+"&agreementUnitId="+this.agreementUnitInfo.id;
            }else{
                this.url.list = this.url.baseList+"?status=1&agreementUnitId="+this.agreementUnitInfo.id;
            }
            // if (!this.queryParam.startTime=="") {
            //     this.url.list = this.url.list + "&startDate=" + this.queryParam.startTime
            // }
            // if (!this.queryParam.endTime=="") {
            //     this.url.list = this.url.list + "&endDate=" + this.queryParam.endTime
            // }
            this.loadData(1);
            this.selectedRowKeys = [];
            this.selectionRows = [];
        },
        onTypeChange(e) {
            if (this.settleType == 1 || this.settleType == 2){
                this.url.list = this.url.baseList +"?status="+this.settleType+"&agreementUnitId="+this.agreementUnitInfo.id;
            }else{
                this.url.list = this.url.baseList+"?agreementUnitId="+this.agreementUnitInfo.id;
            }
            // if (!this.queryParam.startTime=="") {
            //     this.url.list = this.url.list + "&startDate=" + this.queryParam.startTime
            // }
            // if (!this.queryParam.endTime=="") {
            //     this.url.list = this.url.list + "&endDate=" + this.queryParam.endTime
            // }
            this.loadData(1);
            this.selectedRowKeys = [];
            this.selectionRows = [];
        },
        handleClick(type){
            if (type == 1){
                this.$refs.goodsConsumeForm.edit();
                this.$refs.goodsConsumeForm.title="入账";
                this.$refs.goodsConsumeForm.disableSubmit = true;
            }
            else if(type == 2){
                this.$refs.accountEnterForm.edit();
                this.$refs.accountEnterForm.title="入账";
                this.$refs.accountEnterForm.disableSubmit = true;
            }
            else if(type == 3){
                if (this.selectedRowKeys.length <= 0) {
                    this.$message.warning("请选择一条记录！");
                    return;
                }
                let ids = '';
                this.selectedRowKeys.forEach(function (val) {
                    ids += val + ",";
                });
                this.$refs.accountTransferForm.edit();
                this.$refs.accountTransferForm.title="转账";
                this.$refs.accountTransferForm.orderIds=ids;
                this.$refs.accountTransferForm.disableSubmit = true;
            }
            else if(type == 4){
                if (this.selectedRowKeys.length <= 0) {
                    this.$message.warning("请选择一条记录！");
                    return;
                }
                let ids = '';
                var idList = []
                this.selectedRowKeys.forEach(function (val) {
                    ids += val + ",";
                    idList.push(val)
                });
                var dataSource = this.dataSource;
                var amount = 0;
                if(dataSource && dataSource.length > 0){
                    for(var a=0;a<dataSource.length;a++){
                        if (idList.indexOf(dataSource[a].id) >= 0){
                            if (dataSource[a].type == 2){
                                amount -= parseFloat(dataSource[a].payPrice)
                            }else{
                                amount += parseFloat(dataSource[a].payPrice)
                            }
                        }
                    }
                }
                this.$refs.settlementForm.edit();
                this.$refs.settlementForm.title="结算";
                this.$refs.settlementForm.maxMoney=amount;
                this.$refs.settlementForm.orderIds=ids;
                this.$refs.settlementForm.disableSubmit = true;
            }
            else if(type == 5){
                this.$refs.accountReverseEnterForm.edit();
                this.$refs.accountReverseEnterForm.title="冲账";
                this.$refs.accountReverseEnterForm.disableSubmit = true;
            }
        },
        modalFormOk() {
            this.loadData(1);
            this.getAccount();
        },
        handleCommodityRecord(record){
            //打开商品消费明细
            this.$refs.commodityRecordForm.show();
            this.$refs.commodityRecordForm.title="详细信息";
            this.$refs.commodityRecordForm.agreementOrderFeeId = record.id;
            this.$refs.commodityRecordForm.disableSubmit = true;
        },
        handleGoodsReturn(record){
            //退货
            this.$refs.commodityReturnForm.show();
            this.$refs.commodityReturnForm.title="退货";
            this.$refs.commodityReturnForm.agreementOrderFeeId = record.id;
            this.$refs.commodityReturnForm.disableSubmit = true;
        },
        handleRevoke(record){
            const that = this;
            that.confirmLoading = true;
            let httpurl = this.url.revoke;
            let method = 'post';
            var data = {
                id:record.id
            }
            httpAction(httpurl,data,method).then((res)=>{
                if(res.success){
                    that.$message.success(res.message);
                    that.$emit('ok');
                    that.loadData(1);
                }else{
                    that.$message.warning(res.message);
                }
            }).finally(() => {
                that.confirmLoading = false;
            })
        },
        getAccount(){
            var that = this;
            getAction(this.url.queryAgreementAccount, {
                agreementUnitId: this.agreementUnitInfo.id,
            }).then((res) => {
                console.log(res)
                if (res.success) {
                    that.accountModel = res.result;
                }
            });
        },
        handleAccountRemarks(record){
            console.log(record)
            const that = this;
            that.confirmLoading = true;
            let httpurl = this.url.editRemarks;
            let method = 'put';
            httpAction(httpurl,record,method).then((res)=>{
                if(res.success){
                    that.$message.success(res.message);
                    // that.$emit('ok');
                    // that.loadData(1);
                }else{
                    that.$message.warning(res.message);
                }
            }).finally(() => {
                that.confirmLoading = false;
            })
        }
    }
}
</script>

<style scoped>
.info {
    text-align: center;
}

.title {
    font-size: 16px;
    font-weight: 500;
}

.value {
    padding-top: 10px;
}

.bak_red {
    background-color: red;
}

.padding_8 {
    padding: 8px 0;
    border-radius: 10px;
}

.border_radius_10 {
    border-radius: 10px;
}

.oper-wrapper {
    display: flex;
    width: 100%;
}

.oper-item {
    margin-right: 10px;
}

.kajimi {
    margin-top: 20px;
    display: flex;
    align-items: center;
}
.project_name{
    color: #2e9c69;
    border-color: #2e9c69;
}
.project_name:hover{
background-color: #2e9c69;
    color: white;
}
</style>

