<template>
    <div>
        <!--:row-style="{height:'20px',padding:'0px',fontSize:'12px'}"-->
        <avue-crud :option="option" :data="tableData" id="out-table" ref="crud"
            @selection-change="handleSelectionChange" :header-cell-style="tableHeaderCellStyle"
            :row-class-name="rowClassName" :cell-style="cellStyle"
            @resetColumn="resetColumn('crud', 'option', 'optionBack', 493)"
            @saveColumn="saveColumn('crud', 'option', 'optionBack', 493)">
            <template slot="menuLeft">
                <slot name="menuLeft"></slot>
            </template>
            <tempalte slot="currentStlAmountRMB" slot-scope="{ row }">
                <el-input-number v-if="(brfalse && !editSave)" v-model="row.currentStlAmountRMB"
                    @change="armbChange(row)" :controls="false" placeholder="请输入 本次对账CNY" size="mini"
                    style="width: 100%;"
                    :disabled="row.curCode != getLocalCurrency() || settlementdistar || !(form.status == '0' || form.status == '4' || form.status == null)"></el-input-number>
                <span v-else>{{ row.currentStlAmountRMB }}</span>
            </tempalte>
            <tempalte slot="currentStlAmountUSD" slot-scope="{ row }">
                <el-input-number v-if="(brfalse && !editSave)" v-model="row.currentStlAmountUSD"
                    @change="ausdChange(row)" :controls="false" placeholder="请输入 本次对账USD" size="mini"
                    style="width: 100%;"
                    :disabled="row.curCode == getLocalCurrency() || settlementdistar || !(form.status == '0' || form.status == '4' || form.status == null)"></el-input-number>
                <span v-else>{{ row.currentStlAmountUSD }}</span>
            </tempalte>
            <template slot="remarkss" slot-scope="{ row }">
                <el-input style="width: 100%;" v-model="row.remarkss" v-if="(brfalse && !editSave)" size="mini"
                    autocomplete="off" clearable placeholder="请输入 备注">
                </el-input>
                <span v-else>{{ row.remarkss }}</span>
            </template>
            <template slot="taxInvoiceNumber" slot-scope="{ row }">
                <el-input style="width: 100%;" v-model="row.taxInvoiceNumber"
                    v-if="row.feeCnName == '增值税' && (brfalse && !editSave)" size="mini" autocomplete="off" clearable
                    placeholder="请输入税票号">
                </el-input>
                <span v-else>{{ row.taxInvoiceNumber }}</span>
            </template>
            <template slot="taxInvoiceDate" slot-scope="{ row }">
                <el-date-picker style="width: 100%;" v-model="row.taxInvoiceDate"
                    v-if="row.feeCnName == '增值税' && (brfalse && !editSave)" size="mini" type="date" placeholder="选择日期"
                    format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                </el-date-picker>
                <span v-else>{{ row.taxInvoiceDate }}</span>
            </template>
            <template slot="deductionTime" slot-scope="{ row }">
                <el-date-picker style="width: 100%;" v-model="row.deductionTime"
                    v-if="row.feeCnName == '增值税' && (brfalse && !editSave)" size="mini" type="date" placeholder="选择日期"
                    format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                </el-date-picker>
                <span v-else>{{ row.deductionTime }}</span>
            </template>
        </avue-crud>
    </div>
</template>

<script>
import { getWorkDicts } from "@/api/system/dictbiz";
import SearchQuery from "@/components/iosbasic-data/searchquery.vue";
import { getRateList } from "@/api/iosBasicData/rateManagement";
import costDetails from "@/views/iosBasicData/finstlbills/assembly/costDetails.vue";
import { feecenterSelectByAccNoList } from "@/api/iosBasicData/finstlbills";

