<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
        >
            <el-form-item label="月份">
                <el-date-picker
                    v-model="searchDate"
                    type="monthrange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    align="left"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    clearable
                    size="small"
                    style="width: 260px"
                >
                </el-date-picker>

                <!-- <el-date-picker
                    v-model="searchDate"
                    type="monthrange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始月份"
                    end-placeholder="结束月份"
                    :default-time="['00:00:00', '23:59:59']"
                    >
                </el-date-picker> -->
            </el-form-item>

            <el-form-item
                label="个体户编号"
                prop="merchantIndex"
                style="margin-left: 30px"
            >
                <el-input
                    v-model="queryParams.merchantIndex"
                    placeholder="请输入个体户编号"
                    maxlength="30"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item
                label="个体户姓名"
                prop="merchantName"
                style="margin-left: 30px"
            >
                <el-input
                    v-model="queryParams.merchantName"
                    placeholder="请输入个体户姓名"
                    maxlength="20"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item
                label="状态"
                prop="settleStatus"
                style="margin-left: 30px"
            >
                <el-select
                    v-model="queryParams.settleStatus"
                    placeholder="请选择"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                >
                    <el-option label="全部" value=""></el-option>
                    <el-option label="待结算" value="001"></el-option>
                    <el-option label="已支付" value="002"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-search"
                    @click="handleQuery"
                    plain
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="small"
                    @click="resetQuery"
                    >重置</el-button
                >
                <el-button
                    style="margin-left: 10px"
                    size="small"
                    @click="handleExport"
                    >导出</el-button
                >
            </el-form-item>
        </el-form>
        <p style="font-size: 14px; text-align: left">
            <el-button
                style="margin-left: 10px"
                size="small"
                @click="batchSettle"
                >批量结算</el-button
            ><span style="margin-left: 10px"
                >注：批量结算需选择同一个个体户账单，多个月一起结算。</span
            >

            <span style="margin-left: 400px">待结算&nbsp;&nbsp;</span
            ><span style="font-size: 28px; color: #f59a23">{{
                formatMoney(amountInfo.pendingSettlementAmount, 2)
            }}</span>
            <span style="margin-left: 30px">已支付&nbsp;&nbsp;</span
            ><span style="font-size: 28px; color: #f59a23">{{
                formatMoney(amountInfo.paidAmount, 2)
            }}</span>
        </p>
        <el-table
            v-loading="loading"
            :data="dataList"
            border
            stripe
            @selection-change="handleSelectionChange"
        >
            <!-- <el-table-column label="序号" align="center" type="index" /> -->
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
                label="月份"
                align="center"
                prop="yearMonth"
                show-overflow-tooltip
            />
            <el-table-column
                label="个体户编号"
                align="center"
                prop="merchantIndex"
                show-overflow-tooltip
            />
            <el-table-column
                label="个体户姓名"
                align="center"
                prop="merchantName"
                show-overflow-tooltip
            />

            <el-table-column
                label="实际收入（元）"
                align="center"
                prop="actualIncome"
            />

            <el-table-column
                label="状态"
                align="center"
                prop="settleStatusName"
            >
                <!-- <template slot-scope="scope">
                    <span v-if="scope.row.settleStatus == '001'">待结算</span>
                    <span v-if="scope.row.settleStatus == '002'">已支付</span>
                </template> -->
            </el-table-column>

            <el-table-column
                label="操作"
                align="center"
                width="220"
                fixed="right"
            >
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        icon="el-icon-view"
                        @click="queryDetail(scope.row)"
                        v-hasPermi="['shop:audit:audit']"
                        v-if="scope.row.settleStatus == '002'"
                        >查看凭证
                    </el-button>
                    <el-button
                        type="text"
                        icon="el-icon-circle-check"
                        @click="clearingClick(scope.row)"
                        v-hasPermi="['shop:audit:audit']"
                        v-if="scope.row.settleStatus == '001'"
                        >结算
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 结算凭证对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            max-width="1080px"
            height="auto"
            append-to-body
        >
            <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="100px"
            >
                <Images label="上传支付凭证" prop="resourceUrl" :limit="6" />
                <!-- <el-form-item label="上传支付凭证" class="form-item">   
          <Upload @imageUrl="setImageUrl" :url="form.urlImg"  />
        </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click.stop="submitForm"
                    >确 定</el-button
                >
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 查看支付凭证 -->
        <el-dialog :title="title" :visible.sync="lookDetail" append-to-body>
            <!-- <el-image
                  style="border-radius:8px;"
                  :src="urlImg"
                  :preview-src-list="[urlImg]"
                  alt="结算凭证"
                >
                  <div slot="error">
                    <img src="../../../assets/images/image_placeholder.png" />
                  </div>
                </el-image> -->
            <div
                :gutter="10"
                class="add-td"
                v-for="(item, index) in resourceImages"
                :key="index"
            >
                <el-image
                    style="
                        width: 100px;
                        height: 100px;
                        border-radius: 8px;
                        margin-left: 20px;
                    "
                    :src="item.resourceUrl"
                    :preview-src-list="[item.resourceUrl]"
                    alt="结算凭证"
                >
                    <div slot="error">
                        <img
                            src="../../../assets/images/image_placeholder.png"
                        />
                    </div>
                </el-image>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    personalSettleList,
    exportData,
    getPersonalMerchantSettleAmountInfo,
    settlePersonalMerchantOrder,
    getPersonalSettleResource,
} from "@/api/reconciliation/adminReconciliation";
import Upload from "@/components/Upload/index.vue";

