<style>
#table_time_selected1 tr {
  border: 1px solid rgb(102, 162, 243);
}

.plug-timer-grid th {
  line-height: 25px;
}

.module-form .ant-form-item-required::before {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '';
}
.else-label .ant-form-item-label label::after {
  content: '';
  position: relative;
  top: -0.5px;
  margin: 0 8px 0 2px;
}
</style>
<style scoped>
ul {
  padding-left: 0;
}
li {
  list-style: none;
}
li:hover {
  background: #f2f2f2;
}
</style>
<template>
  <a-form :form="form" class="module-form" @submit="handleSubmit">
    <a-form-item
      label="地区"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
    >
      <a-radio-group @change="regionChange" v-model="allForm.regionType" buttonStyle="solid">
        <a-radio-button value="noLimit">不限</a-radio-button>
        <a-radio-button value="limit">指定地区</a-radio-button>
      </a-radio-group>
      <div v-if="allForm.regionType == 'limit'" style="margin-top:10px">
        <select-region :checkData.sync="allForm.region" :dataValue="allForm.region" />
        <!-- v-model="allForm.region" -->
        <!-- {{ getData('region') }} -->
        <!-- <el-cascader
          ref="cascaderRegion"
          v-decorator="['region', { rules: [{ required: true, message: '请选择地区' }] }]"
          :options="options"
          :props="optionProps"
          clearable
          filterable
          style="width:100%"
          @change="getRegion"
        ></el-cascader> -->
      </div>
    </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-model="allForm.ageType" buttonStyle="solid" @change="ageChange">
        <a-radio-button value="noLimit">不限</a-radio-button>
        <a-radio-button value="ageLimit">限定年龄段</a-radio-button>
        <a-radio-button value="ageCustom">自定义年龄段</a-radio-button>
      </a-radio-group>
      <div v-if="allForm.ageType == 'ageLimit'">
        <!-- v-model="allForm.ages_range" -->
        <a-checkbox-group v-decorator="['ages_range', { rules: [{ required: true, message: '请选择年龄段' }] }]">
          <a-checkbox value="0">0-11岁</a-checkbox>
          <a-checkbox value="12">12-27岁</a-checkbox>
          <a-checkbox value="18">18-23岁</a-checkbox>
          <a-checkbox value="24">24-30岁</a-checkbox>
          <a-checkbox value="31">31-40岁</a-checkbox>
          <a-checkbox value="41">41-49岁</a-checkbox>
          <a-checkbox value="50">50+</a-checkbox>
        </a-checkbox-group>
      </div>
      <div v-if="allForm.ageType == 'ageCustom'">
        <a-slider
          range
          :marks="marks"
          :min="5"
          :max="55"
          v-decorator="[
            'age',
            {
              rules: [{ required: true, message: '请选择年龄段' }, { validator: handleConfirmValue }],
              initialValue: [10, 50]
            }
          ]"
        />
      </div>
    </a-form-item>
    <a-form-item
      label="性别"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
    >
      <a-radio-group
        buttonStyle="solid"
        v-decorator="[
          'gender',
          {
            initialValue: '0'
          }
        ]"
      >
        <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-group>
    </a-form-item>
    <a-form-item
      label="最低版本"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
    >
      <a-radio-group
        buttonStyle="solid"
        v-decorator="[
          'platform_os',
          {
            initialValue: '0'
          }
        ]"
      >
        <a-radio-button value="0" v-if="getApp == '0'">不限</a-radio-button>
        <a-radio-button value="1" v-if="getApp == '0' || getApp == '1'">Android系统</a-radio-button>
        <a-radio-button value="2" v-if="getApp == '0' || getApp == '2'">IOS系统</a-radio-button>
        <div v-if="getData('platform_os') == '1'" style="margin-top:10px">
          <a-radio-group
            v-decorator="[
              'android_osv',
              {
                initialValue: '3'
              }
            ]"
          >
            <a-radio value="3">不限</a-radio>
            <a-radio value="4">4X+</a-radio>
            <a-radio value="5">5x+</a-radio>
            <a-radio value="6">6x+</a-radio>
            <a-radio value="7">7x+</a-radio>
          </a-radio-group>
        </div>
        <div v-if="getData('platform_os') == '2'" style="margin-top:10px">
          <a-radio-group
            v-decorator="[
              'ios_osv',
              {
                initialValue: '6'
              }
            ]"
          >
            <a-radio value="6">不限</a-radio>
            <a-radio value="7">7X+</a-radio>
            <a-radio value="8">8x+</a-radio>
            <a-radio value="9">9x+</a-radio>
            <a-radio value="10">10x+</a-radio>
          </a-radio-group>
        </div>
      </a-radio-group>
    </a-form-item>
    <a-form-item
      v-if="getData('platform_os') != '2'"
      label="设备品牌"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
    >
      <a-radio-group buttonStyle="solid" v-model="allForm.device">
        <a-radio-button value="0">不限</a-radio-button>
        <a-radio-button value="1">选择品牌</a-radio-button>
      </a-radio-group>
      <div v-if="allForm.device == '1'" style="width:120%">
        <a-checkbox-group
          v-decorator="['device_brand', { rules: [{ required: true, message: '请选择设备品牌' }] }]"
          style="width:120%"
        >
          <a-checkbox value="1">OPPO</a-checkbox>
          <a-checkbox value="2">VIVO</a-checkbox>
          <a-checkbox value="3">华为</a-checkbox>
          <a-checkbox value="4">小米</a-checkbox>
          <a-checkbox value="5">荣耀</a-checkbox>
          <a-checkbox value="6">三星</a-checkbox>
          <a-checkbox value="7">金立</a-checkbox>
          <a-checkbox value="8">魅族</a-checkbox>
          <a-checkbox value="9">乐视</a-checkbox>
          <a-checkbox value="10">其他</a-checkbox>
          <a-checkbox value="11" v-if="getData('platform_os') == '0'">苹果</a-checkbox>
        </a-checkbox-group>
      </div>
    </a-form-item>
    <a-form-item
      label="设备价格"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
    >
      <a-radio-group buttonStyle="solid" v-model="allForm.price">
        <a-radio-button value="0">不限</a-radio-button>
        <a-radio-button value="1">选择价格</a-radio-button>
      </a-radio-group>
      <div v-if="allForm.price == '1'" style="width:120%">
        <a-checkbox-group
          v-decorator="['device_price', { rules: [{ required: true, message: '请选择设备价格' }] }]"
          style="width:120%"
        >
          <a-checkbox value="1">1500以下</a-checkbox>
          <a-checkbox value="2">1501~2000</a-checkbox>
          <a-checkbox value="3">2001~2500</a-checkbox>
          <a-checkbox value="4">2501~3000</a-checkbox>
          <a-checkbox value="5">3001~3500</a-checkbox>
          <a-checkbox value="6">3501~4000</a-checkbox>
          <a-checkbox value="7">4001~4500</a-checkbox>
          <a-checkbox value="8">4501~5000</a-checkbox>
          <a-checkbox value="9">5001~5500</a-checkbox>
          <a-checkbox value="10">5500以上</a-checkbox>
        </a-checkbox-group>
      </div>
    </a-form-item>
    <a-form-item
      label="APP行为"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      v-show="getData('platform_os') == '1'"
    >
      <a-radio-group buttonStyle="solid" v-model="allForm.appType" @change="getAppType">
        <a-radio-button value="0">不限</a-radio-button>
        <a-radio-button value="1">按分类</a-radio-button>
        <a-radio-button value="2">按APP名称</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-show="getData('platform_os') == '1' && allForm.appType == '1'"
      class="else-label"
    >
      <a-select
        mode="multiple"
        style="width: 100%"
        optionFilterProp="children"
        showSearch
        :filterOption="filterOption"
        v-decorator="['app_interest', { rules: [{ required: true, message: '请选择APP行为' }] }]"
      >
        <a-select-option v-for="item in optionsAppActive" :key="item.tagId" :value="item.tagId">{{
          item.tagName
        }}</a-select-option>
      </a-select>

      <!-- <el-cascader
        ref="cascader"
        v-decorator="['app_interest', { rules: [{ required: true, message: '请选择分类' }] }]"
        :options="optionsAppActive"
        :props="optionPropsApp"
        clearable
        filterable
        style="width:100%"
      ></el-cascader> -->
    </a-form-item>
    <a-form-item
      label=" "
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      v-if="getData('platform_os') == '1' && allForm.appType == '2'"
      class="else-label"
    >
      <div style="position:relative;" v-clickoutside="handleClose">
        <a-input
          placeholder="请输入搜索内容"
          @change="getAppAll"
          @focus="getAppAll"
          style="width:100%;position:relative;"
        />
        <div
          style="width:100%;position:absolute;z-index:10;height:200px;background:white;overflow:auto;box-shadow: 0 2px 8px 0 rgba(0,0,0,.15);"
          v-if="closeDialog"
        >
          <ul>
            <li style="padding:0 10px">
              <a-checkbox
                style="float:left;margin:0 5px"
                @change="onCheckAllChange"
                :indeterminate="indeterminate"
                :checked="checkAll"
              ></a-checkbox
              >全选
            </li>
            <a-checkbox-group @change="onChange" v-model="checkArr" class="home-card" style="width:100%">
              <li style="padding:0 10px;width:100%;" v-for="item of optionsApp" :key="item.app_id">
                <a-checkbox :value="item.app_id" style="float:left;margin:0 5px"></a-checkbox>{{ item.app_name }}
              </li>
            </a-checkbox-group>
          </ul>
        </div>
        <div style="width:100%" v-if="checkArr.length > 0">
          <a-button @click="clearAll">清空</a-button>
          <br />
          <a-tag v-for="item of checkArr" :key="item" closable :afterClose="() => log(item)">
            {{ showAppName(item) }}
          </a-tag>
        </div>
      </div>
    </a-form-item>
    <a-form-item
      label="商业兴趣"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
    >
      <a-radio-group
        buttonStyle="solid"
        @change="businessInterest"
        v-decorator="[
          'business_interest_type',
          {
            initialValue: '0'
          }
        ]"
      >
        <a-radio-button value="0">不限</a-radio-button>
        <a-radio-button value="2">兴趣标签</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 } }"
      class="else-label"
      v-show="getData('business_interest_type') == '2'"
    >
      <a-select
        mode="multiple"
        style="width: 100%"
        optionFilterProp="children"
        showSearch
        :filterOption="filterOption"
        v-decorator="['business_interest', { rules: [{ required: true, message: '请选择商业兴趣' }] }]"
      >
        <a-select-option v-for="item in businessOptions" :key="item.tagId" :value="item.tagId">{{
          item.tagName
        }}</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item
      label="网络环境"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
    >
      <a-radio-group
        buttonStyle="solid"
        v-decorator="[
          'network',
          {
            initialValue: '0'
          }
        ]"
      >
        <a-radio-button value="0">不限</a-radio-button>
        <a-radio-button value="1">Wi-Fi</a-radio-button>
        <a-radio-button value="2">移动网络</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 } }"
    >
      <a-radio-group buttonStyle="solid" v-model="allForm.fansStar" @change="fansStar">
        <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 } }"
      class="else-label"
      v-if="allForm.fansStar == '1'"
    >
      <a-select
        mode="multiple"
        style="width: 100%"
        optionFilterProp="children"
        showSearch
        :filterOption="filterOption"
        v-decorator="['fans_star', { rules: [{ required: true, message: '请选择网红类别' }] }]"
      >
        <a-select-option v-for="item in fansStarOptions" :key="item.tagId" :value="item.tagId">{{
          item.tagName
        }}</a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item
      label="兴趣视频用户"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
    >
      <a-radio-group buttonStyle="solid" v-model="allForm.interestVideo" @change="interestVideo">
        <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 } }"
      class="else-label"
      v-if="allForm.interestVideo == '1'"
    >
      <a-select
        mode="multiple"
        style="width: 100%"
        optionFilterProp="children"
        showSearch
        :filterOption="filterOption"
        v-decorator="['interest_video', { rules: [{ required: true, message: '请选择视频标签' }] }]"
      >
        <a-select-option v-for="item in interestVideoOptions" :key="item.tagId" :value="item.tagId">{{
          item.tagName
        }}</a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item
      label="智能扩量"
      :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
    >
      <a-radio-group
        buttonStyle="solid"
        v-decorator="[
          'is_open',
          {
            initialValue: '0'
          }
        ]"
        @change="interestVideo"
      >
        <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 } }"
      class="else-label"
      v-if="getData('is_open') == '1'"
    >
      <a-checkbox
        :disabled="allForm.ageType != 'ageCustom'"
        v-decorator="[
          'no_age_break',
          {
            initialValue: false
          }
        ]"
        >不可突破年龄</a-checkbox
      >
      <a-checkbox
        :disabled="getData('gender') == '0'"
        v-decorator="[
          'no_gender_break',
          {
            initialValue: false
          }
        ]"
        >不可突破性别</a-checkbox
      >
      <a-checkbox
        :disabled="allForm.regionType != 'limit'"
        v-decorator="[
          'no_area_break',
          {
            initialValue: false
          }
        ]"
        >不可突破地域</a-checkbox
      >
    </a-form-item>
  </a-form>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import moment from 'moment'
