<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 class="grid-form-options">
                    <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"
                            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-model-item>
                    <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="default" class="reset-class" @click="handleResetList">重置</a-button>
                        <a-button type="primary" @click="handleQueryList">查询</a-button>
                    </a-form-item>
                </a-row>
            </a-form>
            <a-button type="primary" class="upload-person" @click="handleAddAccountConfig">新增文案</a-button>
        </div>
        <div class="control-con-table">
            <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}"
                    >
                    </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}"
                    >
                    </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="新建文案"
            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">
                                    通用
                                </a-radio-button>
                                <a-radio-button value="vertical">
                                    指定素材
                                </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"></acount-search>
                        </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">
                            <a-upload
                                name="file"
                                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                :file-list="fileList"
                                @change="handleChange"
                            >
                                <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><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-icon" @click="handleDelAlone(item)"><a-icon type="close"/></span>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="copywrittypeName === 'vertical'" 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'" 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>
        </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>
                            <!-- <div class="checkbox-select-show"><a>查看视频</a></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 {getAction, postFileAction, postAction} from '@/api/manage';
import {fileCheck, fileEdit, fileEditAll, fileInsertV2, fileEditUpdate, fileEditUpdateBatch} from '@/api/actor';
import {mapGetters} from 'vuex';
import {urlAcount} from './copy-library-server.js';

let COS = require('cos-js-sdk-v5');
let cos = new COS({
    SecretId: 'AKIDE6IpMi8fJQRCg1iuWzFajjRs43kbbets',
    SecretKey: 'tXzuwMfplTTK3c9GFUyETilasvQfePu9'
});

