<template>
    <div class="settlement-account-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 v-if="userSaleList.includes(userInfo().roleName)" 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.advertiserName" placeholder="请输入广告主名称" allow-clear/>
                    </a-form-item>
                    <a-form-item
                        class="grid-form-item"
                        label="产品名称："
                        :colon="false"
                    >
                        <a-input v-model="configForm.productName" placeholder="请输入产品名称" allow-clear/>
                    </a-form-item>
                    <a-form-item
                        class="grid-form-item"
                        label="项目名称："
                        :colon="false"
                    >
                        <a-input v-model="configForm.projectName" placeholder="请输入项目名称" allow-clear/>
                    </a-form-item>
                    <a-form-item
                        class="grid-form-item"
                        label="账户名称："
                        :colon="false"
                    >
                        <a-input v-model="configForm.accountName" placeholder="请输入账户名称" allow-clear/>
                    </a-form-item>
                </a-row>
                <a-row>
                    <a-form-item label="负责人：">
                        <a-select
                            v-model="configForm.createUserName"
                            style="width: 100px"
                            :filter-option="handleFilterOption"
                            show-search
                            allow-clear
                        >
                            <a-select-option
                                v-for="item in allSaleListOption"
                                :key="item.saleId"
                                :value="item.saleName"
                            >
                                {{ item.saleName }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                    <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
                            v-model="configForm.time"
                            format="YYYY-MM-DD"
                            @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: 1800}"
                :loading="controlLoading"
            >
                <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="mediaId" slot-scope="text">
                    <span>{{ text === 1 ? '头条' : '快手' }}</span>
                </span>
                <span slot="operateType" slot-scope="text">
                    <span>{{ text === 1 ? '自运营' : '代运营' }}</span>
                </span>
                <span slot="status" slot-scope="text, record">
                    <a-switch :checked="text === 0" @change="handleSwitchChang($event, record)"/>
                </span>
                <span slot="action" 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="settlement-modal-class"
            :confirmLoading="confirmLoading"
            @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="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="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
                            @change="handleProductOptionChange"
                        >
                            <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">
                        <a-select
                            v-model="policyOperationForm.projectId"
                            placeholder="请选择产品名称"
                            :filter-option="handleFilterOption"
                            show-search
                        >
                            <a-select-option
                                v-for="item in allProjectListOption"
                                :key="item.id"
                                :value="item.id"
                            >
                                {{ item.projectName }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="运营方式">
                        <a-radio-group v-model="policyOperationForm.operateType" 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="附件上传">
                        <a-upload
                            name="file"
                            :file-list="policyOperationForm.fileList"
                            :customRequest="handleCustomRequest"
                            :remove="handleRemoveUpload"
                        >
                            <a-button><a-icon type="upload"/>文件上传</a-button>
                        </a-upload>
                        <a class="file-down-title" @click="handleFileDownTitle">文件格式下载</a>
                        <p class="upload-txt-rules">支持扩展名：.xlsx、.xls</p>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
    </div>
</template>
<script>
import {mapGetters} from 'vuex';
import moment from 'moment';
import {getAction, postFileAction} from '@/api/manage';
import {urlAcount} from './settlement-account-server.js';

export default {
    name: 'settlement-account',
    data() {
        return {
            userSaleList: ['外部销售', '销售总监', '销售', '销售助理', '销售支持经理', '销售AM', '媒介', '管理员'],
            confirmLoading: false,
            allProjectListOption: [],
            allAdverListOption: [],
            allProductListOption: [],
            controlLoading: false,
            allSaleListOption: [],
            labelCol: {span: 7},
            wrapperCol: {span: 14},
            policyOperationForm: {
                advertiserId: undefined,
                productId: undefined,
                projectId: undefined,
                mediaId: 1,
                operateType: 1,
                fileList: []
            },
            policyOperationRules: {
                advertiserId: [{required: true, message: '请选择广告主公司名称', trigger: 'change'}],
                productId: [{required: true, message: '请选择产品名称', trigger: 'change'}],
                projectId: [{required: true, message: '请选择项目名称', trigger: 'change'}]
            },
            policyOperationStatus: false,
            totalAll: 0,
            dataSource: [],
            settlementColumns: [
                {
                    title: '广告主主体名称',
                    align: 'center',
                    dataIndex: 'advertiserName',
                    width: 240,
                    ellipsis: true,
                    scopedSlots: {customRender: 'advertiserName'}
                },
                {
                    title: '产品名称',
                    align: 'center',
                    dataIndex: 'productName',
                    ellipsis: true,
                    width: 200,
                    scopedSlots: {customRender: 'productName'}
                },
                {
                    title: '项目名称',
                    align: 'center',
                    dataIndex: 'projectName',
                    width: 180
                },
                {
                    title: '账户ID',
                    align: 'center',
                    dataIndex: 'accountId',
                    width: 150
                },
                {
                    title: '账户名称',
                    dataIndex: 'accountName',
                    align: 'center',
                    width: 160,
                    ellipsis: true,
                    scopedSlots: {customRender: 'accountName'}
                },
                {
                    title: '媒体',
                    dataIndex: 'mediaId',
                    align: 'center',
                    width: 150,
                    scopedSlots: {customRender: 'mediaId'}
                },
                {
                    title: '负责人',
                    dataIndex: 'createUserName',
                    width: 180,
                    align: 'center'
                },
                {
                    title: '运营方式',
                    dataIndex: 'operateType',
                    align: 'center',
                    width: 150,
                    scopedSlots: {customRender: 'operateType'}
                },
                {
                    title: '账户状态',
                    align: 'center',
                    dataIndex: 'status',
                    width: 150,
                    scopedSlots: {customRender: 'status'}
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align: 'center',
                    width: 250,
                    fixed: 'right',
                    scopedSlots: {customRender: 'action'}
                }
            ],
            configForm: {
                advertiserName: '',
                productName: '',
                projectName: '',
                accountName: '',
                creativeSale: 2,
                mediaId: 'no',
                time: [moment().subtract(7, 'days'), moment()]
            },
            tablePag: {
                page: 1,
                siz: 10
            }
        };
    },
    created() {
        this.searchForm = this.$form.createForm(this);
    },
    mounted() {
        this.handleInitTable();
        this.handleGetAllSaleList();
        this.handleGetAllAdverList(1);
    },
    methods: {
        ...mapGetters(['userInfo']),
        moment,
        handleMediaIdChange(e) {
            this.policyOperationForm.advertiserId = undefined;
            this.policyOperationForm.productId = undefined;
            this.policyOperationForm.projectId = undefined;
            this.policyOperationForm.operateType = 1;
            this.policyOperationForm.fileList = [];
            this.handleGetAllAdverList(e.target.value)
        },
        handleAddTimesChange(date, dateString) {
            this.configForm.time = date;
        },
        handleProductOptionChange(e) {
            this.policyOperationForm.projectId = undefined;
            const paramsData = {
                pageNo: 1,
                pageSize: 1000,
                mediaId: this.policyOperationForm.mediaId === 1 ? '1,3' : '2,4',
                advertiserId: this.policyOperationForm.advertiserId,
                productId: e
            };
            getAction('/ctop/project/list', paramsData).then(result => {
                if (result.success) {
                    this.allProjectListOption = result.result.records || [];
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleAdverOptionChange(e) {
            this.policyOperationForm.productId = undefined;
            this.policyOperationForm.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');
            });
        },
        handleFilterOption(input, option) {
            return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
        // 获取所有的广告主列表
        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');
            });
        },
        // 获取所有的媒体 枚举值
        handleGetAllSaleList() {
            const paramsData = {
                userId: this.userInfo().id
            };
            getAction(urlAcount + '/finance/cwjsSaleAssistantInfo/getSaleListByUserDepart', paramsData).then(result => {
                if (result.success) {
                    this.allSaleListOption = result.result || [];
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        // 获取默认的列表数据
        handleInitTable() {
            this.controlLoading = true;
            const paramsData = {
                createUserId: this.userInfo().id,
                advertiserName: this.configForm.advertiserName,
                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 && this.configForm.time[0] ? moment(this.configForm.time[0]).format('YYYY-MM-DD') : '',
                endTime: this.configForm.time && this.configForm.time[1] ? moment(this.configForm.time[1]).format('YYYY-MM-DD') : '',
                pageNo: this.tablePag.page,
                pageSize: this.tablePag.size
            };
            getAction(urlAcount + '/finance/settLementController/getSettlementList', 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;
            });
        },
        // 文件格式下载
        handleFileDownTitle() {
            const {mediaId} = this.policyOperationForm;
            if (mediaId === 1) {
                window.location.href = 'http://media-1301855440.cos.ap-chongqing.myqcloud.com/undefined/2021-08-17/%E5%A4%B4%E6%9D%A1%E8%B4%A6%E6%88%B7%E4%B8%8A%E4%BC%A0%E6%A8%A1%E6%9D%BF-1629185054420.xlsx';
            }
            else if (mediaId === 2) {
                window.location.href = 'http://media-1301855440.cos.ap-chongqing.myqcloud.com/undefined/2021-08-17/%E5%BF%AB%E6%89%8B%E8%B4%A6%E6%88%B7%E4%B8%8A%E4%BC%A0%E6%A8%A1%E6%9D%BF-1629185318124.xlsx';
            }
        },
        handleCustomRequest(info) {
            const isZip = info.file.name.indexOf('xlsx') !== -1 || info.file.name.indexOf('xls') !== -1;
            if (!isZip) {
                this.$message.error('上传模板只能是 xls、xlsx格式!');
                return;
            }
            this.policyOperationForm.fileList = [];
            this.$nextTick(() => {
                this.policyOperationForm.fileList.push(info.file);
            });
        },
        handleRemoveUpload(data) {
            let index = this.policyOperationForm.fileList.indexOf(data);
            let newUploadFile = this.policyOperationForm.fileList;
            newUploadFile.splice(index, 1);
            this.policyOperationForm.fileList = newUploadFile;
        },
        // 上传确定按钮操作
        handlePolicyOperationSure() {
            const {advertiserId, productId, projectId, mediaId, operateType, fileList} = this.policyOperationForm;
            this.$refs.policyOperationForm.validate(valid => {
                if (valid) {
                    if (!fileList.length) {
                        this.$message.error('请上传文件');
                        return;
                    }
                    let paramsData = new FormData();
                    paramsData.append('advertiserId', advertiserId);
                    paramsData.append('productId', productId);
                    paramsData.append('projectId', projectId);
                    paramsData.append('mediaId', mediaId);
                    paramsData.append('operateType', operateType);
                    paramsData.append('file', fileList[0]);
                    paramsData.append('createUserId', this.userInfo().id);
                    this.confirmLoading = true;
                    postFileAction(urlAcount + '/finance/settLementController/settlementAccountImport', paramsData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).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 {
                    return false;
                }
            });
        },
        // 上传取消按钮操作
        handlePolicyOperationCancel() {
            this.policyOperationForm = {
                advertiserId: undefined,
                productId: undefined,
                projectId: undefined,
                mediaId: 1,
                operateType: 1,
                fileList: []
            };
            this.policyOperationStatus = false;
        },
        // 删除操作
        handleSettleDel(list) {
            let that = this;
            this.$confirm({
                title: '提示',
                content: '是否确认删除该条数据',
                onOk() {
                    getAction(urlAcount + '/finance/settLementController/deleteSettlementById', {id: list.id}).then(result => {
                        if (result.code === 0) {
                            that.handleInitTable();
                            that.$message.success('删除成功');
                        }
                        else {
                            that.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        // 分页操作按钮
        onShowSizeChange(current, pageSize) {
            this.tablePag = {
                page: current,
                size: pageSize
            };
            this.handleInitTable();
        },
        // table 开关 操作按钮
        handleSwitchChang(checked, data) {
            const paramsData = {
                id: data.id,
                status: checked ? 0 : 1
            };
            getAction(urlAcount + '/finance/settLementController/updSettlementStatusById', paramsData).then(result => {
                if (result.code === 0) {
                    this.$message.success(result.message);
                    this.handleInitTable();
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        // 账户上传按钮
        handleUploadAccount() {
            this.policyOperationStatus = true;
        },
        // 查询的按钮
        handleQueryList() {
            this.tablePag = {
                page: 1,
                size: 10
            };
            this.handleInitTable();
        },
        // 重置的按钮
        handleResetList() {
            this.configForm = {
                advertiserName: '',
                productName: '',
                projectName: '',
                accountName: '',
                creativeSale: 2,
                mediaId: 'no',
                time: [moment().subtract(7, 'days'), moment()]
            };
            this.tablePag = {
                page: 1,
                size: 10
            };
            this.handleInitTable();
        }
    }
};
</script>
<style lang="less" scoped>
    @import "settlement-account";
</style>