import { mapGetters } from 'vuex'
import jq from 'jquery'

import selectRegion from './selectRegion'
import pick from 'lodash.pick'
let dateQuantumRangeConst = ''
const clickoutside = {
  // 初始化指令
  bind(el, binding, vnode) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e)
      }
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = documentHandler
    document.addEventListener('click', documentHandler)
  },
  update() {},
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.__vueClickOutside__)
    delete el.__vueClickOutside__
  }
}

export default {
  name: 'BaseForm',
  components: { selectRegion },
  props: {
    campaignId: {
      type: String,
      default() {
        return null
      }
    },
    platform: {
      default() {
        return null
      }
    },
    populationData: {}
  },
  watch: {
    platform(n, o) {
      console.log(n, o)
      if (n == 1 || n == 2) {
        // platform_os
        this.form.setFieldsValue({ platform_os: '1' })
      } else if (n == 3 || n == 4) {
        this.form.setFieldsValue({ platform_os: '2' })
      } else {
        this.form.setFieldsValue({ platform_os: '0' })
      }
    }
  },
  directives: { clickoutside },
  data() {
    return {
      form: this.$form.createForm(this),
      marks: {
        5: '5岁',
        10: '10岁',
        15: '15岁',
        20: '20岁',
        25: '25岁',
        30: '30岁',
        35: '35岁',
        40: '40岁',
        45: '45岁',
        50: '50岁',
        55: '55岁'
      },
      step: 0,
      loading: false,
      checkArr: [],
      checkAll: false,
      allForm: {
        regionType: 'noLimit',
        region: [],
        ageType: 'noLimit',
        ages_range: [],
        age: [],
        device: '0',
        price: '0',
        appType: '0',
        fansStar: '0',
        interestVideo: '0'
      },
      options: [],
      optionsAll: [],
      optionProps: {
        value: 'regionId',
        label: 'name',
        children: 'children',
        multiple: true,
        emitPath: false
        // checkStrictly: true
      },
      optionsApp: [],
      optionsAppActive: [],
      checkOptions: [],
      businessOptions: [],
      fansStarOptions: [],
      interestVideoOptions: [],
      optionPropsApp: {
        value: 'tagId',
        label: 'tagName',
        children: 'children',
        multiple: true,
        emitPath: false
      },
      getApp: '0',
      closeDialog: false,
      indeterminate: false,
      checkAll: false
    }
  },
  computed: {},
  methods: {
    getRegion(data) {
      this.$refs.cascaderRegion.getCheckedNodes()
      console.log(this.$refs.cascaderRegion.getCheckedNodes())
      var dataName = this.$refs.cascaderRegion.getCheckedNodes()
      var jsonArr = data
      for (let i = 0; i < dataName.length; i++) {
        for (let j = 0; j < data.length; j++) {
          if (dataName[i].children.length > 0) {
            if (data[j].substring(0, 2) == dataName[i].value) {
              jsonArr.splice(j, 1)
            }
          }
        }
      }
      console.log(jsonArr)
    },
    showAppName(appId) {
      var data = this.checkOptions.filter(item => {
        return item.app_id == appId
      })
      return data[0].app_name
    },
    log(appId) {
      var index = this.checkArr.findIndex(item => item === appId)
      this.checkArr.splice(index, 1)
      if (this.checkArr.length == 0) {
        this.indeterminate = false
        this.checkAll = false
      }
    },
    handleClose(e) {
      this.closeDialog = false
    },
    clearAll() {
      this.checkArr = []
      this.indeterminate = false
      this.checkAll = false
    },
    onChange(checkedList) {
      this.indeterminate =
        !!checkedList.length &&
        checkedList.length <
          this.optionsApp.map(item => {
            return item.app_id
          }).length
      this.checkAll =
        checkedList.length ===
        this.optionsApp.map(item => {
          return item.app_id
        }).length
    },
    onCheckAllChange(e) {
      Object.assign(this, {
        checkArr: e.target.checked
          ? this.optionsApp.map(item => {
              return item.app_id
            })
          : [],
        indeterminate: false,
        checkAll: e.target.checked
      })
      if (this.checkArr.length > 20) {
        this.$message.error('最多选择20个APP行为')
        this.checkArr = []
        this.indeterminate = false
        this.checkAll = false
      }
      //   if (this.checkAll) {
      //     this.checkArr = []
      //   } else {
      //     this.checkArr = this.optionsApp.map(item => {
      //       return item.app_id
      //     })
      //   }
      //   this.checkAll = !this.checkAll
    },
    handleSubmit() {
      //   e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          //   this.checkArr
          var json = {}
          if (this.allForm.appType == '2') {
            json.app_ids = this.checkArr
          }
          if (this.allForm.regionType == 'limit') {
            json.region = this.allForm.region.map(item => {
              return item.value
            })
          }
          var dataJson = {
            ...values,
            ...json,
            no_age_break: values.no_age_break ? 1 : 0,
            no_gender_break: values.no_gender_break ? 1 : 0,
            no_area_break: values.no_area_break ? 1 : 0,
            allForm: this.allForm
          }
          this.$emit('update:populationData', dataJson)
        }
      })
    },
    handleConfirmValue(rule, value, callback) {
      console.log(value)
      if (Math.abs(value[0] - value[1]) < 5) {
        callback('自定义年龄段需要间隔大于5岁')
      }
      callback()
    },
    manyValidator(rule, value, callback) {
      if (value.length > 20) {
        callback('最多只能选择20个选项')
      }
      callback()
    },
    regionChange() {
      this.allForm.region = []
      //   getAction('/kuaishou/batch/getRegion').then(res => {
      //     console.log(res)
      //     this.options = res.result
      //     this.optionsAll = res.result
      //   })
    },
    ageChange() {
      this.allForm.ages_range = []
    },
    search(e) {},
    put() {
      var data = this.allForm.region.map(item => {
        return item[1] + ''
      })
      console.log(data)
      var dataElse = data.map(item => {
        return [item.substring(0, 2), item]
      })
      console.log(dataElse)
    },
    getAppAll(e) {
      console.log(e.target.value)

      if (e.target.value !== '') {
        getAction('/kuaishou/batch/getAppSearch', {
          accountId: localStorage.getItem('accountId'),
          appName: e.target.value
        }).then(res => {
          if (res.result) {
            this.optionsApp = res.result
            this.checkOptions.push(...res.result)
            this.closeDialog = true
          } else {
            this.optionsApp = []
            this.closeDialog = false
          }
        })
      } else {
        this.optionsApp = []
        this.closeDialog = false
      }
    },
    getAppType(e) {
      console.log(e.target.value)
      this.optionsApp = []
      this.form.setFieldsValue({ app_interest: [] })
      this.checkArr = []
      if (e.target.value == '1') {
        getAction('/kuaishou/batch/getTargetList', { tagType: 'APP_INTEREST' }).then(res => {
          console.log(res)
          if (res.success) {
            this.optionsApp = res.result
          }
        })
      }
    },
    businessInterest(e) {
      this.form.setFieldsValue({ business_interest: [] })
      if (e.target.value == '2') {
        this.getDataType('BUSINESS_INTEREST', 'businessOptions')
      }
    },
    fansStar(e) {
      if (e.target.value == '1') {
        this.getDataType('FANS_STAR', 'fansStarOptions')
      }
    },
    interestVideo(e) {
      if (e.target.value == '1') {
        this.getDataType('INTEREST_VIDEO', 'interestVideoOptions')
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    getDataType(type, dataList) {
      getAction('/kuaishou/batch/getTargetList', { tagType: type }).then(res => {
        console.log(res)
        if (res.success) {
          this[dataList] = res.result
        }
      })
    },
    getData(className) {
      return this.form.getFieldValue(className)
    }
  },
  mounted: function() {
    this.getDataType('APP_INTEREST', 'optionsAppActive')
    this.getDataType('BUSINESS_INTEREST', 'businessOptions')
    this.getDataType('FANS_STAR', 'fansStarOptions')
    this.getDataType('INTEREST_VIDEO', 'interestVideoOptions')
    if (this.populationData.allForm) {
      this.allForm = this.populationData.allForm
      this.$nextTick(() => {
        //   setTimeout(() => {
        console.log(this.populationData)
        this.form.setFieldsValue(
          pick(this.populationData, [
            'business_interest_type',
            'fans_star',
            'interest_video',
            'app_interest',
            'platform_os',
            'is_open',
            'gender',
            'network',
            'ages_range',
            'android_osv',
            'device_brand',
            'device_price',
            'no_age_break',
            'no_gender_break',
            'no_area_break',
            'business_interest'
          ])
        )
        //   }, 100)
        //   setTimeout(() => {
        //     console.log(this.populationData)
        //     this.form.setFieldsValue(pick(this.populationData, ['app_interest', 'business_interest']))
        //   }, 100)
      })
    }
  }
}

