<template>
    <div>
        <div class="customer-head">
            <div class="customer-back">
                <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                    @click="goBack()">返回列表
                </el-button>
            </div>
            <div class="add-customer-btn">
                <el-button size="small" style="margin-right: 8px" :disabled="!form.id"
                    @click="$refs.print.openDialog()">打印账单
                </el-button>
                <el-button size="small" style="margin-right: 8px" :disabled="!form.id"
                    @click="$refs.report.openDialog()">报表设计
                </el-button>
                <el-button class="el-button--small-yh" style="margin-left: 6px;" type="primary" size="small"
                    v-if="editButton" @click="inEdit">编 辑
                </el-button>
                <el-button v-if="!editButton" class="el-button--small-yh" style="margin-left: 6px;" type="primary"
                    size="small" :disabled="form.status == '已开票'" @click="submit">保 存
                </el-button>
                <el-button v-if="form.id && form.status == '录入'" class="el-button--small-yh" style="margin-left: 6px;"
                    type="success" size="small" @click="confirm">确认开票
                </el-button>
                <el-button v-if="form.id && form.status == '已开票'" class="el-button--small-yh" style="margin-left: 6px;"
                    type="danger" size="small" @click="revoke">撤销开票
                </el-button>
            </div>
        </div>
        <div style="margin-top: 50px">
            <trade-card title="基础信息">
                <avue-form :option="optionForm" v-model="form" ref="form">
                    <tempalte slot="corporateName" slot-scope="{ row }">
                        <dic-select v-model="form.corporateName" placeholder="销售公司" key="id" label="cnName"
                            res="records" url="/blade-los/bcorps/listByType" :filterable="true" :remote="true"
                            dataName="cnName" @selectChange="dicChange('corporateName', $event)"
                            :disabled="form.invoicingItemList.length > 0 || editButton || form.status == '已开票'"
                            :searchShow="true" :treeShow="true"></dic-select>
                    </tempalte>
                    <tempalte slot="contractNumber" slot-scope="{ row }">
                        <el-input v-model="form.contractNumber" placeholder="请输入 合同号"
                            :disabled="form.invoicingItemList.length > 0 || editButton || form.status == '已开票'"
                            size="small"></el-input>
                    </tempalte>
                    <tempalte slot="businessOrganizerName" slot-scope="{ row }">
                        <dic-select v-model="form.businessOrganizerName" placeholder="销售公司" key="id" label="realName"
                            res="records" url="/blade-user/page" :filterable="true" :remote="true" dataName="realName"
                            :disabled="editButton || form.status == '已开票'">
                        </dic-select>
                    </tempalte>
                    <!-- <tempalte slot="openingBank" slot-scope="{ row }">
                        <dic-select ref="bank" v-model="form.openingBank" placeholder="开户行" key="id" label="accountBank"
                            :filterable="true" :disabled="editDisabled"></dic-select>
                    </tempalte>
                    <tempalte slot="accountNumber" slot-scope="{ row }">
                        <dic-select ref="bank2" v-model="form.accountNumber" placeholder="账号" key="id" label="accountNo"
                            :filterable="true" :disabled="editDisabled"></dic-select>
                    </tempalte>
                    <tempalte slot="addressTel" slot-scope="{ row }">
                        <dic-select ref="user" v-model="form.addressTel" placeholder="地址、电话" key="id" label="addr"
                            :filterable="true" :disabled="editDisabled" :slotRight="true" rightLabel="tel" @selectChange="dicChange('addressTel', $event)"></dic-select>
                    </tempalte> -->
                </avue-form>
            </trade-card>
            <trade-card title="基础明细">
                <avue-crud :option="option" :data="form.invoicingItemList" id="out-table" ref="crud"
                    @selection-change="selectionChange" @resetColumn="resetColumn('crud', 'option', 'optionBack', 454)"
                    @saveColumn="saveColumn('crud', 'option', 'optionBack', 454)">
                    <template slot="menuLeft">
                        <el-button type="primary" size="small" icon="el-icon-plus" @click="addRow"
                            :disabled="form.invoicingItemList.length || editButton || form.status == '已开票'">导 入
                        </el-button>
                    </template>
                    <tempalte slot="quantityForm" slot-scope="{ row }">
                        <el-input-number v-if="row.$cellEdit" v-model="row.quantity" @change="countChange(row)"
                            :controls="false" placeholder="请输入 数量" size="small" style="width: 100%;"></el-input-number>
                        <span v-else>{{ row.quantity }}</span>
                    </tempalte>
                    <template slot="menu" slot-scope="{ row, index }">
                        <el-button size="small" icon="el-icon-edit" type="text" @click="rowEdit(row)"
                            :disabled="editButton || form.status == '已开票'">{{ row.$cellEdit ?
                                "保存" : "编辑" }}</el-button>
                        <el-button size="small" icon="el-icon-delete" type="text" @click="rowDel(row)"
                            :disabled="editButton || form.status == '已开票'">删 除</el-button>
                    </template>
                </avue-crud>
            </trade-card>
            <business-reports :id="form.id" ref="print" businessValue="MYDL_KPSQ" :type="true"></business-reports>
            <reports :id="form.id" ref="report" :assemblyForm="form" businessValue="MYDL_KPSQ"></reports>
        </div>
    </div>
