<template>
    <div class="directional-content">
        <div class="table-page-search-wrapper">
            <a-form layout="inline"  :form="form"
                hide-required-mark :selfUpdate="true" 
                @submit="handleQueryList">
                <a-row :gutter="24">
                    <a-col :md="8" :sm="8" :xxl="6">
                        <!-- <a-form-item label="项目名称"> -->
                        <selectTable :projectId.sync="projectId" ref="selectTable" :requireCheck="false"></selectTable>
                    </a-col>
                    <a-col :md="8" :sm="8" :xxl="6">
                        <a-form-item label="应用名称">
                            <a-input
                                v-decorator="['appName']" type="text"
                                placeholder="请输入应用名称"
                            />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="8" :xxl="6">
                        <a-form-item label="应用标识">
                            <a-input
                                v-decorator="['name']" type="text"
                                placeholder="请输入应用标记"
                            />
                        </a-form-item>
                    </a-col>
                    <!--  -->
                    <a-col :md="8" :sm="8" :xxl="6">
                        <a-form-item label="系统平台">
                            <a-select
                                v-decorator="['status',{initialValue:''}]"
                                placeholder="请选择"
                                allow-clear
                            >
                                <a-select-option v-for="item in platform" :key="item.label">
                                    {{ item.value }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="8" :xxl="6">
                        <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                            <a-button type="primary" icon="search" @click="handleQueryList">查询</a-button>
                            <a-button type="primary" @click="handleResetForm" icon="reload" class="middle-button">重置</a-button>
                            <a-button type="primary" @click="addNewApp(null)">添加应用</a-button>
                             <a-button type="primary" @click="handleUpdatePerson"  class="middle-button" v-if="realShow" :loading="realLoading">
                                更新应用
                            </a-button>
                        </span>
                        
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <div class="control-con-table">
            <a-table
                ref="table"
                size="middle"
                bordered
                :columns="columns"
                :dataSource="dataSource"
                :pagination="ipagination"
                :loading="dataLoading"
            >
                <span slot="action" slot-scope="text, record">
                    <a @click="handlePush(record)">推送</a>
                    <a-divider type="vertical" />
                    <a @click="handleEdit(record)">编辑</a>
                    <a-divider type="vertical" />
                    <a @click="handleDelete(record)">删除</a>
                </span>

                <span slot="accountCount" slot-scope="text, record">
                    <a @click="handleAcountRelax('account', record)">{{ text }}</a>
                </span>
                <span slot="unitCount" slot-scope="text, record">
                    <a @click="handleAcountRelax('unit', record)">{{ text }}</a>
                </span>
                
                <span slot="actionMore" slot-scope="text, record">
                    <a @click="handleCause(record)">推送历史</a>
                </span>
            </a-table>
        </div>
        <a-modal
            title="推送账户"
            v-if="pushVisible"
            :visible="pushVisible"
            :confirm-loading="pushConfirmLoading"
            dialog-class="push-modal"
            @ok="handlePushSure"
            @cancel="handlePushCancel"
            okText="下一步"
        >
            <div>
                <tree-select httpSrc="/kuaishouAppPackage/getAccountByProjectId" @applyType="handleApplyType" :projectId="tableSelectList.projectId" :templateId="tableSelectList.id"></tree-select>
            </div>
        </a-modal>
        <a-modal
            title="为定向包设置自定义人群"
            v-if="setPersonVisible"
            :visible="setPersonVisible"
            :confirm-loading="setPersonLoading"
            dialog-class="push-modal"
            @ok="handleSetPerson"
            @cancel="handlePersonCancel"
        >
             <!-- @change="handleChange" -->
            <el-collapse v-model="activeKey" accordion>
                <el-collapse-item :name="item.key" :key="index" v-for="(item ,index) in finallyRightTree">
                    <template slot="title">
                        <h2>{{item.title}}</h2>
                    </template>
                    <a-form  
                        :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
                    >
                        <div class="acount-title">
                            <div class="acount-title-left">自定义人群</div>
                            <div class="acount-title-right"> 
                                <a-radio-group v-model="item.people" buttonStyle="solid" @change="checkPerson(item)">
                                    <a-radio-button value="0">不限</a-radio-button>
                                    <a-radio-button value="1">定向</a-radio-button>                           
                                    <a-radio-button value="2">排除</a-radio-button>                           
                                    <a-radio-button value="3">同时定向排除</a-radio-button>                           
                                </a-radio-group>
                            </div>
                        </div>
                        <div class="dingxiang_paichu" v-if="item.people!='0'" style="width:100%">
                            <a-tabs v-model="item.tabKey" @change="retargetAccountId(item.key)"  >
                                <a-tab-pane key="1" tab="定向池" v-if="item.people!='2'">
                                    <a-table
                                        :columns="retargetColumns"
                                        :row-key="record => record.key"
                                        :data-source="retargetDataAll"                                        
                                        :loading="loading"
                                        style="width:100%;margin:15px 0"
                                        :pagination='false'
                                        @change="retargetTableChange"
                                        :scroll="{ y: 250 }"
                                        :row-selection="rowSelectionMin"
                                        bordered
                                    >
                                        <template slot="name" slot-scope="name"> {{ name }} </template>
                                        <template slot="populationType" slot-scope="populationType"> {{ populationType | customCrowdHandler}} </template>
                                    </a-table>
                                </a-tab-pane>
                                <a-tab-pane key="2" tab="排除池" v-if="item.people!='1'">
                                    <a-table
                                        :columns="retargetColumns"
                                        :row-key="record => record.key"
                                        :data-source="retargetDataAll"                                        
                                        :loading="loading"
                                        style="width:100%;margin:15px 0"
                                        :pagination='false'
                                        @change="retargetTableChange"
                                        :scroll="{ y: 250 }"
                                        :row-selection="rowSelectionMax"
                                        bordered
                                    >
                                        <template slot="name" slot-scope="name"> {{ name }} </template>
                                        <template slot="populationType" slot-scope="populationType"> {{ populationType | customCrowdHandler}} </template>
                                    </a-table>
                                </a-tab-pane>
                            </a-tabs>
                                
                        </div>  
                    </a-form>
                </el-collapse-item>
            </el-collapse>
        </a-modal>
        <a-modal
            title="推送历史"
            v-if="causeVisible"
            :visible="causeVisible"
            :confirm-loading="causeConfirmLoading"
            :footer="null"
            dialog-class="cause-modal"
            @cancel="handleCauseCancel"
        >
            <div>
                <div class="cause-modal-table-class">
                    <a-select
                        style="width:200px;margin-bottom:10px"
                        v-model="resultHistory"
                        placeholder="请选择"
                        allow-clear
                    >
                        <a-select-option :value="2">不限</a-select-option>
                        <a-select-option :value="1">推送成功</a-select-option>
                        <a-select-option :value="0">推送失败</a-select-option>
                    </a-select>
                    <a-table :columns="causeColumns" :data-source="causeData" bordered :pagination="false">
                        <span slot="action" slot-scope="text, record">
                            <a-popconfirm
                                title="是否重新推送?"
                                ok-text="是"
                                cancel-text="否"
                                @confirm="handleAgian(record)"
                            >
                                <a :disabled="record.result==='推送成功'">重新推送</a>
                            </a-popconfirm>
                            
                        </span>
                    </a-table>
                </div>
                <a-pagination
                    class="pagin-table-class"
                    :total="totalAllCause"
                    size="small"
                    @change="handleCauseSizeChange"
                />
            </div>
        </a-modal>   
        <a-modal
            :title="relaxStatus === 'unit' ? '相关组' : '相关账户'"
            v-if="relaxVisible"
            :visible="relaxVisible"
            :confirm-loading="relaxConfirmLoading"
            :footer="null"
            dialog-class="relax-modal"
            @cancel="handleRelaxCancel"
            rowKey="index"
        >
            <div class="acount-title">
                <div class="acount-title-left">应用名称</div>
                <div class="acount-title-right">{{ relaxData.appName }}</div>
            </div>
            <div class="acount-title">
                <div class="acount-title-left">应用标记</div>
                <div class="acount-title-right">
                   {{ relaxData.appVersion }}
                </div>
            </div>
             <div class="acount-title push-plate" v-if="relaxData.packageName">
                <div class="acount-title-left">应用包名</div>
                <div class="acount-title-right">
                    {{ relaxData.packageName }}
                </div>
            </div>
            <div v-if="relaxStatus === 'account'">
                <a-table :columns="acountColumns" :data-source="acountData" bordered :pagination="accountIpagination">
                    <a @click="handleEditPerson(record)" slot="action" slot-scope="text,record">
                        编辑自定义人群
                    </a>
                </a-table>
            </div>
            <div v-else>
                <AcountSearch :appId.sync="unitAccountId" :multiple="false"  request="2,4"   ref="treeSelect" style="margin-bottom:8px;width:300px " />   
                <a-table :columns="depColumns" :data-source="acountData" bordered :pagination="accountIpagination">
                </a-table>
            </div>
        </a-modal>
        <a-modal
            :title="'编辑自定义人群(' + personName + ')'"
            :visible="personNameVisible"
            @ok="handleAddPopulation"
            dialog-class="relax-modal"
            @cancel="handleCancelPerson"
            :confirm-loading="personLoading"
            rowKey="index">
            <a-form  
                :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
            >
                <a-form-item label="定向包名称">
                    <a-input
                        disabled
                        :default-value="(personDetail ? personDetail.templateName : '-') "
                        placeholder="请输入"
                    />
                </a-form-item>
                <a-form-item label="账户名称">
                    <a-input
                        disabled
                        :default-value="(personDetail ? personDetail.authName : '-') "
                        placeholder="请输入"
                    />
                </a-form-item>
                <a-form-item label="自定义人群">
                    <a-radio-group v-model="people" buttonStyle="solid" @change="customCrowdChange">
                        <a-radio-button value="0">不限</a-radio-button>
                        <a-radio-button value="1">定向</a-radio-button>                           
                        <a-radio-button value="2">排除</a-radio-button>                           
                        <a-radio-button value="3">同时定向排除</a-radio-button>                           
                    </a-radio-group>
                </a-form-item>
                <div class="dingxiang_paichu" v-if="people!='0'" style="width:100%">
                    <a-tabs v-model="tabKey" @change="retargetTabChange"  >
                        <a-tab-pane key="1" tab="定向池" v-if="people!='2'">
                            <a-table
                                :columns="retargetColumns"
                                :row-key="record => record.key"
                                :data-source="retargetDataAll"                                        
                                :loading="loading"
                                style="width:100%;margin:15px 0"
                                :pagination='false'
                                @change="retargetTableChange"
                                :scroll="{ y: 250 }"
                                :row-selection="rowSelection"
                                bordered
                                v-if="people!='0'"
                            >
                                <template slot="name" slot-scope="name"> {{ name }} </template>
                                <template slot="populationType" slot-scope="populationType"> {{ populationType | customCrowdHandler}} </template>
                            </a-table>
                        </a-tab-pane>
                        <a-tab-pane key="2" tab="排除池" v-if="people!='1'">
                            <a-table
                                :columns="retargetColumns"
                                :row-key="record => record.key"
                                :data-source="retargetDataAll"                                        
                                :loading="loading"
                                style="width:100%;margin:15px 0"
                                :pagination='false'
                                @change="retargetTableChange"
                                :scroll="{ y: 250 }"
                                :row-selection="rowSelection2"
                                bordered
                                v-if="people!='1'"
                            >
                                <template slot="name" slot-scope="name"> {{ name }} </template>
                                <template slot="populationType" slot-scope="populationType"> {{ populationType | customCrowdHandler}} </template>
                            </a-table>
                        </a-tab-pane>
                    </a-tabs>
                        
                </div>  
            </a-form>
        </a-modal>
        <creat-application ref="application" @getDataList="handleResetForm"/>
        <editApplication ref="editApplication" @getDataList="handleResetForm"/>
    </div>
</template>
<script>
import TreeSelect from './components/tree-select';
import {getAction, postAction} from '@/api/manage';
import AcountSearch from '@/views/modules/Statistics/components/Treeselect.vue';
import AppMarketService from './application-service';
import selectTable from '@/views/modules/Statistics/components/selectPagination.vue';
import BMF from 'browser-md5-file';
import creatApplication from './components/creatApplication.vue'
import editApplication from './components/editApplication.vue'
import { mapGetters } from 'vuex'
let retargetColumns=[
    {
        title: '人群包',
        dataIndex: 'name',
        sorter: true,
        width: '40%',
        scopedSlots: { customRender: 'name' },
    },
    {
    title: '属性',
      dataIndex: 'populationType',
      scopedSlots: {
        customRender: 'populationType'
      },
      width: 200
    },
    {
        title: '所属账号',
        dataIndex: 'accountId',
        sorter: true,
        width: '40%',
        scopedSlots: { customRender: 'accountId' },
    },
    
]
let COS = require('cos-js-sdk-v5');
let cos = new COS({
    SecretId: 'AKIDE6IpMi8fJQRCg1iuWzFajjRs43kbbets',
    SecretKey: 'tXzuwMfplTTK3c9GFUyETilasvQfePu9'
});
export default {
    name: 'application',
    components: {
        TreeSelect,
        AcountSearch,
        selectTable,
        creatApplication,
        editApplication
    },
    data() {
        let that = this;
        return {
            //自定义人群参数
            personLoading: false,
            retargetColumns,
            retargetData: [],
            retargetDataAll: [],
            loading: false,
            customCrowd: 'NONE',//自定义人群 选择的值
            selectedRowKeys: [],
            incluedSelectedRowKeys: [],
            incluedSelectedKeys: [],
            excludeSelectedKeys: [],
            excludeSelectedRowKeys: [],
            //自定义人群参数结束
            resultHistory: 2,
            unitAccountId: "",
            activeKey: "",
            setPersonVisible: false,
            setPersonLoading: false,
            tabKey:'1',
            people: '0',
            peopleList: [],
            dataElse: [],
            personName: "",
            personNameVisible: false,
            personDetail: null,
            dataLoading: false,
            personResourceDisabled: false,
            personNameDisabled: false,
            totalAllCause: 0,
            projectId: undefined, // 搜索的账户ID
            uploadAcountIds: '',
            totalAll: 10,
            finallyRightTree: [],
            fileList: [],
            relaxVisible: false,
            relaxConfirmLoading: false,
            pushVisible: false,
            pushConfirmLoading: false,
            causeVisible: false,
            causeConfirmLoading: false,
            labelCol: {span: 4},
            wrapperCol: {span: 14},
            confirmLoading: false,
            mateTypeTasks: AppMarketService.setMateTypeTasks(), // 匹配类型
            populationTypeTasks: AppMarketService.setPopulationTypeTasks(), // 人群包类型
            platform: AppMarketService.setPlatform(), // 状态枚举
            relaxStatus: '',
            relaxData: null,
            causeData: [], // 原因的table列表数据,
            depData: [], // 相关项目的table列表数据,
            acountData: [], // 相关账户的table列表数据,
            acountColumns: AppMarketService.setAcountColumns(), // 相关账户的table列表
            depColumns: AppMarketService.setDepColumns(), // 相关项目的table列表
            causeColumns: AppMarketService.setCauseColumns(), // 原因的table列表
            dataSource: [],
            ipagination: {
                current: 1,
                pageSize: 10,
                //   pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + "-" + range[1] + " 共" + total + "条"
                },
                showQuickJumper: true,
                showSizeChanger:false,
                pageSizeOptions: ['10', '30', '50'],
                total: 0,
                onChange: (current, pageSize) => {
                    // 切换分页时的回调，
                    // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
                    this.ipagination.current = current;
                    this.ipagination.pageSize= pageSize;
                    this.handleGetTableList({})
                }
            },
            accountIpagination: {
                current: 1,
                pageSize: 10,
                //   pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + "-" + range[1] + " 共" + total + "条"
                },
                showQuickJumper: true,
                showSizeChanger:false,
                pageSizeOptions: ['10', '30', '50'],
                total: 0,
                onChange: (current, pageSize) => {
                    // 切换分页时的回调，
                    // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
                    this.accountIpagination.current = current;
                    this.accountIpagination.pageSize= pageSize;
                    this.handleAcountRelax(this.relaxStatus  ,this.relaxData)
                }
            },
            columns: [
                {
                    title: '应用名称',
                    align: 'center',
                    width: 200,
                    dataIndex: 'appName'
                },
                {
                    title: '应用标记',
                    align: 'center',
                    dataIndex: 'appVersion'
                },
                {
                    title: '系统平台',
                    align: 'center',
                    dataIndex: 'platformStr',
                },
                {
                    title: '应用包名',
                    align: 'center',
                    dataIndex: 'packageName',
                    customRender(t) {
                        if(t) {
                            return t
                        }
                        else {
                            return '-'
                        }
                    }
                },
                 {
                    title: '更新时间',
                    dataIndex: 'createTime',
                    align: 'center'
                },
                {
                    title: '所属项目',
                    align: 'center',
                    dataIndex: 'projectName',
                    customRender(t) {
                        if(t) {
                            return t
                        }
                        else {
                            return '-'
                        }
                    }
                },
                {
                    title: '相关账户',
                    dataIndex: 'accountCount',
                    scopedSlots: {customRender: 'accountCount'},
                    align: 'center'
                },
                {
                    title: '相关组',
                    dataIndex: 'unitCount',
                     scopedSlots: {customRender: 'unitCount'},
                    align: 'center'
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align: 'center',
                    width: 150,
                    scopedSlots: {customRender: 'action'}
                },
                {
                    title: '更多',
                    dataIndex: 'actionMore',
                    align: 'center',
                    scopedSlots: {customRender: 'actionMore'},
                    ellipsis: true
                },
            ],
            tablePag: {
                page: 1,
                size: 10
            },
            // table 原因的分页
            causePag: {
                page: 1,
                size: 10
            },
            tableSelectList: {},
            acountRelaxDetail: {},
            causeDetailData: {},
            editPerson: null,
            realShow: false,
            realLoading: false
        };
    },
    watch: {
        unitAccountId: function(n,o) {
            if(this.relaxVisible){
                this.handleAcountRelax(this.relaxStatus  ,this.relaxData)
            }
        },
        resultHistory: function(n,o) {
            this.handleCauseTableData(this.tableSelectList.id);
        },
    },
    computed: {
        hasSelected() {
            return this.selectedRowKeys.length > 0;
        },
        rowSelection() {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.incluedSelectedRowKeys = selectedRowKeys;
                    this.incluedSelectedKeys = selectedRows
                },
                selectedRowKeys: this.incluedSelectedRowKeys,
                getCheckboxProps: record => ({
                    props: {
                        disabled: this.excludeSelectedRowKeys?this.excludeSelectedRowKeys.indexOf(record.key)>-1:undefined,  
                        name: record.name,
                        defaultChecked:this.incluedSelectedRowKeys?this.incluedSelectedRowKeys.indexOf(record.key)>-1:undefined,
                    },
                }),
            };
        },
        rowSelection2() {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.excludeSelectedRowKeys = selectedRowKeys;
                    this.excludeSelectedKeys = selectedRows;
                },
                selectedRowKeys: this.excludeSelectedRowKeys,
                getCheckboxProps: record => ({
                    props: {
                        disabled: this.incluedSelectedRowKeys?this.incluedSelectedRowKeys.indexOf(record.key)>-1:undefined, 
                        name: record.name,
                        defaultChecked:this.excludeSelectedRowKeys?this.excludeSelectedRowKeys.indexOf(record.key)>-1:undefined
                    },
                }),
            };
        },
        rowSelectionMin() {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    let index = this.finallyRightTree.findIndex(item => item.key === this.activeKey);
                    this.finallyRightTree[index].incluedSelectedRowKeys = selectedRowKeys;
                    this.finallyRightTree[index].incluedSelectedKeys = selectedRows;
                },
                selectedRowKeys:this.finallyRightTree[this.finallyRightTree.findIndex(item => item.key === this.activeKey)].incluedSelectedRowKeys,
                getCheckboxProps: record => ({
                    props: {
                        disabled: this.finallyRightTree[this.finallyRightTree.findIndex(item => item.key === this.activeKey)].excludeSelectedRowKeys.indexOf(record.key)>-1,  
                        name: record.name,
                        defaultChecked:this.finallyRightTree[this.finallyRightTree.findIndex(item => item.key === this.activeKey)].incluedSelectedRowKeys.indexOf(record.key)>-1
                    },
                }),
            };
        },
        rowSelectionMax() {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    let index = this.finallyRightTree.findIndex(item => item.key === this.activeKey);
                    this.finallyRightTree[index].excludeSelectedRowKeys = selectedRowKeys;
                    this.finallyRightTree[index].excludeSelectedKeys = selectedRows;
                },
                selectedRowKeys:this.finallyRightTree[this.finallyRightTree.findIndex(item => item.key === this.activeKey)].excludeSelectedRowKeys,
                getCheckboxProps: record => ({
                    props: {
                        disabled: this.finallyRightTree[this.finallyRightTree.findIndex(item => item.key === this.activeKey)].incluedSelectedRowKeys.indexOf(record.key)>-1, 
                        name: record.name,
                        defaultChecked:this.finallyRightTree[this.finallyRightTree.findIndex(item => item.key === this.activeKey)].excludeSelectedRowKeys.indexOf(record.key)>-1
                    },
                }),
            };
        },
    },
    created() {
        this.form = this.$form.createForm(this);
    },
    mounted() {
        this.realShow = this.userInfo().realname === '管理员' ? true : false
        if(!this.realShow) {
            getAction('/kuaishou/batch/syncUserAppList',{ userId:this.userInfo().id, type:0}).then(res => {
                if(res.success) {
                    // this.$message.success('更新成功');
                }
            })
        }
        this.handleGetTableList({});
    },
    methods: {
        ...mapGetters(['nickname', 'avatar', 'userInfo']),
        addNewApp() {   
            this.$refs.application.showApplication()
        },
        onSelectExcludePerson(selectedRowKeys, selectedRows) {
            
            let index = this.finallyRightTree.findIndex(item => item.key === this.activeKey);
            this.finallyRightTree[index].incluedSelectedRowKeys = selectedRowKeys;
            this.finallyRightTree[index].incluedSelectedKeys = selectedRows;
        },
        onSelectPerson(selectedRowKeys, selectedRows) {
            let index = this.finallyRightTree.findIndex(item => item.key === this.activeKey);
            this.finallyRightTree[index].excludeSelectedRowKeys = selectedRowKeys;
            this.finallyRightTree[index].excludeSelectedKeys = selectedRows;
        },
        // 自定义人群的改变
        retargetTableChange(pagination, filters, sorter){
            // //console.log(pagination);
        },
        checkPerson(item) {
            if(item.people === '1' || item.people === '2'){
                this.retargetAccountId(item.key);
                item.tabKey = item.people
            }
            else if(item.people === '3'){
                this.retargetAccountId(item.key);
                item.tabKey='1'
            }
            this.$nextTick(() => {
                item.incluedSelectedRowKeys = [];
                item.incluedSelectedKeys = [];
                item.excludeSelectedKeys = [];
                item.excludeSelectedRowKeys = [];
            })
        },
        // 自定义人群的--同时定向排除tab切换事件
        retargetAccountId(accountId){
            //console.log()
            this.retargetDataAll=[];
            this.loading=true;
            
            getAction('/kuaishou/batch/getPopulationList',{
                accountId:accountId
            }).then((res)=>{
                // //console.log(res)
                this.loading=false;
                if(res.success){
                    res.result.forEach((ele)=>{
                        ele.key=ele.orientationId;
                        ele.id= ele.orientationId;
                        ele.name=ele.orientationName+"("+ele.orientationId+")";
                        // ele.accountName=this.accountInfo.title
                        ele.accountId=accountId;      
                    })
                    // this.retargetData=res.data;
                    this.retargetDataAll=[...this.retargetDataAll,...res.result];
                    
                }
            })
        },
        customCrowdChange(e){
            //console.log(e);
            this.incluedSelectedRowKeys = [];
            this.incluedSelectedKeys = [];
            this.excludeSelectedKeys = [];
            this.excludeSelectedRowKeys = [];
            if(e.target.value=='1' || e.target.value=='2'){
                this.retargetTabChange();
                this.tabKey=e.target.value
            }else if(e.target.value=='3'){
                this.retargetTabChange();
                this.tabKey = '1';
            }
            this.$forceUpdate()
        },
        // 自定义人群的--同时定向排除tab切换事件
        retargetTabChange(){
            //console.log()
            this.retargetDataAll=[];
            this.loading=true;
           
            getAction('/kuaishou/batch/getPopulationList',{
                accountId:this.personDetail.accountId
            }).then((res)=>{
                // //console.log(res)
                this.loading=false;
                if(res.success){
                    res.result.forEach((ele)=>{
                        ele.key=ele.orientationId   
                        ele.id= ele.orientationId 
                        ele.name=ele.orientationName+"("+ele.orientationId+")"
                        // ele.accountName=this.accountInfo.title
                        ele.accountId=this.personDetail.accountId           
                    })
                    // this.retargetData=res.data;
                    this.retargetDataAll=[...this.retargetDataAll,...res.result];
                    
                }
            })
        },
        getPeople() {
            var data = ''
            return new Promise((resolve, reject) => {
                getAction('/kuaishou/batch/getPopulationList', { accountId: this.personDetail.accountId }).then((res) => {
                if (res.success) {
                    if (res.result) {
                        this.peopleList = res.result.map((item, index) => {
                            return {
                                ...item,
                                key: index,
                            }
                        })
                        this.dataElse = this.peopleList
                        resolve(res.result)
                    }
                }
                })
            })
        },
        handleCancelPerson() {
            this.personNameVisible = false;
        },
        handleEdit(val){
            // /kuaishouAppPackage/queryById
            this.$refs.editApplication.showApplication(val)
        },
        handleEditPerson(val) {
            this.personNameVisible = true;
            this.relaxVisible = false;
            this.personDetail = val;
            this.personName = val.authName;
            let params = {};
            params.accountId = val.accountId;
            params.templateId = val.templateId;
            this.retargetTabChange()
            getAction('/kuaishouDirectionalPackage/queryPopulationById' ,params).then(res => {
                if(res.success) {
                    this.people = '0';
                    this.retargetAccountId(val.accountId);
                    this.editPerson = res.result;
                    if(res.result.population&&res.result.excludePopulation){
                        this.people = '3';
                    }
                    else if(res.result.population && !res.result.excludePopulation){
                        this.people = '1';
                    }
                    else if(!res.result.population&&!res.result.excludePopulation){
                        this.people = '0';
                    }
                    else{
                        this.people = '2';
                    }
                    this.incluedSelectedRowKeys = res.result.population ? res.result.population : [];
                    this.excludeSelectedRowKeys = res.result.excludePopulation ? res.result.excludePopulation : [];
                    
                }
            })
        },
        handleAddPopulation() {
            this.personLoading = true;
            let params = {};
            params.id = this.personDetail.id;
            params.accountId = this.personDetail.accountId;
            params.templateId = this.personDetail.templateId;
            params.templateName = this.personDetail.templateName;
            if(this.people == '0') {
                params.population = [];
                params.excludePopulation = [];
            }
            else if(this.people == '1') {
                params.population = this.incluedSelectedRowKeys;
                params.excludePopulation = [];
            }
            else if(this.people == '2') {
                params.excludePopulation = this.excludeSelectedRowKeys;
                params.population = [];
            }
            else {
                if(this.incluedSelectedRowKeys.length === 0 || this.excludeSelectedRowKeys.length === 0){
                    this.$message.error("同时定向排除需要定向池与排除池都选择");
                    this.personLoading = false;
                    return
                }
                params.population = this.incluedSelectedRowKeys;
                params.excludePopulation = this.excludeSelectedRowKeys;
            }
            postAction('/kuaishouDirectionalPackage/editPopulation', params).then(res => {
                if(res.success) {
                    this.personLoading = false;
                    this.$message.success('人群包修改成功');
                    this.handleCancelPerson()
                }
                else {
                    this.personLoading = false;
                    this.$message.error(res.message);
                }
            }).catch(error => {

            })


        },
        getTemplateList() {
            this.form.resetFields();
            this.projectId = undefined;
            this.handleGetTableList({});
        },
        handleCauseSizeChange(current, pageSize) {
            this.causePag = {
                page: current,
                size: pageSize
            };
            this.handleCauseTableData();
        },
        handleGetTableList(data) {
            const paramsData = {
                appVersion: data.name,
                appName: data.appName,
                projectId: this.projectId,
                platform: data.status,
                pageNo:  this.ipagination.current,
                pageSize: this.ipagination.pageSize
            };
            this.dataSource = []
            this.dataLoading = true;
            getAction('/kuaishouAppPackage/list', paramsData).then(result => {
                this.dataLoading = false;
                if (result.code === 200) {
                    this.dataSource = result.result.list || [];
                    this.ipagination.total = result.result.total || 0;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                this.dataLoading = false;
                console.log(error, 'eeee');
            });
        },
        handleDelete(data) {
            let that = this
            this.$confirm({
                title: '删除提示',
                content: '是否删除该应用包？',
                onOk() {
                    postAction('/kuaishouAppPackage/delete', {id: data.id}).then(result => {
                        if (result.code === 200) {
                            that.handleGetTableList({});
                            that.$message.success('删除成功');
                        }
                        else {
                            that.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        handleAcountRelax(txt, recd) {
            this.relaxStatus = txt;
            this.relaxData = recd;
            this.relaxVisible = true;
            let url = "";
            let params = {};
            params.id = recd.id;
            params.pageNo = this.accountIpagination.current;
            params.pageSize = this.accountIpagination.pageSize;
            if(txt === 'unit') {
                params.accountId = this.unitAccountId;
                url = "/kuaishouAppPackage/getRelatedGroups"
            }else{
                url = "/kuaishouAppPackage/getRelatedAccounts"
            }
            
            // acountData
            getAction(url, params).then( res => {
                if(res.success) {
                    this.acountData = res.result.page.list;
                    this.accountIpagination.total = res.result.page.total;
                }
            })
        },
        handleRelaxCancel() {
            this.unitAccountId = ''
            this.relaxVisible = false;
        },
        handleCause(list) {
            this.causeVisible = true;
            this.handleCauseTableData(list.id);
            this.tableSelectList = list;
        },
        handleCauseTableData(id) {
            const paramsData = {
                id: id,
                pageNo: this.causePag.page,
                pageSize: this.causePag.size,
                status: this.resultHistory !== 2 ? this.resultHistory : null
            };
            postAction('/kuaishouAppPackage/queryPushHistory', paramsData).then(result => {
                if (result.code === 200) {
                    this.causeData = result.result.list || [];
                    this.totalAllCause = result.result.total || 0;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleApplyType(list) {
            if(list.length > 0) {
                this.finallyRightTree = list.map(item => {
                    return {
                        ...item,
                        incluedSelectedRowKeys: [],
                        incluedSelectedKeys: [],
                        excludeSelectedKeys: [],
                        excludeSelectedRowKeys: [],
                        people: '0',
                        tabKey: '1'
                    }
                });
            }
            else {
                this.finallyRightTree = []
            }
            
        },
        handlePush(val) {
            this.finallyRightTree = [];
            this.tableSelectList = val;
            this.pushVisible = true;
        },
        handleCauseCancel() {
            this.resultHistory = 2;
            this.causeVisible = false;
        },
        handleAgian(val) {
            this.finallyRightTree = [];
            this.finallyRightTree.push({
                key: val.accountId,
                title: val.authName,
            });
            this.causeVisible = false;
            this.resultHistory = 2;
            this.handlePushSure();
        },
        handleSetPerson() {
            this.setPersonLoading = true;
            // this.finallyRightTree
            let params = {};
            params.id = this.tableSelectList.id;
            params.datas = this.finallyRightTree.map(item => {
                return {
                    accountId: item.key,
                    population: item.people === '0' ? []: item.people === '1' || item.people === '3' ? item.incluedSelectedRowKeys : [],
                    excludePopulation: item.people === '0' ? []: item.people === '2' || item.people === '3' ? item.excludeSelectedRowKeys : [],
                }
            })
            postAction('/kuaishouDirectionalPackage/pushDirectionalPackage' ,params).then(res => {
                this.setPersonLoading = false;
                if(res.success) {
                    this.$message.success('推送中，请稍候')
                    this.handlePersonCancel()
                }
                else {
                    this.$message.error(res.result)
                }
            }).catch(error => {

            })
            
        },
        handlePersonCancel() {
            this.setPersonVisible = false;
        },
        handlePushSure() {
            if(this.finallyRightTree.length > 0) {
                this.pushConfirmLoading = true;
                const paramsData = {
                    accountIds: this.finallyRightTree.map(item => item.key),
                    id: this.tableSelectList.id
                };
                postAction('/kuaishouAppPackage/pushAppPackage', paramsData).then(result => {
                   
                    if (result.code === 200) {
                        
                        if(!this.realShow) {
                            getAction('/kuaishou/batch/syncUserPopulationList',{ userId:this.userInfo().id, type:1}).then(res => {
                                if(res.success) {
                                    this.pushConfirmLoading = false;
                                    this.pushVisible = false;
                                    this.handleGetTableList({});
                                    this.$message.success('推送成功')
                                }
                                else {
                                    this.$message.error(res.message)
                                }
                            })
                        }
                        else {
                            this.pushConfirmLoading = false;
                            this.pushVisible = false;
                            this.handleGetTableList({});
                            this.$message.success('推送成功')
                        }
                    }
                    else {
                        this.$message.error(result.message);
                    }
                }).catch(error => {
                    this.pushConfirmLoading = false;
                    console.log(error, 'eeeeeee');
                });
            }
            else {
                this.$message.error("请选择要推送的账户")
            }
           
        },
        handlePushCancel() {
            this.pushVisible = false;
        },
        beforeUpload(file) {
            this.cosUpload(file);
        },
        handleChange(info) {
            this.fileList = info.fileList;
        },
        handleQueryList(event) {
            this.ipagination.current = 1;
            event.preventDefault();
            const paramsData = this.form.getFieldsValue();
            this.handleGetTableList(paramsData);
        },
        handleResetForm() {
            this.ipagination.current = 1;
            this.form.resetFields();
            this.projectId = undefined;
            this.handleGetTableList({});
            this.$refs.selectTable.keyValue = "";
            this.$refs.selectTable.getData()
        },
        handleUpdatePerson() {
            if(this.realShow) {
                this.realLoading = true;
                getAction('/kuaishou/batch/syncUserAppList',{ userId:this.userInfo().id, type:0}).then(res => {
                    if(res.success) {
                        this.$message.success('更新成功');
                        this.realLoading = false;
                        this.handleResetForm();
                    }
                    else {
                        this.realLoading = false;
                        this.$message.error('更新失败');
                    }
                })
            }
        },
    }
};
</script>
<style lang="less" scoped>
    @import "application";
</style>