var box_id
var StartTD = null
var StartIndex = null
var EndTD = null
var EndIndex = null
var Selected = 'Selected'
var Start_x = null
var Start_y = null
//点击中表格的小时值
var hour
//点击选中的星期值
var week
//1为这个格子在此次鼠标拖拽过程中被选中（不执行选中方法），0为没选中过
var td_state = 0
//生成星期数组
var num = ['一', '二', '三', '四', '五', '六', '日']
//生成时间值数组
var arr_hour = get_hour_arr()

//按下鼠标左键拖动选中单元格
function SelectTD(StartIndex, EndIndex, Selected) {
  var MinX = null
  var MaxX = null
  var MinY = null
  var MaxY = null

  var coordinate = get_coordinate(StartIndex, EndIndex)
  MinX = coordinate[0]
  MaxX = coordinate[1]
  MinY = coordinate[2]
  MaxY = coordinate[3]

  for (var i = MinY; i <= MaxY; i++) {
    for (var j = MinX; j <= MaxX; j++) {
      var SelectTR = jq('#' + box_id + ' table tbody tr ').eq(i)
      var td_class = jq('td', SelectTR)
        .eq(j)
        .attr('class')
      td_state = jq('td', SelectTR)
        .eq(j)
        .attr('td_state')

      //在同一次鼠标按下的过程中，选中过的表格不进行选中或取消操作
      if (!td_state) {
        if (td_class == Selected) {
          jq('td', SelectTR)
            .eq(j)
            .removeClass(Selected)
        } else {
          //筛选掉标明为星期的表格
          jq('td', SelectTR)
            .eq(j)
            .attr('class', Selected)
        }
        jq('td', SelectTR)
          .eq(j)
          .attr('td_state', '1')
      }
    }
  }

  //改变二进制值
  get_time_val()
  //改变日期显示
  convert_date()
}

