<template>
    <div class="copy-library-content">
        <div class="control-con-header">
            <a-form
                class="grid-form"
                layout="inline"
                :form="form"
                hide-required-mark
            >
                <a-row>
                    <a-form-item
                        v-if="controlTypeModel === '1'"
                        class="grid-form-item"
                        label="账户："
                        :colon="false"
                    >
                        <acount-search
                            class="acount-search-class"
                            :appId.sync="configForm.acountId"
                            :multiple="false"
                            request="1,3"
                        >
                        </acount-search>
                    </a-form-item>
                    <a-form-model-item v-if="controlTypeModel === '2'" label="项目：">
                        <a-select
                            class="common-input-long"
                            show-search
                            v-model="configForm.adConvertId"
                            :filter-option="filterOption"
                            allowClear
                            placeholder="请选择项目"
                        >
                            <a-select-option
                                v-for="(item, index) in optimizationOption"
                                :key="index"
                                :value="item.projectId"
                            >
                                {{ item.projectName }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-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"
                            :disabled-date="disabledDate"
                            @change="handleLaunchData"
                        />
                    </a-form-item>
                    <a-form-item v-show="configForm.acountId || configForm.adConvertId" 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-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-button type="primary" class="upload-person" @click="handleAddAccountConfig">新增文案</a-button>
            <a-tabs v-model="controlTypeModel" @change="handleTabsChange">
                <a-tab-pane key="1" tab="通用">
                    <a-table
                        ref="table"
                        size="middle"
                        bordered
                        :columns="currencyColumns"
                        :dataSource="currencyData"
                        :pagination="false"
                        :scroll="{x: 1500}"
                    >
                        <span slot="currencyAction" slot-scope="text, record">
                            <a :disabled="record.status === '已删除'" @click="handleCurrencyEdit(record)">编辑</a>
                            <a-divider type="vertical"/>
                            <a :disabled="record.status === '已删除'" @click="handleCurrencyDelete(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"
                    />
                </a-tab-pane>
                <a-tab-pane key="2" tab="指定">
                    <a-table
                        ref="table"
                        size="middle"
                        bordered
                        :columns="appointColumns"
                        :dataSource="appointData"
                        :pagination="false"
                        :scroll="{x: 1500}"
                    >
                        <span slot="appointAction" slot-scope="text, record">
                            <a :disabled="record.status === '已删除'" @click="handleCurrencyEdit(record)">编辑</a>
                            <a-divider type="vertical"/>
                            <a :disabled="record.status === '已删除'" @click="handleAppointDelete(record)">删除</a>
                        </span>
                    </a-table>
                    <a-pagination
                        class="pagin-table-class"
                        v-model="appointPag.page"
                        :page-size="appointPag.size"
                        :total="appointTotalAll"
                        :show-total="total => `共 ${appointTotalAll} 条`"
                        size="small"
                        show-size-changer
                        show-quick-jumper
                        @change="handleAppointPage"
                        @showSizeChange="handleAppointPage"
                    />
                </a-tab-pane>
            </a-tabs>
        </div>
        <a-modal
            v-if="causeVisible"
            :title="copywritingType === 'add' ? '新建文案' : '编辑文案'"
            dialog-class="copywrit-modal"
            :visible="causeVisible"
            @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">
                            <a-radio-group v-model="copywrittypeName" button-style="solid" @change="handleFormLayoutChange">
                                <a-radio-button value="horizontal" :disabled="copywritingEditList.controlTypeModel === '2'">通用</a-radio-button>
                                <a-radio-button value="vertical" :disabled="copywritingEditList.controlTypeModel === '1'">指定素材</a-radio-button>
                            </a-radio-group>
                        </div>
                    </div>
                </div>
                <div v-if="copywrittypeName === 'horizontal'" 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="1,3" :disabled="copywritingType === 'edit'"></acount-search>
                        </div>
                    </div>
                </div>
                <div v-if="copywrittypeName === 'horizontal' && 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>
                        </div>
                    </div>
                </div>
                <div v-if="copywrittypeName === 'vertical'" class="acount-title">
                    <div class="acount-title-left">选择素材</div>
                    <div class="acount-title-right">
                        <div class="only-title-mater">
                            <div v-if="copywritingType === 'add'"><a @click="handleSelectMaterial">选择素材</a></div>
                            <div class="title-mater-list">
                                <p
                                    class="mater-list-name"
                                    v-for="item in modalSelectMaterial"
                                    :key="item.id"
                                >
                                    <span class="mater-list-show">{{ item.materialName }}</span>
                                    <span class="mater-list-show">123</span>
                                    <span v-if="copywritingType === 'add'" class="mater-list-icon" @click="handleDelAlone(item)"><a-icon type="close"/></span>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="copywrittypeName === 'vertical' && copywritingType === 'add'" class="acount-title push-plate">
                    <div class="acount-title-left">创意标题</div>
                    <div class="acount-title-right">
                        <a-button type="primary" @click="handleAddOrigin"><a-icon type="plus" />创意标题</a-button>
                        <span style="margin-left: 20px;">已填：{{ titleFiledResult.length || 0 }}</span>
                    </div>
                </div>
                <div v-if="copywrittypeName === 'vertical' && copywritingType === 'add'" class="acount-title">
                    <div class="acount-title-left"></div>
                    <div class="acount-title-right">
                        <a-form :form="examinForm">
                            <a-form-item
                                v-for="item in defaultFormList"
                                :key="item.id"
                                class="examin-form-model"
                                :label-col="labelCol"
                                :wrapper-col="wrapperCol"
                                label=""
                            >
                                <a-input
                                    v-decorator="[
                                        item.name,
                                        {rules: [
                                            {validator: validatePass, trigger: 'blur'}
                                        ]}
                                    ]"
                                    class="examin-form-input"
                                    :id="item.name"
                                    placeholder="请输入"
                                    @change="handleFormInputChang($event, item.name, item.id)"
                                />
                                <span class="examin-form-num">{{ item.lenSize }}/30</span>
                                <a-icon class="examin-form-icon" type="delete" @click="handleDelOrigin(item)"/>
                                <div class="ad-name-tags-class">
                                    <div v-if="item.tabStatus === 'alone'" class="name-tags-left">
                                        <a-tag
                                            v-for="val in item.updateTagsList"
                                            :key="val.id"
                                            color="#1890ff"
                                            @click="handleGetChangeAll(val.name, item.name, item.id)"
                                        >
                                            + {{ val.name }}
                                        </a-tag>
                                    </div>
                                    <div v-if="item.tabStatus === 'all'" class="name-tags-left">
                                        <a-tag
                                            v-for="val in item.defaultTagsList"
                                            :key="val.id"
                                            color="#1890ff"
                                            @click="handleGetChangeAll(val.name, item.name, item.id)"
                                        >
                                            + {{ val.name }}
                                        </a-tag>
                                    </div>
                                    <div v-if="item.tabStatus === 'alone'">
                                        <a @click="handleMoreTagsShow(item.id, 'more')">更多</a>
                                    </div>
                                    <div v-if="item.tabStatus === 'all'">
                                        <a @click="handleMoreTagsShow(item.id, 'little')">收起</a>
                                    </div>
                                </div>
                            </a-form-item>
                        </a-form>
                    </div>
                </div>
                <div v-if="copywritingType === 'edit'" class="acount-title push-plate">
                    <div class="acount-title-left">创意标题</div>
                    <div class="acount-title-right">
                        <a-form :form="examinForm">
                            <a-form-item
                                v-for="item in defaultFormList"
                                :key="item.id"
                                class="examin-form-model"
                                :label-col="labelCol"
                                :wrapper-col="wrapperCol"
                                label=""
                            >
                                <a-input
                                    v-decorator="[
                                        item.name,
                                        {rules: [
                                            {validator: validatePass, trigger: 'blur'}
                                        ]}
                                    ]"
                                    class="examin-form-input"
                                    :id="item.name"
                                    placeholder="请输入"
                                    @change="handleFormInputChang($event, item.name, item.id)"
                                />
                                <span class="examin-form-num">{{ item.lenSize }}/30</span>
                                <div class="ad-name-tags-class">
                                    <div v-if="item.tabStatus === 'alone'" class="name-tags-left">
                                        <a-tag
                                            v-for="val in item.updateTagsList"
                                            :key="val.id"
                                            color="#1890ff"
                                            @click="handleGetChangeAll(val.name, item.name, item.id)"
                                        >
                                            + {{ val.name }}
                                        </a-tag>
                                    </div>
                                    <div v-if="item.tabStatus === 'all'" class="name-tags-left">
                                        <a-tag
                                            v-for="val in item.defaultTagsList"
                                            :key="val.id"
                                            color="#1890ff"
                                            @click="handleGetChangeAll(val.name, item.name, item.id)"
                                        >
                                            + {{ val.name }}
                                        </a-tag>
                                    </div>
                                    <div v-if="item.tabStatus === 'alone'">
                                        <a @click="handleMoreTagsShow(item.id, 'more')">更多</a>
                                    </div>
                                    <div v-if="item.tabStatus === 'all'">
                                        <a @click="handleMoreTagsShow(item.id, 'little')">收起</a>
                                    </div>
                                </div>
                            </a-form-item>
                        </a-form>
                    </div>
                </div>
            </div>
        </a-modal>
        <a-modal
            v-if="visibleMatemal"
            title="选择素材"
            :visible="visibleMatemal"
            dialog-class="select-matermal-modal"
            @ok="handleOkShow"
            @cancel="handleCancelAll"
        >
            <div class="mater-viedo-content">
                <div class="viedo-header-class">
                    <div></div>
                    <div> 
                        当前选择数量 {{ viedoCheckValue.length }}/{{ materTotalAll }}
                        <a-button type="primary" class="refush-btn-mat" @click="handleRefreshMaster">刷新素材</a-button>
                    </div>
                </div>
                <a-row class="viedo-serach-class" :gutter="24">
                    <a-col :span="9">
                        <a-form-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-select
                                class="common-input-long"
                                show-search
                                v-model="projectModelValue"
                                placeholder="请选择"
                                :filter-option="filterOption"
                                allowClear
                            >
                                <a-select-option
                                    v-for="(item, index) in optimizationOption"
                                    :key="index"
                                    :value="item.projectId"
                                >
                                    {{ item.projectName }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="9">
                        <a-form-item label="日期选择" :labelCol="modalCol" :wrapperCol="modalWrapper">
                            <a-range-picker
                                v-model="masterTimes"
                                format="YYYY-MM-DD"
                                @change="handleSelectTimeChange"
                            />
                        </a-form-item>
                    </a-col>
                    <a-col :span="4">
                        <a-button style="position: relative;top: 4px;" @click="handleAllChecked">全选</a-button>
                        <a-button type="primary" style="position: relative;top: 4px;margin-left:5px" @click="handleSearchMaster">搜索</a-button>
                    </a-col>
                </a-row>
                <div class="viedo-content-class">
                    <a-checkbox-group class="viedo-content-group" v-model="viedoCheckValue">
                        <li class="content-modal-li" v-for="(item, index) in viedoDefaultList" :key="index">
                            <a-checkbox
                                class="viedo-content-checkbox"
                                :value="item.id"
                            >
                            </a-checkbox>
                            <img :src="item.coverUrl"/>
                            <div class="checkbox-select-time">时间：{{ item.createTime }}</div>
                        </li>
                    </a-checkbox-group>
                    <a-pagination
                        class="pagin-table-class"
                        v-model="masterPag.page"
                        :page-size="masterPag.size"
                        :total="materTotalAll"
                        :show-total="total => `共 ${materTotalAll} 条`"
                        size="small"
                        show-size-changer
                        show-quick-jumper
                        @change="handleMasterPageChange"
                        @showSizeChange="handleMasterPageChange"
                    />
                </div>
            </div>
        </a-modal>
    </div>
</template>
<script>
import AcountSearch from '@/views/modules/Statistics/components/Treeselect.vue';

import moment from 'moment';
import {getAction, postFileAction, postAction, deleteAction} from '@/api/manage';
import {mapGetters} from 'vuex';
import {urlAcount} from './copy-library-server.js';

export default {
    name: 'copy-library',
    components: {
        AcountSearch
    },
    data() {
        return {
            moment,
            copywritingEditList: {},
            copywritingType: 'add',
            projectModelValue: '',
            optimizationOption: [], // 账户option
            controlTypeModel: '1',
            fileList: [],
            modalSelectMaterial: [],
            materTotalAll: 0,
            viedoCheckValue: [],
            viedoDefaultList: [],
            visibleMatemal: false,
            advertisingAccount: [],
            copywrittypeName: 'horizontal',
            adNameTags: [],
            causeVisible: false,
            labelCol: {span: 4},
            wrapperCol: {span: 14},
            modalCol: {
                lg: {span: 6},
                sm: {span: 6},
                xs: {span: 6},
                md: {span: 6}
            },
            modalWrapper: {
                lg: {span: 18},
                sm: {span: 18},
                xs: {span: 14},
                md: {span: 14}
            },
            configForm: {
                acountId: '',
                num: '',
                adConvertId: undefined,
                launchDateRange: [],
                searchStatus: 2
            },
            currencyPag: {
                page: 1,
                size: 10
            },
            currencyData: [],
            currencyTotalAll: 0,
            currencyColumns: [
                {
                    title: '文案',
                    align: 'center',
                    width: 200,
                    dataIndex: 'textCopywriter'
                },
                // {
                //     title: '状态',
                //     align: 'center',
                //     width: 150,
                //     dataIndex: 'status'
                // },
                {
                    title: '相关创意',
                    align: 'center',
                    width: 150,
                    dataIndex: 'count'
                },
                {
                    title: '花费（元）',
                    align: 'center',
                    width: 150,
                    dataIndex: 'cost',
                    sorter: (a, b) => a.cost - b.cost
                },
                {
                    title: '展示数',
                    dataIndex: 'showNum',
                    width: 150,
                    align: 'center',
                    sorter: (a, b) => a.showNum - b.showNum
                },
                {
                    title: '平均千次展现费用',
                    dataIndex: 'costPerThousandShow',
                    align: 'center',
                    width: 200,
                    sorter: (a, b) => a.costPerThousandShow - b.costPerThousandShow
                },
                {
                    title: '点击数',
                    dataIndex: 'click',
                    width: 150,
                    align: 'center',
                    sorter: (a, b) => a.click - b.click
                },
                {
                    title: '平均点击单价',
                    dataIndex: 'costPerClick',
                    width: 150,
                    align: 'center',
                    sorter: (a, b) => a.costPerClick - b.costPerClick
                },
                {
                    title: '点击率',
                    dataIndex: 'clickRate',
                    align: 'center',
                    width: 150,
                    sorter: (a, b) => a.clickRate - b.clickRate
                },
                {
                    title: '转化数',
                    dataIndex: 'convertNum',
                    align: 'center',
                    width: 150,
                    sorter: (a, b) => a.convertNum - b.convertNum
                },
                {
                    title: '转化率',
                    dataIndex: 'convertRate',
                    align: 'center',
                    width: 150,
                    sorter: (a, b) => a.convertRate - b.convertRate
                },
                {
                    title: '转化成本',
                    dataIndex: 'costConvert',
                    align: 'center',
                    width: 150,
                    sorter: (a, b) => a.costConvert - b.costConvert
                }
            ],
            appointColumns: [
                {
                    title: '文案',
                    align: 'center',
                    width: 200,
                    dataIndex: 'slogan'
                },
                // {
                //     title: '状态',
                //     align: 'center',
                //     width: 150,
                //     dataIndex: 'status'
                // },
                {
                    title: '相关创意',
                    align: 'center',
                    width: 150,
                    dataIndex: 'count'
                },
                {
                    title: '花费（元）',
                    align: 'center',
                    width: 150,
                    dataIndex: 'cost',
                    sorter: (a, b) => a.cost - b.cost
                },
                {
                    title: '展示数',
                    dataIndex: 'showNum',
                    width: 150,
                    align: 'center',
                    sorter: (a, b) => a.showNum - b.showNum
                },
                {
                    title: '平均千次展现费用',
                    dataIndex: 'costPerThousandShow',
                    align: 'center',
                    width: 200,
                    sorter: (a, b) => a.costPerThousandShow - b.costPerThousandShow
                },
                {
                    title: '点击数',
                    dataIndex: 'click',
                    width: 150,
                    align: 'center',
                    sorter: (a, b) => a.click - b.click
                },
                {
                    title: '平均点击单价',
                    dataIndex: 'costPerClick',
                    width: 150,
                    align: 'center',
                    sorter: (a, b) => a.costPerClick - b.costPerClick
                },
                {
                    title: '点击率',
                    dataIndex: 'clickRate',
                    align: 'center',
                    width: 150,
                    sorter: (a, b) => a.clickRate - b.clickRate
                },
                {
                    title: '转化数',
                    dataIndex: 'convertNum',
                    align: 'center',
                    width: 150,
                    sorter: (a, b) => a.convertNum - b.convertNum
                },
                {
                    title: '转化率',
                    dataIndex: 'convertRate',
                    align: 'center',
                    width: 150,
                    sorter: (a, b) => a.convertRate - b.convertRate
                },
                {
                    title: '转化成本',
                    dataIndex: 'costConvert',
                    align: 'center',
                    width: 150,
                    sorter: (a, b) => a.costConvert - b.costConvert
                }
            ],
            appointData: [],
            appointTotalAll: 0,
            appointPag: {
                page: 1,
                size: 10
            },
            masterPag: {
                page: 1,
                size: 10
            }, 
            defaultFormList: [],
            titleFiledResult: 0,
            examinForm: this.$form.createForm(this),
            changeShowmasterData: [],
            masterTimes: [] // 选择素材的时间选择
        };
    },
    watch: {
        defaultFormList: {
            deep: true,
            handler(n, o) {
                const result = [];
                this.defaultFormList = n;
                this.$nextTick(() => {
                    this.defaultFormList.forEach(item => {
                        if (item.value) {
                            result.push(item.value);
                        }
                        this.examinForm.setFieldsValue({[item.name]: item.value});
                    });
                    this.titleFiledResult = result;
                });
            }
        }
    },
    created() {
        this.form = this.$form.createForm(this);
    },
    mounted() {
        this.handleGetCurrencyList();
        this.handleGetProjectList();
        this.handleGetCreativeWord();
    },
    methods: {
        ...mapGetters(['nickname', 'avatar', 'userInfo']),
        handleGetEditProjectList(data) {
            const paramsData = {
                slogan: data.slogan,
                projectId: data.projectId
            };
            getAction(urlAcount + '/bytedance-api/ctop/bytedanceVideoSlogenInfo/queryBySlogenAndProjectId', paramsData).then(result => {
                if (result.code === 0) {
                    const defaultData = result.result.materialNameArray;
                    const updateData = [];
                    defaultData.forEach((item, index) => {
                        updateData.push({
                            id: index + 1,
                            materialName: item
                        });
                    });
                    this.modalSelectMaterial = [...updateData];
                }
                else {
                    that.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleCurrencyEdit(data) {
            const defaultData = data;
            defaultData.controlTypeModel = this.controlTypeModel;
            if (this.controlTypeModel === '1') {
                this.advertisingAccount[0] = defaultData.accountId;
            }
            if (this.controlTypeModel === '2') {
                this.$nextTick(() => {
                    this.handleGetEditProjectList(defaultData);
                });
            }
            this.causeVisible = true;
            this.copywritingType = 'edit';
            this.copywrittypeName = this.controlTypeModel === '1' ? 'horizontal' : 'vertical';
            this.copywritingEditList = defaultData;
            this.$nextTick(() => {
                let changeValue = this.controlTypeModel === '1' ? data.textCopywriter : data.slogan;
                let finallyLenList = this.handleJudgeExec(changeValue);
                let newOptionList = [];
                finallyLenList.forEach(item => {
                    this.adNameTags.forEach(val => {
                        if (item === val.name) {
                            newOptionList.push(val);
                        }
                    });
                });
                let resultSelectSize = 0;
                if (newOptionList.length) {
                    const inputDefaultLen = this.handleExportRules(changeValue);
                    let tagsLen = newOptionList.length * 2;
                    let tagsSureLen = 0;
                    newOptionList.forEach(item => {
                        this.adNameTags.forEach(val => {
                            if (item.name === val.name) {
                                tagsSureLen += val.maxWordLen;
                            }
                        });
                    });
                    finallyLenList.forEach(item => {
                        tagsLen += item.length;
                    });
                    resultSelectSize = inputDefaultLen - tagsLen + tagsSureLen + newOptionList.length;
                }
                else {
                    resultSelectSize = this.handleExportRules(changeValue);
                }
                const defaultList = this.adNameTags;
                const randomNum = new Date().getTime() + Math.ceil(Math.random() * 1000);
                this.defaultFormList.push({
                    id: randomNum,
                    name: 'username' + randomNum,
                    value: changeValue,
                    lenSize: resultSelectSize,
                    tabStatus: 'alone',
                    defaultTagsList: defaultList,
                    updateTagsList: defaultList.slice(0, 4)
                });
            });
        },
        handleCurrencyDelete(data) {
            let that = this;
            this.$confirm({
                content: '确定是否删除该条文案',
                iconType: 'exclamation-circle',
                onOk() {
                    deleteAction(urlAcount + '/bytedance-api/advertiser/bytedanceGeneralCopywriter/delete', {id: data.id}).then(result => {
                        if (result.code === 0) {
                            that.handleGetCurrencyList();
                            that.$message.success('删除成功');
                        }
                        else {
                            that.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        handleAppointDelete(data) {
            let that = this;
            this.$confirm({
                content: '确定是否删除该条文案',
                iconType: 'exclamation-circle',
                onOk() {
                    deleteAction(urlAcount + '/bytedance-api/ctop/bytedanceVideoSlogenInfo/deleteBySlogenAndProjectId', {
                        slogan: data.slogan,
                        projectId: data.projectId
                    }).then(result => {
                        if (result.code === 0) {
                            that.handleGetAppointList();
                            that.$message.success('删除成功');
                        }
                        else {
                            that.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        disabledDate(current) {
            return current > moment().subtract(1, 'day');
        },
        handleRefreshMaster() {
            this.projectModelValue = '';
            this.masterTimes = [];
            this.viedoCheckValue = [];
            this.hendleMaterialInfo();
        },
        handleAllChecked() {
            this.viedoCheckValue = this.viedoDefaultList.map(item => item.id);
        },
        filterOption(input, option) {
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        handleGetProjectList() {
            getAction('/ctop/projectMember/bytedanceProjectParticipateInList', {userId: this.userInfo().id}).then(result => {
                if (result.code === 0) {
                    this.optimizationOption = result.result;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        hendleMaterialInfo() {
            const paramsData = {
                projectId: this.projectModelValue,
                startDate: this.masterTimes[0],
                endDate: this.masterTimes[1],
                offlineFlag: 0,
                pageNo: this.masterPag.page,
                pageSize: this.masterPag.size
            };
            getAction('/ctop/materialInfo/listV2', paramsData).then(result => {
                if (result.code === 0) {
                    this.viedoDefaultList = result.data.list;
                    this.materTotalAll = result.data.total;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleTabsChange(e) {
            const page = {
                page: 1,
                size: 10
            };
            this.currencyPag = page;
            this.appointPag = page;
            this.configForm = {
                acountId: '',
                num: '',
                adConvertId: undefined,
                launchDateRange: [],
                searchStatus: 2
            };
            if (this.currencyColumns[this.currencyColumns.length - 1].title === '操作') {
                this.currencyColumns.pop();
                this.currencyColumns.splice(1, 1);
            }
            if (this.appointColumns[this.appointColumns.length - 1].title === '操作') {
                this.appointColumns.pop();
                this.appointColumns.splice(1, 1);
            }
            if (e === '1') {
                this.handleGetCurrencyList();
            }
            else if (e === '2') {
                this.handleGetAppointList();
            }
        },
        handleGetCurrencyList() {
            let paramsData = {
                accountId: this.configForm.acountId,
                keyWord: this.configForm.num,
                userId: this.userInfo().id,
                startTime: this.configForm.launchDateRange[0],
                endTime: this.configForm.launchDateRange[0],
                status: this.configForm.searchStatus === 2 ? '' : this.configForm.searchStatus,
                pageNo: this.currencyPag.page,
                pageSize: this.currencyPag.size
            };
            getAction(urlAcount + '/bytedance-api/advertiser/bytedanceGeneralCopywriter/queryPageListByText', paramsData).then(result => {
                if (result.code === 0) {
                    this.currencyData = result.result.list ? result.result.list.map(item => {
                        item.status = item.status === 0 ? '已删除' : '可投放';
                        return item;
                    }) : [];
                    this.currencyTotalAll = result.result.total || 0;
                }
                else {
                    this.currencyData = [];
                    this.currencyTotalAll = 0;
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleGetAppointList() {
            let paramsData = {
                projectId: this.configForm.adConvertId,
                userId: this.userInfo().id,
                keyWord: this.configForm.num,
                startTime: this.configForm.launchDateRange[0],
                endTime: this.configForm.launchDateRange[0],
                status: this.configForm.searchStatus === 2 ? '' : this.configForm.searchStatus,
                pageNo: this.appointPag.page,
                pageSize: this.appointPag.size
            };
            getAction(urlAcount + '/bytedance-api/ctop/bytedanceVideoSlogenInfo/queryPageListByText', paramsData).then(result => {
                if (result.code === 0) {
                    this.appointData = result.result.list ? result.result.list.map(item => {
                        item.status = item.status === 0 ? '已删除' : '可投放';
                        return item;
                    }) : [];
                    this.appointTotalAll = result.result.total || 0;
                }
                else {
                    this.appointData = [];
                    this.appointTotalAll = 0;
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        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;
        },
        handleSearchMaster() {
            this.hendleMaterialInfo();
        },
        handleSelectTimeChange(date, dateString) {
            this.masterTimes = dateString;
        },
        handleDelAlone(data) {
            this.modalSelectMaterial = this.modalSelectMaterial.filter(item => item.id !== data.id);
        },
        handleMasterPageChange(current, pageSize) {
            this.masterPag = {
                page: current = pageSize !== this.masterPag.size ? 1 : current,
                size: pageSize
            };
            this.hendleMaterialInfo();
        },
        handleSelectMaterial() {
            this.masterPag = {
                page: 1,
                size: 10
            };
            this.handleRefreshMaster();
            this.visibleMatemal = true;
        },
        // 选择素材的取消按钮
        handleCancelAll() {
            this.projectModelValue = '';
            this.masterTimes = [];
            this.viedoCheckValue = [];
            this.visibleMatemal = false;
        },
        // 选择素材的确认按钮
        handleOkShow() {
            const defaultList = this.viedoDefaultList;
            const defaultCheckValue = this.viedoCheckValue;
            let changeSelectMaterData = defaultList.filter(item => {
                if (defaultCheckValue.includes(item.id)) {
                    return item;
                }
            });
            if (this.modalSelectMaterial.length) {
                this.changeShowmasterData = [...this.modalSelectMaterial];
                this.changeShowmasterData = this.changeShowmasterData.concat(changeSelectMaterData);
                let temp = {}; // 用于id判断
                let result = []; // 最后的新数组
                this.changeShowmasterData.map(item => {
                    if (!temp[item.id]) {
                        result.push(item);
                        temp[item.id] = true;
                    }
                });
                if (result.length > 10) {
                    this.$message.error('最多上传10个素材');
                    return;
                }
                this.modalSelectMaterial = [...result];
            }
            else {
                if (changeSelectMaterData.length > 10) {
                    this.$message.error('最多上传10个素材');
                    return;
                }
                this.modalSelectMaterial = [...changeSelectMaterData];
            }
            this.handleCancelAll();
        },
        handleFormLayoutChange(e) {
            const defaultValue = e.target.value;
            this.copywrittypeName = defaultValue;
            if (defaultValue === 'horizontal') {
                this.modalSelectMaterial = [];
                this.defaultFormList = [];
            }
            else if (defaultValue === 'vertical') {
                this.advertisingAccount = [];
                this.fileList = [];
                const defaultList = this.adNameTags;
                for (let i = 0; i < 3; i++) {
                    const randomNum = new Date().getTime() + Math.ceil(Math.random() * 1000);
                    this.defaultFormList.push({
                        id: randomNum,
                        name: 'username' + randomNum,
                        value: '',
                        lenSize: 0,
                        tabStatus: 'alone',
                        defaultTagsList: defaultList,
                        updateTagsList: defaultList.slice(0, 4)
                    });
                }
            }
        },
        handleExportRules(value) {
            let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
            let length = 0;
            let strArr = value.split('');
            strArr.forEach(item => {
                if (cnReg.test(item)) {
                    length += 1;
                }
                else {
                    length += 0.5;
                }
            });
            return Math.ceil(length);
        },
        handleFormInputChang(e, field, formId) {
            const changeFiled = [];
            this.defaultFormList.forEach(item => {
                if (item.id === formId) {
                    item.value = e.target.value;
                }
            });
            this.defaultFormList.forEach(item => {
                if (item.value) {
                    changeFiled.push(item.value);
                }
            });
            this.$nextTick(() => {
                const dynamicWordPackIds = [];
                let finallyLenList = this.handleJudgeExec(this.examinForm.getFieldsValue()[field]);
                let newOptionList = [];
                finallyLenList.forEach(item => {
                    this.adNameTags.forEach(val => {
                        if (item === val.name) {
                            newOptionList.push(val);
                        }
                    });
                });
                let updateFinallyResult = newOptionList.map(val => val.name);
                const inputDefaultLen = this.handleExportRules(this.defaultFormList.filter(item => item.id === formId)[0].value);
                let tagsLen = updateFinallyResult.length * 2;
                let tagsSureLen = 0;
                let resultSelectSize = 0;
                updateFinallyResult.forEach(item => {
                    this.adNameTags.forEach(val => {
                        if (item === val.name) {
                            tagsSureLen += val.maxWordLen;
                            dynamicWordPackIds.push(val.creativeWordId);
                        }
                    });
                });
                updateFinallyResult.forEach(item => {
                    tagsLen += item.length;
                });
                resultSelectSize = inputDefaultLen - tagsLen + tagsSureLen + updateFinallyResult.length;
                this.defaultFormList.forEach(item => {
                    if (item.id === formId) {
                        item.lenSize = resultSelectSize;
                        item.wordPackId = dynamicWordPackIds;
                    }
                });
                this.titleFiledResult = changeFiled;
            });
        },
        handleJudgeExec(item) {
            let re = /\{(.+?)\}/g;
            let array = [];
            let temp;
            while ((temp = re.exec(item))) {
                array.push(temp[1]);
            };
            return array;
        },
        // 点击获取光标位置进行字段插入
        handleGetChangeAll(item, field, formId) {
            let node = document.getElementById(field);
            let startPos = node.selectionStart; // input 第0个字符到选中的字符
            let endPos = node.selectionEnd; // 选中的字符到最后的字符
            let txt = node.value;
            this.$nextTick(() => {
                let finallyLenList = this.handleJudgeExec(txt);
                let arr = [];
                finallyLenList.forEach(item => {
                    this.adNameTags.forEach(val => {
                        if (item === val.name) {
                            arr.push(val);
                        }
                    });
                });
                let updateFinallyResult = arr.map(val => val.name);
                if (updateFinallyResult.length >= 2) {
                    this.$message.error('最多选择两个词包');
                    return;
                }
                if (startPos === 0 || endPos === 0) {
                    txt += '{' + item + '}';
                    this.examinForm.setFieldsValue({[field]: txt});
                }
                else {
                    this.examinForm.setFieldsValue({[field]: txt.substring(0, startPos) + '{' + item + '}' + txt.substring(endPos)});
                    node.selectionStart = startPos + item.length + 6;
                    node.selectionEnd = startPos + item.length + 6;
                }
                node.focus();
                node.blur();
            });
            this.$nextTick(() => {
                const dynamicWordPackIds = [];
                let changeData = this.handleJudgeExec(this.examinForm.getFieldsValue()[field]);
                let newOptionList = [];
                changeData.forEach(item => {
                    this.adNameTags.forEach(val => {
                        if (item === val.name) {
                            newOptionList.push(val);
                        }
                    });
                });
                let updateChangeData = newOptionList.map(val => val.name);
                const inputDefaultLen = this.handleExportRules(this.examinForm.getFieldsValue()[field]);
                let tagsLen = updateChangeData.length * 2;
                let tagsSureLen = 0;
                let resultSelectSize = 0;
                updateChangeData.forEach(item => {
                    this.adNameTags.forEach(val => {
                        if (item === val.name) {
                            tagsSureLen += val.maxWordLen;
                            dynamicWordPackIds.push(val.creativeWordId);
                        }
                    });
                });
                updateChangeData.forEach(item => {
                    tagsLen += item.length;
                });
                resultSelectSize = inputDefaultLen - tagsLen + tagsSureLen + updateChangeData.length;
                this.defaultFormList.forEach(item => {
                    if (item.id === formId) {
                        item.lenSize = resultSelectSize;
                        item.value = this.examinForm.getFieldsValue()[field];
                        item.wordPackId = dynamicWordPackIds;
                    }
                });
            });
        },
        validatePass(rule, value, callback) {
            this.$nextTick(() => {
                let finallyLenList = this.handleJudgeExec(value);
                let newOptionList = [];
                finallyLenList.forEach(item => {
                    this.adNameTags.forEach(val => {
                        if (item === val.name) {
                            newOptionList.push(val);
                        }
                    });
                });
                let updateFinallyResult = newOptionList.map(val => val.name);
                let resultSelectSize = 0;
                if (updateFinallyResult.length) {
                    const inputDefaultLen = this.handleExportRules(value);
                    let tagsLen = updateFinallyResult.length * 2;
                    let tagsSureLen = 0;
                    updateFinallyResult.forEach(item => {
                        this.adNameTags.forEach(val => {
                            if (item === val.name) {
                                tagsSureLen += val.maxWordLen;
                            }
                        });
                    });
                    updateFinallyResult.forEach(item => {
                        tagsLen += item.length;
                    });
                    resultSelectSize = inputDefaultLen - tagsLen + tagsSureLen + updateFinallyResult.length;
                }
                else {
                    resultSelectSize = this.handleExportRules(value);
                }
                if (resultSelectSize === 0) {
                    callback(new Error('请输入'));
                }
                else if (resultSelectSize > 30 || resultSelectSize < 5) {
                    callback(new Error('创意标题5-30个字'));
                }
                else if (updateFinallyResult.length > 2) {
                    callback(new Error('最多选择两个词包'));
                }
                else {
                    callback();
                }
            });
        },
        handleMoreTagsShow(val, type) {
            if (type === 'more') {
                this.defaultFormList.forEach(item => {
                    if (item.id === val) {
                        item.tabStatus = 'all';
                    }
                });
            }
            else if (type === 'little') {
                this.defaultFormList.forEach(item => {
                    if (item.id === val) {
                        item.tabStatus = 'alone';
                    }
                });
            }
        },
        handleUploadWxeclAdd() {
            if (!this.advertisingAccount.length) {
                this.$message.error('请选择账户');
                return;
            }
            if (!this.fileList.length) {
                this.$message.error('请上传文件');
                return;
            }
            let paramsData = new FormData();
            paramsData.append('accountId', this.advertisingAccount);
            paramsData.append('excelFile', this.fileList[0]);
            postFileAction(urlAcount + '/bytedance-api/advertiser/bytedanceGeneralCopywriter/loadExcel', paramsData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(result => {
                if (result.code === 0) {
                    this.$message.success(result.message);
                    this.controlTypeModel = '1';
                    this.handleCauseCancel();
                    this.handleGetCurrencyList();
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleVerticalAdd() {
            if (!this.modalSelectMaterial.length) {
                this.$message.error('请选择素材');
                return;
            }
            if (this.defaultFormList && this.defaultFormList.length < 3) {
                this.$message.error('请至少输入3条标题');
                return;
            }
            let changeSlogan = this.defaultFormList;
            changeSlogan.forEach(item => {
                item.title = item.value;
                item.creative_word_ids = item.wordPackId;
            });
            let paramsData = {
                materialIds: this.modalSelectMaterial.map(item => item.id),
                userId: this.userInfo().id,
                slogans: changeSlogan
            };
            this.examinForm.validateFields(err => {
                if (!err) {
                    postAction(urlAcount + '/bytedance-api/ctop/bytedanceVideoSlogenInfo/addList', paramsData).then(result => {
                        if (result.code === 0) {
                            this.$message.success(result.message);
                            this.controlTypeModel = '2';
                            this.modalSelectMaterial = [];
                            this.handleCauseCancel();
                            this.handleGetAppointList();
                        }
                        else {
                            this.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        handleUploadWxeclEdit() {
            if (!this.defaultFormList[0].value) {
                this.$message.error('文案标题不能为空');
                return;
            }
            const paramsData = {
                id: this.copywritingEditList.id,
                textCopywriter: this.defaultFormList[0].value
            };
            postAction(urlAcount + '/bytedance-api/advertiser/bytedanceGeneralCopywriter/edit', paramsData).then(result => {
                if (result.code === 0) {
                    this.$message.success(result.message);
                    this.causeVisible = false;
                    this.controlTypeModel = '1';
                    this.handleCauseCancel();
                    this.handleGetCurrencyList();
                }
                else {
                    this.$message.success(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleVerticalEdit() {
            if (!this.defaultFormList[0].value) {
                this.$message.error('文案标题不能为空');
                return;
            }
            const paramsData = {
                slogan: this.copywritingEditList.slogan,
                projectId: this.copywritingEditList.projectId,
                newSlogan: this.defaultFormList[0].value
            };
            postAction(urlAcount + '/bytedance-api/ctop/bytedanceVideoSlogenInfo/edit', paramsData).then(result => {
                if (result.code === 0) {
                    this.$message.success(result.message);
                    this.causeVisible = false;
                    this.controlTypeModel = '2';
                    this.handleCauseCancel();
                    this.handleGetAppointList();
                }
                else {
                    this.$message.success(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleCauseSure() {
            if (this.copywritingType === 'add') {
                if (this.copywrittypeName === 'horizontal') {
                    this.handleUploadWxeclAdd();
                }
                else if (this.copywrittypeName === 'vertical') {
                    this.handleVerticalAdd();
                }
            }
            else if (this.copywritingType === 'edit') {
                if (this.copywrittypeName === 'horizontal') {
                    this.handleUploadWxeclEdit();
                }
                else if (this.copywrittypeName === 'vertical') {
                    this.handleVerticalEdit();
                }
            }
        },
        handleCauseCancel() {
            this.copywrittypeName = 'horizontal';
            this.advertisingAccount = [];
            this.fileList = [];
            this.causeVisible = false;
            this.defaultFormList = [];
            this.modalSelectMaterial = [];
            this.copywritingType = '';
        },
        handleGetCreativeWord() {
            getAction('/ctop/ByteDanceCreativeWordPackage/list').then(result => {
                if (result.code === 0) {
                    this.adNameTags = result.result.records;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleAddOrigin() {
            const randomNum = new Date().getTime() + Math.ceil(Math.random() * 1000);
            this.defaultFormList.push({
                id: randomNum,
                name: 'username' + randomNum,
                value: '',
                lenSize: 0,
                tabStatus: 'alone',
                defaultTagsList: this.adNameTags,
                updateTagsList: this.adNameTags.slice(0, 4)
            });
        },
        handleDelOrigin(list) {
            let formData = this.defaultFormList;
            this.defaultFormList = formData.filter(item => list.id !== item.id);
        },
        handleAddAccountConfig() {
            this.causeVisible = true;
            this.copywritingType = 'add';
            this.copywritingEditList = {};
        },
        handleLaunchData(date, dateString) {
            this.configForm.launchDateRange = dateString;
        },
        handleQueryList() {
            const page = {
                page: 1,
                size: 10
            };
            this.currencyPag = page;
            this.appointPag = page;
            if (this.configForm.acountId) {
                if (this.currencyColumns[this.currencyColumns.length - 1].title !== '操作') {
                    this.currencyColumns.splice(1, 0, {
                        title: '状态',
                        align: 'center',
                        width: 150,
                        dataIndex: 'status'
                    });
                    this.currencyColumns.push({
                        title: '操作',
                        dataIndex: 'currencyAction',
                        align: 'center',
                        width: 150,
                        fixed: 'right',
                        scopedSlots: {customRender: 'currencyAction'}
                    });
                }
            }
            if (this.configForm.adConvertId) {
                if (this.appointColumns[this.appointColumns.length - 1].title !== '操作') {
                    this.appointColumns.splice(1, 0, {
                        title: '状态',
                        align: 'center',
                        width: 150,
                        dataIndex: 'status'
                    });
                    this.appointColumns.push({
                        title: '操作',
                        dataIndex: 'appointAction',
                        align: 'center',
                        width: 150,
                        fixed: 'right',
                        scopedSlots: {customRender: 'appointAction'}
                    });
                }
            }
            if (this.controlTypeModel === '1') {
                this.handleGetCurrencyList();
            }
            else if (this.controlTypeModel === '2') {
                this.handleGetAppointList();
            }
        },
        handleResetList() {
            this.configForm = {
                acountId: '',
                num: '',
                adConvertId: undefined,
                launchDateRange: [],
                searchStatus: 2
            };
            const page = {
                page: 1,
                size: 10
            };
            this.currencyPag = page;
            this.appointPag = page;
            if (this.currencyColumns[this.currencyColumns.length - 1].title === '操作') {
                this.currencyColumns.pop();
                this.currencyColumns.splice(1, 1);
            }
            if (this.appointColumns[this.appointColumns.length - 1].title === '操作') {
                this.appointColumns.pop();
                this.appointColumns.splice(1, 1);
            }
            if (this.controlTypeModel === '1') {
                this.handleGetCurrencyList();
            }
            else if (this.controlTypeModel === '2') {
                this.handleGetAppointList();
            }
        },
        handleCurrentPage(current, pageSize) {
            this.currencyPag = {
                page: current = pageSize !== this.currencyPag.size ? 1 : current,
                size: pageSize
            };
            this.handleGetCurrencyList();
        },
        handleAppointPage(current, pageSize) {
            this.appointPag = {
                page: current = pageSize !== this.appointPag.size ? 1 : current,
                size: pageSize
            };
            this.handleGetAppointList();
        }
    }
};
</script>
<style lang="less" scoped>
    @import "copy-library";
</style>