<template>
    <div class="app-container">
        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <el-input v-model="listQuery.type.receivingWithdrawingPeople" clearable class="filter-item" size="small"
                style="width: 200px;" placeholder="请输入提款人姓名" />
            <!-- <el-input v-model="listQuery.type.receivingWithdrawingRegion" clearable class="filter-item" size="small"
                style="width: 200px;" placeholder="请输入提款地" /> -->

            <!-- <el-input v-model="listQuery.receiptPaymentDate" clearable class="filter-item" size="small"
                style="width: 200px;" placeholder="请输入提款日期" /> -->
            <el-select v-model="listQuery.type.receivingWithdrawingRegion" placeholder="请选择收款地" style="margin:0 20px;"
                size="small">
                <el-option :label="item.country" :value="item.country" v-for="(item, index) in placeList" :key="index">
                </el-option>
            </el-select>
            <el-date-picker style="margin-right:20px" size="small" v-model="selectDate" type="daterange" value-format="yyyy-MM-dd"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>

            <el-button v-permission="['collectionPayment:collectionpayment:list']" class="filter-item" type="primary"
                size="mini" icon="el-icon-search" @click="handleFilter">查找</el-button>
            <el-button v-permission="['collectionPayment:collectionpayment:create']" class="filter-item" type="primary"
                size="mini" icon="el-icon-edit" @click="handleCreate">添加</el-button>
            <el-button v-permission="['collectionPayment:collectionpayment:create']" class="filter-item" type="primary"
                size="mini" icon="el-icon-edit" @click="exportlist">导出</el-button>

            <el-upload style="margin-left: 8px;margin-bottom:0" class="filter-item" action="" :on-change="importClick"
                :show-file-list="false"
                accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                :auto-upload="false">
                <el-button v-permission="['collectionPayment:collectionpayment:create']" class="filter-item"
                    type="primary" size="mini" icon="el-icon-edit">导入</el-button>
            </el-upload>

        </div>

        <!-- 查询结果 -->
        <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。" border fit
            highlight-current-row show-summary :summary-method="getSummaries" @selection-change="handleSelectionChange">
            <el-table-column :selectable="selectInit" type="selection"></el-table-column>
            <el-table-column type="index" label="序号">
                <template scope="scope">
                    <span v-if="scope.$index < 9">0{{ scope.$index + 1 }}</span>
                    <span v-else>{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="提款日期" prop="receiptPaymentDate">
                <template slot-scope="scope">
                    {{ scope.row.receiptPaymentDate | formatDate }}</template>
            </el-table-column>
            <el-table-column align="center" label="提款地" prop="receivingWithdrawingRegion" />
            <el-table-column align="center" label="提款人" prop="receivingWithdrawingPeople" />
            <el-table-column align="center" label="金额（欧元）" prop="deductionEuro" />
            <el-table-column align="center" label="金额（人民币）" prop="deductionRmb" />
            <el-table-column align="center" label="备注1" prop="remarks" />
            <el-table-column align="center" label="备注2" prop="remark" />
            <el-table-column align="center" label="状态" prop="status">
                <template slot-scope="scope">
                    {{ scope.row.status == 1 ? '已作废' : '' }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作人" prop="updatePeople" />
            <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-permission="['collectionPayment:collectionpayment:edit']" type="primary" size="mini"
                        @click="handleUpdate(scope.row)">编辑</el-button>
                            <el-button v-permission="['collectionPayment:collectionpayment:edit']" type="primary" size="mini"
                        @click="updateData1(scope.row)">作废</el-button>
                    <!-- <el-button v-permission="['collectionPayment:collectionpayment:delete']" type="danger" size="mini"
                        @click="handleDelete(scope.row)">删除</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!-- <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList"/> -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="[100,200,300,400,500,600]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
        <!-- 添加或修改对话框 -->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left"
                label-width="150px" style="width: 400px; margin-left:50px;">
                <el-form-item label="id" prop="id" hidden>
                    <el-input v-model="dataForm.id" />
                </el-form-item>
                <el-form-item label="提款人" prop="receivingWithdrawingPeople">
                    <el-input v-model="dataForm.receivingWithdrawingPeople" />
                </el-form-item>
                <el-form-item label="提款地" prop="receivingWithdrawingRegion">
                    <!-- <el-input v-model="dataForm.receivingWithdrawingRegion" /> -->
                    <el-select v-model="dataForm.receivingWithdrawingRegion" placeholder="请选择提款地点" style="width:100%">
                        <el-option :label="item.country" :value="item.country" v-for="(item, index) in placeList"
                            :key="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="提款日期" prop="receiptPaymentDate">
                    <!-- <el-input v-model="dataForm.receiptPaymentDate" /> -->
                    <el-date-picker v-model="dataForm.receiptPaymentDate" type="date" class="tkdate" value-format="yyyy-MM-dd"
                        style="width: 100%;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="金额（欧元）" prop="deductionEuro">
                    <el-input v-model="dataForm.deductionEuro" />
                </el-form-item>
                <el-form-item label="金额（人民币）" prop="deductionRmb">
                    <el-input v-model="dataForm.deductionRmb" />
                </el-form-item>
                <el-form-item label="备注1" prop="remarks">
                    <el-input v-model="dataForm.remarks" />
                </el-form-item>
                <el-form-item label="备注2" prop="remark">
                    <el-input v-model="dataForm.remark" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button v-if="dialogStatus == 'create'" :loading="submiting" type="primary" @click="createData">确定
                </el-button>
                <el-button v-else type="primary" :loading="submiting" @click="updateData">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    dayjs,
    EventBus
} from 'base-core-lib'
import {
    listCountry
} from '@/api/country'
import {
    downloadFile
} from '@/utils/batchDown'
import {
    importWord,
    listCollectionPayment,
    createCollectionPayment,
    updateCollectionPayment,
    deleteCollectionPayment,
    exportXlsx
} from '@/api/collectionPayment'
// import {
//     exportXlsx
// } from '@/model/export'

import Pagination from '@/components/Pagination'
import store from '@/store'
export default {
    name: 'CollectionPayment',
    components: { Pagination },
    data() {
        return {
            isAllowExport: true,
            countryList: [],
            modification: [],
            selectDate: '',
            date: {
                year: dayjs().format('YYYY'),
                month: dayjs().format('MM'),
            },
            accessoryTFs: false,
            fileList: [],
            appendixIdsAdd: '',
            excelFreightspace: [],
            fileTemp: null,
            placeList: [],
            list: null,
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                type: {
                    businessType: 2,
                    receivingWithdrawingPeople: '',
                    receivingWithdrawingRegion: '',
                    startDate: '',
                    endDate: '',
                },



            },
            listPlace: {
                page: 1,
                limit: 2000,
                type: {
                    country: ''
                }
            },
            dataForm: {
                id: undefined
            },
            dialogFormVisible: false,
            submiting: false,
            dialogStatus: '',
            textMap: {
                update: '编辑',
                create: '创建'
            },
            rules: {
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
         handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      console.log(`当前页: ${val}`)
      this.getList()
    },
        handleSelectionChange(val) {
            this.modification = val
        },
        selectInit(row) {
            return true
        },
        async exportlist() {
            if (this.modification.length == 0) {
                this.$message.warning('请选择要导出的条目！')
            } else {
                console.log('导出数据', this.modification)
                let _data = {
                    collectionPaymentTiDTOList: this.modification,
                }
                const {
                    data
                } = await exportXlsx(_data).then((response) => {
                    this.download(response.data.data)
                    //   downloadFile({
                    //     res: data,
                    //     fileName: `${
                    //     this.date.year + (this.date.month ? `-${this.date.month}` : '')
                    //     }提款信息`,
                    //     type: 'xls',
                    //     })

                    if (response.status == '200') {

                    }
                })

            }









        },
        importClick(file, fileList) {
            this.fileTemp = file.raw
            let fileName = file.raw.name
            let fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
            // 判断上传文件格式
            if (this.fileTemp) {
                if (fileType == 'xlsx' || fileType == 'xls') {
                    this.importf(this.fileTemp)
                } else {
                    this.$message({
                        type: 'warning',
                        message: '附件格式错误，请删除后重新上传！',
                    })
                }
            } else {
                this.$message({
                    type: 'warning',
                    message: '请上传附件！',
                })
            }
        },
        importf(obj) {
            this.excelFreightspace = []
            // this.dialogVisible = true;
            let _this = this;
            let inputDOM = this.$refs.inputer; // 通过DOM取文件数据
            this.file = event.currentTarget.files[0];
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;
            var reader = new FileReader();
            //if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function (f) {
                var binary = '';
                var rABS = false; //是否将文件读取为二进制字符串
                var pt = this;
                var wb; //读取完成的数据
                var outdata;
                var reader = new FileReader();
                reader.onload = function (e) {
                    var bytes = new Uint8Array(reader.result);
                    var length = bytes.byteLength;
                    for (var i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    var XLSX = require('xlsx');
                    if (rABS) {
                        wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                            type: 'base64',
                            cellDates: true
                        });
                    } else {
                        wb = XLSX.read(binary, {
                            type: 'binary'
                        });
                    }
                    // outdata就是你想要的东西 excel导入的数据
                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                    // excel 数据再处理
                    let arr = []
                    outdata.map(v => {
                        // let jsonString = JSON.stringify(v).replace(/\*/g, '').replace(/\s/ig,'');
                        let jsonString = JSON.stringify(v).replace(/\//g, '').replace(/\s/ig, '');
                        v = JSON.parse(jsonString);
                        let obj = {}

                        //xxx代表列名
                        obj.receiptPaymentDate = v.提款日期
                        obj.receivingWithdrawingRegion = v.提款地
                        obj.receivingWithdrawingPeople = v.提款人
                        obj.deductionEuro = v.金额EUR
                        obj.deductionRmb = v.金额RMB
                        obj.businessType = 2
                        obj.remarks = v.备注1
                        obj.remark = v.备注2
                        obj.updatePeople = _this.$store.getters.name
                        if (!obj.deductionEuro) {
                            obj.deductionEuro = 0
                        }
                        if (!obj.deductionRmb) {
                            obj.deductionRmb = 0
                        }
                        for (let i = 0; i < _this.placeList.length; i++) {
                            _this.countryList.push(_this.placeList[i].country)
                        }
                        if (!_this.countryList.includes(obj.receivingWithdrawingRegion)) {
                            _this.isAllowExport = false
                            _this.$notify({
                                title: '失败',
                                message: '导入失败，导入数据中收款地在系统中不存在，请重新编辑',
                                type: 'error'
                            });
                            return
                        } else {
                            _this.excelFreightspace.push(obj)
                            _this.isAllowExport = true
                        }
                    })
                    if (_this.excelFreightspace && _this.isAllowExport) {
                        importWord(_this.excelFreightspace).then((response) => {

                            if (response.status == '200') {
                                _this.$notify({
                                    title: '成功',
                                    message: '导入成功',
                                    type: 'success'
                                });
                                _this.getList()
                            }
                        })

                    }
                }
                reader.readAsArrayBuffer(f);
            }
            if (rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }

        },
        formatDate(numb, format) {
            const old = numb - 1;
            const t = Math.round((old - Math.floor(old)) * 24 * 60 * 60);
            const time = new Date(1900, 0, old, 0, 0, t)
            const year = time.getFullYear();
            const month = time.getMonth() + 1;
            const date = time.getDate();
            return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date) + ' 00:00:00'
        },
        getSummaries(param) {

            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                } else if (index == 5 || index == 6) {
                    const values = data.map((item) => Number(item[column.property]));
                    if (!values.every((value) => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] += "";
                    } else {
                        sums[index] = "--";
                    }
                } else {
                    // sums[index] = "--";
                }
            });

            return sums;

        },
        getList() {

            console.log(this.selectDate)
            listCountry(this.listPlace).then(response => {
                this.placeList = response.data.data.items
            })
                .catch(() => {
                    this.placeList = []
                })
            this.listLoading = true
            console.log(this.selectDate)
            if (this.selectDate.length > 0) {

                this.listQuery.type.startDate = dayjs(this.selectDate[0]).format('YYYY-MM-DD')
                this.listQuery.type.endDate = dayjs(this.selectDate[1]).format('YYYY-MM-DD')
            }

            listCollectionPayment(this.listQuery).then(response => {
                this.list = response.data.data.items
                this.total = response.data.data.total
                this.listLoading = false
            })
                .catch(() => {
                    this.list = []
                    this.total = 0
                    this.listLoading = false
                })
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        resetForm() {
            this.dataForm = {
                id: undefined
            }
        },
        handleCreate() {
            this.resetForm()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.$refs['dataForm'].validate(valid => {
                if (valid) {
                    this.submiting = true
                    this.dataForm.businessType = 2
                    this.dataForm.updatePeople = this.$store.getters.name
                    if (!this.dataForm.deductionEuro) {
                        this.dataForm.deductionEuro = 0
                    }
                    if (!this.dataForm.deductionRmb) {
                        this.dataForm.deductionRmb = 0
                    }
                    createCollectionPayment(this.dataForm).then(response => {
                        this.list.unshift(response.data.data)
                        this.dialogFormVisible = false
                        this.$notify.success({
                            title: '成功',
                            message: '添加成功'
                        })
                        this.submiting = false
                    })
                        .catch(response => {
                            this.$notify.error({
                                title: '失败',
                                message: response.data.errmsg
                            })
                            this.submiting = false
                        })
                }
            })
        },
        handleUpdate(row) {
            this.dataForm = Object.assign({}, row)
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.$refs['dataForm'].validate(valid => {
                if (valid) {
                    this.submiting = true
                    this.dataForm.updatePeople = this.$store.getters.name
                    updateCollectionPayment(this.dataForm).then(() => {
                        for (const v of this.list) {
                            if (v.id === this.dataForm.id) {
                                const index = this.list.indexOf(v)
                                this.list.splice(index, 1, this.dataForm)
                                break
                            }
                        }
                        this.dialogFormVisible = false
                        this.submiting = false
                        this.$notify.success({
                            title: '成功',
                            message: '更新成功'
                        })
                    })
                        .catch(response => {
                            this.$notify.error({
                                title: '失败',
                                message: response.data.errmsg
                            })
                            this.submiting = false
                        })
                }
            })
        },
        updateData1(row) {
            this.dataForm.flag = 1
            this.dataForm.id = row.id
            updateCollectionPayment(this.dataForm).then(() => {

                this.submiting = false
                this.$notify.success({
                    title: '成功',
                    message: '更新成功',
                })
                this.getList()
            })
                .catch(response => {
                    this.$notify.error({
                        title: '失败',
                        message: response.data.errmsg
                    })
                    this.submiting = false
                })

        },
        handleDelete(row) {
            this.$confirm('此操作将永久删除该记录---' + row.id + '---, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteCollectionPayment(row.id).then(response => {
                    this.$notify.success({
                        title: '成功',
                        message: '删除成功'
                    })
                    const index = this.list.indexOf(row)
                    this.list.splice(index, 1)
                })
                    .catch(response => {
                        this.$notify.error({
                            title: '失败',
                            message: response.data.errmsg
                        })
                    })
            }).catch(() => {
                return false
            })
        }
    }
}
</script>
<style>
</style>
