<template>
    <div id="product_batch_import">
        <el-form :inline="true">
            <el-form-item>
                <el-input
                    v-model="search.entTaxId"
                    clearable
                    prefix-icon="el-icon-search"
                    placeholder="请输入企业税号"
                    class="file_input"
                >
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-input
                    v-model="search.fileName"
                    clearable
                    prefix-icon="el-icon-search"
                    placeholder="请输入文件名称"
                    class="file_input"
                >
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="search.fileUploadDateTime"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="上传开始日期"
                    end-placeholder="上传结束日期"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-select
                    v-model="search.fileStatus"
                    placeholder="请选择文件处理状态"
                >
                    <el-option
                        v-for="item in fileStatusOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleSearch" type="primary"
                    >搜 索</el-button
                >
            </el-form-item>
        </el-form>
        <div>
            <el-button type="primary" @click="handleFilesCommit"
                >批量提交
            </el-button>
            <el-button @click="handleShowDialogSelectFiles"
                >{{ $t("excel.importExcel") }}
            </el-button>
        </div>
        <br />
        <el-container>
            <el-table
                :data="search.resultList"
                border
                style="width: 100%"
                @selection-change="handleSearchResultCheckChange"
            >
                <el-table-column
                    type="selection"
                    width="55"
                    :selectable="handleSelectable"
                ></el-table-column>
                <el-table-column
                    prop="fileName"
                    label="文件名"
                ></el-table-column>
                <el-table-column
                    prop="status"
                    label="文件处理状态"
                    width="100"
                    :formatter="fmtFileStatus"
                ></el-table-column>
                <el-table-column
                    prop="successCnt"
                    label="提交成功数"
                    width="90"
                ></el-table-column>
                <el-table-column
                    prop="totalCnt"
                    label="提交总数"
                    width="90"
                ></el-table-column>
                <el-table-column
                    prop="operatorName"
                    label="操作人员名称"
                    width="100"
                ></el-table-column>
                <el-table-column
                    prop="operatorMobile"
                    label="操作人员手机号"
                    width="120"
                ></el-table-column>
                <el-table-column
                    prop="createTime"
                    label="上传文件时间"
                    width="180"
                ></el-table-column>
                <el-table-column
                    fixed="right"
                    label="操作"
                    align="center"
                    width="160"
                >
                    <template slot-scope="scope">
                        <el-button
                            @click="handleFileDetails(scope.row)"
                            type="primary"
                            >文件详情</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </el-container>
        <br />
        <el-row type="flex" :gutter="20">
            <el-col :span="12"> </el-col>
            <el-col :span="12">
                <div style="text-align: right">
                    <el-pagination
                        @size-change="handleSearchResultSizeChange"
                        @current-change="handleSearchResultCurrentChange"
                        :current-page="search.resultPagination.currentPage"
                        :page-sizes="search.resultPagination.pageSizes"
                        :page-size="search.resultPagination.pageSize"
                        layout="total, sizes, prev, pager, next"
                        :total="search.resultPagination.total"
                    >
                    </el-pagination>
                </div>
            </el-col>
        </el-row>
        <el-dialog
            title="文件上传"
            :visible.sync="batchUpload.dialogVisible"
            @close="handleCloseDialogBatchUpload('batch-upload')"
            :show-close="false"
            :close-on-press-escape="false"
            :close-on-click-modal="false"
            center
            width="500px"
        >
            <div
                style="text-align: center"
                v-loading="importLoading"
                element-loading-text="文件上传中，请稍等"
            >
                <el-upload
                    ref="batch-upload"
                    drag
                    action=""
                    multiple
                    :auto-upload="false"
                    :http-request="customBatchUpload"
                    :on-change="handleChangeBatchFiles"
                >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text"><em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">
                        只能上传.xlsx格式文件，且不超过10M
                    </div>
                </el-upload>
                <br />
                <span slot="footer" class="dialog-footer">
                    <el-button
                        type="primary"
                        @click="submitBatchUpload('batch-upload')"
                    >
                        立即上传
                    </el-button>
                    <el-button @click="batchUpload.dialogVisible = false"
                        >取 消</el-button
                    >
                </span>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    BatchProductFileSave,
    BatchProductUploadFileSearch,
    BatchProductFilesCommit,
} from "@/api/ent_init";

// 文件状态选项
const fileStatusOptions = [
    {
        value: 1,
        label: "文件处理中",
    },
    {
        value: 2,
        label: "文件处理失败",
    },
    {
        value: 3,
        label: "文件处理成功",
    },
];

