<style>
.account-index .ant-card-body .count {
  display: inline-block;
  /* height: 32px; */
  /* line-height: 32px; */
}

/* .account-index .ant-table td {
    white-space: nowrap;
  } */
</style>
<template>
  <div class="account-index">
    <a-row class="image-list-heading vm-panel">
      <a-col :span="24" style="display: flex">
        <Treeselect :appId.sync="appId" :multiple="false" request="2,4" ref="treeSelect" style="margin: 8px 20px" />
        <a-button type="primary" style="margin: 10px" @click="addUser">搜索</a-button>
        <a-button type="primary" style="margin: 10px; float: right" @click="newCreat">批量创建</a-button>
      </a-col>
    </a-row>
    <a-form layout="inline">
      <a-row class="image-list-heading vm-panel" style="padding: 8px 20px">
        <a-col :md="7" :sm="8" style="display: flex">
          <a-form-item label="计划id">
            <a-input placeholder="请输入计划id" v-model="campaignIdSearch"></a-input>
          </a-form-item>
        </a-col>
        <a-col :md="7" :sm="8" style="display: flex">
          <a-form-item label="计划名称">
            <a-input placeholder="请输入计划名称" v-model="campaignName"></a-input>
          </a-form-item>
        </a-col>
        <a-col :md="4" :sm="8" style="display: flex">
          <a-button type="primary" style="margin: 0 10px" @click="searchLabel">查询</a-button>
          <a-button type="primary" style="margin: 0 10px" @click="searchRe">重置</a-button>
        </a-col>
      </a-row>
    </a-form>
    <a-row :gutter="15" style="margin-top: 15px">
      <a-col :span="12">
        <a-card hoverable title="总花费">
          <countTo :startVal="0" :endVal="cost" :duration="duration" :decimals="2" class="count"></countTo>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card hoverable title="余额">
          <countTo :startVal="0" :endVal="balance" :duration="duration" :decimals="2" class="count"></countTo>
        </a-card>
      </a-col>
    </a-row>
    <a-row style="margin-top: 15px">
      <a-card>
        <a-button @click="dianji" style="margin-bottom: 15px">新增广告计划</a-button>
        <div v-show="selectedRowKeys.length > 0">
          请输入修改金额：
          <a-select style="width: 120px" v-model="allPrice">
            <a-select-option value="1">比例</a-select-option>
            <a-select-option value="2">出价</a-select-option>
          </a-select>
          <a-input-number
            :min="-1"
            :step="0.1"
            v-model="allMoneyProportion"
            style="width: 150px"
            @fouse.stop
            v-if="allPrice == '1'"
          />
          <a-input-number :min="0" :step="0.01" v-model="allMoney" style="width: 150px" @fouse.stop v-else />

          <!-- <a-input-number :min="0" :step="0.01" v-model="allMoney" style="width:150px" @fouse.stop /> -->
          <a-button @click="editMoney" style="margin: 0 15px 15px 15px" type="primary" :loading="loadingMoney"
            >修改</a-button
          >

          批量操作：
          <a-select style="width: 120px" v-model="allType">
            <a-select-option value="1">启动</a-select-option>
            <a-select-option value="2">暂停</a-select-option>
            <a-select-option value="3">删除</a-select-option>
          </a-select>
          <a-button @click="editStatus" style="margin: 0 0 15px 15px" type="primary" :loading="loadingState"
            >确认</a-button
          >
        </div>
        <a-modal v-model="visible" title="错误信息" onOk="handleOk" :footer="null">
          <div v-if="visibleData">
            修改条数：{{ visibleData.totalCount }} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;失败条数：{{
              visibleData.failCount
            }}
            <div style="margin-top: 20px">
              <p v-for="(item, index) of visibleData.failInfo" :key="index">
                <span>名称：{{ item.campaignName ? item.campaignName : item.unitName }}</span
                ><br />
                <span>错误信息：{{ item.message }}</span>
              </p>
            </div>
          </div>
        </a-modal>
        <a-table
          size="middle"
          :loading="loadingList"
          :columns="columns"
          :dataSource="dataList"
          bordered
          :scroll="{ x: 2000 }"
          :customRow="rowClick"
          :pagination="ipagination"
          @change="sort"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="campaignName" slot-scope="text, record">
            <div style="display: flex; justify-content: center">
              <a @click="toDetail(record)" class="count" v-show="!record.editName">{{ text }}</a>
              <a-input v-show="record.editName" v-model="record.campaignName" style="width: 150px" @fouse.stop />
              <a-icon
                :type="record.editName ? 'check' : 'edit'"
                @click.stop="editShowName(record)"
                style="margin-left: 10px"
                class="count"
              />
            </div>
          </template>
          <span slot="action" slot-scope="text, record">
            <a-switch v-model="record.showSwich" @change="onChangeSwitch(record)" />
          </span>
          <span slot="actionTwo" slot-scope="text, record">
            <a-popconfirm @confirm="getInfo(record)">
              <div slot="title">
                <div>
                  计划名称:
                  <a-input placeholder="请输入" v-model="refuseReason" style="display: inline-block; width: 500px" />
                </div>
              </div>
              <!-- <a-button slot="okText" type="primary" :disabled="refuseReason == ''">确定</a-button> -->
              <a @click="setData(record)">复制</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a @click="realTimedata(record)">查看实时数据</a>
            <a-divider type="vertical" />
            <a-popconfirm @confirm="getInfo(record, 'allUnit')">
              <div slot="title">
                <div>
                  计划名称:
                  <a-input placeholder="请输入" v-model="refuseReason" style="display: inline-block; width: 500px" />
                </div>
              </div>

              <a @click="setData(record)">复制此计划下所有组</a>
            </a-popconfirm>
          </span>
          <span slot="campaignType" slot-scope="text">
            {{ text | typeStatus }}
          </span>
          <span slot="status" slot-scope="text">
            {{ text | status }}
          </span>
          <span slot="putStatus" slot-scope="text">
            {{ text | putStatus }}
          </span>
          <span slot="createChannel" slot-scope="text">
            {{ text | createChannel }}
          </span>

          <template slot="dayBudget" slot-scope="text, record">
            <div style="display: flex; justify-content: center">
              <span v-show="!record.edit" class="count">{{ text ? (text / 1000).toFixed(2) : '不限制预算' }}</span>
              <a-input-number
                :min="0"
                :step="0.01"
                v-show="record.edit"
                v-model="record.elseMoney"
                style="width: 150px"
                @fouse.stop
              />
              <a-icon
                :type="record.edit ? 'check' : 'edit'"
                @click.stop=";(record.edit = !record.edit), editShow(record)"
                style="margin-left: 10px"
                class="count"
              />
            </div>
          </template>
        </a-table>
      </a-card>
    </a-row>
    <a-modal v-model="jihua" title="广告组选择" @afterClose="clear" :width="900" :maskClosable="false">
      <a-form-item
        label="广告组名称"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
      >
        <a-select
          v-model="unitId"
          style="width: 100%"
          optionFilterProp="children"
          showSearch
          :filterOption="filterOption"
          @change="getUnitData($event)"
        >
          <a-select-option v-for="item in groupList" :key="item.unitId" :value="item.unitId">{{
            item.unitName
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <copyGroup
        ref="copyGroup"
        v-show="unitId != ''"
        @failInfo="failInfoShow"
        :loadingGroup.sync="loadingGroup"
        :jihua.sync="jihua"
      />
      <template slot="footer">
        <a-button key="submit" type="primary" @click="handleSubmit" :loading="loadingGroup"> 确定 </a-button>
      </template>
    </a-modal>
    <a-modal v-model="nameEdit" title="广告计划名称修改" @afterClose="clear" :width="900" :maskClosable="false">
      <a-form-item
        label="广告计划名称"
        :labelCol="{ lg: { span: 4 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
      >
        <a-input placeholder="请输入" v-model="campaignNameEdit" style="display: inline-block" />
      </a-form-item>
      <template slot="footer">
        <a-button key="submit" type="primary" @click="campaignEdit" :loading="loadingCampaign"> 确定 </a-button>
      </template>
    </a-modal>

    <!-- 实时数据 -->
    <a-modal
      v-model="realTimeVisiable"
      title="广告计划实时数据"
      @afterClose="clear"
      width="80%"
      :maskClosable="false"
      :footer="false"
    >
      <div class="optBody">
        <a-range-picker
          :disabled-date="disabledDate"
          format="YYYY-MM-DD"
          style="width: 250px"
          @change="dateValueChange"
          v-model="dateValue"
        />
      </div>
      <div class="tableBox" style="margin-top: 20px; min-height: 400px">
        <a-table
          size="middle"
          :columns="realTimeColumn"
          :dataSource="realTimeData"
          bordered
          :pagination="false"
          :scroll="{ x: scrollX }"
          :loading="realTimeLoading"
          ref="accountTable"
          style="word-break: break-all"
        >
          <span slot="ctr" slot-scope="text">{{ text | toPercentage }}</span>
          <span slot="action_ratio" slot-scope="text">{{ text | toPercentage }}</span>
          <span slot="photo_click_ratio" slot-scope="text">{{ text | toPercentage }}</span>

          <span slot="charge" slot-scope="text">{{ text | decimalsHandle }}</span>
          <span slot="activationCost" slot-scope="text, records">{{
            (records.activation / records.charge) | decimalsHandle
          }}</span>
          <span slot="event_register_cost" slot-scope="text">{{ text | decimalsHandle }}</span>
          <span slot="form_cost" slot-scope="text">{{ text | decimalsHandle }}</span>
          <span slot="event_order_paid_cost" slot-scope="text">{{ text | decimalsHandle }}</span>

          <span slot="show" slot-scope="text">{{ text | formatCurrency }}</span>
          <span slot="photo_click" slot-scope="text">{{ text | formatCurrency }}</span>
          <span slot="aclick" slot-scope="text">{{ text | formatCurrency }}</span>
          <span slot="bclick" slot-scope="text">{{ text | formatCurrency }}</span>
          <span slot="activation" slot-scope="text">{{ text | formatCurrency }}</span>
          <span slot="event_register" slot-scope="text">{{ text | formatCurrency }}</span>
          <span slot="form_count" slot-scope="text">{{ text | formatCurrency }}</span>
          <span slot="event_order_paid" slot-scope="text">{{ text | formatCurrency }}</span>
        </a-table>
      </div>
    </a-modal>

    <a-modal v-model="allUnitCopy" title="复制计划下所有组" width="80%" :maskClosable="false">
      <a-form-item
        label="是否修改定向与出价"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
      >
        <a-radio-group buttonStyle="solid" v-model="editUnit" @change="editUnitType">
          <a-radio-button value="1">是</a-radio-button>
          <a-radio-button value="2">否</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <copyAllUnit ref="copyAllUnit" v-if="editUnit == '1'" @getUnitData="getUnitDataAll" />
      <template slot="footer">
        <a-button key="submit" type="primary" @click="handleEditAllUnit"> 确定 </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import ARow from 'ant-design-vue/es/grid/Row'
import ACol from 'ant-design-vue/es/grid/Col'
import moment from 'moment'
import countTo from 'vue-count-to'
import { mapGetters } from 'vuex'
import { deleteAction, getAction, postAction } from '@/api/manage'

import Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'

import copyGroup from './copyGroup'
import copyAllUnit from './copyAllUnit'
var columns = [
  {
    title: '开关',
    align: 'center',
    dataIndex: 'action',
    fixed: 'left',
    width: 100,
    scopedSlots: {
      customRender: 'action',
    },
  },
  {
    title: '广告计划名称',
    align: 'center',
    dataIndex: 'campaignName',
    fixed: 'left',
    width: 300,
    scopedSlots: {
      customRender: 'campaignName',
    },
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'actionTwo',
    fixed: 'left',
    width: 300,
    scopedSlots: {
      customRender: 'actionTwo',
    },
  },
  {
    title: '计划单日预算金额',
    align: 'center',
    dataIndex: 'dayBudget',
    scopedSlots: {
      customRender: 'dayBudget',
    },
    width: 200,
  },
  {
    title: '计划状态',
    align: 'center',
    dataIndex: 'status',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '计划类型',
    align: 'center',
    dataIndex: 'campaignType',
    scopedSlots: {
      customRender: 'campaignType',
    },
  },

  {
    title: '渠道',
    align: 'center',
    dataIndex: 'createChannel',
    filters: [
      {
        text: '投放后台创建',
        value: '0',
      },
      {
        text: '汇创助手创建',
        value: '1',
      },
    ],
    onFilter: (value, record) => record.createChannel.toString().toLowerCase().includes(value.toLowerCase()),
    scopedSlots: {
      customRender: 'createChannel',
    },
  },
  {
    title: '投放状态',
    align: 'center',
    dataIndex: 'putStatus',
    scopedSlots: {
      customRender: 'putStatus',
    },
    filters: [
      {
        text: '投放中',
        value: '1',
      },
      {
        text: '暂停',
        value: '2',
      },
    ],
    onFilter: (value, record) => record.putStatus.toString().toLowerCase().includes(value.toLowerCase()),
  },
  {
    title: '创建时间',
    align: 'center',
    dataIndex: 'putCreateTime',
  },
  {
    title: '更新时间',
    align: 'center',
    dataIndex: 'putUpdateTime',
  },
]

let realTimeColumn = [
  {
    title: '广告计划名称',
    align: 'center',
    dataIndex: 'campaignName',
    fixed: 'left',
    width: 300,
    scopedSlots: {
      customRender: 'campaignName',
    },
  },
  {
    title: '时间',
    align: 'center',
    dataIndex: 'stat_date',
    fixed: 'left',
    width: 200,
    scopedSlots: {
      customRender: 'stat_date',
    },
  },
  {
    title: '消耗',
    align: 'center',
    dataIndex: 'charge',
    scopedSlots: { customRender: 'charge' },
  },
  {
    title: '封面曝光数',
    align: 'center',
    dataIndex: 'show',
    scopedSlots: { customRender: 'show' },
  },
  {
    title: '封面点击数',
    align: 'center',
    dataIndex: 'photo_click',
    scopedSlots: { customRender: 'photo_click' },
  },
  {
    title: '素材曝光数',
    align: 'center',
    dataIndex: 'aclick',
    scopedSlots: { customRender: 'aclick' },
  },
  {
    title: '行为数',
    align: 'center',
    dataIndex: 'bclick',
    scopedSlots: { customRender: 'bclick' },
  },
  {
    title: '行为率',
    align: 'center',
    dataIndex: 'action_ratio',
    scopedSlots: { customRender: 'action_ratio' },
  },
  {
    title: '封面点击率',
    align: 'center',
    dataIndex: 'photo_click_ratio',
    scopedSlots: { customRender: 'photo_click_ratio' },
  },
  {
    title: '激活数',
    align: 'center',
    dataIndex: 'activation',
    scopedSlots: { customRender: 'activation' },
  },
  {
    title: '激活成本',
    align: 'center',
    dataIndex: 'activationCost',
    scopedSlots: { customRender: 'activationCost' },
  },
  {
    title: '注册数',
    align: 'center',
    dataIndex: 'event_register',
    scopedSlots: { customRender: 'event_register' },
  },
  {
    title: '注册成本',
    align: 'center',
    dataIndex: 'event_register_cost',
    scopedSlots: { customRender: 'event_register_cost' },
  },
  {
    title: '表单提交数',
    align: 'center',
    dataIndex: 'form_count',
    scopedSlots: { customRender: 'form_count' },
  },
  {
    title: '表单提交单价',
    align: 'center',
    dataIndex: 'form_cost',
    scopedSlots: { customRender: 'form_cost' },
  },
  {
    title: '付费数',
    align: 'center',
    dataIndex: 'event_order_paid',
    scopedSlots: { customRender: 'event_order_paid' },
  },
  {
    title: '付费成本',
    align: 'center',
    dataIndex: 'event_order_paid_cost',
    scopedSlots: { customRender: 'event_order_paid_cost' },
  },
]

export default {
  name: 'account-statistics',
  components: {
    ACol,
    ARow,
    countTo,
    Treeselect,
    copyGroup,
    copyAllUnit,
  },
  data: function () {
    return {
      // 实时数据
      editUnit: '2',
      allUnitCopy: false,
      realTimeVisiable: false,
      realTimeColumn,
      realTimeData: [],
      scrollX: 2500,
      realTimeLoading: false,
      dateValue: [moment(), moment()],
      realTimeRecords: {},

      // 实时数据

      loadingMoney: false,
      loadingState: false,
      nameEdit: false,
      campaignIdSearch: '',
      loadingList: false,
      form: this.$form.createForm(this),
      jihua: false,
      refuseReason: '',
      visibleEdit: false,
      loadingGroup: false,
      allType: '1',
      duration: 1000,
      showEdit: false,
      many: 0,
      manyTwo: 0,
      cost: 0,
      balance: 0,
      columns,
      dataList: [],
      groupList: [],
      appId: '',
      planId: '',
      selectedRowKeys: [],
      selectedRowKeysValue: [],
      allMoney: null,
      allPrice: '1',
      allMoneyProportion: 1.2,
      visible: false,
      visibleData: null,
      rowClick: (record, index) => ({
        // 事件
        on: {
          dblclick: () => {},
        },
      }),
      ipagination: {
        current: 1,
        pageSize: 10,
        //   pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '30', '50'],
        total: 0,
        onChange: (current, pageSize) => {
          // 切换分页时的回调，
          // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
          this.ipagination.current = current
          this.ipagination.pageSize = pageSize
          // if (this.campaignId == '' && this.campaignName == '') {
          //   this.addUser()
          // } else {
          //   var params = {}
          //   params.accountId = this.appId + ''
          //   params.pageNo = this.ipagination.current
          //   params.pageSize = this.ipagination.pageSize
          //   params.campaignId = this.campaignId
          //   params.campaignName = this.campaignName
          //   this.getCampaignList(params)
          // }
        },
        total: 0,
      },
      url: {},
      type: '',
      campaignName: '',
      campaignNameEdit: '',
      loadingCampaign: false,
      campaignIdEdit: '',
      campaignBudget: 'UNLIMITED',
      unitId: '',
      campaignId: '',
      oldCampaignId: '',
      oldCampaignName: '',
      newCampaignId: '',
      campaignType: '',
    }
  },
  filters: {
    typeStatus(type) {
      // 2 - 提升应用安装;
      // 3 - 获取电商下单;
      // 4 - 推广品牌活动;
      // 5 - 收集销售线索;
      var data = ['', '', '提升应用安装', '获取电商下单', '推广品牌活动', '收集销售线索', '', '提高应用活跃']
      return data[type]
    },
    status(sta) {
      var data = {
        '-1': '不限',
        1: '已暂停',
        3: '计划超预算',
        4: '有效',
        6: '余额不足',
      }
      return data[sta]
    },
    putStatus(sta) {
      var data = {
        1: '投放中',
        2: '暂停',
      }
      return data[sta]
    },
    createChannel(sta) {
      var data = {
        0: '投放后台',
        1: '汇创助手',
      }
      return data[sta]
    },

    toPercentage(val) {
      if (val) {
        if (typeof val != 'string') {
          return (val * 100).toFixed(2) + '%'
        } else {
          return val
        }
      } else if (typeof val == 'string') {
        return val
      } else {
        return 0
      }
    },
    //保留两位小数并且变成货币格式
    decimalsHandle(val) {
      if (val && typeof val != 'string') {
        if (val >= 0) {
          val = parseFloat(val).toFixed(2)
          let numberStr = val.toString()
          let str = numberStr.split('.')

          let str0 = str[0].split('').reverse()
          for (let i = 0; i < str0.length; i++) {
            if ((i + 1) % 4 === 0) {
              str0.splice(i, 0, ',')
            }
          }
          str0.reverse()
          let handleResult = ''
          for (let j = 0; j < str0.length; j++) {
            handleResult += str0[j]
          }

          return handleResult + '.' + str[1]
        } else {
          val = parseFloat(val).toFixed(2)
          let numberStr = val.toString()
          let str = numberStr.split('.')

          let str0 = str[0].substr(1).split('').reverse()
          for (let i = 0; i < str0.length; i++) {
            if ((i + 1) % 4 === 0) {
              str0.splice(i, 0, ',')
            }
          }
          str0.reverse()
          let handleResult = ''
          for (let j = 0; j < str0.length; j++) {
            handleResult += str0[j]
          }

          return '-' + handleResult + '.' + str[1]
        }
      } else if (typeof val == 'string') {
        return val
      } else {
        return 0
      }
    },
    //变成货币格式
    formatCurrency(val) {
      if ((val || val == 0) && typeof val != 'string') {
        let numberStr = val.toString()
        let str = numberStr.split('').reverse()
        for (let i = 0; i < str.length; i++) {
          if ((i + 1) % 4 === 0) {
            str.splice(i, 0, ',')
          }
        }
        str.reverse()
        let handleResult = ''
        for (let j = 0; j < str.length; j++) {
          handleResult += str[j]
        }
        return handleResult
      } else if (typeof val == 'string') {
        return val
      } else {
        return '-'
      }
    },
  },
  methods: {
    newCreat() {
      if (this.appId) {
        window.open('/user/new-batch?accountId=' + this.appId, '_blank')
      } else {
        window.open('/user/new-batch', '_blank')
      }
    },
    disabledDate(current) {
      // console.log(current)
      return (current && current > moment()) || (current && current < moment().subtract(7, 'days'))
    },
    // 查看实时数据
    realTimedata(records) {
      this.realTimeRecords = records
      this.realTimeVisiable = true
      this.realTimeHttp()
    },
    dateValueChange(date, dateString) {
      this.realTimeHttp()
    },
    // 获取实时数据请求
    realTimeHttp() {
      this.realTimeLoading = true
      postAction('/kuaishou/realTime/getCampaignDate', {
        accountId: this.realTimeRecords.accountId,
        campaignId: this.realTimeRecords.campaignId,
        startDate: this.dateValue[0].format('YYYY-MM-DD'),
        endDate: this.dateValue[1].format('YYYY-MM-DD'),
      }).then((res) => {
        this.realTimeData = []
        this.realTimeLoading = false
        if (res.success) {
          if (res.result) {
            res.result.forEach((item) => {
              item.campaignName = this.realTimeRecords.campaignName
            })
            this.realTimeData = res.result
          }
        }
      })
    },
    sort(pagination, filters, sorter, { currentDataSource }) {
      this.ipagination.current = pagination.current

      this.ipagination.pageSize = pagination.pageSize
      // this.search()
      if (this.campaignId == '' && this.campaignName == '') {
        this.addUser()
      } else {
        var params = {}
        params.accountId = this.appId + ''
        params.pageNo = this.ipagination.current
        params.pageSize = this.ipagination.pageSize
        params.campaignId = this.campaignId
        params.campaignName = this.campaignName
        this.getCampaignList(params)
      }
    },
    failInfoShow(item) {
      if (item) {
        this.visible = true
        this.visibleData = item
      } else {
        this.$message.success('创建成功')
        this.addUser()
      }
    },
    handleOkEdit(e) {},
    clear() {
      this.unitId = ''
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    getUnitData(e) {
      var params = {
        accountId: this.appId,
        unitId: this.unitId,
        campaignId: this.campaignId,
        planId: this.planId,
      }
      localStorage.setItem('advertisingGroupKey', this.campaignId)
      this.$refs.copyGroup.handleOk(params)
      //   handleSubmit
    },
    editUnitType() {
      if (this.editUnit == '2') {
      } else {
        var params = {
          accountId: this.appId,
          oldCampaignId: this.oldCampaignId,
          oldCampaignName: this.oldCampaignName,
          newCampaignId: this.newCampaignId,
          campaignType: this.campaignType,
        }
        this.$nextTick(() => {
          this.$refs.copyAllUnit.handleOk(params)
        })
      }
    },
    getUnitDataAll() {
      this.addUser()
      this.allUnitCopy = false
      this.editUnit = '2'
      this.$message.success('复制成功，异步创建中，请稍后')
    },
    handleEditAllUnit(e) {
      if (this.editUnit == '1') {
        this.$nextTick(() => {
          this.$refs.copyAllUnit.handleSubmit(e)
        })
      } else {
        postAction('/kuaishouCampaignCopyData/add', {
          accountId: this.appId,
          oldCampaignId: this.oldCampaignId,
          oldCampaignName: this.oldCampaignName,
          newCampaignId: this.newCampaignId,
        }).then((res) => {
          if (res.success) {
            this.addUser()
            this.allUnitCopy = false
            this.$message.success(res.message)
          } else {
            this.allUnitCopy = false
            this.$message.error(res.message)
          }
        })
      }
    },
    handleSubmit(e) {
      if (this.unitId) {
        this.$refs.copyGroup.handleSubmit(e)
      } else {
        this.$message.error('请选择广告组后操作')
      }
    },
    toDetail(record) {
      localStorage.setItem('advertisingGroupKey', record.campaignId)
      localStorage.setItem('accountId', this.appId)

      getAction('/kuaishou/batch/getAsyncCreativeList', {
        campaignId: record.campaignId,
        accountId: this.appId,
      }).then(() => {
        localStorage.setItem('campaignId', record.campaignId)
        if (localStorage.getItem('advertisingGroup')) {
          var dataElse = JSON.parse(localStorage.getItem('advertisingGroup'))

          for (let i = 0; i < dataElse.length; i++) {
            if (dataElse[i].key == record.key) {
              this.$router.replace({
                path: '/account/advertisingGroup',
              })
              return
            }
          }
          dataElse.push(record)
          localStorage.setItem('advertisingGroup', JSON.stringify(dataElse))
        } else {
          var data = [record]
          localStorage.setItem('advertisingGroup', JSON.stringify(data))
        }
        this.$router.replace({
          path: '/account/advertisingGroup',
        })
      })
    },
    setData(item) {
      let date = new Date()
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      this.refuseReason = item.campaignName + '-' + y + '/' + MM + '/' + d
    },
    getInfo(item, type) {
      this.editUnit == '2'
      if (this.refuseReason == '') {
        this.$message.error('请输入计划名称')
        return
      } else {
        let params = {}
        params.type = item.campaignType
        //   params.campaignBudget = this.campaignBudget
        params.dayBudget = item.dayBudget
        params.campaignName = this.refuseReason
        params.accountId = this.appId + ''
        postAction('/kuaishou/batch/campaignCreate', params).then((res) => {
          if (res.success) {
            if (type) {
              this.allUnitCopy = true
              this.oldCampaignId = item.campaignId
              this.oldCampaignName = item.campaignName
              this.newCampaignId = res.result
              this.campaignType = item.campaignType
            } else {
              this.jihua = true
              this.loadingGroup = false
              this.refuseReason = ''
              this.unitId = ''
              // 7156834
              this.planId = res.result
              this.campaignId = item.campaignId
              this.getDataList(item.campaignId)
              this.addUser()
            }
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    onChangeSwitch(item) {
      var params = {}
      params.accountId = this.appId + ''
      params.putStatus = item.showSwich ? 1 : 2
      params.userId = this.userInfo().id
      params.campaignIds = [item.campaignId]
      postAction('/kuaishou/batch/batchUpdateStatus', params).then((res) => {})
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    searchLabel() {
      this.ipagination.current = 1
      if (this.appId) {
        var params = {}
        params.accountId = this.appId + ''
        params.pageNo = this.ipagination.current
        params.pageSize = this.ipagination.pageSize
        params.campaignId = this.campaignIdSearch
        params.campaignName = this.campaignName
        this.getCampaignList(params)
      } else {
        this.$message.error('请选择账户')
      }
    },
    searchRe() {
      this.campaignIdSearch = ''
      this.campaignName = ''
      this.ipagination.current = 1
      this.searchLabel()
    },
    addUser() {
      this.loading = true
      this.dataList = []
      var params = {}
      params.accountId = this.appId + ''
      params.pageNo = this.ipagination.current
      params.pageSize = this.ipagination.pageSize
      if (this.appId) {
        this.getSpend(params)
        this.getCampaignList(params)
        localStorage.setItem('accountId', this.appId)
      } else {
        this.$message.error('请选择账户')
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRowKeysValue = selectionRows.map((item) => {
        return item.campaignId
      })
      //    this.selectedRowKeysValue.length > 0 ? this.selectedRowKeysValue :
    },
    editStatus() {
      this.loadingState = true
      var params = {}
      params.accountId = this.appId + ''
      params.putStatus = this.allType
      params.userId = this.userInfo().id
      params.campaignIds = this.selectedRowKeysValue
      postAction('/kuaishou/batch/batchUpdateStatus', params).then((res) => {
        if (res.success) {
          this.addUser()
          this.selectedRowKeysValue = []
          this.selectedRowKeys = []
          this.loadingState = false
        } else {
          this.loadingState = false
        }
      })
    },
    editMoney() {
      this.loadingMoney = true
      if (this.allPrice == '1') {
        var params = {}
        params.accountId = this.appId + ''
        params.proportion = this.allMoneyProportion
        params.userId = this.userInfo().id
        params.campaignIds = this.selectedRowKeysValue
        postAction('/kuaishou/batch/batchUpdateDayBudgetByProportion', params).then((res) => {
          if (res.success) {
            if (res.result.failCount > 0) {
              this.visible = true
              this.visibleData = res.result
              this.addUser()
              this.loadingMoney = false
            } else {
              this.addUser()
              this.selectedRowKeysValue = []
              this.selectedRowKeys = []
              this.loadingMoney = false
            }
          } else {
            this.$message.error(res.message)
            this.loadingMoney = false
          }
        })
      } else if (this.allPrice == '2') {
        var params = {}
        params.accountId = this.appId + ''
        params.dayBudget = this.allMoney * 1000
        params.userId = this.userInfo().id
        params.campaignIds = this.selectedRowKeysValue
        postAction('/kuaishou/batch/batchUpdateDayBudget', params).then((res) => {
          if (res.success) {
            if (res.result.failCount > 0) {
              this.visible = true
              this.visibleData = res.result
              this.addUser()
              this.loadingMoney = false
            } else {
              this.addUser()
              this.selectedRowKeysValue = []
              this.selectedRowKeys = []
              this.loadingMoney = false
            }
          } else {
            this.$message.error(res.message)
            this.loadingMoney = false
          }
        })
      }
    },
    getCampaignList(params) {
      this.loadingList = true
      getAction('/kuaishou/batch/getCampaignList', params).then((res) => {
        if (res.code == 0) {
          this.loadingList = false
          this.dataList = res.result.records.map((v, index) => {
            return {
              ...v,
              key: index,
              edit: false,
              editName: false,
              showSwich: v.putStatus == 1 ? true : false,
            }
          })
          this.ipagination.total = res.result.total
        } else {
          this.loadingList = false
          this.$message.error(res.message)
        }
      })
    },
    getSpend(item) {
      getAction('/kuaishou/batch/spend', {
        accountId: item.accountId,
      }).then((res) => {
        if (res.success) {
          this.many = res.result.budget
          this.manyTwo = res.result.budget
          this.cost = res.result.cost
          this.balance = res.result.balance
        } else {
          this.$message.error(res.message)
        }
      })
    },
    show() {
      if (!this.showEdit) {
        this.many = this.manyTwo
      } else {
        this.manyTwo = this.many
      }
    },
    editShow(item) {
      if (!item.edit) {
        if (item.elseMoney < 500 || item.elseMoney > 100000000) {
          this.$message.error('请输入大于500并且小于100000000的预算')
          return
        } else {
          item.dayBudget = item.elseMoney * 1000
          var params = {}
          params.accountId = this.appId + ''
          params.dayBudget = item.elseMoney * 1000
          params.userId = this.userInfo().id
          params.campaignIds = [item.campaignId]
          postAction('/kuaishou/batch/batchUpdateDayBudget', params).then((res) => {
            if (res.result.failCount > 0) {
              this.$message.error(
                '广告计划：' +
                  res.result.failInfo[0].campaignName +
                  '          ' +
                  '错误：' +
                  res.result.failInfo[0].message
              )
            }
          })
        }
      } else {
        item.elseMoney = item.dayBudget / 1000
      }
    },
    campaignEdit(e) {
      this.loadingCampaign = true
      var params = {}
      params.accountId = this.appId + ''
      params.campaignId = this.campaignIdEdit
      params.campaignName = this.campaignNameEdit
      postAction('/kuaishou/batch/updateCampaign', params).then((res) => {
        if (res.result.code == 0) {
          this.loadingCampaign = false
          this.nameEdit = false
          this.$message.success('修改成功')
          this.addUser()
        } else {
          this.loadingCampaign = false
          this.$message.error(res.result.message)
        }
      })
    },
    editShowName(item) {
      this.nameEdit = true
      this.campaignNameEdit = item.campaignName
      this.campaignIdEdit = item.campaignId
    },
    dianji() {
      if (this.appId == '') {
        this.$message.error('尚未选择需要创建的账户')
      } else {
        localStorage.setItem('accountId', this.appId)
        if (localStorage.getItem('step')) {
          this.$message.error('正在进行广告组创建,请关闭创建页面后,重新进行创建')
          return
        } else {
          localStorage.setItem('step', 0)
          this.$router.replace({
            path: '/account/stepForm',
          })
        }
      }
    },
    getDataList(id) {
      this.groupList = []
      var params = {}
      params.campaignId = id
      params.accountId = this.appId
      params.pageNo = 1
      params.pageSize = 1000
      getAction('/kuaishou/batch/getUnitList', params).then((res) => {
        if (res.success) {
          this.groupList = res.result.records
        }
      })
    },
  },
  watch: {
    allUnitCopy: function (n, o) {
      if (!n) {
        this.editUnit = '2'
      }
    },
  },

  computed: {},
  activated() {
    this.manyTwo = this.many
    // this.$refs.treeSelect.getParticipateList()
    if (this.appId == '') {
      return
    } else {
      this.searchLabel()
    }
  },
}
</script>