//点击选中或去掉选中整行、整列
function SelectTD_click(StartIndex, EndIndex, Selected) {
  var MinX = null
  var MaxX = null
  var MinY = null
  var MaxY = null
  var Selected_true = 0
  var Selected_false = 0

  var coordinate = get_coordinate(StartIndex, EndIndex)
  MinX = coordinate[0]
  MaxX = coordinate[1]
  MinY = coordinate[2]
  MaxY = coordinate[3]

  //列出此列当中的表格选中状态
  for (var i = MinY; i <= MaxY; i++) {
    for (var j = MinX; j <= MaxX; j++) {
      var SelectTR = jq('#' + box_id + ' table tbody tr ').eq(i)
      var td_class = jq('td', SelectTR)
        .eq(j)
        .attr('class')

      if (td_class == Selected) {
        //表格里存在已选中的元素
        Selected_true = 1
      } else {
        //表格里存在未选中的元素
        Selected_false = 1
      }
    }
  }

  //执行选中或去掉选中方法
  for (var i = MinY; i <= MaxY; i++) {
    for (var j = MinX; j <= MaxX; j++) {
      var SelectTR = jq('#' + box_id + ' table tbody tr ').eq(i)
      var td_class = jq('td', SelectTR)
        .eq(j)
        .attr('class')

      //一列当中存在已选中与未选中的表格处理:整列全部选中
      if (Selected_true == 1 && Selected_false == 1) {
        jq('td', SelectTR)
          .eq(j)
          .attr('class', Selected)
      } else if (Selected_false == 1) {
        //一列当中只存在未选中的表格处理:整列全部选中
        jq('td', SelectTR)
          .eq(j)
          .attr('class', Selected)
      } else {
        //一列当中只存在已选中的表格处理:整列全部去掉选中
        jq('td', SelectTR)
          .eq(j)
          .removeClass(Selected)
      }
    }
  }
  //改变二进制值
  get_time_val()
  //改变日期显示
  convert_date()
}

