<template>
    <div class="auto-copylibrary-content">
        <div class="control-con-header">
            <a-form
                class="grid-form"
                layout="inline"
                hide-required-mark
            >
                <a-row>
                    <a-form-item
                        class="grid-form-item"
                        label="账户："
                        :colon="false"
                    >
                        <acount-search
                            class="acount-search-class"
                            :appId.sync="configForm.acountId"
                            :multiple="false"
                            request="2,4"
                        >
                        </acount-search>
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-select v-model="configForm.searchStatus" style="width: 100px">
                            <a-select-option :value="2">不限</a-select-option>
                            <a-select-option :value="0">可投放</a-select-option>
                            <a-select-option :value="1">已下架</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-row>
                <a-row class="grid-form-options">
                    <a-form-item
                        class="grid-form-item"
                        label="关键词："
                        :colon="false"
                    >
                        <a-input v-model="configForm.num" placeholder="请输入关键词"/>
                    </a-form-item>
                    <a-form-item
                        class="grid-form-item"
                        label="选择时间："
                        :colon="false"
                    >
                        <a-range-picker
                            v-model="configForm.launchDateRange"
                            format="YYYY-MM-DD"
                            @change="handleLaunchData"
                        />
                    </a-form-item>
                    <a-form-item class="form-handle-btn">
                        <a-button type="primary" class="reset-class" icon="reload" @click="handleResetList">重置</a-button>
                        <a-button type="primary" class="reset-class" icon="search" @click="handleQueryList">查询</a-button>
                        <a-button type="primary" @click="handleAddAccountConfig">新增文案</a-button>
                    </a-form-item>
                </a-row>
            </a-form>
        </div>
        <div class="control-con-table">
            <a-table
                ref="table"
                size="middle"
                bordered
                :columns="currencyColumns"
                :dataSource="currencyData"
                :pagination="false"
                :loading="controlLoading"
            >
                <span slot="action" slot-scope="text, record">
                    <a @click="handleEditCopyLibrary(record)" :disabled="record.status !== 0">编辑</a>
                    <a-divider type="vertical"/>
                    <a @click="handleOffSheif(record)" :disabled="record.status !== 0">下架</a>
                </span>
                <span slot="reason" slot-scope="text, record">
                    <a @click="handleRejectionReason(record)">被拒创意详情</a>
                </span>
            </a-table>
            <a-pagination
                class="pagin-table-class"
                v-model="currencyPag.page"
                :page-size="currencyPag.size"
                :total="currencyTotalAll"
                :show-total="total => `共 ${currencyTotalAll} 条`"
                size="small"
                show-size-changer
                show-quick-jumper
                @change="handleCurrentPage"
                @showSizeChange="handleCurrentPage"
            />
        </div>
        <a-modal
            v-if="causeVisible"
            :title="copywritingType === 'add' ? '新建文案' : '编辑文案'"
            :visible="causeVisible"
            :confirmLoading="confirmLoading"
            dialog-class="auto-copy-library-modal"
            @ok="handleCauseSure"
            @cancel="handleCauseCancel"
        >
            <div>
                <div class="acount-title">
                    <div class="acount-title-left">广告账户</div>
                    <div class="acount-title-right">
                        <div class="only-title-mater">
                            <acount-search :appId.sync="advertisingAccount" request="2,4"></acount-search>
                        </div>
                    </div>
                </div>
                <div v-if="copywritingType === 'add'" class="acount-title">
                    <div class="acount-title-left">批量上传</div>
                    <div class="acount-title-right">
                        <div class="only-title-mater">
                            <a-upload
                                name="file"
                                :file-list="fileList"
                                :customRequest="handleCustomRequest"
                                :remove="handleRemoveUpload"
                            >
                                <a-button><a-icon type="upload"/>文件上传</a-button>
                            </a-upload>
                            <p class="upload-prompt-information special-number-line">1、 文件格式为xls或xlsx，每行一条文案，每条文案不多于30字</p>
                            <p class="upload-prompt-information">2、 请将文案写在Excel表的第一列，否则将无法上传</p>
                        </div>
                    </div>
                </div>
                <div v-if="copywritingType === 'edit'" class="acount-title">
                    <div class="acount-title-left">文案</div>
                    <div class="acount-title-right">
                        <div class="only-title-mater">
                            <a-input v-model="editTextShow.copy_writer" disabled/>
                        </div>
                    </div>
                </div>
            </div>
        </a-modal>
        <a-modal
            v-if="rejectIdeasVisible"
            title="被拒创意详情"
            dialog-class="reject-ideas-modal"
            :visible="rejectIdeasVisible"
            :footer="null"
            @cancel="handleRejectIdeasCancel"
        >
            <div>
                <a-table
                    ref="table"
                    size="middle"
                    bordered
                    :columns="rejectIdeasColumns"
                    :dataSource="rejectIdeasData"
                    :pagination="false"
                >
                </a-table>
                <a-pagination
                    class="pagin-table-class"
                    v-model="rejectIdeasPag.page"
                    size="small"
                    :page-size="rejectIdeasPag.size"
                    :total="rejectIdeasTotalAll"
                    :show-total="total => `共 ${rejectIdeasTotalAll} 条`"
                    @change="handleRejectIdeasPage"
                    @showSizeChange="handleRejectIdeasPage"
                />
            </div>
        </a-modal>
    </div>
