<template>
    <div class="settlement-information-content">
        <div class="control-con-title">
            <div>
                <span class="policy-export-btn">结算单信息</span>
                <span>
                    <a-tooltip>
                        <template slot="title">显示运营人员上传账户消耗截图，运营人员可查看自己所上传数据，销售人员可查看自己所负责产品的消耗截图数据</template>
                        <a-icon class="settlement-header-icon" type="question-circle"/>
                    </a-tooltip>
                    显示列表信息，销售人员只能操作与自己相关的项目
                </span>
            </div>
            <div>
                <span class="add-acount-policy-btn"><a-button @click="handleDownloadProfit">下载利润表</a-button></span>
                <span class="add-acount-policy-btn"><a-button @click="handleDownloadSettlement">下载结算单</a-button></span>
                <span class="add-acount-policy-btn"><a-button type="primary" @click="handleUploadAccount">上传截图</a-button></span>
            </div>
        </div>
        <div class="control-con-header">
            <a-form
                class="grid-form"
                layout="inline"
                :form="searchForm"
                hide-required-mark
            >
                <a-row class="grid-form-options">
                    <a-form-item
                        class="grid-form-item"
                        label="产品名称："
                        :colon="false"
                    >
                        <a-input v-model="configForm.productName" placeholder="请输入产品名称"/>
                    </a-form-item>
                    <a-form-item
                        class="grid-form-item"
                        label="项目名称："
                        :colon="false"
                    >
                        <a-input v-model="configForm.projectName" placeholder="请输入项目名称"/>
                    </a-form-item>
                    <a-form-item
                        class="grid-form-item"
                        label="账户名称："
                        :colon="false"
                    >
                        <a-input v-model="configForm.accountName" placeholder="请输入账户名称"/>
                    </a-form-item>
                    <a-form-item label="运营：">
                        <a-select
                            v-model="configForm.createUserName"
                            style="width: 140px"
                            :filter-option="handleFilterOption"
                            show-search
                            allow-clear
                        >
                            <a-select-option
                                v-for="item in allSaleListOption"
                                :key="item.id"
                                :value="item.realName"
                            >
                                {{ item.realName }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-row>
                <a-row>
                    <a-form-item label="媒体：">
                        <a-select v-model="configForm.mediaId" style="width: 100px">
                            <a-select-option value="no">不限</a-select-option>
                            <a-select-option :value="1">头条</a-select-option>
                            <a-select-option :value="2">快手</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item
                        class="grid-form-item"
                        label="时间："
                        :colon="false"
                    >
                        <a-range-picker
                            :placeholder="['开始月份', '结束月份']"
                            format="YYYY-MM"
                            v-model="configForm.time"
                            :mode="mode2"
                            @panelChange="handlePanelChange2"
                            @change="handleAddTimesChange"
                        />
                    </a-form-item>
                    <a-form-item class="form-handle-btn">
                        <a-button type="default" class="reset-class" @click="handleResetList">重置</a-button>
                        <a-button type="primary" @click="handleQueryList">搜索</a-button>
                    </a-form-item>
                </a-row>
            </a-form>
        </div>
        <div class="control-con-table">
            <a-table
                ref="table"
                size="middle"
                bordered
                :columns="settlementColumns"
                :dataSource="dataSource"
                :pagination="false"
                :loading="controlLoading"
            >
                <span slot="mediaId" slot-scope="text">
                    <span>{{ text === 1 ? '头条' : '快手' }}</span>
                </span>
                <span slot="actions" slot-scope="text, record">
                    <a @click="handleSettleDel(record)">删除</a>
                    <a-divider type="vertical"/>
                    <a disabled>更多</a>
                </span>
            </a-table>
            <a-pagination
                class="pagin-table-class"
                :total="totalAll"
                :show-total="total => `共 ${totalAll} 条`"
                size="small"
                show-size-changer
                show-quick-jumper
                @change="onShowSizeChange"
                @showSizeChange="onShowSizeChange"
            />
        </div>
        <!-- 上传截图 -->
        <a-modal
            v-if="policyOperationStatus"
            title="账户截图上传"
            :visible="policyOperationStatus"
            dialog-class="information-modal-class"
            @ok="handlePolicyOperationSure"
            @cancel="handlePolicyOperationCancel"
        >
            <div>
                <a-form-model
                    class="policy-operation-form"
                    ref="policyOperationForm"
                    :model="policyOperationForm"
                    :rules="policyOperationRules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-model-item label="选择广告主公司名称" prop="advertiserId">
                        <a-select
                            v-model="policyOperationForm.advertiserId"
                            placeholder="请选择广告主名称"
                            :filter-option="handleFilterOption"
                            show-search
                            @change="handleAdverOptionChange"
                        >
                            <a-select-option
                                v-for="item in allAdverListOption"
                                :key="item.id"
                                :value="item.id"
                            >
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="选择产品名称" prop="productId">
                        <a-select
                            v-model="policyOperationForm.productId"
                            placeholder="请选择产品名称"
                            :filter-option="handleFilterOption"
                            show-search
                        >
                            <a-select-option
                                v-for="item in allProductListOption"
                                :key="item.id"
                                :value="item.id"
                            >
                                {{ item.productName }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="选择媒体">
                        <a-radio-group v-model="policyOperationForm.mediaId" button-style="solid">
                            <a-radio-button :value="1">头条</a-radio-button>
                            <a-radio-button :value="2">快手</a-radio-button>
                        </a-radio-group>
                    </a-form-model-item>
                    <a-form-model-item label="时间" prop="uploadYears">
                        <a-month-picker
                            v-model="policyOperationForm.uploadYears"
                            format="YYYY-MM"
                            placeholder="请选择时间"
                            @change="handleLaunchData"
                        />
                    </a-form-model-item>
                    <a-form-model-item label="附件上传">
                        <a-upload
                            name="file"
                            :file-list="policyOperationForm.settlementList"
                            :before-upload="beforeUpload"
                            :remove="handleFileRemove"
                        >
                            <a-button><a-icon type="upload"/>文件上传</a-button>
                        </a-upload>
                        <p class="upload-txt-rules">1、支持扩展名：.jpg、.png</p>
                        <p>2、上传图片名称账户ID，若有多个图片则账户ID-1、账户ID-2</p>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
        <!-- 下载结算单 -->
        <a-modal
            v-if="settlementModalStatus"
            title="下载结算单"
            :visible="settlementModalStatus"
            dialog-class="information-modal-class"
            @ok="handleSettlementModalSure"
            @cancel="handleSettlementModalnCancel"
        >
            <div>
                <a-form-model
                    class="policy-operation-form"
                    ref="settlementModalForm"
                    :model="settlementModalForm"
                    :rules="settlementModalRules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-model-item label="选择广告主公司名称" prop="name6">
                        <a-select v-model="settlementModalForm.name6" placeholder="请选择广告主公司名称">
                            <a-select-option :value="1">快手</a-select-option>
                            <a-select-option :value="2">头条</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="选择产品名称" prop="name7">
                        <a-select v-model="settlementModalForm.name7" placeholder="请选择产品名称">
                            <a-select-option :value="1">快手</a-select-option>
                            <a-select-option :value="2">头条</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="选择媒体">
                        <a-radio-group v-model="settlementModalForm.name9" button-style="solid">
                            <a-radio-button value="a">头条</a-radio-button>
                            <a-radio-button value="b">快手</a-radio-button>
                        </a-radio-group>
                    </a-form-model-item>
                    <a-form-model-item label="时间" prop="time">
                        <a-month-picker
                            v-model="settlementModalForm.time"
                            format="YYYY-MM"
                            placeholder="请选择时间"
                            @change="handleLaunchData"
                        />
                    </a-form-model-item>
                    <a-form-model-item label="账户数量">
                        <span>23</span>
                    </a-form-model-item>
                    <a-form-model-item label="截图已上传">
                        <span>20</span>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
        <!-- 下载利润表 -->
        <a-modal
            v-if="profitModalStatus"
            title="下载利润单"
            :visible="profitModalStatus"
            dialog-class="information-modal-class"
            @ok="handleProfitModalSure"
            @cancel="handleProfitModalnCancel"
        >
            <div>
                 <a-form-model
                    class="policy-operation-form"
                    ref="profitModalForm"
                    :model="profitModalForm"
                    :rules="profitModalRules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-model-item label="选择媒体">
                        <a-radio-group v-model="profitModalForm.name9" button-style="solid">
                            <a-radio-button value="a">头条</a-radio-button>
                            <a-radio-button value="b">快手</a-radio-button>
                        </a-radio-group>
                    </a-form-model-item>
                    <a-form-model-item label="时间" prop="launchDateRange">
                        <a-range-picker
                            v-model="profitModalForm.launchDateRange"
                            format="YYYY-MM-DD"
                            @change="handleLaunchDateRange"
                        />
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
    </div>
</template>
<script>
import {getAction, postAction} from '@/api/manage';
import moment from 'moment';
import {mapGetters} from 'vuex';
import {urlAcount} from './settlement-information-server.js';

import BMF from 'browser-md5-file';
let COS = require('cos-js-sdk-v5');
let cos = new COS({
    SecretId: 'AKIDE6IpMi8fJQRCg1iuWzFajjRs43kbbets',
    SecretKey: 'tXzuwMfplTTK3c9GFUyETilasvQfePu9'
});

export default {
    name: 'settlement-information',
    data() {
        return {
            mode2: ['month', 'month'],
            allAdverListOption: [],
            allProductListOption: [],
            controlLoading: false,
            allSaleListOption: [],
            profitModalForm: {
                name9: 'a',
                launchDateRange: []
            },
            profitModalRules: {
                launchDateRange: [{required: true, message: '请选择时间', trigger: 'change'}]
            },
            profitModalStatus: false,
            settlementModalStatus: false,
            labelCol: {span: 7},
            wrapperCol: {span: 14},
            settlementModalForm: {
                name6: undefined,
                name7: undefined,
                name8: undefined,
                name9: 'a',
                name10: 'a',
                time: ''
            },
            settlementModalRules: {
                name6: [{required: true, message: '请选择广告主公司名称', trigger: 'change'}],
                name7: [{required: true, message: '请选择产品名称', trigger: 'change'}],
                name8: [{required: true, message: '请选择项目名称', trigger: 'change'}],
                time: [{required: true, message: '请选择时间', trigger: 'change'}]
            },
            policyOperationForm: {
                advertiserId: undefined,
                productId: undefined,
                mediaId: 1,
                uploadYears: '',
                settlementList: []
            },
            policyOperationRules: {
                advertiserId: [{required: true, message: '请选择广告主公司名称', trigger: 'change'}],
                productId: [{required: true, message: '请选择产品名称', trigger: 'change'}],
                uploadYears: [{required: true, message: '请选择时间', trigger: 'change'}]
            },
            policyOperationStatus: false,
            tablePag: {
                page: 1,
                size: 10
            },
            totalAll: 100,
            dataSource: [],
            settlementColumns: [
                {
                    title: '广告主主体名称',
                    align: 'center',
                    dataIndex: 'advertiserName'
                },
                {
                    title: '产品名称',
                    align: 'center',
                    dataIndex: 'productName',
                    width: 220
                },
                {
                    title: '账户名称',
                    align: 'center',
                    dataIndex: 'accountName',
                    width: 220
                },
                {
                    title: '媒体',
                    align: 'center',
                    dataIndex: 'mediaId',
                    width: 200,
                    scopedSlots: {customRender: 'mediaId'}
                },
                {
                    title: '上传人',
                    align: 'center',
                    dataIndex: 'operateUserName',
                    width: 150
                },
                {
                    title: '上传数量',
                    dataIndex: 'imgNum',
                    align: 'center',
                    width: 150
                },
                {
                    title: '时间',
                    align: 'center',
                    dataIndex: 'uploadYears',
                    width: 150
                },
                {
                    title: '操作',
                    align: 'center',
                    dataIndex: 'actions',
                    width: 250,
                    fixed: 'right',
                    scopedSlots: {customRender: 'actions'}
                }
            ],
            configForm: {
                productName: '',
                projectName: '',
                accountName: '',
                createUserName: undefined,
                mediaId: 'no',
                time: []
            }
        };
    },
    created() {
        this.searchForm = this.$form.createForm(this);
    },
    mounted() {
        this.handleInitTable();
        this.handleGetAllSaleList();
        this.handleGetAllAdverList();
    },
    methods: {
        ...mapGetters(['userInfo']),
        moment,
        handlePanelChange2(value, mode) {
            this.configForm.time = [moment(value[0]).format('YYYY-MM'), moment(value[1]).format('YYYY-MM')];
            this.mode2 = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]];
        },
        // 获取所有的广告主列表
        handleGetAllAdverList() {
            const paramsData = {
                pageNo: 1,
                pageSize: 1000
            };
            getAction('/ctop/advertiser/list', paramsData).then(result => {
                if (result.success) {
                    this.allAdverListOption = result.result.records || [];
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleAdverOptionChange(e) {
            this.policyOperationForm.productId = undefined;
            const paramsData = {
                pageNo: 1,
                pageSize: 1000,
                advertiserId: e
            };
            getAction('/ctop/product/list', paramsData).then(result => {
                if (result.success) {
                    this.allProductListOption = result.result.records || [];
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleAddTimesChange(data) {
            this.configForm.time = data;
        },
        // 获取所有的媒体 枚举值
        handleGetAllSaleList() {
            const paramsData = {
                userId: this.userInfo().id
            };
            getAction(urlAcount + '/finance/settLementController/getAllOperationUser', paramsData).then(result => {
                if (result.code === 0) {
                    this.allSaleListOption = result.result || [];
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleFilterOption(input, option) {
            return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
         // 获取默认的列表数据
        handleInitTable() {
            this.controlLoading = true;
            const paramsData = {
                userId: this.userInfo().id,
                productName: this.configForm.productName,
                projectName: this.configForm.projectName,
                accountName: this.configForm.accountName,
                createUserName: this.configForm.createUserName,
                mediaId: this.configForm.mediaId === 'no' ? '' : this.configForm.mediaId,
                startTime: this.configForm.time[0],
                endTime: this.configForm.time[1],
                pageNo: this.tablePag.page,
                pageSize: this.tablePag.size
            };
            getAction(urlAcount + '/finance/settLementFileController/getSettlementSheetList', paramsData).then(result => {
                if (result.code === 0) {
                    let defaultList = result.result.list;
                    this.dataSource = defaultList;
                    this.totalAll = result.result.total;
                }
                else {
                    this.dataSource = [];
                    this.totalAll = 0;
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            }).finally(() => {
                this.controlLoading = false;
            });
        },
        handleLaunchDateRange(date, dateString) {
            this.profitModalForm.launchDateRange = dateString;
        },
        handleProfitModalSure() {
            this.$refs.profitModalForm.validate(valid => {
                if (valid) {
                    console.log('条件完全');
                }
                else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        handleProfitModalnCancel() {
            this.profitModalStatus = false;
        },
        handleSettlementModalSure() {
            console.log(this.settlementModalForm, '下载结算单确定按钮');
            this.$refs.settlementModalForm.validate(valid => {
                if (valid) {
                    console.log('条件完全');
                }
                else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        handleSettlementModalnCancel() {
            this.settlementModalStatus = false;
        },
        // 月份时间选择器
        handleLaunchData(date, dateString) {
            this.policyOperationForm.uploadYears = dateString;
        },
        // 查询的按钮
        handleQueryList() {
            this.tablePag = {
                page: 1,
                size: 10
            };
            this.handleInitTable();
        },
        // 重置的按钮
        handleResetList() {
            this.configForm = {
                productName: '',
                projectName: '',
                accountName: '',
                createUserName: undefined,
                mediaId: 'no',
                time: [moment().subtract(6, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
            };
            this.tablePag = {
                page: 1,
                size: 10
            };
            this.handleInitTable();
        },
        handleFileRemove(file) {
            let formData = this.policyOperationForm.settlementList;
            this.policyOperationForm.settlementList = formData.filter(item => file.uid !== item.uid);
        },
        beforeUpload(file) {
            const isZip = file.type.includes('png') || file.type.includes('jpeg');
            if (!isZip) {
                this.$message.error('请上传正确的图片');
                return;
            }
            this.cosUpload(file);
        },
        handleMd5(file) {
            let bmf = new BMF();
            let that = this;
            return new Promise(function (resolve, reject) {
                bmf.md5(file, (err, md5) => {
                    // getAction('kuaishouPopulationPackage/checkPopulationPackage', {signature: md5}).then(result => {
                    //     if (result.code === 200) {
                    //         that.personNameDisabled = false;
                    //         that.personResourceDisabled = false;
                    //         resolve();
                    //     }
                    //     else if (result.code === 201) {
                    //         that.$message.error(result.message);
                    //         that.personForm.name = result.result.orientationName;
                    //         that.personForm.resource = result.result.type;
                    //         that.personNameDisabled = true;
                    //         that.personResourceDisabled = true;
                    //         reject();
                    //     }
                    // }).catch(error => {
                    //     console.log(error, 'eeee');
                    //     reject();
                    // });
                });
            });
        },
        cosUpload(file) {
            let that = this;
            let date = new Date();
            let y = date.getFullYear();
            let MM = date.getMonth() + 1;
            MM = MM < 10 ? '0' + MM : MM;
            let d = date.getDate();
            d = d < 10 ? '0' + d : d;
            let timeElse = new Date().getTime();
            let arr = file.name.split('.');
            let str = '';
            for (let i = 0; i < arr.length; i++) {
                if (i === arr.length - 1) {
                }
                else {
                    if (i === arr.length - 2) {
                        str += arr[i];
                    }
                    else {
                        str += arr[i] + '.';
                    }
                }
            }
            cos.putObject(
                {
                    Bucket: 'media-1301855440',
                    Region: 'ap-chongqing',
                    // 存储桶所在地域，必须字段
                    Key: that.uploadType + '/' + y + '-' + MM + '-' + d + '/' + str + '-' + timeElse + '.' + arr[arr.length - 1],
                    StorageClass: 'STANDARD',
                    Body: file // 上传文件对象
                },
                function (err, data) {
                    if (err) {
                        that.$message.error('上传失败!!!' + err);
                        return;
                    }
                    that.loadingElse = false;
                    that.policyOperationForm.settlementList.push({
                        uid: file.name,
                        name: file.name,
                        status: 'done',
                        url: '//' + data.Location
                    });
                    // that.handleMd5(file);
                }
            );
        },
        // 上传确定按钮操作
        handlePolicyOperationSure() {
            const {advertiserId, productId, mediaId, uploadYears, settlementList} = this.policyOperationForm;
            const changeFile = settlementList.map(item => {
                item.fileUrl = item.url;
                item.fileName = item.name;
                return item;
            });
            this.$refs.policyOperationForm.validate(valid => {
                if (valid) {
                    if (!settlementList.length) {
                        this.$message.error('请上传图片');
                        return;
                    }
                    const paramsData = {
                        advertiserId,
                        productId,
                        mediaId,
                        uploadYears,
                        settlementList: changeFile,
                        createUserId: this.userInfo().id
                    };
                    postAction(urlAcount + '/finance/settLementFileController/insertAccountImages', paramsData).then(result => {
                        if (result.code === 0) {
                            this.$message.success(result.message);
                            this.handlePolicyOperationCancel();
                            this.handleInitTable();
                        }
                        else {
                            this.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    }).finally(() => {
                        this.confirmLoading = false;
                    });
                }
                else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 上传取消按钮操作
        handlePolicyOperationCancel() {
            this.policyOperationForm = {
                advertiserId: undefined,
                productId: undefined,
                mediaId: 1,
                uploadYears: '',
                settlementList: []
            };
            this.policyOperationStatus = false;
        },
        // 分页操作按钮
        onShowSizeChange(current, pageSize) {
            this.tablePag = {
                page: current,
                size: pageSize
            };
            this.handleInitTable();
        },
        // 删除操作
        handleSettleDel(list) {
            let that = this;
            const paramsData = {
                advertiserId: list.advertiserId,
                productId: list.productId,
                mediaId: list.mediaId,
                uploadYears: list.uploadYears,
                operateUserId: list.operateUserId
            };
            this.$confirm({
                title: '提示',
                content: '确认删除该条数据',
                onOk() {
                    getAction(urlAcount + '/finance/settLementFileController/deleteSettlementFile', paramsData).then(result => {
                        if (result.code === 0) {
                            that.handleInitTable();
                            that.$message.success('删除成功');
                        }
                        else {
                            that.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        // 下载利润单
        handleDownloadProfit() {
            console.log('下载利润单');
            this.profitModalStatus = true;
        },
        // 下载结算单
        handleDownloadSettlement() {
            console.log('下载结算单');
            this.settlementModalStatus = true;
        },
        // 上传截图
        handleUploadAccount() {
            console.log('上传截图');
            this.policyOperationStatus = true;
        }
    }
}
</script>
<style lang="less" scoped>
    @import "settlement-information";
</style>