<template>
  <div class="newPlan">
    
    <div class="moduler">
        <div v-if="projectInfo.length>0">
         <span style="margin-right:8px"> 项目：<strong>{{projectInfo[0].name||''}}</strong></span>
         <span style="margin-right:8px"> 推广目的：<strong>{{projectInfo[0].landingType=='APP'?'应用推广':'销售线索收集'||''}}</strong></span>
         <span style="margin-right:8px"> 投放媒体：<strong>{{projectInfo[0].deliveryRange=="DEFAULT"?'默认':'穿山甲'||''}}</strong></span>
         <span style="margin-right:8px"> 投放方式：
             <strong v-if="projectInfo[0].adTarget=='CPA'">优先成本</strong>
             <strong v-if="projectInfo[0].adTarget=='COST'">优先跑量</strong>
             <strong v-if="projectInfo[0].adTarget=='PUSH'">激进抢量</strong>
        </span>
          
        </div>
    </div>
   
        
        <div class="moduler">
            
            <a-form :form="form">
                <div class="moduler-title">预算与出价</div>
                <div class="ad-range">
                    <div class="row-item" >
                        <div class="hint-item"></div>
                        <div class="label-item">
                        <div class="text-item">投放时间</div>
                        <!-- <div class="required-item"></div> -->
                        </div>
                        <div class="input-item">
                        <a-form-item>
                            <a-radio-group v-decorator="['scheduleType', { initialValue:'SCHEDULE_FROM_NOW' }]">
                            <a-radio-button value="SCHEDULE_FROM_NOW">从今天起长期投放</a-radio-button>
                            <a-radio-button value="SCHEDULE_START_END">设置开始和结束时间</a-radio-button>
                            </a-radio-group>
                            <p style="margin-top:15px">
                            <a-range-picker
                                @change="dateChange"
                                v-model="dateRange"
                                v-if="getFormData('scheduleType')=='SCHEDULE_START_END'"
                            />
                            </p>
                        </a-form-item>
                        </div>
                    </div>
                    <div class="row-item">
                        <div class="hint-item"></div>
                        <div class="label-item">
                        <div class="text-item">投放时段</div>
                        <!-- <div class="required-item"></div> -->
                        </div>
                        <div class="input-item">
                        <a-form-item>
                            <a-radio-group v-decorator="['scheduleTime', { initialValue:'' }]">
                            <a-radio-button value=''>不限</a-radio-button>
                            <a-radio-button value="SpecifiedTImePeriod">指定时间段</a-radio-button>
                            </a-radio-group>
                            <div
                            v-show="getFormData('scheduleTime')=='SpecifiedTImePeriod'"
                            style="margin-top:15px"
                            >
                            <selectCheckAll
                                style="width:100%"
                                :scheduleTime.sync="scheduleTimeData"
                                ref="selectCheck"
                            />
                            </div>
                        </a-form-item>
                        </div>
                    </div>
                    <div class="row-item">
                      <div class="hint-item">
                        <a-tooltip>
                          <template slot="title">
                            <span>单次预算修改幅度不小于100元,日修改预算不超过20次。如果是总预算广告，且设了起始日期，将要求您预算设置需要大于或等于[投放天数 * 100]，即满足每日最低预算300的要求</span>
                          </template>
                          <a-icon type="question-circle" />
                        </a-tooltip>
                      </div>
                      <div class="label-item">
                        <div class="text-item">预算</div>
                        <div class="required-item"></div>
                      </div>
                      <div class="input-item">
                        <a-form-item>
                          <a-input-group compact>
                            <a-select :disabled="true" v-decorator="['budgetMode', { initialValue:'BUDGET_MODE_DAY' }]">
                              <a-select-option value="BUDGET_MODE_DAY" >日预算</a-select-option>
                              <!-- <a-select-option
                                value="BUDGET_MODE_TOTAL"
                                v-if="getFormData('smartBidType')=='SMART_BID_CUSTOM'"
                              >总预算</a-select-option> -->
                            </a-select>
                            <a-input style="width: 25%" v-decorator="['budget', { initialValue:300 }]" />
                          </a-input-group>
                          <span class="tip" v-if="getFormData('budget')<300">请输入预算，不少于300元，不超过9999999.99元</span>
                        </a-form-item>
                      </div>
                    </div>
                    <div class="row-item" >
                        <div class="hint-item"></div>
                        <div class="label-item">
                        <div class="text-item">付费方式</div>
                        <div class="required-item"></div>
                        </div>
                        <div class="input-item">
                        <a-form-item>
                            <a-radio-group v-decorator="['pricing', { initialValue:'PRICING_OCPM' }]">
                              <a-radio-button value="PRICING_OCPM" >按展示付费（oCPM）</a-radio-button>
                              <!-- <a-radio-button value="PRICING_CPC" >按点击付费（CPC）</a-radio-button>
                              <a-radio-button value="PRICING_CPM" >按展示付费（CPM）</a-radio-button>
                              <a-radio-button value="PRICING_CPA">按转化付费（CPA）</a-radio-button>
                              <a-radio-button  value="PRICING_OCPC">按点击付费（oCPC）</a-radio-button> -->
                            </a-radio-group>
                        </a-form-item>
                        </div>
                    </div>
                    <div class="row-item" >
                      <div class="hint-item">
                        <a-tooltip>
                          <template slot="title">
                            <span>请填入您当前预算下，每个转化事件的真实预期成本，预期成本过低可能影响模型的优化能力。此成本仅作为投放参考，实际扣费仍以后台展示为准。</span>
                          </template>
                          <a-icon type="question-circle" />
                        </a-tooltip>
                      </div>
                      <div class="label-item">
                        <div class="text-item">预期成本</div>
                        <div class="required-item"></div>
                      </div>
                      <div class="input-item">
                        <a-form-item>
                          <a-input-number
                            style="width:200px"
                            :max="1500"
                            :step="0.1"
                            v-decorator="['bid', {rules:validationRules.bid} ]"
                          />
                          <span style="margin-left:5px">元</span>
                          <!-- <span style="margin-left:20px">请填入必填字段，获取建议出价</span> -->
                        </a-form-item>
                        <span
                          class="tip"
                          v-if="getFormData('bid')<0.1"
                        >请输入预期成本，不少于0.1元，不超过10000元</span>
                      </div>
                    </div>

                    <div class="row-item" >
                      <div class="hint-item"> </div>
                      <div class="label-item">
                        <div class="text-item">深度优化方式</div>
                        <div class="required-item"></div>
                      </div>
                      <div class="input-item">
                        <a-form-item>
                          <a-radio-group
                            v-decorator="['deepBidType', { initialValue:'DEEP_BID_MIN' }]"
                          >                            
                            <a-radio-button value="DEEP_BID_MIN" >自定义双出价</a-radio-button>
                          </a-radio-group>
                        </a-form-item>
                      </div>
                    </div>
                    <div class="row-item" >
                      <div class="hint-item"> </div>
                      <div class="label-item">
                        <div class="text-item">深度转化出价</div>
                        <div class="required-item"></div>
                      </div>
                      <div class="input-item">
                        <a-form-item>
                          <a-input-number
                            style="width:200px"
                            :max="10000"
                            :step="0.1"
                            :min='0.1'
                            v-decorator="['deepBid', {rules:validationRules.bid} ]"                 
                          />
          
                          <span style="margin-left:5px">元</span>
                        </a-form-item>
                        <span
                          class="tip"
                          v-if="getFormData('pricing')!='PRICING_CPA'&&getFormData('deepCpabid')<0.1"
                        >请输入深度转化出价，不少于0.1元，不超过10000元</span>
                      </div>
                    </div>
                    <div class="row-item">
                        <div class="hint-item"></div>
                        <div class="label-item">
                        <div class="text-item">超成本自动暂停</div>
                        <div class="required-item"></div>
                        </div>
                        <div class="input-item">
                        <a-form-item>
                            <a-radio-group v-decorator="['autoStop', { initialValue:0 }]">
                              <a-radio-button :value="1">开启</a-radio-button>
                              <a-radio-button :value="0">关闭</a-radio-button>
                            </a-radio-group>
                        </a-form-item>
                        </div>
                    </div>
                </div>
            </a-form>  
        </div>
            
            <!-- 当前账户 -->
            <div class="moduler">
                <div class="adName">
                    <span>当前账户：</span> 
                    <div class="nameList">
                        <strong v-for="item in LHKaccountInfo" :key="item.value" class="item">{{item.title+'('+item.value+')'}}</strong>
                    </div>
                </div>
            </div>
            <!-- 操作 -->
            <div class="moduler">
                <!-- <div class="moduler-title">计划名称</div> -->
                <div class="opt">
                <a-button type="default" style="margin-right:15px" @click="goBack">取消</a-button>
                
                <a-button type="primary" @click="goNext"  :loading="goNextloading">下一步</a-button>
                </div>
            </div>
        
      <!-- 投放链接 -->
    
    <div class="infoModal">
         <a-modal v-model="visible" title="提示"  @ok="handleOk" :keyboard='false' :maskClosable='false'>
            <ul>
              <li v-for="(item,index) in errorInfo" :key="index">
                  <span>账户{{LHKaccountInfo[index].title}}：</span>{{item.message || '设置转化信息成功'}}
              </li>
            </ul>
            <template slot="footer">
              <a-button key="back" @click="handleCancel">
                返回本页
              </a-button>
              <a-button key="submit" type="primary"  @click="handleOk">
                下一步
              </a-button>
            </template>
          </a-modal>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { getAction, postAction, downFile, downFilePost } from '@/api/manage'
