<template>
  <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
    <a-form @submit="handleSubmit" :form="form">
      <a-form-item
          label="选择头条账户"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-select
            v-model="accountId"
            showSearch
            placeholder="选择头条账户"
            optionFilterProp="children"
            style="width: 200px"
          >
            <a-select-option v-for="user in userList" :key="user.id" :value="user.id">{{user.accountName}}</a-select-option>
          </a-select>
      </a-form-item>

      <a-form-item
        label="模板名称"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-input v-model="templateName" placeholder="请输入模板名称">
        </a-input>
      </a-form-item>
      <a-form-item
        label="投放范围"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group v-model="deliveryRange" @change="onChangedeliveRange">
          <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="投放形式"
        v-if="deliveryRangeShow"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group v-model="deliveryForm">
          <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="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group v-model="adCategory">
          <a-radio-button value="1">售卖</a-radio-button>
          <a-radio-button value="2">换量</a-radio-button>
          <a-radio-button value="4">配送</a-radio-button>
          <a-radio-button value="5">内广</a-radio-button>
          <a-radio-button value="7">补量</a-radio-button>
        </a-radio-group>
      </a-form-item>-->
      <a-form-item
        label="投放目标"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group v-model="deliveryTarget" @change="onChangeDeliveryTarget">
          <a-radio-button value="11">转化量</a-radio-button>
          <a-radio-button value="2">点击量</a-radio-button>
          <a-radio-button value="1">展示量</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        label="下载方式"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">

        <a-radio-group @change="onChangeDownloadType" v-model="downloadType">
          <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
        v-if="showDownloadMode"
        label="下载类型"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group @change="onChangeDownloadMode" v-model="downloadMode">
          <a-radio-button value="android">安卓下载</a-radio-button>
          <a-radio-button value="IOS">IOS下载</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        label="下载链接"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-select
          v-model="urlId"
          style="width: 300px">
          <a-select-option v-for="url in urlList" :key="url.id" :value="url.id">{{url.name}}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        v-if="showConvertTarget"
        label="选择转化跟踪方式"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-select
          v-model="convertType"
          showSearch
          placeholder="选择投放目标模板"
          optionFilterProp="children"
          style="width: 200px"
          @change="changeConvertType"
        >
          <a-select-option v-if="showSimple"value="SIMPLE">普通应用下载</a-select-option>
          <!--<a-select-option value="API">应用下载API</a-select-option>-->
        </a-select>
      </a-form-item>

      <a-form-item
        v-if="showConvertTarget&&showConvertTargetSimple"
        label="选择转化目标"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-select
          v-model="simpleDeliverytarget"
          showSearch
          placeholder="选择转化目标"
          optionFilterProp="children"
          style="width: 200px"
        >
          <a-select-option value="AD_CONVERT_TYPE_INSTALL_FINISH">安装完成</a-select-option>
          <a-select-option value="AD_CONVERT_TYPE_DOWNLOAD_FINiSH">下载完成</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        v-if="showConvertTarget&&showConvertTargetApi"
        label="选择转化目标"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-select
          v-model="convertId"
          showSearch
          placeholder="选择转化目标"
          optionFilterProp="children"
          style="width: 800px"
        >
          <a-select-option v-for="activeConvert in activeConvertList" :key="activeConvert.id" :value="activeConvert.id">{{activeConvert.name}}</a-select-option>
        </a-select>
      </a-form-item>

      <!--<a-form-item
        label="直达链接"
        v-if="showOpenUrlStatus"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group>
          <a-radio-button value="disabled">不启用</a-radio-button>
          <a-radio-button value="enabled">启用</a-radio-button>
        </a-radio-group>
      </a-form-item>-->

<!--      <a-form-item-->
<!--        label="直达链接生成方式"-->
<!--        :labelCol="labelCol"-->
<!--        :wrapperCol="wrapperCol">-->
<!--        <a-radio-group>-->
<!--          <a-radio-button value="auto_create" disabled>自动生成</a-radio-button>-->
<!--          <a-radio-button value="hand_create">手动生成</a-radio-button>-->
<!--        </a-radio-group>-->
<!--      </a-form-item>-->
<!--      <a-form-item-->
<!--        label="跳转app链接"-->
<!--        :labelCol="labelCol"-->
<!--        :wrapperCol="wrapperCol">-->
<!--        <a-input v-model="redirectUrl"></a-input>-->
<!--      </a-form-item>-->
      <a-form-item
        label="出价方式"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group v-model="bidType">
          <a-radio-button value="0">手动</a-radio-button>