</template>
<script>

import AcountSearch from '@/views/modules/Statistics/components/Treeselect.vue';
import {getAction, postAction} from '@/api/manage';
import {mapGetters} from 'vuex';

export default {
    name: 'autoCopyLibrary',
    components: {
        AcountSearch
    },
    data() {
        return {
            editShowAccountList: [],
            confirmLoading: false,
            controlLoading: false,
            refusedReasonList: {},
            rejectIdeasVisible: false,
            rejectIdeasPag: {
                page: 1,
                size: 10
            },
            rejectIdeasTotalAll: 0,
            rejectIdeasColumns: [
                {
                    title: '账户名称',
                    align: 'center',
                    dataIndex: 'accountName'
                },
                {
                    title: '广告组ID',
                    align: 'center',
                    dataIndex: 'unitId'
                },
                {
                    title: '创意名称',
                    align: 'center',
                    dataIndex: 'creativeName'
                },
                {
                    title: '被拒原因',
                    align: 'center',
                    dataIndex: 'reviewDetail'
                }
            ],
            rejectIdeasData: [],
            editTextShow: {},
            fileList: [],
            advertisingAccount: [],
            currencyData: [],
            currencyTotalAll: 0,
            currencyPag: {
                page: 1,
                size: 20
            },
            currencyColumns: [
                {
                    title: '文案',
                    align: 'center',
                    dataIndex: 'copy_writer'
                },
                {
                    title: '相关创意数',
                    align: 'center',
                    dataIndex: 'relatedSize'
                },
                {
                    title: '被拒创意数',
                    align: 'center',
                    dataIndex: 'refusedSize'
                },
                {
                    title: '状态',
                    align: 'center',
                    dataIndex: 'status',
                    customRender(d) {
                        return d === 0 ? '可投放' : '已下架'
                    }
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align: 'center',
                    scopedSlots: {customRender: 'action'}
                },
                {
                    title: '更多',
                    dataIndex: 'reason',
                    align: 'center',
                    scopedSlots: {customRender: 'reason'}
                }
            ],
            causeVisible: false,
            copywritingType: 'add',
            configForm: {
                acountId: '',
                num: '',
                adConvertId: undefined,
                launchDateRange: [],
                searchStatus: 2
            }
        };
    },
    mounted() {
        this.handleInitTable();
    },
    methods: {
        ...mapGetters(['userInfo']),
        handleInitTable() {
            this.controlLoading = true;
            const paramsData = {
                accountIds: this.configForm.acountId,
                status: this.configForm.searchStatus,
                keywords: this.configForm.num,
                startDate: this.configForm.launchDateRange[0] || '',
                endDate: this.configForm.launchDateRange[1] || '',
                pageNumber: this.currencyPag.page,
                pageSize: this.currencyPag.size
            };
            getAction('/document/library/getDocumentList', paramsData).then(result => {
                if (result.code === 0) {
                    this.currencyData = result.result.list;
                    this.currencyTotalAll = result.result.total;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            }).finally(() => {
                this.controlLoading = false;
            });
        },
        handleRejectIdeasCancel() {
            this.refusedReasonList = {};
            this.rejectIdeasVisible = false;
        },
        handleRejectIdeasPage(current, pageSize) {
            this.currencyPag = {
                page: current,
                size: pageSize
            };
            this.handleGetRefusedList(this.refusedReasonList);
        },
        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.fileList = [];
            this.$nextTick(() => {
                this.fileList.push(info.file);
            });
        },
        handleRemoveUpload(data) {
            let index = this.fileList.indexOf(data);
            let newUploadFile = this.fileList;
            newUploadFile.splice(index, 1);
            this.fileList = newUploadFile;
        },
        handleCauseSure() {
            if (!this.advertisingAccount.length) {
                this.$message.error('请选择账户');
                return;
            }
            let paramsData = new FormData();
            paramsData.append('accountIds', [...this.advertisingAccount, ...this.editShowAccountList]);
            if (this.copywritingType === 'add') {
                if (!this.fileList.length) {
                    this.$message.error('请上传文件');
                    return;
                }
                this.confirmLoading = true;
                paramsData.append('file', this.fileList[0]);
                this.handleSubmitOperation(paramsData, '/document/library/createdocument');
            }
            else if (this.copywritingType === 'edit') {
                this.confirmLoading = true;
                paramsData.append('copyWriterId', this.editTextShow.copyWriterId);
                paramsData.append('copyWriter', this.editTextShow.copy_writer);
                this.handleSubmitOperation(paramsData, '/document/library/updateDocument');
            }
        },
        handleSubmitOperation(data, url) {
            postAction(url, data).then(result => {
                if (result.code === 200) {
                    this.$message.success(result.message);
                    this.advertisingAccount = [];
                    this.fileList = [];
                    this.editShowAccountList = [];
                    this.causeVisible = false;
                    this.currencyPag = {
                        page: 1,
                        size: 10
                    };
                    this.handleInitTable();
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            }).finally(() => {
                this.confirmLoading = false;
            });
        },
        handleCauseCancel() {
            this.advertisingAccount = [];
            this.fileList = [];
            this.editShowAccountList = [];
            this.causeVisible = false;
        },
        handleEditCopyLibrary(list) {
            const defaultData = list;
            this.editTextShow = defaultData;
            this.handleGetAcoountId(list);
            this.copywritingType = 'edit';
            this.$nextTick(() => {
                this.causeVisible = true;
            });
        },
        handleGetAcoountId(list) {
            getAction('/document/library/getAcoountId', {copyWriterId: list.copyWriterId}).then(result => {
                if (result.code === 0) {
                    const defaultData = result.result.map(item => Number(item));
                    this.editShowAccountList = defaultData;
                    this.advertisingAccount = defaultData;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleOffSheif(list) {
            let that = this;
            this.$confirm({
                title: '提示',
                content: '是否确认下架该条文案',
                onOk() {
                    const params = {
                        copyWriterId: list.copyWriterId,
                        status: 1
                    };
                    getAction('/document/library/updateStatus', params).then(result => {
                        if (result.code === 200) {
                            that.$message.success(result.message);
                            that.handleInitTable();
                        }
                        else {
                            that.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        handleCurrentPage(current, pageSize) {
            this.currencyPag = {
                page: current = pageSize !== this.currencyPag.size ? 1 : current,
                size: pageSize
            };
            this.handleInitTable();
        },
        // 被拒理由的操作
        handleRejectionReason(list) {
            this.refusedReasonList = list;
            this.handleGetRefusedList(list);
            this.rejectIdeasVisible = true;
        },
        handleGetRefusedList(list) {
            const paramsData = {
                copyWriterId: list.copyWriterId,
                pageNumber: this.rejectIdeasPag.page,
                pageSize: this.rejectIdeasPag.size
            };
            getAction('/document/library/getRefusedList', paramsData).then(result => {
                if (result.code === 0) {
                    this.rejectIdeasData = result.result.list;
                    this.rejectIdeasTotalAll = result.result.total;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleAddAccountConfig() {
            this.causeVisible = true;
            this.copywritingType = 'add';
        },
        handleResetList() {
            this.configForm = {
                acountId: '',
                num: '',
                adConvertId: undefined,
                launchDateRange: [],
                searchStatus: 2
            };
            this.currencyPag = {
                page: 1,
                size: 20
            };
            this.handleInitTable();
        },
        handleQueryList() {
            this.handleInitTable();
        },
        handleLaunchData(date, dateString) {
            this.configForm.launchDateRange = dateString;
        }
    }
}
</script>
<style lang="less" scoped>
    @import "auto-copy-library";
</style>