//获取选中范围的开始与结束的坐标
function get_coordinate(StartIndex, EndIndex) {
  var MinX = null
  var MaxX = null
  var MinY = null
  var MaxY = null

  if (StartIndex.x < EndIndex.x) {
    MinX = StartIndex.x
    MaxX = EndIndex.x
  } else {
    MinX = EndIndex.x
    MaxX = StartIndex.x
  }
  if (StartIndex.y < EndIndex.y) {
    MinY = StartIndex.y
    MaxY = EndIndex.y
  } else {
    MinY = EndIndex.y
    MaxY = StartIndex.y
  }
  return [MinX, MaxX, MinY, MaxY]
}

//改变二进制值
function get_time_val() {
  var time_type = ''
  jq('#' + box_id + ' table tbody')
    .find('td')
    .each(function(k) {
      var Selected_type = jq(this).attr('class')
      var week = jq(this).attr('week')

      if (Selected_type == Selected && !week) {
        time_type += '1'
      } else if (!week) {
        time_type += '0'
      }
    })
  jq('#' + box_id + '_time_num').val(time_type)
  // convert_date();
}

//二进制数转换日期
function convert_date(external_binary) {
  //初始化周数数组
  var time_week_arr = []
  if (!external_binary) {
    //内部调用，进行选中表格和输出时间操作。
    var binary = jq('#' + box_id + '_time_num').val()
  } else {
    //存在外部参入传入，此函数进行返回时间操作。
    var date_html = ''
    var binary = external_binary
  }

  for (var y = 0; y < 7; y++) {
    //初始化小时数组
    var time_hour_arr = []

    for (var x = 0; x < 24; x++) {
      //获取当前点击元素的位置
      if (y == 0) {
        var index = x
      } else {
        var index = y * 24 + x
      }
      //获取td对应的二进制值
      var Selected_val = binary.charAt(index)

      if (Selected_val == 1) {
        //组装保存进数组里
        if (time_hour_arr == []) {
          //表格的第一个位置的值
          time_hour_arr = arr_hour[x]
        } else if (binary.charAt(index - 1) == 1 && binary.charAt(index - 2) == 1) {
          //此位置（包含上一行）的前两个都为选中时

          if (x == 0 && binary.charAt(index + 1) == 0) {
            //选中行里第一个，后一个表格没选中，加逗号
            time_hour_arr[time_hour_arr.length] = arr_hour[x] + ', '
          } else if (x == 0 && binary.charAt(index + 1) == 1) {
            //选中行里第一个，后一个表格已选中，不加逗号
            time_hour_arr[time_hour_arr.length] = arr_hour[x]
          } else if (x == 1 && binary.charAt(index - 1) == 0) {
            //选中行里第二个，上一个表格没选中，加逗号
            time_hour_arr[time_hour_arr.length] = arr_hour[x] + ', '
          } else if (x == 1 && binary.charAt(index - 1) == 1) {
            //选中行里第二个，上一个表格已选中，前加-号，后加逗号
            time_hour_arr[time_hour_arr.length] = '-' + arr_hour[x] + ', '
          } else {
            //选中行里除第一、二的表格以外，前一个表格已经选中，此元素前加- 后加逗号
            time_hour_arr[time_hour_arr.length - 1] = '-' + arr_hour[x] + ', '
          }
        } else if (binary.charAt(index - 1) == 1 && x > 0) {
          //选中的前一个已选中，且此次选中的不是行里第一个，此次选中的元素前加-后加逗号
          time_hour_arr[time_hour_arr.length] = '-' + arr_hour[x] + ', '
        } else if (binary.charAt(index + 1) != 1 || x == 23) {
          //选中的后一个没选中，或者此次选中的是行里最后一个，此次选中的元素加逗号
          time_hour_arr[time_hour_arr.length] = arr_hour[x] + ', '
        } else {
          //选中的后一已选中，此次选中的元素不加逗号
          time_hour_arr[time_hour_arr.length] = arr_hour[x]
        }
      }
    }

    time_week_arr[y] = time_hour_arr
  }
  // console.info(box_id);
  if (!external_binary) {
    jq('#' + box_id + '_time_seled').html('')
  }
  //再次组装并输出数组
  var time_html = []
  for (var y = 0; y < 7; y++) {
    for (var x = 0; x < time_week_arr[y].length; x++) {
      if (!time_html[y]) {
        time_html[y] = time_week_arr[y][x]
      } else {
        time_html[y] += time_week_arr[y][x]
      }
    }

    if (time_html[y]) {
      time_html[y] = time_html[y].substring(0, time_html[y].length - 2)

      if (!external_binary) {
        jq('#' + box_id + '_time_seled').append('<div>星期' + num[y] + ' (' + time_html[y] + ')' + '</div>')
      } else {
        date_html += '星期' + num[y] + ' (' + time_html[y] + ')' + ', '
      }
    }
  }

  if (external_binary) {
    return date_html
  }
  // console.info(time_html);
}

