<style>
.create-campaign .ant-form-item-control {
  line-height: inherit;
}
</style>
<template>
  <a-card :body-style="{ padding: '24px 32px' }" :bordered="false" class="create-campaign">
    <a-form @submit="handleSubmit" :form="form">
      <a-form-item
        label="选择账户"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      >
        <Treeselect :appId.sync="accountIds" request="2,4" ref="treeSelect" style="width: 100%" />
      </a-form-item>
      <a-form-item
        label="推广目的"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      >
        <a-radio-group v-decorator="['type', { initialValue: 2 }]" buttonStyle="solid">
          <!-- <a-radio-button
            v-for="purpose in typeList"
            :key="purpose.itemText"
            :value="purpose.itemValue"
          >{{purpose.itemText}}</a-radio-button> -->
          <a-radio-button :value="2">提升应用安装</a-radio-button>
          <a-radio-button :value="3">获取电商下单</a-radio-button>
          <a-radio-button :value="4">推广品牌活动</a-radio-button>
          <a-radio-button :value="5">收集销售线索</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        label="创建数量"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      >
        <!-- {{ createTotal }} -->
        <a-input-number
          v-decorator="['createTotal', { initialValue: 1 }]"
          :min="1"
          :max="10"
          @change="changeCreateTotal"
        />
      </a-form-item>
      <a-form-item
        label="命名方式"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      >
        <a-radio-group v-decorator="['nameType', { initialValue: 0 }]" buttonStyle="solid" @change="nameTypeChange">
          <a-radio-button :value="0">统一命名</a-radio-button>
          <a-radio-button :value="1">分别命名</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="计划名称"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        v-if="getData('nameType') == 0"
      >
        <!-- campaignName -->

        <a-input
          class="rending"
          placeholder="请输入计划名称"
          v-model="campaignName"
          style="margin-bottom: 20px"
        ></a-input>
        <br />
        <a-tag color="#2db7f5" @click="getChange('项目名称', 0)">项目名称</a-tag>
        <a-tag color="#2db7f5" @click="getChange('计划类型', 0)">计划类型</a-tag>
        <a-tag color="#2db7f5" @click="getChange('日期', 0)">日期</a-tag>
        <a-tag color="#2db7f5" @click="getChange('数值', 0)">数值</a-tag>
      </a-form-item>
      <a-form-item
        label="计划名称"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        v-if="getData('nameType') == 1"
      >
        <!-- campaignName -->
        <!-- @change="callback" -->
        <!-- {{ tabs }} -->
        <a-tabs v-model="active" type="card">
          <a-tab-pane :key="item.accountId" :tab="item.authName" v-for="(item, index) of tabs">
            <div v-for="(items, indexBest) of item.campaignNames" :key="indexBest" style="margin-bottom: 10px">
              <a-input
                class="rending"
                placeholder="请输入计划名称"
                v-model="items.campaignName"
                style="margin-bottom: 10px"
              ></a-input>
              <br />
              <a-tag color="#2db7f5" @click="getChangeAll('项目名称', indexBest, index, items)">项目名称</a-tag>
              <a-tag color="#2db7f5" @click="getChangeAll('计划类型', indexBest, index, items)">计划类型</a-tag>
              <a-tag color="#2db7f5" @click="getChangeAll('日期', indexBest, index, items)">日期</a-tag>
              <a-tag color="#2db7f5" @click="getChangeAll('数值', indexBest, index, items)">数值</a-tag>
            </div>
          </a-tab-pane>
        </a-tabs>
        <!-- <a-input
          class="rending"
          placeholder="请输入计划名称"
          v-model="campaignName"
          style="margin-bottom: 20px"
        ></a-input>
        <br />
        <a-tag color="#2db7f5" @click="getChange('项目名称')">项目名称</a-tag>
        <a-tag color="#2db7f5" @click="getChange('计划类型')">计划类型</a-tag>
        <a-tag color="#2db7f5" @click="getChange('日期')">日期</a-tag>
        <a-tag color="#2db7f5" @click="getChange('数值')">数值</a-tag> -->
      </a-form-item>
      <a-form-item
        label="单日预算"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      >
        <a-radio-group @change="showBudgetStatusChange" v-model="campaignBudget" buttonStyle="solid">
          <a-radio-button value="UNLIMITED">不限</a-radio-button>
          <a-radio-button value="AS_BUDGET">统一预算</a-radio-button>
          <a-radio-button value="DAY_BUDGET">分日预算</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="预算金额"
        v-if="campaignBudget == 'AS_BUDGET'"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      >
        <a-input
          v-decorator="[
            'dayBudget',
            { rules: [{ required: true, message: 'error:' }, { validator: handleConfirmValue }] },
          ]"
          placeholder="不小于500，不超过100000000，仅支持输入自然数"
          type="number"
          style="width: 70%"
        ></a-input
        >元
      </a-form-item>
      <a-form-item
        label="分日预算"
        v-if="campaignBudget == 'DAY_BUDGET'"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
      >
        <!-- <a-input
          v-decorator="[
            'dayBudget',
            { rules: [{ required: true, message: 'error:' }, { validator: handleConfirmValue }] },
          ]"
          placeholder="不小于500，不超过100000000，仅支持输入自然数"
          type="number"
          style="width: 70%"
        ></a-input
        >元 -->
        <a-row>
          <a-col :span="3" v-for="(item, index) of dayBudgetSchedule" :key="index">
            <a-card :title="'周' + numberReturn(index)">
              <a-input-number :min="500" :max="100000000" v-model="item.one" :precision="1" />
            </a-card>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button htmlType="submit" type="primary" :loading="loading">下一步</a-button>
        <!-- <a-button style="margin-left: 8px">保存</a-button> -->
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import { deleteAction, postAction, getAction } from '@/api/manage'
import moment from 'moment'
import { mapActions, mapGetters } from 'vuex'
import Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'
export default {
  name: 'create-campaign',
  components: {
    Treeselect,
  },
  data() {
    return {
      accountIds: [],
      active: null,
      promotionName: '',
      tabs: [],
      dayBudgetSchedule: [{ one: '' }, { one: '' }, { one: '' }, { one: '' }, { one: '' }, { one: '' }, { one: '' }],
      type: '2',
      typeList: {},
      appList: {},
      showBudgetDaily: false,
      campaignName: '',
      campaignBudget: 'UNLIMITED',
      dayBudget: 0,
      appId: '0', //应用目标
      showApp: true,
      redirectUrl: '', // 链接地址
      showRedirect: false,
      urlType: '1',
      showUrlType: false,
      channelType: '1',
      showChannelType: false,
      loading: false,
      form: this.$form.createForm(this),
      url: {
        dictListUrl: 'toutiao/dictitem/list',
        appListUrl: '/kuaishou/kuaiShouCreateAppTemplate/list',
        insertTemplateUrl: '/kuaishou/batch/campaignCreate',
      },
      createTotal: [],
    }
  },
  methods: {
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    numberReturn(num) {
      var arr = ['一', '二', '三', '四', '五', '六', '天']
      return arr[num]
    },
    getCampaignId(campaignId) {
      alert(1)
    },
    changeCreateTotal() {
      this.$nextTick(() => {
        this.createTotal = []
        for (let i = 0; i < this.getData('createTotal'); i++) {
          this.createTotal.push({ campaignName: '' })
        }
      })
    },
    nameTypeChange(e) {
      console.log(e.target.value)
      if (e.target.value == 1) {
        if (this.accountIds.length > 0) {
          postAction('/kuaishou/crossAccount/getAuthName', { accountArr: this.accountIds }).then((res) => {
            if (res.success) {
              this.tabs = res.result.map((item) => {
                return {
                  ...item,
                  campaignNames: JSON.parse(JSON.stringify(this.createTotal)),
                }
              })
              this.active = res.result[0].accountId
            } else {
              this.tabs = []
            }
          })
        }
      } else {
      }
    },
    getChangeAll(name, indexBest, index, items) {
      var node = document.getElementsByClassName('rending')[indexBest + this.getData('createTotal') * index]
      var v = '{{' + name + '}}-'
      if (document.selection) {
        //IE
        node.focus()
        var sel = document.selection.createRange()
        sel.text = v
        sel.select()
        items.campaignName = v
      } else if (node.selectionStart || node.selectionStart == '0') {
        //MOZILLA/GOOGLE
        var startPos = node.selectionStart
        var endPos = node.selectionEnd
        var restoreTop = node.scrollTop
        node.value = node.value.substring(0, startPos) + v + node.value.substring(endPos, node.value.length)
        if (restoreTop > 0) {
          node.scrollTop = restoreTop
        }
        items.campaignName = node.value
        node.focus()
        node.selectionStart = startPos + v.length
        node.selectionEnd = startPos + v.length
        // this.campaignName = node.value
      } else {
        //OTHER
        node.value += v
        console.log(node.value)
        items.campaignName = node.value
        node.focus()
        // this.campaignName = node.value
      }
    },
    getChange(name, index) {
      console.log(index, document.getElementsByClassName('rending'))
      var node = document.getElementsByClassName('rending')[index]
      var v = '{{' + name + '}}-'
      if (document.selection) {
        //IE
        node.focus()
        var sel = document.selection.createRange()
        sel.text = v
        sel.select()
        this.campaignName = v
      } else if (node.selectionStart || node.selectionStart == '0') {
        //MOZILLA/GOOGLE
        var startPos = node.selectionStart
        var endPos = node.selectionEnd
        var restoreTop = node.scrollTop
        node.value = node.value.substring(0, startPos) + v + node.value.substring(endPos, node.value.length)
        if (restoreTop > 0) {
          node.scrollTop = restoreTop
        }
        this.campaignName = node.value
        node.focus()
        node.selectionStart = startPos + v.length
        node.selectionEnd = startPos + v.length
        // this.campaignName = node.value
      } else {
        //OTHER
        node.value += v
        this.campaignName = node.value
        node.focus()
        // this.campaignName = node.value
      }
    },
    handleConfirmValue(rule, value, callback) {
      if (value == '' || value < 500 || value >= 100000000) {
        callback('请输入正确预算金额')
      }
      callback()
    },

    handleConfirmAppId(rule, value, callback) {
      if (this.type == 2 && (this.appId == '0' || this.appId == '')) {
        callback('请选择目标应用')
      }
      callback()
    },

    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true

          let params = {}
          params.type = values.type
          //   params.campaignBudget = this.campaignBudget
          if (this.campaignBudget == 'UNLIMITED') {
            params.dayBudget = 0
          } else if (this.campaignBudget == 'AS_BUDGET') {
            params.dayBudget = values.dayBudget * 1000
          } else {
            params.dayBudgetSchedule = this.dayBudgetSchedule.map((item) => {
              if (item.one == '') {
                return 0
              } else {
                return item.one * 1000
              }
            })
          }
          if (this.getData('nameType') == 0) {
            var dataArr = this.campaignName.split('-')
            if (dataArr[dataArr.length - 1] == '') {
              dataArr.pop()
            }
            params.campaignName = dataArr.join('-')
          } else {
            params.nameArr = this.tabs.map((item) => {
              return {
                accountId: item.accountId,
                campaignNames: item.campaignNames.map((i) => {
                  return i.campaignName
                }),
              }
            })
          }

          params.accountArr = this.accountIds
          params.nameType = values.nameType
          params.createTotal = values.createTotal
          console.log(params)

          postAction('/kuaishou/crossAccount/batchCampaignCreate', params).then((res) => {
            console.log(res)
            if (res.success) {
              this.$message.success('创建成功')
              localStorage.setItem('crossAccountCampaign', JSON.stringify(res.result))
              this.loading = false
              this.$router.replace({ path: '/crossAccount/createUnit' })
              this.$bus.$emit('remove', '/crossAccount/createCampaign')
            } else {
              this.$message.error(res.message)
              this.loading = false
            }
          })
        }
      })
    },
    onChange(value) {
      console.log(value)
    },
    showBudgetStatusChange() {
      if (this.campaignBudget == 'UNLIMITED') {
        this.showBudgetDaily = false
        this.dayBudget = 0
      } else {
        this.showBudgetDaily = true
        this.dayBudget = ''
      }
    },
    typeChange() {
      if (this.type == 2) {
        this.promotionName = '提升应用安装'
        this.showApp = true
        this.showRedirect = false
        this.showUrlType = false
        this.showChannelType = false
      }
      if (this.type == 3) {
        this.promotionName = '获取电商下单'
        this.showApp = false
        this.showRedirect = true
        this.showUrlType = true
        this.showChannelType = false
      }
      if (this.type == 4) {
        this.promotionName = '推广品牌活动'
        this.showApp = false
        this.showRedirect = true
        this.showUrlType = false
        this.showChannelType = false
      }
      if (this.type == 5) {
        this.promotionName = '收集销售线索'
        this.showApp = false
        this.showRedirect = true
        this.showUrlType = false
        this.showChannelType = true
      }
      this.campaignName = this.promotionName + '_' + moment(new Date())
    },
    handleChange(value) {
      console.log(`selected ${value}`)
    },
    handleBlur() {
      console.log('blur')
    },
    handleFocus() {
      console.log('focus')
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    nextStep() {
      this.$emit('nextStep')
    },
    getData(className) {
      return this.form.getFieldValue(className)
    },
  },
  mounted: function () {
    this.$nextTick(() => {
      this.changeCreateTotal()
    })
  },
}
</script>