import selectCheckAll from '../BatchCreate/toutiaoTime'
import qs from 'qs'
var str = ""
for (let i = 0; i < 7*48; i++) {
 str+='0'
  
}
export default {
  components: {
    selectCheckAll,
    // newDirectedPackage,
  },
  data() {
    return {
        projectInfo:[],
        LHKaccountInfo:[],
        
        form: this.$form.createForm(this),

        showIndex:0,

        goNextloading:false,
        goPlanShowloading:false,
        
        
        dateRange: [moment(), moment()],
        scheduleTime: '',
        scheduleTimeData:str,

        visible:false,
        errorInfo:[],
       
        validationRules: {
            url: [   
            {          
                required: true,
                validator: this.validateURL,
            },
            ],
            name:[{
            required: true,
            validator: this.validateName,
            }],
            bid:[{
            required: true,
            message:'出价信息必须填写',
            // validator: this.validateBid,
            }],
            roi:[{
            required: true,
            message:'ROI系数必须填写',
            // validator: this.validateBid,
            }],
        },

        currentConvertTypes:[],
        convertIds:[],
    }
  },
  watch: {
    
  },
  methods: {
    
    callback(val) {
      console.log(val);
    },

    
    
    handleOk(e) {
        this.visible=false;
      // this.$router.push('/LaunchHousekeeper/setProjectDirectional')
        this.$router.push({path:'/LaunchHousekeeper/setProjectDirectional'})
        this.$bus.$emit('remove', '/LaunchHousekeeper/setProjectConvert')
        
    },
    handleCancel(e) {
        this.visible = false;
    },
   
   
    
   
    //获取表单的某一个属性值
    getFormData(className) {
      return this.form.getFieldValue(className)
    },
    dateChange(date, dateString) {
      // console.log(date,dateString)
      this.form.getFieldDecorator('startTime')
      this.form.getFieldDecorator('endTime')
      this.form.setFieldsValue({
        startTime: date[0].format('YYYY-MM-DD HH:mm'),
        endTime:  date[1].format('YYYY-MM-DD HH:mm'),
      })
    },
    
    
    
    
    // 验证网址
    IsURL(res) {
      //   var strRegex = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|www\.)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/
      var strRegex = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+(.+[A-Za-z0-9-~\/])+$/
      var re = new RegExp(strRegex)
      // console.log(re.test(res))
      if (re.test(res)) {
        return true
      } else {
        return false
      }
    },
    validateURL(rule, value, callback) {
      // console.log(rule, value, callback);

      if (this.IsURL(value)) {
        callback()
      } else if (value && !this.IsURL(value)) {
        callback('链接地址无法访问，请正确输入')
      } else {
          callback('链接必须填写')
      }
    },
    validateName(rule, value, callback){
      // console.log(rule, value, callback);

        if (value) {
          callback()
        } else {
              callback('应用包名称必须填写')
        }
    },
    validateBid(rule, value, callback){
      // console.log(rule, value, callback);
        if (value) {
          callback()
        } else {
            callback('出价必须填写')
        }
    },

   
    
    goBack() {
      this.$router.replace('/modules/LaunchHousekeeper/LaunchHousekeeperList')
      this.$bus.$emit('remove', '/LaunchHousekeeper/setProjectConvert')
    },
    
    // 保存并新建创意
    goNext() {
      this.$nextTick(()=>{
        
          this.form.validateFields((err, values) => {
            if (!err) {

              console.log('Received values of form: ', values)
              
              this.goNextloading=true;
              if(this.getFormData('scheduleTime')!=''){
                  values.weekTime=this.scheduleTimeData
              }
              
              values.startTime=this.dateRange[0].format('YYYY-MM-DD HH:mm');
              values.endTime= this.dateRange[1].format('YYYY-MM-DD HH:mm');

              let params=[];
              params=this.projectInfo.map((item,index)=>{
                return {
                  ...item,
                  ...values,
                }
              })
              console.log(values)
              postAction('/adlab/Project/setBudget', params).then((res) => {
                console.log(res)
                if (res.success) {
                  this.goNextloading=false;
                
                    if(res.result){
                        // this.errorInfo=res.result;
                        // this.visible=true;

                        // let projectInfo=[]
                        // res.result.forEach(item=>{
                        //     if(item.code==0){
                        //       projectInfo.push(item)
                        //     }
                        // })

                        //  sessionStorage.setItem('projectInfo',JSON.stringify(projectInfo))
                    }
                 
                } else {
                   this.goNextloading=false;
                  this.$message.error(res.message)
                }
              })
            }else{
              this.$message.error('请正确填写必填项目')
            }
          })
        
      })
      
    },
    
    EchoPageInfo(){

    },
    
  },
  
  mounted() {
      this.$bus.$emit('remove', '/LaunchHousekeeper/setProjectCreate')
        let projectInfo=sessionStorage.getItem('projectInfo');
        if(projectInfo){
            this.projectInfo=JSON.parse(projectInfo)
        }
        let LHKaccountInfo=sessionStorage.getItem('LHKaccountInfo');
        if(LHKaccountInfo){
            this.LHKaccountInfo=JSON.parse(LHKaccountInfo)
        }
        let editLHKProjectInfo=sessionStorage.getItem('editLHKProjectInfo');
        if(editLHKProjectInfo){
          this.LHKaccountInfo.push(editLHKProjectInfo);
        }
        
  },
}
</script>
<style lang="scss">
.newPlan{
  .ant-btn-danger {
    background-color: #ff4d4f !important; 
  }
}