//生成时间值数组
function get_hour_arr() {
  var arr_hour = []
  var oDate = new Date('2016/07/01 00:00:00') //实例一个时间对象；
  var oDate_hour = oDate.getHours()
  var oDate_minute = oDate.getMinutes()
  for (var i = 0; i < 24; i++) {
    if (oDate_minute < 10) {
      var oDate_minute = '0' + oDate_minute
    }
    if (i >= 1) {
      oDate.setMinutes(oDate.getMinutes() + 60)
      oDate_hour = oDate.getHours()
      oDate_minute = oDate.getMinutes()
      if (oDate_minute < 10) {
        var oDate_minute = '0' + oDate_minute
      }
    }
    arr_hour[i] = oDate_hour + ':' + oDate_minute
  }
  return arr_hour
}

//更新操作
function renewal(id) {
  if (id) {
    box_id = id
  }
  //解绑鼠标移动监听事件
  jq('#' + box_id + ' table tbody tr td').unbind('mouseover')
  //初始化表格的在此次选中状态
  jq('#' + box_id + ' table tbody tr td').attr('td_state', '')
  //改变二进制值
  get_time_val()
  //改变日期显示
  convert_date()
}

//二进制数赋值选中表格
function binary_selected() {
  var default_time_val = jq('#' + box_id + ' .default_time_val').val()
  if (default_time_val) {
    for (var i = 0; i < 168; i++) {
      var td_selected = default_time_val.charAt(i)
      if (td_selected != 0) {
        jq('#' + box_id + ' table tbody tr td')
          .eq(i)
          .attr('class', 'Selected')
        //更新操作，显示文字形日期
        renewal()
      }
    }
  }
}