export default {
    components: { costDetails, SearchQuery },
    props: {
        tableData: {
            type: Array,
            default: [],
        },
        brfalse: {
            type: Boolean,
            default: true,
        },
        handleSelectionData: {
            type: Array,
            default: []
        },
        // 是否禁用
        editSave: {
            type: Boolean,
            default: false
        },
        settlementdistar: {
            type: Boolean,
            default: false
        },
        form: {
            type: Object,
            default: {},
        },
    },
    data() {
        return {
            ifInvoiceData: [], // 是否数据
            invoicelosDara: [],// 发票
            curCodeData: [], // 币种
            option: {},
            optionBack: {
                height: 'auto',
                calcHeight: 30,
                menuWidth: 60,
                tip: false,
                menu: false,
                border: true,
                addBtn: false,
                viewBtn: false,
                editBtn: false,
                delBtn: false,
                refreshBtn: false,
                index: true,
                selection: true,
                align: 'center',
                column: [
                    {
                        label: "所属公司",
                        prop: "branchName",
                        width: 120,
                        overHidden: true
                    },
                    {
                        label: "收付",
                        prop: "dc",
                        width: 60,
                        type: 'select',
                        dicData: [{
                            label: '收',
                            value: 'D'
                        }, {
                            label: '付',
                            value: 'C'
                        }],
                        overHidden: true,
                    },
                    {
                        label: "费用名称",
                        prop: "feeCnName",
                        width: 80,
                        overHidden: true
                    },
                    {
                        label: "MB/L NO",
                        prop: "mblno",
                        width: 100,
                        overHidden: true
                    },
                          {
                        label: "HB/L NO",
                        prop: "hblno",
                        width: 100,
                        overHidden: true
                    },
                    {
                        label: "币种",
                        prop: "currentStlCurCode",
                        width: 60,
                        overHidden: true
                    },
                    {
                        label: "汇率",
                        prop: "currentStlExrate",
                        width: 80,
                        overHidden: true
                    },
                    {
                        label: "本次本币",
                        prop: "currentStlAmountRMB",
                        width: 100,
                        overHidden: true
                    },
                    {
                        label: "本次外币",
                        prop: "currentStlAmountUSD",
                        width: 100,
                        overHidden: true
                    },
                    {
                        label: "ETD",
                        prop: "etd",
                        width: 90,
                        overHidden: true
                    },
                    {
                        label: "船名",
                        prop: "vesselEnName",
                        width: 90,
                        overHidden: true
                    },
                    {
                        label: "航次",
                        prop: "voyageNo",
                        width: 90,
                        overHidden: true
                    },
                    {
                        label: "目的港",
                        prop: "podCnName",
                        width: 90,
                        overHidden: true
                    },
                    {
                        label: "应结算本币",
                        prop: "amountRMB",
                        width: 90,
                        overHidden: true
                    },
                    {
                        label: "应结算外币",
                        prop: "amountUSD",
                        width: 90,
                        overHidden: true
                    },
                    {
                        label: "已结算本币",
                        prop: "stlTtlAmountRMB",
                        width: 90,
                        overHidden: true
                    },
                    {
                        label: "已结算外币",
                        prop: "stlTtlAmountUSD",
                        width: 90,
                        overHidden: true
                    },
                    {
                        label: "ETA",
                        prop: "eta",
                        width: 120,
                        overHidden: true
                    }
                ]
            },
        }
    },
    async created() {
        this.option = await this.getColumnData(this.getColumnName(493), this.optionBack);
        this.isSignforWorkDicts()
        this.invoicelosWorkDictsfun()
    },
    methods: {
        armbChange(row) {
            if (row.dc == 'C') {
                if (Number(row.amount - (row.appliedAmount - row.appliedAmountStl) - row.stlTtlAmount) > 0) {
                    if (Number(row.currentStlAmountRMB) < 0) {
                        row.currentStlAmountRMB = 0
                        return this.$message.error("本次对账金额不能输入负数");
                    }
                    if (Number(row.currentStlAmountRMB) > Number(row.amount - (row.appliedAmount - row.appliedAmountStl) - row.stlTtlAmount)) {
                        row.currentStlAmountRMB = 0
                        return this.$message.error("本次对账金额不能超过未对账金额");
                    }
                }
                if (Number(row.amount - (row.appliedAmount - row.appliedAmountStl) - row.stlTtlAmount) < 0) {
                    if (Number(row.currentStlAmountRMB) >= 0) {
                        row.currentStlAmountRMB = Number(row.amount - (row.appliedAmount - row.appliedAmountStl) - row.stlTtlAmount)
                        return this.$message.error("本次对账金额不能输入非负数");
                    }
                    if (Number(row.currentStlAmountRMB) < Number(row.amount - (row.appliedAmount - row.appliedAmountStl) - row.stlTtlAmount)) {
                        row.currentStlAmountRMB = Number(row.amount - (row.appliedAmount - row.appliedAmountStl) - row.stlTtlAmount)
                        return this.$message.error("本次对账金额不能超过未对账金额");
                    }
                }
            }
            if (row.dc == 'D') {
                if (Number(row.amount - row.stlTtlAmount) > 0) {
                    if (Number(row.currentStlAmountRMB) < 0) {
                        row.currentStlAmountRMB = 0
                        return this.$message.error("本次对账金额不能输入负数");
                    }
                    if (Number(row.currentStlAmountRMB) > Number(row.amount - row.stlTtlAmount)) {
                        row.currentStlAmountRMB = 0
                        return this.$message.error("本次对账金额不能超过未对账金额");
                    }
                }
                if (Number(row.amount - row.stlTtlAmount) < 0) {
                    if (Number(row.currentStlAmountRMB) >= 0) {
                        row.currentStlAmountRMB = Number(row.amount - row.stlTtlAmount)
                        return this.$message.error("本次对账金额不能输入非负数");
                    }
                    if (Number(row.currentStlAmountRMB) < Number(row.amount - row.stlTtlAmount)) {
                        row.currentStlAmountRMB = Number(row.amount - row.stlTtlAmount)
                        return this.$message.error("本次对账金额不能超过未对账金额");
                    }
                }
            }
        },
        ausdChange(row) {
            if (row.dc == 'C') {
                if (Number(row.amount - (row.appliedAmount - row.appliedAmountStl) - row.stlTtlAmount) > 0) {
                    if (Number(row.currentStlAmountUSD) < 0) {
                        row.currentStlAmountUSD = 0
                        return this.$message.error("本次对账金额不能输入负数");
                    }
                    if (Number(row.currentStlAmountUSD) > Number(row.amount - (row.appliedAmount - row.appliedAmountStl)  - row.stlTtlAmount)) {
                        row.currentStlAmountUSD = 0
                        return this.$message.error("本次对账金额不能超过未对账金额");
                    }
                }
                if (Number(row.amount - (row.appliedAmount - row.appliedAmountStl)  - row.stlTtlAmount) < 0) {
                    if (Number(row.currentStlAmountUSD) >= 0) {
                        row.currentStlAmountUSD = Number(row.amount - (row.appliedAmount - row.appliedAmountStl)  - row.stlTtlAmount)
                        return this.$message.error("本次对账金额不能输入非负数");
                    }
                    if (Number(row.currentStlAmountUSD) < Number(row.amount - (row.appliedAmount - row.appliedAmountStl)  - row.stlTtlAmount)) {
                        row.currentStlAmountUSD = Number(row.amount - (row.appliedAmount - row.appliedAmountStl)  - row.stlTtlAmount)
                        return this.$message.error("本次对账金额不能超过未对账金额");
                    }
                }
            }
            if (row.dc == 'D') {
                if (Number(row.amount - row.stlTtlAmount) > 0) {
                    if (Number(row.currentStlAmountUSD) < 0) {
                        row.currentStlAmountUSD = 0
                        return this.$message.error("本次对账金额不能输入负数");
                    }
                    if (Number(row.currentStlAmountUSD) > Number(row.amount - row.stlTtlAmount)) {
                        row.currentStlAmountUSD = 0
                        return this.$message.error("本次对账金额不能超过未对账金额");
                    }
                }
                if (Number(row.amount - row.stlTtlAmount) < 0) {
                    if (Number(row.currentStlAmountUSD) >= 0) {
                        console.log(row.amount - row.stlTtlAmount)
                        row.currentStlAmountUSD = Number(row.amount - row.stlTtlAmount)
                        return this.$message.error("本次对账金额不能输入非负数");
                    }
                    if (Number(row.currentStlAmountUSD) < Number(row.amount - row.stlTtlAmount)) {
                        row.currentStlAmountUSD = Number(row.amount - row.stlTtlAmount)
                        return this.$message.error("本次对账金额不能超过未对账金额");
                    }
                }
            }
        },
        // 展开行或者关闭
        expandChange(row) {
            let accBillId = ''
            if (this.form.id) {
                accBillId = row.accBillId
            } else {
                accBillId = row.id
            }
            feecenterSelectByAccNoList({ accBillId }).then(res => {
                row.costDate = res.data.data.map(item => {
                    if (item.curCode == this.getLocalCurrency()) {
                        this.$set(item, 'rmbAmount', item.amount)
                        this.$set(item, 'usdAmount', '')
                        this.$set(item, 'rmbAmountNet', item.amountNet)
                        this.$set(item, 'usdAmountNet', '')
                    } else {
                        this.$set(item, 'usdAmount', item.amount)
                        this.$set(item, 'rmbAmount', '')
                        this.$set(item, 'usdAmountNet', item.amountNet)
                        this.$set(item, 'rmbAmountNet', '')
                    }
                    return item
                })
            })
        },
        // 明细删除
        deletefun(row, index) {
            this.$emit('deletefun', row.id, index)
        },
        // 币别切换
        corpChange(value, row) {
            this.$set(row, 'currentStlCurCode', value)
            if (value == this.getLocalCurrency()) {
                this.$set(row, 'currentStlAmountRMB', Number(row.amount) - Number(row.stlTtlAmount))
            } else {
                this.$set(row, 'currentStlAmountUSD', Number(row.amount) - Number(row.stlTtlAmount))
            }
        },
        // 接口请求
        // 是否接口
        isSignforWorkDicts() {
            getWorkDicts('ifInvoice').then(res => {
                this.ifInvoiceData = res.data.data
            })
        },
        // 发票
        invoicelosWorkDictsfun() {
            getWorkDicts('invoice_los').then(res => {
                this.invoicelosDara = res.data.data
            })
        },
        // 获取币别数据
        // 获取币别数据
        async getRateListfun(cnName) {
            await this.checkRate(null, null, null, 2)
            this.curCodeData = this.getCheckRate()
            // getRateList({ current: 1, size: 10, cnName }).then(res => {
            //     this.curCodeData = res.data.data.records
            // })
        },
        // 表头样式
        tableHeaderCellStyle({ row, column, rowIndex, columnIndex }) {
            return "padding:4px 0px;fontSize:12px;color:#000;background:#ecf5ff"
        },
        // 更改表格颜色
        headerClassName(tab) {
            //颜色间隔
            let back = ""
            if (tab.columnIndex >= 0 && tab.column.level === 1) {
                if (tab.columnIndex % 2 === 0) {
                    back = "back-one"
                } else if (tab.columnIndex % 2 === 1) {
                    back = "back-two"
                }
            }
            return back;
        },

        // Element UI 表格点击选中行/取消选中 快捷多选 以及快捷连续多选，高亮选中行 ——-------------------------------------——
        // 多选选择的数据
        handleSelectionChange(arr) {
            // // 全选
            // if (arr.length == this.tableData.length) {
            //     for (let item of arr) {
            //         this.$set(item,'tableSelect',1)
            //     }
            // }
            // // 清除全选
            // if (arr.length == 0) {
            //     for (let item of this.tableData) {
            //         this.$set(item,'tableSelect',0)
            //     }
            // }
            this.$emit('handleSelectionChange', arr)
        },
        // // 多选
        // toggleSelection(rows){
        //     if (rows) {
        //         rows.forEach(row => {
        //             this.$refs.tableRef.toggleRowSelection(row);
        //         });
        //     } else {
        //         this.$refs.tableRef.clearSelection();
        //     }
        // },
        // 监听点击表格事件
        rowClick(row, column, event) {
            let refsElTable = this.$refs.tableRef; // 获取表格对象
            if (this.CtrlDown) {
                refsElTable.toggleRowSelection(row); // ctrl多选 如果点击两次同样会取消选中
                return;
            }
            if (this.shiftOrAltDown && this.handleSelectionData.length > 0) {
                // 通过rowIndex判断已选择的行中最上面和最下面的是哪行，再对比按住shift/alt点击的当前行得到新的最上面和最下面的行，把这两行中间的行进行循环选中。
                let topAndBottom = this.getTopAndBottom(row, this.bottomSelectionRow, this.topSelectionRow);
                refsElTable.clearSelection(); //先清空 不然会导致在这两行中间之外的行状态不变
                for (let index = topAndBottom.top; index <= topAndBottom.bottom; index++) { //选中两行之间的所有行
                    refsElTable.toggleRowSelection(this.tableData[index], true);
                }
            } else {
                let findRow = this.handleSelectionData.find(c => c.rowIndex == row.rowIndex); //找出当前选中行
                //如果只有一行且点击的也是这一行则取消选择 否则清空再选中当前点击行
                if (findRow && this.handleSelectionData.length === 1) {
                    refsElTable.toggleRowSelection(row, false);
                    return;
                }
                // refsElTable.clearSelection(); // 清空之前选择的数据(如果放开，选择之前会变成单选)
                refsElTable.toggleRowSelection(row); // 调用选中行方法
            }
        },
        // 行的 style 的回调方法
        rowStyle({ row, rowIndex }) {
            // 直接在一个对象上定义一个新属性，或者修改一个对象的现有属性，并返回此对象
            // object: 要添加或者修改属性的目标对象；prop: 要定义或修改属性的名称；descript: 是一个对象，里面是我们上述的对象属性的特性；
            Object.defineProperty(row, 'rowIndex', { //给每一行添加不可枚举属性rowIndex来标识当前行
                value: rowIndex, // 设置age的值，不设置的话默认为undefined
                writable: true, // 表示属性的值true可以修改,false不可以被修改
                enumerable: false, // 设置为false表示不能通过 for-in 循环返回
                // configurable: false, // configurable 设置为 false，意味着这个属性不能从对象上删除
            })
        },
        keyDown(event) {
            let key = event.keyCode;
            if (key == 17) this.CtrlDown = true;
            if (key == 16 || key == 18) this.shiftOrAltDown = true;
        },
        keyUp(event) {
            let key = event.keyCode;
            if (key == 17) this.CtrlDown = false;
            if (key == 16 || key == 18) this.shiftOrAltDown = false;
        },
        // 文章说明 https://www.jianshu.com/p/48f2c522d2a2
        getTopAndBottom(row, bottom, top) {
            let n = row.rowIndex,
                mx = bottom.rowIndex,
                mi = top.rowIndex;
            if (n > mx) {
                return {
                    top: mi,
                    bottom: n
                };
            } else if (n < mx && n > mi) {
                return {
                    top: mi,
                    bottom: n
                };
            } else if (n < mi) {
                return {
                    top: n,
                    bottom: mx
                };
            } else if (n == mi || n == mx) {
                return {
                    top: mi,
                    bottom: mx
                };
            }
        },
        // 给选中行加上current-row这个class类，所以要使用row-class-name这个属性（其实给每一行添加rowIndex也可以用这个属性），
        // 判断方式也是通过判断rowIndex对比
        rowClassName({ row, rowIndex }) {
            let rowName = "",
                findRow = this.handleSelectionData.find(c => c.rowIndex === row.rowIndex);
            if (findRow) {
                rowName = "current-row"; // elementUI 默认高亮行的class类 不用再样式了^-^,也可通过css覆盖改变背景颜色
            }
            return rowName; //也可以再加上其他类名 如果有需求的话
        },
        // 收付展示不一样的颜色
        cellStyle({ row, rowIndex, columnIndex }) {
            return
            let rowStyle = ''
            let bgStyle = ''
            if (row.dc == 'D') {
                rowStyle = 'color:#8cb24b;'
            } else if (row.dc == 'C') {
                rowStyle = 'color:#F56C6C;'
            }
            if (row.id) {
                bgStyle = 'background: #f0f9eb;'
            }
            return rowStyle + 'padding:0px;fontSize:12px;' + bgStyle
        },
        //自定义列保存
        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;
            }
        },
    },
    mounted() {
        // 按住ctrl实现多选 设置监听keydown事件,以及keyup事件，
        addEventListener("keydown", this.keyDown, false);
        addEventListener("keyup", this.keyUp, false);
    },
    beforeDestroy() { //解绑
        removeEventListener("keydown", this.keyDown);
        removeEventListener("keyup", this.keyUp);
    },
    computed: { //实时得到最上行和最下行
        bottomSelectionRow() {
            if (this.handleSelectionData.length == 0) return null;
            return this.handleSelectionData.reduce((start, end) => {
                return start.rowIndex > end.rowIndex ? start : end;
            });
        },
        topSelectionRow() {
            if (this.handleSelectionData.length == 0) return null;
            return this.handleSelectionData.reduce((start, end) => {
                return start.rowIndex < end.rowIndex ? start : end;
            });
        }
    },
}
</script>

<style scoped>
.textHide {
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
</style>