.ant-tooltip-inner,
.ant-tooltip,
.ant-tooltip-arrow::before {
  background-color: #fff;
  color: #333;
}
.ant-tooltip-inner {
  span {
    display: block;
  }
}
.ant-tooltip {
  max-width: 450px;
}
.newPlan {
  .ant-radio-button-wrapper {
    min-width: 80px;
    text-align: center;
  }
  .ant-form-item {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    font-variant: tabular-nums;
    line-height: 1.5;
    list-style: none;
    -webkit-font-feature-settings: 'tnum';
    font-feature-settings: 'tnum';
    vertical-align: top;
  }
  .directedBody {
    .ant-form-item {
      margin-bottom: 20px;
    }
  }
}
</style>
<style lang="scss" scoped>
.newPlan {
  font-family: PingFangSC-Regular, tahoma, arial, 'Hiragino Sans GB', 'Microsoft yahei', sans-serif;
  color: #333;
  ul,
  li {
    margin: 0;
    padding: 0;
  }
  .moduler {
    background: #fff;
    margin-bottom: 16px;
    position: relative;
    padding: 32px 24px 48px 32px;
    border-radius: 4px;
    box-shadow: 0px 1px 6px 0px rgba(0, 0, 0, 0.05);
    .moduler-title {
      display: flex;
      align-items: center;
      font-size: 22px;
      margin-bottom: 20px;
    }
    .row-item {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: 32px;
    }
    .row-item:last-of-type {
      margin-bottom: 0;
    }
    .row-item .hint-item {
      width: 24px;
      min-width: 24px;
      align-self: flex-start;
      line-height: 20px;
      height: 20px;
      margin-top: 5px;
    }
    .row-item .label-item {
      position: relative;
      align-items: flex-start;
      align-self: flex-start;
      line-height: 20px;
      height: 20px;
      margin-top: 7px;
      width: 80px;
      min-width: 80px;
      .text-item {
        font-size: 14px;
        width: 60px;
      }
    }
    .row-item .required-item {
      width: 4px;
      height: 4px;
      border-radius: 2px;
      background: #f45858;
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
    }
    .row-item .input-item {
      min-width: 480px;
      position: relative;
      // height: 35px;
      .tip {
        font-size: 12px;
        color: tomato;
      }
    }
    .adName{
      display: flex;
      .nameList{
        width: 90%;
      }
      .item{
        display: inline-block;
        width: 30%;
        margin-left: 15px;
        margin-bottom: 10px;
      }
    }
  }
  .opt {
    text-align: right;
  }
}
</style>