export default {
    name: "product_batch_import",
    data() {
        return {
            importLoading: false,
            fileStatusOptions: fileStatusOptions,
            search: {
                entTaxId: "",
                fileName: "",
                fileUploadDateTime: "",
                fileStatus: "",
                resultList: [],
                resultMultipleSelection: [],
                resultPagination: {
                    currentPage: 1,
                    pageSizes: [10, 30, 50, 100],
                    pageSize: 10,
                    total: 0,
                },
            },
            batchUpload: {
                dialogVisible: false,
                files: [],
            },
        };
    },
    created() {
        this.callBatchProductUploadFileSearch(
            this.search.resultPagination.currentPage,
            this.search.resultPagination.pageSize
        );
    },
    methods: {
        pageIndex(index) {
            let currentPage = this.search.resultPagination.currentPage; //当前页码，具体看组件取值
            let pageSize = this.search.resultPagination.pageSize; //每页条数，具体是组件取值
            return index + 1 + (currentPage - 1) * pageSize;
        },
        fmtFileStatus(row, column, cellValue) {
            let result = cellValue;
            for (const item of fileStatusOptions) {
                if (item.value === cellValue) {
                    result = item.label;
                    break;
                }
            }
            return result;
        },
        handleSearch() {
            this.callBatchProductUploadFileSearch(
                1,
                this.search.resultPagination.pageSize
            );
        },
        handleSearchResultCheckChange(val) {
            this.search.resultMultipleSelection = val;
            console.log("选中数据");
            console.log(this.search.resultMultipleSelection);
        },
        handleSearchResultSizeChange(val) {
            this.callBatchProductUploadFileSearch(1, val);
        },
        handleSearchResultCurrentChange(val) {
            this.callBatchProductUploadFileSearch(
                val,
                this.search.resultPagination.pageSize
            );
        },
        customBatchUpload(file) {
            this.batchUpload.files.push(file.file);
            return false;
        },
        handleChangeBatchFiles(file, fileList) {
            let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
            const isType = extension === "xls" || extension === "xlsx";
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isType) {
                this.$message.error("上传的数据文件只能是.xlsx格式！");
                fileList.splice(fileList.indexOf(file), 1);
            }
            if (!isLt10M) {
                this.$message.error("上传的单个数据文件大小不能超过10MB!");
                fileList.splice(fileList.indexOf(file), 1);
            }
            return isType && isLt10M;
        },
        handleCloseDialogBatchUpload(refName) {
            this.$refs[refName].clearFiles();
            this.batchUpload.files = [];
        },
        submitBatchUpload(refName) {
            this.importLoading = true;
            this.$refs[refName].submit();
            BatchProductFileSave(this.batchUpload.files)
                .then((val) => {
                    this.importLoading = false;
                    this.$message.success(val.msg);
                    this.batchUpload.dialogVisible = false;
                    this.callBatchProductUploadFileSearch(
                        1,
                        this.search.resultPagination.pageSize
                    );
                })
                .catch((err) => {
                    this.importLoading = false;
                    this.$message.error(err);
                });
        },
        // 显示文件上传弹窗
        handleShowDialogSelectFiles() {
            this.batchUpload.dialogVisible = true;
        },
        // 查看文件详细
        handleFileDetails(row) {
            this.$router.push({
                name: "product_batch_file_details",
                params: { key: row.batchId.toString() },
            });
        },
        // 批量提交
        handleFilesCommit() {
            if (this.search.resultMultipleSelection.length > 0) {
                this.callBatchProductFilesCommit(
                    this.search.resultMultipleSelection
                );
            } else {
                this.$message("请勾选需要提交保存的文件！");
            }
        },
        //判断当前行是否可以选中
        handleSelectable(row, index) {
            // 提交状态  1：文件处理中  2：文件处理失败 3：文件处理成功
            return row.status === 3 && row.successCnt !== row.totalCnt;
        },
        callBatchProductFilesCommit(selectRows) {
            this.$confirm(
                "商品不含税单价将默认转换为含税单价, 是否继续?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).then(() => {
                let batchIds = new Array();
                for (let index = 0; index < selectRows.length; index++) {
                    const element = selectRows[index];
                    batchIds[index] = element.batchId;
                }
                BatchProductFilesCommit(batchIds)
                    .then((val) => {
                        this.callBatchProductUploadFileSearch(
                            1,
                            this.search.resultPagination.pageSize
                        );
                        this.$message.success(val.msg);
                    })
                    .catch((err) => {
                        this.$message.error(err);
                    });
            });
        },
        /**
         * 批量上架文件查询
         * @param {Number} pageNum : 当前页码
         * @param {Number} pageSize : 每页数量
         */
        callBatchProductUploadFileSearch(pageNum, pageSize) {
            let beginTime = "";
            let endTime = "";
            if (this.search.fileUploadDateTime instanceof Array) {
                beginTime = this.search.fileUploadDateTime[0];
                endTime = this.search.fileUploadDateTime[1];
                beginTime = this.dateFormat(
                    new Date(beginTime),
                    "yyyy-MM-dd HH:mm:ss"
                );
                let endTimeObj = new Date(endTime);
                endTime = this.dateFormat(
                    new Date(
                        endTimeObj.getFullYear(),
                        endTimeObj.getMonth(),
                        endTimeObj.getDate(),
                        "23",
                        "59",
                        "59"
                    ),
                    "yyyy-MM-dd HH:mm:ss"
                );
            }
            BatchProductUploadFileSearch({
                entTaxId: this.search.entTaxId,
                fileName: this.search.fileName,
                uploadDateBegin: beginTime,
                uploadDateEnd: endTime,
                status: this.search.fileStatus,
                pageNum: pageNum,
                pageSize: pageSize,
            })
                .then((val) => {
                    this.search.resultPagination.total = val.data.total;
                    this.search.resultPagination.pageSize = val.data.size;
                    this.search.resultPagination.currentPage = val.data.current;
                    this.search.resultList = val.data.records;
                })
                .catch((err) => {
                    this.$message.error(err);
                });
        },
        dateFormat(date, fmt) {
            // 小时只支持24小时制
            var o = {
                "M+": date.getMonth() + 1, // 月份
                "d+": date.getDate(), // 日
                "H+": date.getHours(), // 24小时,
                "m+": date.getMinutes(), // 分
                "s+": date.getSeconds(), // 秒
                "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
                S: date.getMilliseconds(), // 毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(
                    RegExp.$1,
                    (date.getFullYear() + "").substr(4 - RegExp.$1.length)
                );
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(
                        RegExp.$1,
                        RegExp.$1.length == 1
                            ? o[k]
                            : ("00" + o[k]).substr(("" + o[k]).length)
                    );
            return fmt;
        },
    },
};
</script>

<style scoped>
</style>
