<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 type="primary" @click="noUploadAccount = true">未上传账户</a-button>
                </span>
                <span v-if="profitBtnStatus" class="add-acount-policy-btn">
                    <a-button type="primary" @click="handleDownloadProfit">下载利润表</a-button>
                </span>
                <span v-if="settlementBtnStatus" class="add-acount-policy-btn">
                    <a-button type="primary" @click="handleDownloadSettlement">下载结算单</a-button>
                </span>
                <span v-if="accountBtnStatus" 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"
                :scroll="{ x: 1600 }"
                :loading="controlLoading"
            >
                <span slot="mediaId" slot-scope="text">
                    <span>{{ text === 1 ? '头条' : '快手' }}</span>
                </span>
                <span slot="advertiserName" slot-scope="text">
                    <a-tooltip placement="top">
                        <template slot="title">
                            <span>{{ text }}</span>
                        </template>
                        <span>{{ text }}</span>
                    </a-tooltip>
                </span>
                <span slot="productName" slot-scope="text">
                    <a-tooltip placement="top">
                        <template slot="title">
                            <span>{{ text }}</span>
                        </template>
                        <span>{{ text }}</span>
                    </a-tooltip>
                </span>
                <span slot="accountName" slot-scope="text">
                    <a-tooltip placement="top">
                        <template slot="title">
                            <span>{{ text }}</span>
                        </template>
                        <span>{{ text }}</span>
                    </a-tooltip>
                </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="选择媒体">
                        <a-radio-group
                            v-model="policyOperationForm.mediaId"
                            button-style="solid"
                            @change="handlePolicyUploadChange"
                        >
                            <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="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.advertiserId"
                                :value="item.advertiserId"
                            >
                                {{ item.advertiserName }}
                            </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="时间" 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"
                            :multiple="true"
                        >
                            <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"
            :confirmLoading="settlementConfirmLoad"
            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="选择媒体">
                        <a-radio-group
                            v-model="settlementModalForm.mediaId"
                            button-style="solid"
                            @change="handleMediaIdChange"
                        >
                            <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="advertiserId">
                        <a-select
                            v-model="settlementModalForm.advertiserId"
                            placeholder="请选择广告公司名称"
                            :filter-option="handleFilterOption"
                            show-search
                            @change="handleAdverOptionChange"
                        >
                            <a-select-option
                                v-for="item in allAdverListOption"
                                :key="item.advertiserId"
                                :value="item.advertiserId"
                            >
                                {{ item.advertiserName }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="选择产品名称" prop="productId">
                        <a-select
                            v-model="settlementModalForm.productId"
                            placeholder="请选择产品名称"
                            :filter-option="handleFilterOption"
                            show-search
                            @change="handleProductIdChange"
                        >
                            <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="选择项目名称" prop="projectId">
                        <!-- /ctop/projectMember/participateListV2 -->
                        <a-select
                            v-model="settlementModalForm.projectId"
                            placeholder="请选择项目名称"
                            :filter-option="handleFilterOption"
                            show-search
                        >
                            <a-select-option
                                v-for="item in allProjectListOption"
                                :key="item.projectId"
                                :value="item.projectId"
                            >
                                {{ item.projectName }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                   <!-- <a-form-model-item label="时间" prop="uploadYears">
                        <a-month-picker
                            v-model="settlementModalForm.uploadYears"
                            format="YYYY-MM"
                            placeholder="请选择时间"
                            @change="handleUploadYears"
                        />
                    </a-form-model-item>-->
                    <a-form-model-item label="选择时间" prop="uploadDate">
                        <a-range-picker
                            v-model="settlementModalForm.uploadDate"
                            format="YYYY-MM-DD"
                            placeholder="请选择时间"
                            @change="handleUploadYears"
                        />
                    </a-form-model-item>
                    <a-form-model-item label="账户数量">
                        <span>{{ downLoadAccountNum }}</span>
                    </a-form-model-item>
                    <a-form-model-item label="截图已上传账户数量">
                        <span>{{ downLoadImgNum }}</span>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
        <!-- 下载利润表 -->
        <a-modal
            v-if="profitModalStatus"
            title="下载利润单"
            :visible="profitModalStatus"
            :confirmLoading="profitConfirmLoad"
            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.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="launchDateRange">
                        <a-range-picker
                            v-model="profitModalForm.launchDateRange"
                            format="YYYY-MM-DD"
                            @change="handleLaunchDateRange"
                        />
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>

        <!-- 未上传账户列表 -->
        <a-modal
            v-if="noUploadAccount"
            title="未上传账户列表"
            :visible="noUploadAccount"
            dialog-class="information-modal-class"
            @cancel="handleNoUploadAccountCancel"
            :footer="null"
            width="70%"
        >
            <a-form-model
                class="policy-operation-form"
                ref="noUploadAccountForm"
                :model="noUploadAccountForm"
                :rules="noUploadAccountFormRules"
                layout="inline"
            >
                <a-form-model-item label="选择媒体" prop="mediaId">
                    <a-radio-group
                        v-model="noUploadAccountForm.mediaId"
                        button-style="solid"
                        @change="handleMediaIdChange"
                    >
                        <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="advertiserId">
                    <a-select
                        v-model="noUploadAccountForm.advertiserId"
                        placeholder="请选择广告主名称"
                        :filter-option="handleFilterOption"
                        show-search
                        @change="handleAdverOptionChange"
                        style="width: 200px"
                    >
                        <a-select-option
                            v-for="item in allAdverListOption"
                            :key="item.advertiserId"
                            :value="item.advertiserId"
                        >
                            {{ item.advertiserName }}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="选择产品名称" prop="productId">
                    <a-select
                        v-model="noUploadAccountForm.productId"
                        placeholder="请选择产品名称"
                        :filter-option="handleFilterOption"
                        show-search
                        @change="handleProductIdNoChange"
                        style="width: 200px"
                    >
                        <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="选择项目名称" prop="projectId">
                    <!-- /ctop/projectMember/participateListV2 -->
                    <a-select
                        v-model="noUploadAccountForm.projectId"
                        placeholder="请选择项目名称"
                        :filter-option="handleFilterOption"
                        show-search
                        style="width: 200px"
                    >
                        <a-select-option
                            v-for="item in allProjectListOption"
                            :key="item.projectId"
                            :value="item.projectId"
                        >
                            {{ item.projectName }}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="时间" prop="uploadYears">
                    <a-month-picker
                        v-model="noUploadAccountForm.uploadYears"
                        format="YYYY-MM"
                        placeholder="请选择时间"
                        @change="handleUploadYears"
                    />
                </a-form-model-item>
                <a-form-model-item label="" class="form-handle-btn">
                    <a-button type="default" class="reset-class" @click="handleReset" style="margin-right: 15px"
                        >重置</a-button
                    >
                    <a-button type="primary" @click="getNoUploadAccountDataSource">搜索</a-button>
                </a-form-model-item>
            </a-form-model>
            <a-form-model-item label="未上传账户" class="form-handle-btn">
                <a-table
                    ref="table"
                    size="middle"
                    bordered
                    :columns="noUploadAccountColumns"
                    :dataSource="noUploadAccountDataSource"
                    :pagination="false"
                    :loading="noAccountLoading"
                >
                </a-table>
                <a-pagination
                    class="pagin-table-class"
                    :total="totalAllNoAccount"
                    :show-total="(total) => `共 ${totalAllNoAccount} 条`"
                    size="small"
                    show-size-changer
                    show-quick-jumper
                    @change="onShowSizeChangeNoAccount"
                    @showSizeChange="onShowSizeChangeNoAccount"
                />
            </a-form-model-item>
        </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 {
            userOperateList: [
                '快手运营总监',
                '运营助理',
                '运营专员',
                '头条运营经理',
                '外部运营经理',
                '快手运营',
                '商务运营',
                '运营总经理',
                '直播运营',
                '头条运营总监',
                '快手运营助理',
                '快手运营经理',
                '头条运营',
                '头条运营助理',
            ],
            userSaleList: ['外部销售', '销售总监', '销售', '销售助理', '销售支持经理', '销售AM'],
            settlementConfirmLoad: false,
            profitConfirmLoad: false,
            profitBtnStatus: false,
            settlementBtnStatus: false,
            accountBtnStatus: false,
            downLoadAccountNum: 0,
            downLoadImgNum: 0,
            mode2: ['month', 'month'],
            allAdverListOption: [],
            allProductListOption: [],
            allProjectListOption: [],
            controlLoading: false,
            allSaleListOption: [],
            profitModalForm: {
                mediaId: 1,
                launchDateRange: [],
            },
            profitModalRules: {
                launchDateRange: [{ required: true, message: '请选择时间', trigger: 'change' }],
            },
            profitModalStatus: false,
            settlementModalStatus: false,
            noUploadAccount: false,
            labelCol: { span: 7 },
            wrapperCol: { span: 14 },
            settlementModalForm: {
                advertiserId: undefined,
                productId: undefined,
                mediaId: 1,
                uploadYears: '',
                uploadDate: '',
                projectId: undefined,
            },
            noUploadAccountForm: {
                productId: undefined,
                mediaId: 1,
                uploadYears: undefined,
                projectId: undefined,
                advertiserId: undefined,
            },
            noUploadAccountFormRules: {
                productId: [{ required: true, message: '请选择产品名称', trigger: 'change' }],
                mediaId: [{ required: true, message: '请选择媒体', trigger: 'change' }],
                projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                uploadYears: [{ required: true, message: '请选择时间', trigger: 'change' }],
                advertiserId: [{ required: true, message: '请选择广告主公司名称', trigger: 'change' }],
            },
            settlementModalRules: {
                advertiserId: [{ required: true, message: '请选择广告主公司名称', trigger: 'change' }],
                productId: [{ required: true, message: '请选择产品名称', trigger: 'change' }],
                projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                name8: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                uploadYears: [{ required: true, message: '请选择时间', trigger: 'change' }],
            },
            policyOperationForm: {
                advertiserId: undefined,
                productId: undefined,
                mediaId: 1,
                uploadYears: '',
                settlementList: [],
                projectId: undefined,
            },
            policyOperationRules: {
                advertiserId: [{ required: true, message: '请选择广告主公司名称', trigger: 'change' }],
                productId: [{ required: true, message: '请选择产品名称', trigger: 'change' }],
                uploadYears: [{ required: true, message: '请选择时间', trigger: 'change' }],
                projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
            },
            policyOperationStatus: false,
            tablePag: {
                page: 1,
                size: 10,
            },
            totalAll: 100,
            dataSource: [],
            settlementColumns: [
                {
                    title: '广告主主体名称',
                    align: 'center',
                    dataIndex: 'advertiserName',
                    width: 240,
                    ellipsis: true,
                    scopedSlots: { customRender: 'advertiserName' },
                },
                {
                    title: '产品名称',
                    align: 'center',
                    dataIndex: 'productName',
                    width: 240,
                    ellipsis: true,
                    scopedSlots: { customRender: 'productName' },
                },
                {
                    title: '账户名称',
                    align: 'center',
                    dataIndex: 'accountName',
                    width: 220,
                    ellipsis: true,
                    scopedSlots: { customRender: 'accountName' },
                },
                {
                    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: 200,
                },
                {
                    title: '操作',
                    align: 'center',
                    dataIndex: 'actions',
                    width: 250,
                    fixed: 'right',
                    scopedSlots: { customRender: 'actions' },
                },
            ],
            configForm: {
                productName: '',
                projectName: '',
                accountName: '',
                createUserName: undefined,
                mediaId: 'no',
                time: [moment().startOf('months').format('YYYY-MM'), moment().startOf('months').format('YYYY-MM')],
            },
            noUploadAccountDataSource: [],
            tablePagNoAccount: {
                page: 1,
                size: 10,
            },
            totalAllNoAccount: 0,
            noAccountLoading: false,
            noUploadAccountColumns: [
                {
                    title: '账户ID',
                    align: 'center',
                    dataIndex: 'accountId',
                    ellipsis: true,
                    scopedSlots: { customRender: 'accountId' },
                },
                {
                    title: '账户名称',
                    align: 'center',
                    dataIndex: 'accountName',
                    ellipsis: true,
                    scopedSlots: { customRender: 'accountName' },
                },
                {
                    title: '运营',
                    align: 'center',
                    dataIndex: 'operateUserName',
                    ellipsis: true,
                    scopedSlots: { customRender: 'operateUserName' },
                },
            ],
        }
    },
    created() {
        this.searchForm = this.$form.createForm(this)
    },
    mounted() {
        const userRoleName = this.userInfo().roleName
        if (userRoleName === '财务') {
            this.profitBtnStatus = true
            this.settlementBtnStatus = true
        } else if (this.userOperateList.includes(userRoleName)) {
            this.accountBtnStatus = true
        } else if (this.userSaleList.includes(userRoleName)) {
            this.settlementBtnStatus = true
        } else if (userRoleName === '管理员') {
            this.profitBtnStatus = true
            this.settlementBtnStatus = true
            this.accountBtnStatus = true
        }
        this.handleInitTable()
        this.handleGetAllSaleList()
        this.handleGetAllAdverList(1)
    },
    methods: {
        ...mapGetters(['userInfo']),
        moment,
        getNoUploadAccountDataSource() {
            const { advertiserId, productId, mediaId, uploadYears, projectId } = this.noUploadAccountForm
            this.$refs.noUploadAccountForm.validate((valid) => {
                if (valid) {
                    const paramsData = {
                        advertiserId,
                        productId,
                        mediaId,
                        projectId,
                        uploadYears: uploadYears ? moment(uploadYears).format('YYYY-MM') : '',
                        userId: this.userInfo().id,
                        pageNo: this.tablePagNoAccount.page,
                        pageSize: this.tablePagNoAccount.size,
                    }
                    this.noAccountLoading = true
                    getAction(urlAcount + '/finance/cwjsPolicyInfo/getSettlementNoPictureAccountList', paramsData)
                        .then((result) => {
                            this.noAccountLoading = true
                            if (result.code === 0) {
                                let defaultList = result.result.list
                                this.noUploadAccountDataSource = defaultList
                                this.totalAllNoAccount = result.result.total
                            } else {
                                this.noUploadAccountDataSource = []
                                this.totalAllNoAccount = 0
                                this.$message.error(result.message)
                            }
                        })
                        .catch((error) => {
                            console.log(error, 'eeee')
                        })
                        .finally(() => {
                            this.noAccountLoading = false
                        })
                }
            })
        },
        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]]
        },
        handleProductIdNoChange(e) {
            this.noUploadAccountForm.projectId = undefined
            this.handleProductOptionNoChange(e)
        },
        handleProductOptionNoChange(e) {
            this.policyOperationForm.projectId = undefined
            this.settlementModalForm.projectId = undefined
            const paramsData = {
                pageNo: 1,
                pageSize: 1000,
                productId: e,
                userId: this.userInfo().id,
            }
            getAction('/ctop/projectMember/participateListV2', paramsData)
                .then((result) => {
                    if (result.success) {
                        var data = result.result.records || []

                        if (this.noUploadAccountForm.mediaId == 1) {
                            this.allProjectListOption = data.filter((item) => {
                                return item.mediaId == '1' || item.mediaId == '3'
                            })
                        } else if (this.noUploadAccountForm.mediaId == 2) {
                            this.allProjectListOption = data.filter((item) => {
                                return item.mediaId == '2' || item.mediaId == '4'
                            })
                        }
                    } else {
                        this.$message.error(result.message)
                    }
                })
                .catch((error) => {
                    console.log(error, 'eeee')
                })
        },
        handleProductIdChange(e) {
            if (this.settlementModalForm.uploadDate) {
                this.handleGetDownLoadAllNum()
            }
            this.handleProductOptionChange(e)
        },
        handlePolicyUploadChange(e) {
            this.policyOperationForm.advertiserId = undefined
            this.allAdverListOption = []
            this.policyOperationForm.productId = undefined
            this.allProductListOption = []
            this.handleGetAllAdverList(e.target.value)
        },
        handleMediaIdChange(e) {
            this.settlementModalForm.advertiserId = undefined
            this.allAdverListOption = []
            this.settlementModalForm.productId = undefined
            this.settlementModalForm.projectId = undefined
            this.allProductListOption = []
            this.allProjectListOption = []
            this.downLoadAccountNum = 0
            this.downLoadImgNum = 0
            this.settlementModalForm.uploadYears = ''
            this.settlementModalForm.uploadDate = ''

            this.noUploadAccountForm.advertiserId = undefined
            this.noUploadAccountForm.productId = undefined
            this.noUploadAccountForm.projectId = undefined
            this.noUploadAccountForm.uploadYears = undefined 
            this.handleGetAllAdverList(e.target.value)
        },
        handleGetDownLoadAllNum() {
            const { advertiserId, productId, mediaId, uploadYears, projectId,uploadDate } = this.settlementModalForm
            const paramsData = {
                advertiserId,
                productId,
                mediaId,
                projectId,
              /* uploadYears: uploadYears ? moment(uploadYears).format('YYYY-MM') : '',*/
                startTime: moment(uploadDate[0]).format('YYYY-MM-DD'),
                endTime: moment(uploadDate[1]).format('YYYY-MM-DD'),
            }
            postAction(urlAcount + '/finance/settLementFileController/getAccountNumAndImgNum', paramsData)
                .then((result) => {
                    if (result.success) {
                        this.downLoadAccountNum = result.result.accountNum
                        this.downLoadImgNum = result.result.imageNum
                    }
                })
                .catch((error) => {
                    console.log(error, 'eeee')
                })
        },
        // 获取所有的广告主列表
        handleGetAllAdverList(type) {
            const paramsData = {
                userId: this.userInfo().id,
                mediaId: type,
                pageNo: 1,
                pageSize: 1000,
            }
            getAction('/ctop/projectMember/participateListV3', paramsData)
                .then((result) => {
                    if (result.success) {
                        this.allAdverListOption = result.result || []
                    } else {
                        this.$message.error(result.message)
                    }
                })
                .catch((error) => {
                    console.log(error, 'eeee')
                })
        },
        handleAdverOptionChange(e) {
            this.policyOperationForm.productId = undefined
            this.settlementModalForm.productId = undefined
            this.settlementModalForm.projectId = undefined

            this.noUploadAccountForm.productId = undefined
            this.noUploadAccountForm.projectId = 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')
                })
        },
        handleProductOptionChange(e) {
            this.policyOperationForm.projectId = undefined
            this.settlementModalForm.projectId = undefined
            const paramsData = {
                pageNo: 1,
                pageSize: 1000,
                productId: e,
                userId: this.userInfo().id,
            }
            getAction('/ctop/projectMember/participateListV2', paramsData)
                .then((result) => {
                    if (result.success) {
                        var data = result.result.records || []

                        if (this.settlementModalForm.mediaId == 1) {
                            this.allProjectListOption = data.filter((item) => {
                                return item.mediaId == '1' || item.mediaId == '3'
                            })
                        } else if (this.settlementModalForm.mediaId == 2) {
                            this.allProjectListOption = data.filter((item) => {
                                return item.mediaId == '2' || item.mediaId == '4'
                            })
                        }
                    } 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 = {
                createUserId: 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[0] ? dateString : []
        },
        handleProfitModalSure() {
            this.$refs.profitModalForm.validate((valid) => {
                if (valid) {
                    this.profitConfirmLoad = true
                    const { mediaId, launchDateRange } = this.profitModalForm
                    const paramsData = {
                        mediaId,
                        startTime: launchDateRange[0],
                        endTime: launchDateRange[1],
                    }
                    const urlData =
                        mediaId === 1
                            ? '/finance/exportReportController/porfitReportBytedance'
                            : '/finance/exportReportController/porfitReportKuaiShou'
                    getAction(urlAcount + urlData, paramsData)
                        .then((result) => {
                            if (result.code === -1) {
                                this.$message.error(result.message)
                            } else {
                                this.profitModalStatus = false
                                this.handleProfitModalnCancel()
                                this.$message.success('正在下载利润表，请稍后...', 4)
                                window.location.href = `${urlAcount}${urlData}?startTime=${paramsData.startTime}&endTime=${paramsData.endTime}`
                                // this.handleDownUpdate(url);
                            }
                        })
                        .catch((error) => {
                            console.log(error, 'eeee')
                        })
                        .finally(() => {
                            this.profitConfirmLoad = false
                        })
                } else {
                    return false
                }
            })
        },
        // TODO 文件流下载方法，暂时不用
        handleDownUpdate(url) {
            let xhr = new XMLHttpRequest()
            xhr.open('GET', url, true) // 也可用POST方式
            xhr.responseType = 'blob'
            xhr.onload = function () {
                if (this.status === 200) {
                    var blob = this.response
                    if (navigator.msSaveBlob == null) {
                        var a = document.createElement('a')
                        var headerName = xhr.getResponseHeader('Content-disposition')
                        var fileName = decodeURIComponent(headerName).substring(20)
                        a.download = fileName
                        a.href = URL.createObjectURL(blob)
                        document.body.appendChild(a)
                        // $("body").append(a);    // 修复firefox中无法触发click
                        a.click()
                        URL.revokeObjectURL(a.href)
                        a.remove()
                    } else {
                        navigator.msSaveBlob(blob, fileName)
                    }
                }
                disload()
            }
            xhr.send()
        },
        handleProfitModalnCancel() {
            this.profitModalForm = {
                mediaId: 1,
                launchDateRange: [],
            }
            this.profitModalStatus = false
        },
        handleSettlementModalSure() {
            this.$refs.settlementModalForm.validate((valid) => {
                if (valid) {
                    this.settlementConfirmLoad = true
                    const { advertiserId, productId, projectId, mediaId ,uploadDate} = this.settlementModalForm
                    const paramsData = {
                        advertiserId,
                        productId,
                        mediaId,
                        projectId,
                       /* uploadYears: moment(uploadYears).format('YYYY-MM'),*/
                        userId: this.userInfo().id,
                        startTime: moment(uploadDate[0]).format('YYYY-MM-DD'),
                        endTime:  moment(uploadDate[1]).format('YYYY-MM-DD'),

                    }
                    const urlData =
                        mediaId === 1
                            ? '/finance/exportReportController/settlementReportBytedance'
                            : '/finance/exportReportController/settlementReportKuaiShou'
                    getAction(urlAcount + urlData, paramsData)
                        .then((result) => {
                            if (result.code === -1) {
                                this.$message.error(result.message)
                            } else {
                                this.handleSettlementModalnCancel()
                                this.$message.success('正在下载结算单，请稍后...', 4)
                                window.location.href = `${urlAcount}${urlData}?advertiserId=${advertiserId}&projectId=${projectId}&productId=${productId}&mediaId=${mediaId}&startTime=${paramsData.startTime}&endTime=${paramsData.endTime}
                                &userId=${this.userInfo().id}`
                            }
                        })
                        .catch((error) => {
                            console.log(error, 'eeee')
                        })
                        .finally(() => {
                            this.settlementConfirmLoad = false
                        })
                } else {
                    return false
                }
            })
        },
        handleNoUploadAccountCancel() {
            this.noUploadAccountForm = {
                productId: undefined,
                mediaId: 1,
                uploadYears: undefined,
                projectId: undefined,
                advertiserId: undefined,
            }
            this.noUploadAccountDataSource = []
            this.totalAllNoAccount = 0
            this.tablePagNoAccount = {
                page: 1,
                size: 10,
            }
            this.noUploadAccount = false
        },
        handleSettlementModalnCancel() {
            this.settlementModalForm = {
                advertiserId: undefined,
                productId: undefined,
                projectId: undefined,
                mediaId: 1,
                uploadYears: '',
            }
            this.allProductListOption = []
            this.downLoadAccountNum = 0
            this.downLoadImgNum = 0
            this.settlementModalStatus = false
        },
        // 月份时间选择器
        handleLaunchData(date, dateString) {
            this.policyOperationForm.uploadYears = dateString
        },
        handleUploadYears(date, dateString) {
            this.settlementModalForm.uploadYears = dateString
            if (this.settlementModalForm.productId) {
                this.handleGetDownLoadAllNum()
            }
            if (!dateString) {
                this.downLoadAccountNum = 0
                this.downLoadImgNum = 0
            }
        },
        // 查询的按钮
        handleQueryList() {
            this.tablePag = {
                page: 1,
                size: 10,
            }
            this.handleInitTable()
        },
        // 重置的按钮
        handleReset() {
            this.noUploadAccountForm = {
                productId: undefined,
                mediaId: 1,
                uploadYears: undefined,
                projectId: undefined,
                advertiserId: undefined,
            }
            this.tablePagNoAccount = {
                page: 1,
                size: 10,
            }
            this.totalAllNoAccount = 0
            this.noUploadAccountDataSource = []
            // this.getNoUploadAccountDataSource()
        },
        // 重置的按钮
        handleResetList() {
            this.configForm = {
                productName: '',
                projectName: '',
                accountName: '',
                createUserName: undefined,
                mediaId: 'no',
                time: [moment().startOf('months').format('YYYY-MM'), moment().startOf('months').format('YYYY-MM')],
            }
            this.tablePag = {
                page: 1,
                size: 10,
            }
            this.handleInitTable()
        },
        handleFileRemove(file) {
            let formData = this.policyOperationForm.settlementList
            this.policyOperationForm.settlementList = formData.filter((item) => file.id !== item.id)
        },
        beforeUpload(file) {
            let reg = /[\u4E00-\u9FA5]|[A-Za-z]/g
            const lastPosition = file.name.lastIndexOf('.')
            const name = file.name.slice(0, lastPosition)
            let finallyResult = name.match(reg)
            const isZip = file.type.includes('png') || file.type.includes('jpeg')
            if (!isZip) {
                this.$message.error('请上传正确的图片')
                return
            }
            if (finallyResult && finallyResult.length) {
                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({
                        id: new Date().getTime(),
                        uid: file.name,
                        name: file.name,
                        status: 'done',
                        url: 'https://' + 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,
                projectId: undefined,
                mediaId: 1,
                uploadYears: '',
                settlementList: [],
            }
            this.policyOperationStatus = false
        },
        // 分页操作按钮
        onShowSizeChange(current, pageSize) {
            this.tablePag = {
                page: current,
                size: pageSize,
            }
            this.handleInitTable()
        },
        onShowSizeChangeNoAccount(current, pageSize) {
            this.tablePagNoAccount = {
                page: current,
                size: pageSize,
            }
            this.getNoUploadAccountDataSource()
        },
        // 删除操作
        handleSettleDel(list) {
            let that = this
            const paramsData = {
                advertiserId: list.advertiserId,
                productId: list.productId,
                mediaId: list.mediaId,
                uploadYears: list.uploadYears,
                createUserId: list.operateUserId,
                accountId: list.accountId,
            }
            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() {
            this.profitModalStatus = true
        },
        // 下载结算单
        handleDownloadSettlement() {
            this.settlementModalStatus = true
        },
        // 上传截图
        handleUploadAccount() {
            this.policyOperationStatus = true
        },
    },
}
</script>
<style lang="less" scoped>
@import 'settlement-information';
</style>