//实例化程序
function load_time_table(id, value) {
  //包住table的元素id
  box_id = id
  var html
  html = '<input type="hidden" class="default_time_val" value="' + value + '"/>'
  html +=
    '<table cellspacing="0" cellpadding="0" border="0" class="plug-timer-grid"  onselectstart="return false" onselect="document.selection.empty()">'
  html += '<thead>'
  html += '<tr>'
  html += '<th></th>'
  html += '<th colSpan="12">上午</th>'
  html += '<th colSpan="12">下午</th>'
  html += '</tr>'
  html += '<tr class="hour">'
  html += '<th></th>'
  html += '</tr>'
  html += '</thead>'
  html += '<tbody></tbody>'
  html += '</table>'
  html += '<input class="focus" type="hidden" style="opacity: 0;">'
  html += '<div id="' + box_id + '_time_seled" style="line-height: 15px;font-size:10px;"></div>'
  html +=
    '<input type="hidden" id="' +
    box_id +
    '_time_num" name="time" caption="每日投放时段" switchname="selectTime"  value="' +
    value +
    '">'
  jq('#' + box_id).html('')
  jq('#' + box_id).append(html)
  var html_tbody_td = ''
  var html_thead_td = ''
  //创建表格
  for (var i = 0; i < 7; i++) {
    var week = i + 1
    html_tbody_td += '<tr>'
    for (var j = 0; j < 25; j++) {
      if (j == 0) {
        html_tbody_td += '<th week="' + week + '">星期' + num[i] + '</th>'
      } else {
        html_tbody_td += '<td>' + '</td>'
      }
    }
    html_tbody_td += '</tr>'
  }

  //创建表格小时栏目
  for (var i = 0; i <= 23; i++) {
    html_thead_td += '<td  hour="' + i + '">' + i + '</td>'
  }
  jq('#' + box_id + ' table thead .hour').append(html_thead_td)
  jq('#' + box_id + ' table tbody').html(html_tbody_td)
  //检查是否有赋有二进制值，如有，将选中相应的表格
  binary_selected()

  //控制器，控制当前在哪个表格进行操作
  jq('.plug-timer-grid').hover(function(e) {
    if (1 != e.which) {
      //判断是否为左击
      var id = jq(this)
        .parent()
        .attr('id')
      box_id = id
    }
  })

  //清除所有选中项
  jq('.clear').click(function() {
    jq(this)
      .parent()
      .find('td')
      .removeClass(Selected)
    var id = jq(this)
      .parent()
      .attr('id')
    renewal(id)
  })

  //点击小时选中或去掉整列处理块
  jq('#' + box_id + ' table thead tr td').click(function() {
    hour = jq(this).attr('hour')
    if (hour >= 0) {
      var rows = jq('#' + box_id + ' table tbody tr').length
      Start_x = jq(this).index() * 2 - 1
      Start_y = 0

      StartIndex = { x: Start_x, y: Start_y }

      EndTD = jq(this)
      var x = jq(this).index() * 2 - 2
      var y = rows - 1 //为了配合for计算公式-1

      EndIndex = { x: x, y: y }
      //改变第一次按下鼠标时候的改变选中状态
      SelectTD_click(StartIndex, EndIndex, Selected)
    }
  })

  //点击星期选中或去掉整行处理块
  jq('#' + box_id + ' table tbody tr th').click(function() {
    var week = jq(this).attr('week')
    if (week >= 0) {
      var line = jq('#' + box_id + ' table tbody tr td').length / jq('#' + box_id + ' table tbody tr').length

      Start_x = 0
      Start_y = jq(this)
        .parent()
        .index()

      StartIndex = { x: Start_x, y: Start_y }

      EndTD = jq(this)
      var y = jq(this)
        .parent()
        .index()
      var x = line - 1 //为了配合for计算公式-1

      EndIndex = { x: x, y: y }

      //改变第一次按下鼠标时候的改变选中状态
      SelectTD_click(StartIndex, EndIndex, Selected)
    }
  })

  //监听鼠标按下事件(鼠标按下左键拖动选中处理块)
  jq('#' + box_id + ' table tbody tr td')
    .unbind('mousedown')
    .bind('mousedown', function() {
      //记录刚开始点击的元素位置
      Start_x = jq(this).index() - 1
      Start_y = jq(this)
        .parent()
        .index()
      StartIndex = { x: Start_x, y: Start_y }

      EndTD = jq(this)
      var x = jq(this).index() - 1
      var y = jq(this)
        .parent()
        .index()
      EndIndex = { x: x, y: y }
      //改变第一次按下鼠标时候的改变选中状态
      SelectTD(StartIndex, EndIndex, Selected)

      StartTD = jq(this)

      StartIndex = { x: Start_x, y: Start_y }

      //监听鼠标移动事件，实现改变后续鼠标拖拽时候的表格选中状态
      jq('#' + box_id + ' table tbody tr td').mouseover(function(e) {
        EndTD = jq(this)
        var x = jq(this).index() - 1
        var y = jq(this)
          .parent()
          .index()
        EndIndex = { x: x, y: y }
        if (1 != e.which) {
          //判断是否为左击
          jq('#' + box_id + ' table tbody tr td').unbind('mouseover')
        }
        //去除停留在td上的光标
        jq('#' + box_id + ' .focus').focus()
        SelectTD(StartIndex, EndIndex, Selected)
      })

      //放开鼠标左键时，初始化相关参数和解绑相关监听
      jq('html')
        .unbind('mouseup')
        .bind('mouseup', function() {
          renewal()
        })
    })
}