<!--          <a-radio-button value="1">保守</a-radio-button>-->
          <a-radio-button value="2" v-if="deliveryTarget==='11'">自动</a-radio-button>
        </a-radio-group>

      </a-form-item>
      <a-form-item
        label="投放方式"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group v-model="flowControlMode">
            <a-radio-button value="0">优先跑量</a-radio-button>
            <a-radio-button value="1">均衡投放</a-radio-button>
            <a-radio-button value="3">优先低成本</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="预算"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-input v-model="budgetPrice"
                 style="width: 70%">
          <a-select
            slot="addonBefore"
            v-model="budgetPriceMode"
            style="width: 100px">
            <a-select-option value="0">日预算</a-select-option>
            <a-select-option value="1">总预算</a-select-option>
          </a-select>
        </a-input>
        元
      </a-form-item>

      <a-form-item
        label="投放时间"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group @change="onChangeFlowDate" v-model="flowDateType">

          <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="labelCol"
                   v-if="showDateFlowRange"
                   :wrapperCol="wrapperCol">
        <a-range-picker
          name="buildTime"
          style="width: 100%"
          v-model="time"/>
      </a-form-item>


      <a-form-item
        label="投放时段"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group @change="dateQuantumChange" v-model="dateQuantum">
          <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="设置时间段"
        v-if="showDateQuantumRange"
        :labelCol="labelCol"
        v-model="dateQuantumRange"
        :wrapperCol="wrapperCol">
        <div id="table_time_selected1" class="table_time_selected1">
        </div>
      </a-form-item>


      <a-form-item
        label="付费方式"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-radio-group @change="onChange" v-model="pricing">
          <a-radio-button v-if="deliveryTarget==='11'" value="9">按展示付费(oCPM)</a-radio-button>
          <a-radio-button v-else-if="deliveryTarget==='2'" value="2">按点击付费(CPC)</a-radio-button>
          <a-radio-button v-else-if="deliveryTarget==='1'" value="1">按展示付费(CPM)</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="目标转化出价"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-input-number v-model="convertPrice" :min="0" :max="10000000" @change="onChange"/>
        元
      </a-form-item>

      <a-form-item
        label="迭代数量"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-input-number v-model="itratorNum" :min="1" :max="1000" @change="onChange"/>
      </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 pick from 'lodash.pick'
  import jq from 'jquery'
  import moment from 'moment';
  import AFormItem from "ant-design-vue/es/form/FormItem";

  let dateQuantumRangeConst = '';
  export default {
    name: 'InternalModel',
    components: {AFormItem},
    data() {
      return {
        loading:false,
        templateName:'',
        title: "操作",
        visible: false,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        itratorNum:1,
        accountId:'',
        userList:[],
        urlId:'',
        urlList:[],
        showDownloadMode:'true',
        downloadMode:'android',
        convertId:'',
        showSimple:true,
        showConvertTargetSimple:false,
        showConvertTargetApi:false,
        convertType:'',
        simpleDeliverytarget:'',
        activeConvertList:[],
        deliverytargetId:null,
        templateName: '', //模板名称
        deliveryRange: '1',//投放范围
        deliveryForm: '1',//投放形式
        adCategory: '5',//广告类别
        deliveryTarget: '11', //投放目标
        downloadType: '1',//下载方式
        deliveryRangeShow: false,
        downloadUrl: '',// 下载链接
        externalUrl: '', //h5链接地址
        packageName: '',//应用包名
        // 直达链接
        // 直达链接生成方式
        bidType: '0',//出价方式
        budgetPriceMode: '0',//预算类型
        flowControlMode: '0',//投放方式
        budgetPrice: 0,//预算金额
        flowDateType: '1', //投放时间类型
        time: [], //投放时间段值
        dateQuantum: '1', //投放时段类型
        dateQuantumRange: '',// 投放时段选择值
        pricing: '9', //付费方式
        convertPrice: 0, //目标转化出价
        convertTarget: '',
        showDownloadUrl: true,
        showConvertTarget: true,
        showOpenUrlStatus: false,
        openUrlStatus: 'disabled',
        redirectUrl: '',
        showToAppUrl: false,
        showOpenUrlCreateMode: false,
        openUrlCreateMode: 'hand_create',
        name: '',
        showDateFlowRange: false,
        showDateQuantumRange: false,
        price: 0,
        filterType: "NO_EXCLUDE",
        flowDateList: {},
        form: this.$form.createForm(this),
        url: {
          urllist: '/ctop/bytedanceUrlInfo/list',
          userAllocationList:'/template/bind/login/list',
          dictListUrl: 'toutiao/dictitem/list',
          insertUrl: 'test/create',
          convertList:'template/convert/list/url'
        }
      }
    },
    methods: {
      refreshConvertApiId(){
        let params = {};
        getAction(this.url.convertList+'?accountId='+this.accountId+'&urlId='+this.urlId ,params).then((res)=>{
          console.log(res);
          if(res.code == 0){
            this.activeConvertList = res.data.active_convert_list;
          }else{
            this.$message.error(res.message);
          }
        });
      },
      changeConvertType(){
        if(this.convertType == 'SIMPLE'){
          this.showConvertTargetSimple = true;
          this.showConvertTargetApi = false;
        }else{
          this.refreshConvertApiId();
          this.showConvertTargetSimple = false;
          this.showConvertTargetApi = true;
        }
      },
      refreshUrl(value){
        let params = {};
        params.pageSize = '1000';
        params.type = value;
        getAction(this.url.urllist, params).then((res) => {
          if (res.success) {
            this.urlList = res.result.records
          }
        });
      },
      onChangedeliveRange() {
        if (this.deliveryRange == '1') {
          this.deliveryRangeShow = false;
        } else if (this.deliveryRange == '2') {
          this.deliveryRangeShow = true;
        }
      },
      add() {
        this.edit({
          id: null,
          time: [],
          convertPrice: 0,
          pricing: '9',
          dateQuantum: '1',
          dateQuantumRange: '',
          flowDateType: '1',
          budgetPrice: 0,
          budgetPriceMode: '0',
          flowControlMode: '0',
          bidType: '0',
          filterType: 'NO_EXCLUDE'
        });
      },
      edit(record) {
        // this.form.resetFields();

        // this.time[0] = record.startDate
        // this.time[1] = record.endDate
        this.model = Object.assign({}, record);
        this.visible = true;
        this.id = record.id
        this.name = record.name
        this.convertPrice = record.convertPrice
        this.budgetPrice = record.budgetPrice
        this.budgetPriceMode = record.budgetPriceMode
        this.flowControlMode = record.flowControlMode
        this.flowDateType = record.flowDateType
        this.dateQuantum = record.dateQuantum
        if (record.dateQuantumRange != undefined) {
          this.dateQuantumRange = record.dateQuantumRange
          dateQuantumRangeConst = record.dateQuantumRange
        }
        if (record.startDate != null && record.endDate != null) {
          this.time = [moment(record.startDate), moment(record.endDate)]
        }
        this.bidType = record.bidType
        this.pricing = record.pricing
        this.price = record.price
        this.filterType = record.filterType
        if (this.flowDateType == '1') {
          this.showDateFlowRange = false;
        } else {
          this.showDateFlowRange = true;
        }
        if (this.dateQuantum == '1') {
          this.showDateQuantumRange = false;
        } else {
          this.showDateQuantumRange = true;
          jq(function () {
            load_time_table('table_time_selected1', dateQuantumRangeConst);
          });
        }
        // this.$nextTick(() => {
        //   this.form.setFieldsValue(pick(this.model, 'name', 'convertPrice', 'priceType', 'dateQuantum', 'flowDateType', 'budgetPriceMode', 'flowControlMode', 'bidType','budgetPrice','startDate','endDate'))
        //   //时间格式化
        // });
      },
      close() {
        this.$emit('close');
        this.visible = false;
      },
      handleCancel() {
        this.close()
      },
      moment,
      disabledDate(current) {
        return current < moment().endOf('day');
      },
      onChangeDownloadType(value) {
        console.log(value);
        if (this.downloadType == '1') {
          this.urlId = null;
          this.showDownloadUrl = true;
          this.showOpenUrlStatus = false;
          this.showDownloadMode = true;
          this.refreshUrl('android');
        } else {
          this.urlId = null;
          this.showDownloadUrl = false;
          this.showOpenUrlStatus = true;
          this.showDownloadMode = false;
          this.refreshUrl('page');
        }
      },
      onChangeDeliveryTarget(value) {
        console.log(value);
        if (this.deliveryTarget == '11') {
          this.showConvertTarget = true;
          this.pricing='9'
        } else {
          this.showConvertTarget = false;
          if(this.deliveryTarget == '2'){
            this.pricing='2'
          }else if(this.deliveryTarget == '1'){
            this.pricing='1'
          }
        }
      },
      onChangeOpenUrlStatus() {
        if (this.openUrlStatus == 'disabled') {
          this.showOpenUrlCreateMode = false;
          this.showToAppUrl = false;
        } else {
          this.showOpenUrlCreateMode = true;
          this.showToAppUrl = true;
        }
      },
      handleSubmit(e) {
        let params = {};
        console.log("模板名称：" + this.templateName);
        console.log("投放范围：" + this.deliveryRange);
        console.log("投放形式：" + this.deliveryForm);
        console.log("广告类别：" + this.adCategory);
        console.log("投放目标：" + this.deliveryTarget);
        console.log("下载方式：" + this.downloadType);
        console.log("下载方式为下载链接，下载地址：" + this.downloadUrl);
        console.log("下载方式为落地页，链接地址：" + this.externalUrl);
        console.log("应用包名：" + this.packageName);
        console.log("跳转app链接：" + this.redirectUrl);
        console.log("出价方式：" + this.bidType);
        console.log("投放方式：" + this.flowControlMode);
        console.log("预算类型：" + this.budgetPriceMode);
        console.log("预算金额：" + this.budgetPrice);
        console.log("投放时间类型：" + this.flowDateType);
        console.log("选择起始时间：" + this.time);
        console.log("投放时段类型：" + this.dateQuantum);
        this.dateQuantumRange = '';
        if (this.dateQuantum == '2') {
          this.dateQuantumRange = jq("#table_time_selected1_time_num").val();
        }
        console.log("付费方式：" + this.priceType);
        console.log("目标转化出价：" + this.convertPrice);

        params.templateName = this.templateName;
        params.accountId = this.accountId;
        params.deliveryRange = this.deliveryRange;
        params.deliveryForm =this.deliveryForm;
        params.adCategory =this.adCategory;
        params.deliveryTarget =this.deliveryTarget;
        params.downloadType =this.downloadType;
        params.downloadUrl =this.downloadUrl;
        params.externalUrl =this.externalUrl;
        params.packageName =this.packageName;
        params.redirectUrl =this.redirectUrl;
        params.bidType =this.bidType;
        params.flowControlMode =this.flowControlMode;
        params.budgetPriceMode = this.budgetPriceMode;
        params.budgetPrice =this.budgetPrice;
        params.flowDateType =this.flowDateType;
        params.dateQuantum =this.dateQuantum;
        params.pricing = this.pricing;
        params.convertPrice = this.convertPrice;
        params.itratorNum = this.itratorNum;
        params.templateName = this.templateName;
        if (this.time != [] && this.time.length == 2) {
          params.startDate = moment(this.time[0]).format('YYYY-MM-DD HH:mm')
          params.endDate = moment(this.time[1]).format('YYYY-MM-DD HH:mm')
        }

        params.dateQuantumRange = this.dateQuantumRange;
        params.urlId = this.urlId;
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (!err) {
          /*  console.log('Received values of form: ', values);

            this.dateQuantumRange = jq("#table_time_selected1_time_num").val();
            params.id = this.id;
            params.name = this.name;
            params.bidType = this.bidType;
            params.flowControlMode = this.flowControlMode;
            params.budgetPrice = this.budgetPrice;
            params.budgetPriceMode = this.budgetPriceMode;
            params.flowDateType = this.flowDateType;

            params.dateQuantum = this.dateQuantum;
            params.priceType = this.priceType;
            params.convertPrice = this.convertPrice;
            params.filterType = this.filterType;
            params.dateQuantumRange = this.dateQuantumRange;*/
            this.loading = true;
            console.log(params)
             postAction(this.url.insertUrl, params).then((res) => {
               console.log(res)
               if (res.success) {
                 this.$message.success("批量创建成功");
                 this.$emit('ok');
                 this.close();
               } else {
                 this.$message.warning(res.message);
               }
               this.loading = false;

             });
          }
        })
      },
      onChange(value) {
        console.log(value)
      },
      dateQuantumChange(value) {
        if (this.dateQuantum == '1') {
          this.showDateQuantumRange = false;
          this.dateQuantumRange = '';
        } else {
          this.showDateQuantumRange = true;
          jq(function () {
            load_time_table('table_time_selected1', dateQuantumRangeConst);
          });
        }
      },
      onChangeDownloadMode(){
        this.urlId = null;
        this.refreshUrl(this.downloadMode);
      },
      onChangeFlowDate() {
        console.log(this.flowDateType)
        if (this.flowDateType == '1') {
          this.showDateFlowRange = false;
          this.time = [];
        } else {
          this.showDateFlowRange = true;
        }
      }
    },
    created: function () {
      this.refreshUrl("android");
      let params = {};
      params.pageSize = '1000';
      params.id = this.accountId;
      postAction(this.url.userAllocationList, params).then((res) => {
        if (res.success) {
          this.userList = res.result.records
        }
      });
    }
  }

  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 < 48; x++) {

        //获取当前点击元素的位置
        if (y == 0) {
          var index = x;
        } else {
          var index = (y * 48) + 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 == 47) {
            //选中的后一个没选中，或者此次选中的是行里最后一个，此次选中的元素加逗号
            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 < 48; i++) {
      if (oDate_minute < 10) {
        var oDate_minute = "0" + oDate_minute;
      }
      if (i >= 1) {
        oDate.setMinutes(oDate.getMinutes() + 30);
        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 < 336; 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="24">上午</th>';
    html += '<th colSpan="24">下午</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 < 49; 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 colSpan="2" 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;
  }

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

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

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

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