export default {
    name: "Banner",
    components: {
        Upload,
    },
    name: "adminMember",
    data() {
        return {
            showSearch: true,
            loading: true,
            total: 0,
            dataList: [],
            amountInfo: {},
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                merchantIndex: "",
                merchantName: "",
                settleStatus: "",
                yearMonthStart: "",
                yearMonthEnd: "",
            },

            form: {
                personalMerchantSettleList: [],
                resourceUrl: "",
            },
            // 弹出层标题
            title: "",
            open: false,
            lookDetail: false,

            searchDate: "",

            statusList: [],
            multipleSelection: [],
            resourceImages: [],

            images: [],
            rules: {
                urlImg: [
                    {
                        required: true,
                        message: "图片资源地址不能为空",
                        trigger: "blur",
                    },
                ],
                id: [
                    { required: true, message: "ID不能为空", trigger: "blur" },
                ],
            },
        };
    },
    created() {
        this.getList();
        this.getAmountInfo();
    },
    methods: {
        // 查询个体户账单结算分页列表
        getList() {
            this.loading = true;
            if (this.searchDate == null) {
                this.searchDate = "";
            }
            const [searchBegin, searchEnd] = this.searchDate;
            let sBegin = searchBegin;
            let sEnd = searchEnd;
            if (typeof searchBegin == "undefined") {
                 var start = new Date()
                start.setTime(start.getTime()-3600 * 1000 * 24 * 30)
                this.searchDate = [start,new Date()]
                sBegin = this.timeStamp2String(start)
            }
            if (typeof searchEnd == "undefined") {
                sEnd = this.timeStamp2String(new Date())
                this.searchDate=[sBegin,sEnd]
            }
            console.log(this.searchDate);
            console.log(this.queryParams);

            this.queryParams.yearMonthStart = sBegin.substring(
                0,
                sBegin.lastIndexOf("-")
            );
            this.queryParams.yearMonthEnd = sEnd.substring(
                0,
                sEnd.lastIndexOf("-")
            );
            // 查询个体户账单结算分页列表
            personalSettleList(this.queryParams)
                .then((response) => {
                    this.dataList = response.rows;
                    this.total = parseInt(response.total);
                    // 查询统计金额
                    getPersonalMerchantSettleAmountInfo(this.queryParams)
                        .then((res) => {
                            if (res.code === 200) {
                                if (res.data) {
                                    this.amountInfo = res.data;
                                }
                            } else {
                                this.$modal.msgError(res.msg);
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                })
                .catch((err) => {
                    console.log(err);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        // 表单重置
        reset() {
            this.form = {
                personalMerchantSettleList: [],
                resourceUrl: "",
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
            this.getPersonalMerchantSettleAmountInfo();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.searchDate = [];
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                yearMonthStart: "",
                yearMonthEnd: "",
                merchantIndex: "",
                merchantName: "",
                settleStatus: "",
            };
            this.handleQuery();
        },

        // 点击结算
        clearingClick(row) {
            this.form = {
                personalMerchantSettleList: [],
                resourceUrl: "",
            };
            this.open = true;
            this.form.personalMerchantSettleList.push(row);

            this.title = "结算";
        },

        /** 提交 结算凭证 按钮 */
        submitForm() {
            if (this.form.resourceUrl == null || this.form.resourceUrl == "") {
                return this.$message.error("结算凭证不能为空");
            }
            if (
                this.form.personalMerchantSettleList == null ||
                this.form.personalMerchantSettleList.size == 0
            ) {
                return this.$message.error("结算列表不能为空");
            }
            // 调用结算接口
            settlePersonalMerchantOrder(this.form)
                .then((res) => {
                    if (res.code == 200) {
                        this.$message.success("结算成功");
                        this.open = false;
                        this.getList();
                        this.getAmountInfo();
                    } else {
                        this.$message.error(res.msg);
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },

        // 查看结算凭证图片
        queryDetail(row) {
            this.title = "查看结算凭证";
            this.resourceImages = [];
            this.lookDetail = true;
            // 查询个体户账单结算资源
            let personalMerchantSettleId = {
                personalMerchantSettleId: row.personalMerchantSettleId,
            };
            getPersonalSettleResource(personalMerchantSettleId)
                .then((res) => {
                    if (res.code == 200) {
                        this.resourceImages = res.data;
                    } else {
                        this.$message.error(res.msg);
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        formatMoney(s, type) {
            if (/[^0-9\.]/.test(s)) return "0";
            if (s == null || s == "") return "0";
            s = s.toString().replace(/^(\d*)$/, "$1.");
            s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
            s = s.replace(".", ",");
            var re = /(\d)(\d{3},)/;
            while (re.test(s)) s = s.replace(re, "$1,$2");
            s = s.replace(/,(\d\d)$/, ".$1");
            if (type == 0) {
                // 不带小数位(默认是有小数位)
                var a = s.split(".");
                if (a[1] == "00") {
                    s = a[0];
                }
            }
            return s;
        },
        // 批量选择
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 批量结算
        batchSettle() {
            if (this.multipleSelection.length > 0) {
                this.form = {
                    personalMerchantSettleList: [],
                    resourceUrl: "",
                };
                for (let i in this.multipleSelection) {
                    // 过滤掉已经结算过的数据
                    if (this.multipleSelection[i].settleStatus === "001") {
                        this.form.personalMerchantSettleList.push(
                            this.multipleSelection[i]
                        );
                    }
                }
                if (
                    this.form.personalMerchantSettleList.length > 0 &&
                    this.multipleSelection.length !=
                        this.form.personalMerchantSettleList.length
                ) {
                    this.$message.error(
                        "已选择的数据中存在已支付数据，请重新选择待结算的数据！"
                    );
                }
                if (this.form.personalMerchantSettleList.length === 0) {
                    return this.$message.error(
                        "不存在待结算的数据，请重新选择！"
                    );
                }
                // 打开结算对话框
                this.open = true;
                this.title = "批量结算";
            } else {
                this.$message.error("请先选择需要操作的数据！");
            }
        },
        setImageUrl(val) {
            this.form.urlImg = val;
        },

        // Excel导出数据
        handleExport() {
            exportData(this.queryParams)
                .then((res) => {
                    if (res.code === 200) {
                        if (res.data) {
                            this.$modal.msgSuccess("导出成功");
                            let url =
                                "http://fresh-life.oss-cn-shanghai.aliyuncs.com/" +
                                res.data;
                            window.open(url);
                        } else {
                            this.$modal.msgError("导出失败");
                        }
                    } else {
                        this.$modal.msgError(res.msg);
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },

        // 查询个体户账单结算金额信息
        getAmountInfo() {
            if (this.searchDate == null) {
                this.searchDate = "";
            }
            const [searchBegin, searchEnd] = this.searchDate;
            let sBegin = searchBegin;
            let sEnd = searchEnd;
            if (typeof searchBegin == "undefined") {
                sBegin = "";
            }
            if (typeof searchEnd == "undefined") {
                sEnd = "";
            }

            this.queryParams.yearMonthStart = sBegin.substring(
                0,
                sBegin.lastIndexOf("-")
            );
            this.queryParams.yearMonthEnd = sEnd.substring(
                0,
                sEnd.lastIndexOf("-")
            );
            getPersonalMerchantSettleAmountInfo(this.queryParams)
                .then((res) => {
                    if (res.code === 200) {
                        if (res.data) {
                            this.amountInfo = res.data;
                        }
                    } else {
                        this.$modal.msgError(res.msg);
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        timeStamp2String(datetime){
           
            var year = datetime.getFullYear();
            var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
            var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
            var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : datetime.getHours();
            var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
            var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
            return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
        }
    },
};
</script>

<style scoped>
.add-td {
    display: inline-block;
}
/* /deep/  */
.image-item {
    height: auto;
}
</style>