/*外部调用接口*/

//解绑鼠标松开监听事件
function unbundle_mouseover() {
  jq('html').unbind('mouseup')
}

/*二进制获取转换后的时间*/
function get_time_html(binary) {
  return convert_date(binary)
}

jq(function() {
  load_time_table('table_time_selected1', this.dateQuantumRange)
})
</script>

<style type="text/css">
.plug-timer-grid {
  width: 100%;
}

.plug-timer-grid td,
.plug-timer-grid th {
  border: 1px solid #97b4d1;
  text-align: center; /*cursor:pointer;*/
  font-size: 10px;
  line-height: 10px;
}

.Selected {
  background-color: rgb(102, 162, 243);
  opacity: 0.5;
}

.plug-timer-grid {
  border-collapse: collapse;
  z-index: 4;
}

.plug-timer-grid thead tr {
  display: table-row;
  vertical-align: inherit;
  border-color: inherit;
}

.group-creat table td {
  height: 20px;
  max-width: 5px;
  border: 1px solid #dfe6ec;
  font-size: 12px;
  text-align: center;
  vertical-align: middle;
  overflow: hidden;
  transition: background 0.5s;
  -webkit-transition: background 0.5s;
}

.plug-timer-grid tbody th {
  width: 4%;
}

.plug-timer-grid tbody tr td {
  width: 2%;
}

/*.clear{*/
/*  margin:20px 0px 20px 0px;*/
/*}*/
</style>