</template>

<script>
import { submit, getDetail, confirmInvoicing, revokeInvoicing, getImport, itemRemove } from "@/api/iosBasicData/revenueInvoicing";
import dicSelect from "@/components/dicSelect/main";
import { getBcorpsDetail } from "@/api/iosBasicData/bcorps";
import businessReports from "@/components/tradeAgency/businessReports.vue";
import reports from "@/components/tradeAgency/reports.vue";
import _ from "lodash";
export default {
    name: "detailsPage",

    data() {
        return {
            editButton: false,
            userList: [],
            form: {
                billNoFormat: 'MYDL_KPSQ',
                businessTypeCode: 'MYDL_KPSQ',
                invoicingItemList: []
            },
            optionForm: {
                menuBtn: false,
                span: 8,
                disabled: false,
                column: [
                    {
                        label: "销售公司",
                        prop: "corporateName",
                        rules: [{
                            required: true,
                            message: " ",
                            trigger: "blur"
                        }],
                        disabled: false
                    },
                    {
                        label: "公司名称",
                        prop: "buyCorporateName",
                        rules: [{
                            required: true,
                            message: " ",
                            trigger: "blur"
                        }],
                        disabled: false
                    },
                    {
                        label: "合同号",
                        prop: "contractNumber",
                        rules: [{
                            required: true,
                            message: " ",
                            trigger: "blur"
                        }],
                        disabled: false,
                    },
                    {
                        label: "业务主办",
                        prop: "businessOrganizerName",
                        // type: 'select',
                        // filterable: true,
                        // remote: true,
                        // dicUrl: "/api/blade-user/page?current=1&size=20&realName={{key}}",
                        // props: {
                        //     label: 'realName',
                        //     value: 'realName',
                        //     res: 'data.records'
                        // },
                        disabled: false
                    },
                    {
                        label: "开具发票号码",
                        prop: "invoiceNo",
                        disabled: false
                    },
                    {
                        label: "纳税人识别号",
                        prop: "taxpayerIdentification",
                        disabled: false
                    },
                    {
                        label: "开户行",
                        prop: "openingBank",
                        disabled: false
                    },
                    {
                        label: "账号",
                        prop: "accountNumber",
                        disabled: false
                    },
                    {
                        label: "地址、电话",
                        prop: "addressTel",
                        disabled: false
                    },
                    {
                        label: "备注",
                        prop: "remarks",
                        disabled: false
                    }
                ]
            },
            option: {},
            optionBack: {
                height: 'auto',
                calcHeight: 30,
                menuWidth: 140,
                border: true,
                index: true,
                addBtn: false,
                viewBtn: false,
                editBtn: false,
                delBtn: false,
                menu: true,
                refreshBtn: false,
                align: 'center',
                summaryText: "合计",
                showSummary: true,
                sumColumnList: [
                    {
                        name: "quantity",
                        type: "sum",
                        decimals: 0
                    }, {
                        name: "amount",
                        type: "sum",
                        decimals: 2
                    }, {
                        name: "thisAmount",
                        type: "sum",
                        decimals: 2
                    }, {
                        name: "invoicedAmount",
                        type: "sum",
                        decimals: 2
                    }
                ],
                column: [
                    {
                        label: "货物名称",
                        prop: "labelProductName",
                        overHidden: true
                    },
                    {
                        label: "规格",
                        prop: "specifications",
                        overHidden: true
                    },
                    {
                        label: "数量",
                        prop: "quantity",
                        cell: true,
                        slot: true,
                        formslot: true,
                        rules: [{
                            required: true,
                            message: " ",
                            trigger: "blur"
                        }],
                        overHidden: true
                    },
                    {
                        label: "计量单位",
                        prop: "units",
                        overHidden: true,
                        cell: true,
                        type: 'select',
                        filterable: true,
                        remote: true,
                        dicUrl: "/api/blade-los/bunits/list?current=1&size=20&cnName={{key}}",
                        props: {
                            label: 'cnName',
                            value: 'cnName',
                            res: 'data.records'
                        },
                    },
                    {
                        label: "销售单价(含税)",
                        prop: "price",
                        overHidden: true
                    },
                    {
                        label: "销售金额(含税)",
                        prop: "amount",
                        overHidden: true
                    },
                    {
                        label: "本次发票金额",
                        prop: "thisAmount",
                        overHidden: true
                    },
                    {
                        label: "已开发票金额",
                        prop: "invoicedAmount",
                        overHidden: true
                    },
                    {
                        label: "备注",
                        prop: "remarks",
                        cell: true,
                        overHidden: true
                    }
                ]
            },
        }
    },
    components: {
        dicSelect,
        businessReports,
        reports
    },
    props: {
        detailData: Object
    },
    async created() {
        this.option = await this.getColumnData(this.getColumnName(454), this.optionBack);
        if (this.detailData.id) {
            this.editButton = true
            this.optionForm.disabled = true
            this.getDetails(this.detailData.id)
        }
    },
    methods: {
        inEdit() {
            this.editButton = false
            if (this.form.status == '录入') {
                this.optionForm.disabled = false
            }
        },
        addRow() {
            if (!this.form.corporateId) {
                return this.$message.error("请选择销售公司");
            }
            if (!this.form.contractNumber) {
                return this.$message.error("请输入合同号");
            }
            let obj = {
                corpId: this.form.corporateId,
                contractNo: this.form.contractNumber
            }
            getImport(obj).then(res => {
                res.data.data.forEach(item => {
                    this.form.invoicingItemList.push({
                        srcId: item.id,
                        labelProductName: item.labelProductName,
                        specifications: item.specifications,
                        quantity: _.divide(_.subtract(item.amount, item.invoiceAmount), item.price),
                        units: '千克',
                        price: item.price,
                        amount: item.amount,
                        thisAmount: item.amount,
                        invoicedAmount: item.invoiceAmount,
                        $cellEdit: true,
                    })
                })
            })

        },
        countChange(row) {
            row.thisAmount = _.multiply(Number(row.quantity ? row.quantity : 0), Number(row.price ? row.price : 0))
            if (row.thisAmount > Number(row.amount - row.invoicedAmount)) {
                row.quantity = 0
                row.thisAmount = 0
                return this.$message.error("本次金额不能大于金额减去已开票");
            }
        },
        // 编辑
        rowEdit(row) {
            if (row.$cellEdit == true) {
                if (!row.quantity) return this.$message.error("请输入数量");
                this.$set(row, '$cellEdit', false)
            } else {
                this.$set(row, '$cellEdit', true)
            }
        },
        dicChange(name, row) {
            if (name == 'corporateName') {
                if (row) {
                    this.form.corporateId = row.id
                    this.form.corporateName = row.cnName
                    this.form.buyCorporateName = row.cnName
                    this.form.openingBank = null
                    this.form.accountNumber = null
                    this.form.addressTel = null
                    getBcorpsDetail(row.id).then(res => {
                        // this.$refs.bank.getDicData(res.data.data.corpsBankList)
                        // this.$refs.bank2.getDicData(res.data.data.corpsBankList)
                        res.data.data.corpsBankList.forEach((item, index) => {
                            if (index == 0) {
                                this.form.openingBank = item.accountBank
                                this.form.accountNumber = item.accountNo
                            }
                        })
                        // this.$refs.user.getDicData(res.data.data.corpsAttnList)
                        res.data.data.corpsAttnList.forEach((item, index) => {
                            if (index == 0) {
                                this.form.addressTel = item.addr + item.tel
                            }
                        })
                    })
                } else {
                    this.form.corporateId = null
                    this.form.corporateName = null
                    this.form.buyCorporateName = null
                    this.form.openingBank = null
                    this.form.accountNumber = null
                    this.form.addressTel = null
                    // this.$refs.bank.getDicData([])
                    // this.$refs.bank2.getDicData([])
                    // this.$refs.user.getDicData([])
                }
            }
            if (name == 'addressTel') {
                if (row) {
                    this.form.addressTel = row.addr + row.tel

                } else {
                    this.form.addressTel = null
                }
            }

        },
        rowDel(row, index) {
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                if (row.id) {
                    itemRemove({ ids: row.id }).then(res => {
                        this.form.invoicingItemList.splice(index, 1);
                        this.$message.success("操作成功!");
                    });
                } else {
                    this.form.invoicingItemList.splice(index, 1);
                    this.$message.success("操作成功!");
                }
            }
            );
        },
        getDetails(id) {
            const loading = this.$loading({
                lock: true,
                text: '加载中',
                spinner: 'el-icon-loading',
                background: 'rgba(255,255,255,0.7)'
            });
            getDetail({ id: id }).then(res => {
                this.form = res.data.data
                this.$refs.crud.dicInit();
            }).finally(() => {
                loading.close()
            })
        },
        submit() {
            for (let row of this.form.invoicingItemList) {
                if (!row.quantity) {
                    return this.$message.error("请输入数量");
                }
            }
            this.$refs["form"].validate((valid, done) => {
                done();
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: '加载中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(255,255,255,0.7)'
                    });
                    submit(this.form).then(res => {
                        this.$message.success("保存成功");
                        this.getDetails(res.data.data.id)
                    }).finally(() => {
                        loading.close();
                    })

                } else {
                    return false;
                }
            });
        },
        confirm() {
            for (let row of this.form.invoicingItemList) {
                if (!row.quantity) {
                    return this.$message.error("请输入数量");
                }
            }
            this.$refs["form"].validate((valid, done) => {
                done();
                if (valid) {
                    this.$confirm("是否确认开票?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }).then(() => {
                        const loading = this.$loading({
                            lock: true,
                            text: '加载中',
                            spinner: 'el-icon-loading',
                            background: 'rgba(255,255,255,0.7)'
                        });
                        confirmInvoicing(this.form).then(res => {
                            this.$message.success("操作成功");
                            this.getDetails(res.data.data.id)
                            this.editButton = true
                            this.optionForm.disabled = true
                        }).finally(() => {
                            loading.close();
                        })
                    }
                    );
                } else {
                    return false;
                }
            });
        },
        revoke() {
            this.$confirm("是否撤销开票?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: '加载中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(255,255,255,0.7)'
                });
                revokeInvoicing(this.form).then(res => {
                    this.$message.success("操作成功");
                    this.getDetails(res.data.data.id)
                    this.editButton = true
                    this.optionForm.disabled = true
                }).finally(() => {
                    loading.close();
                })
            }
            );
        },
        //自定义列保存
        async saveColumn(ref, option, optionBack, code) {
            const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
            if (inSave) {
                this.$message.success("保存成功");
                //关闭窗口
                this.$refs[ref].$refs.dialogColumn.columnBox = false;
            }
        },
        //自定义列重置
        async resetColumn(ref, option, optionBack, code) {
            this[option] = this[optionBack];
            const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
            if (inSave) {
                this.$message.success("重置成功");
                this.$refs[ref].$refs.dialogColumn.columnBox = false;
            }
        },
        goBack(type) {
            this.$emit("goBack", type);
            this.$emit('updateKey')
        },
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
    margin-bottom: 8px !important;
}

::v-deep .el-table .cell {
    padding: 0 2px !important;

    .el-form-item {
        margin-bottom: 0px !important;
    }

}

::v-deep .avue-crud .el-table .el-form-item__label {
    left: -1px;
}

::v-deep#out-table .back-one {
    background: #ecf5ff !important;
}

::v-deep#out-table .back-two {
    background: #ecf5ff !important;
}
</style>