export default {
    name: 'copy-library',
    components: {
        AcountSearch
    },
    data() {
        return {
            projectModelValue: '',
            optimizationOption: [], // 账户option
            controlTypeModel: '1',
            fileList: [],
            modalSelectMaterial: [],
            materTotalAll: 0,
            viedoCheckValue: [],
            viedoDefaultList: [
                {
                    name: '北京市',
                    id: 1,
                    statDate: '2019-08-08'
                },
                {
                    name: '上海市',
                    id: 2,
                    statDate: '2019-08-08'
                },
                {
                    name: '天津市',
                    id: 3,
                    statDate: '2019-08-08'
                },
                {
                    name: '武汉市',
                    id: 4,
                    statDate: '2019-08-08'
                },
                {
                    name: '贵州市',
                    id: 5,
                    statDate: '2019-08-08'
                },
                {
                    name: '太原市',
                    id: 6,
                    statDate: '2019-08-08'
                },
                {
                    name: '大同市',
                    id: 7,
                    statDate: '2019-08-08'
                }
            ],
            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: '',
                launchDateRange: []
            },
            currencyPag: {
                page: 1,
                size: 10
            },
            currencyData: [],
            currencyTotalAll: 0,
            currencyColumns: [
                {
                    title: '文案',
                    align: 'center',
                    width: 200,
                    dataIndex: 'textCopywriter'
                },
                {
                    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: '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),
            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']),
        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').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],
                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: '',
                launchDateRange: []
            };
            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],
                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;
                    this.currencyTotalAll = result.result.total;
                }
                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],
                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;
                    this.appointTotalAll = result.result.total;
                }
                else {
                    this.appointData = [];
                    this.appointTotalAll = [];
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleChange(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 = info.fileList;
        },
        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.hendleMaterialInfo();
            this.visibleMatemal = true;
        },
        // 选择素材的取消按钮
        handleCancelAll() {
            this.projectModelValue = '';
            this.masterTimes = [];
            this.viedoCheckValue = [];
            this.visibleMatemal = false;
        },
        // 选择素材的确认按钮
        handleOkShow() {
            const defaultList = this.viedoDefaultList;
            const defaultCheckValue = this.viedoCheckValue;
            let finallyIds = new Set();
            let changeSelectMaterData = defaultList.filter(item => {
                if (defaultCheckValue.includes(item.id)) {
                    return item;
                }
            });
            finallyIds = this.modalSelectMaterial.concat(changeSelectMaterData).map(item => item.id);
            this.modalSelectMaterial = defaultList.filter(item => {
                if (finallyIds.includes(item.id)) {
                    return item;
                }
            });
            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)
                    });
                }
            }
        },
        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 updateFinallyResult = this.adNameTags.filter(item => finallyLenList.includes(item.name)).map(val => val.name);
                const inputDefaultLen = this.defaultFormList.filter(item => item.id === formId)[0].value.length;
                let tagsLen = updateFinallyResult.length * 2;
                let tagsSureLen = 0;
                let resultSelectSize = 0;
                this.adNameTags.forEach(item => {
                    updateFinallyResult.forEach(val => {
                        if (item.name === val) {
                            tagsSureLen += item.maxWordLen;
                            dynamicWordPackIds.push(item.creativeWordId);
                        }
                    });
                });
                updateFinallyResult.forEach(item => {
                    tagsLen += item.length;
                });
                resultSelectSize = inputDefaultLen - tagsLen + tagsSureLen;
                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 updateFinallyResult = this.adNameTags.filter(item => finallyLenList.includes(item.name)).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 updateChangeData = this.adNameTags.filter(item => changeData.includes(item.name)).map(val => val.name);
                const inputDefaultLen = this.examinForm.getFieldsValue()[field].length;
                let tagsLen = updateChangeData.length * 2;
                let tagsSureLen = 0;
                let resultSelectSize = 0;
                this.adNameTags.forEach(item => {
                    updateChangeData.forEach(val => {
                        if (item.name === val) {
                            tagsSureLen += item.maxWordLen;
                            dynamicWordPackIds.push(item.creativeWordId);
                        }
                    });
                });
                updateChangeData.forEach(item => {
                    tagsLen += item.length;
                });
                resultSelectSize = inputDefaultLen - tagsLen + tagsSureLen;
                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 updateFinallyResult = this.adNameTags.filter(item => finallyLenList.includes(item.name)).map(val => val.name);
                let resultSelectSize = 0;
                if (updateFinallyResult.length) {
                    const inputDefaultLen = value.length;
                    let tagsLen = updateFinallyResult.length * 2;
                    let tagsSureLen = 0;
                    this.adNameTags.forEach(item => {
                        updateFinallyResult.forEach(val => {
                            if (item.name === val) {
                                tagsSureLen += item.maxWordLen;
                            }
                        });
                    });
                    updateFinallyResult.forEach(item => {
                        tagsLen += item.length;
                    });
                    resultSelectSize = inputDefaultLen - tagsLen + tagsSureLen;
                }
                else {
                    resultSelectSize = value.length;
                }
                // {地点}{日3期}{运8营商}{考3{区县}试}{节11555日}
                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';
                    }
                });
            }
        },
        handleUploadWxecl() {
            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].originFileObj);
            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 = '1';
                            this.handleCauseCancel();
                            this.handleGetCurrencyList();
                        }
                        else {
                            this.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        handleCauseSure() {
            if (this.copywrittypeName === 'horizontal') {
                this.handleUploadWxecl();
            }
            else if (this.copywrittypeName === 'vertical') {
                this.handleVerticalAdd();
            }
        },
        handleCauseCancel() {
            this.copywrittypeName = 'horizontal';
            this.advertisingAccount = [];
            this.fileList = [];
            this.causeVisible = false;
            this.defaultFormList = [];
            this.modalSelectMaterial = [];
        },
        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;
        },
        handleLaunchData(date, dateString) {
            this.configForm.launchDateRange = dateString;
        },
        handleQueryList() {
            const page = {
                page: 1,
                size: 10
            };
            this.currencyPag = page;
            this.appointPag = page;
            if (this.controlTypeModel === '1') {
                this.handleGetCurrencyList();
            }
            else if (this.controlTypeModel === '2') {
                this.handleGetAppointList();
            }
        },
        handleResetList() {
            this.configForm = {
                acountId: '',
                num: '',
                adConvertId: '',
                launchDateRange: []
            };
            const page = {
                page: 1,
                size: 10
            };
            this.currencyPag = page;
            this.appointPag = page;
            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>