<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 buttonStyle="solid" v-model="people" @change="getPeople">
        <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-group>
    </a-form-item>
    <a-form-item v-if="people == '3'" label="定向逻辑" :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }">
      <a-radio-group buttonStyle="solid" v-model="targeted" @change="radioChange">
        <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-group>
      <div :style="{
          border: targeted == '4' ? '1px solid #f2f2f2' : '0',
          padding: targeted == '4' ? '20px' : '0'
        }">
        <div style="display:flex;margin-top:15px" v-if="targeted == '4' || targeted == '2'">
          <span style="white-space:nowrap;width:10%" v-if="targeted == '4'">定向池：</span>
          <a-input placeholder="请至少选择一个自定义人群" @focus="
              topMiddle = true
              topMiddleNo = false
            " v-model="keyValue" />
        </div>

        <div style="background:white;padding:10px;box-shadow: 0 2px 8px 0 rgba(0,0,0,.15);"
          :style="{ width: targeted == '4' ? '90%' : '100%', marginLeft: targeted == '4' ? '10%' : '0' }"
          v-show="topMiddle">
          <a-table :columns="columns" :dataSource="dataList" bordered :pagination="false" :scroll="{ y: 300,x:true }"
            :rowSelection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
              getCheckboxProps: getCheckboxProps
            }">
            <span slot="orientationName" slot-scope="text, record">{{ text }}({{ record.orientationId }})</span>
            <span slot="populationType" slot-scope="text">{{ text | population_type }}</span>
            <span slot="putTime" slot-scope="text">{{ text | getDate }}</span>
          </a-table>
          <div style="text-align:right">
            <a-button style="margin-right:5px" @click="topMiddle = false">取消</a-button>
            <a-button type="primary" @click="okSelect">确定</a-button>
          </div>
        </div>
        <div style="display:flex;margin-top:15px" v-if="targeted == '4' || targeted == '3'">
          <span style="white-space:nowrap;width:10%" v-if="targeted == '4'">排除池：</span>
          <a-input placeholder="请至少选择一个自定义人群" @focus="
              topMiddleNo = true
              topMiddle = false
            " v-model="keyValueNo" />
        </div>

        <div style="background:white;padding:10px;box-shadow: 0 2px 8px 0 rgba(0,0,0,.15);"
          :style="{ width: targeted == '4' ? '90%' : '100%', marginLeft: targeted == '4' ? '10%' : '0' }"
          v-show="topMiddleNo">
          <a-table :columns="columns" :dataSource="dataList" bordered :pagination="false" :scroll="{ y: 300,x:true }"
            :rowSelection="{
              selectedRowKeys: selectedRowKeysNo,
              onChange: onSelectChangeNo,
              getCheckboxProps: getCheckboxPropsNo
            }">
            <span slot="orientationName" slot-scope="text, record">{{ text }}({{ record.orientationId }})</span>
            <span slot="populationType" slot-scope="text">{{ text | population_type }}</span>
            <span slot="putTime" slot-scope="text">{{ text | getDate }}</span>
          </a-table>
          <div style="text-align:right">
            <a-button style="margin-right:5px" @click="topMiddleNo = false">取消</a-button>
            <a-button type="primary" @click="okSelectNo">确定</a-button>
          </div>
        </div>
      </div>
    </a-form-item>
    <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" />
      </div>
    </a-form-item>
    <a-form-item label="年龄" :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }">
      <a-radio-group v-model="allForm.ageType" buttonStyle="solid">
        <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'">
        <a-checkbox-group v-decorator="['agesRange', { 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-model="allForm.platform_os">
        <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>
      </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="allForm.platform_os == '1'" class="else-label">
      <a-radio-group v-decorator="[
          'androidOsv',
          {
            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>
    </a-form-item> -->

    <a-form-item label="性别" :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapperCol="{ lg: { span: 17 }, 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: 17 }, sm: { span: 17 } }">
      <!-- v-decorator="['speed', { initialValue: '1' }]" -->
      <a-radio-group buttonStyle="solid" v-model="allForm.scheduleTime" @change="setTimeAll">
        <a-radio-button value="1">全天</a-radio-button>
        <a-radio-button value="2">特定时间</a-radio-button>
      </a-radio-group>
      <br />
      <selectCheckAll style="width:100%" v-show="allForm.scheduleTime == '2'"
        :scheduleTime.sync="allForm.scheduleTimeData" ref="selectCheck" />
    </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 './stepForm/stepModule/selectRegion'
  import selectCheckAll from './stepForm/stepModule/test'
  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__
    }
  }

  const columns = [{
      title: '人群',
      dataIndex: 'orientationName',
      scopedSlots: {
        customRender: 'orientationName'
      },
      width: 150
    },
    {
      title: '属性',
      dataIndex: 'populationType',
      filters: [{
          text: '上传人群',
          value: '1'
        },
        {
          text: '广告人群',
          value: '2'
        },
        {
          text: '主题专区',
          value: '3'
        },
        {
          text: '逻辑规则',
          value: '4'
        },
        {
          text: '人群扩展',
          value: '5'
        },
        {
          text: '平台定制',
          value: '6'
        },
        {
          text: '定制付费',
          value: '7'
        },
        {
          text: '网红粉丝类别',
          value: '8'
        },
        {
          text: '内容付费行为',
          value: '9'
        },
        {
          text: '移动应用安装',
          value: '10'
        },
        {
          text: '快手使用活跃度',
          value: '11'
        },
        {
          text: '行业分类',
          value: '12'
        },
        {
          text: '商业兴趣',
          value: '13'
        },
        {
          text: '固化标签',
          value: '14'
        },
        {
          text: '行业偏好',
          value: '15'
        },
        {
          text: '第三方标签',
          value: '16'
        },
        {
          text: '产品关键词',
          value: '17'
        }
      ],
      onFilter: (value, record) =>
        record.populationType
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
      scopedSlots: {
        customRender: 'populationType'
      },
      width: 150
    },
    {
      title: '创建时间',
      dataIndex: 'putTime',
      scopedSlots: {
        customRender: 'putTime'
      },
      sorter: (a, b) => a.putTime - b.putTime
    }
  ]

  export default {
    name: 'BaseForm',
    components: {
      selectRegion,
      selectCheckAll
    },
    props: {
      campaignId: {
        type: String,
        default () {
          return null
        }
      },
      platform: {
        default () {
          return null
        }
      },
      populationData: {}
    },
    filters: {
      getDate(value) {
        let date = new Date(value)
        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
        return y + '-' + MM + '-' + d
      },
      population_type(str) {
        var data = {
          1: '上传人群',
          2: '广告人群',
          3: '主题专区',
          4: '逻辑规则',
          5: '人群扩展',
          6: '平台定制',
          7: '定制付费',
          8: '网红粉丝类别',
          9: '内容付费行为',
          10: '移动应用安装',
          11: '快手使用活跃度',
          12: '行业分类',
          13: '商业兴趣',
          14: '固化标签',
          15: '行业偏好',
          16: '第三方标签',
          17: '产品关键词'
        }
        return data[str]
      }
    },
    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岁'
        },
        loading: false,
        allForm: {
          regionType: 'noLimit',
          region: [],
          ageType: 'noLimit',
          age: [],
          scheduleTime: '1',
          scheduleTimeData: '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
        },
        optionsApp: [],
        optionsAppActive: [],
        checkOptions: [],
        businessOptions: [],
        fansStarOptions: [],
        interestVideoOptions: [],
        optionPropsApp: {
          value: 'tagId',
          label: 'tagName',
          children: 'children',
          multiple: true,
          emitPath: false
        },
        closeDialog: false,
        indeterminate: false,
        checkAll: false,
        people: '2',
        targeted: '2',
        topMiddle: false,
        topMiddleNo: false,
        keyValue: '',
        keyValueNo: '',
        columns,
        selectedRowKeys: [],
        selectedRowKeysValue: [],
        selectedRowKeysNo: [],
        selectedRowKeysValueNo: [],
        dataList: []
      }
    },
    computed: {},
    methods: {
      setTimeAll(e) {
        //   console.log(moment('2019-12-27'))
        if (e.target.value == '2') {
          // this.$nextTick(() => {
          //   this.$refs.selectCheck.init()
          // })
        } else {}
      },
      getPeople() {
        return new Promise((resolve, reject) => {
          getAction('/kuaishou/batch/getPopulationList', {
            accountId: localStorage.getItem('accountId')
          }).then(res => {
            if (res.success) {
              console.log(res)
              this.dataList = res.result.map((item, index) => {
                return {
                  ...item,
                  key: index
                }
              })
              resolve(res.result)
            }
          })
        })
      },
      radioChange() {
        this.selectedRowKeys = []
        this.selectedRowKeysValue = []
        this.selectedRowKeysNo = []
        this.selectedRowKeysValueNo = []
        this.keyValue = ''
        this.keyValueNo = ''
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        console.log(selectionRows)
        this.selectedRowKeysValue = selectionRows.map(item => {
          return {
            orientationId: item.orientationId,
            orientationName: item.orientationName
          }
        })
      },
      getCheckboxProps(record) {
        return {
          props: {
            disabled: this.selectedRowKeysValueNo.some(item => item.orientationId === record.orientationId)
          }
        }
      },
      onSelectChangeNo(selectedRowKeys, selectionRows) {
        this.selectedRowKeysNo = selectedRowKeys
        console.log(selectionRows)
        this.selectedRowKeysValueNo = selectionRows.map(item => {
          return {
            orientationId: item.orientationId,
            orientationName: item.orientationName
          }
        })
      },
      getCheckboxPropsNo(record) {
        return {
          props: {
            disabled: this.selectedRowKeysValue.some(item => item.orientationId === record.orientationId)
          }
        }
      },
      okSelect() {
        this.keyValue = ''
        this.topMiddle = false
        for (let i = 0; i < this.selectedRowKeysValue.length; i++) {
          this.keyValue += this.selectedRowKeysValue[i].orientationName + '   '
        }
      },
      okSelectNo() {
        this.keyValueNo = ''
        this.topMiddleNo = false
        for (let i = 0; i < this.selectedRowKeysValueNo.length; i++) {
          this.keyValueNo += this.selectedRowKeysValueNo[i].orientationName + '   '
        }
      },
      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)
              }
            }
          }
        }
      },
      showAppName(appId) {
        var data = this.checkOptions.filter(item => {
          return item.appId == appId
        })
        return data[0].appName
      },
      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
      },
      handleSubmit() {
        //   e.preventDefault()
        console.log(this.selectedRowKeysValue)
        this.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values)
            //   this.checkArr
            var json = {}
            if (this.allForm.regionType == 'limit') {
              json.region = this.allForm.region.map(item => {
                return item.value
              })
            }
            var jsonData = {}
            if (this.targeted == '2') {
              jsonData.population = this.selectedRowKeysValue.map(item => {
                return item.orientationId
              })
            } else if (this.targeted == '3') {
              jsonData.excludePopulation = this.selectedRowKeysValueNo.map(item => {
                return item.orientationId
              })
            } else if (this.targeted == '4') {
              jsonData.population = this.selectedRowKeysValue.map(item => {
                return item.orientationId
              })
              jsonData.excludePopulation = this.selectedRowKeysValueNo.map(item => {
                return item.orientationId
              })
            } else {
              jsonData = {}
            }
            var dataJson = {
              ...values,
              ...json,
              ...jsonData,
              scheduleTime: this.allForm.scheduleTime == '2' ?
                this.allForm.scheduleTimeData :
                '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
            }
            this.$emit('update:populationData', dataJson)
          }
        })
      },
      handleConfirmValue(rule, value, callback) {
        console.log(value)
        if (Math.abs(value[0] - value[1]) < 5) {
          callback('自定义年龄段需要间隔大于5岁')
        }
        callback()
      },
      regionChange() {
        this.allForm.region = []
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      getData(className) {
        return this.form.getFieldValue(className)
      }
    },
    mounted: function () {}
  }
</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;
    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>