<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" v-if="projectInfo.length>0&&projectInfo[0].landingType=='APP'" >
                        <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="['downloadType',{ initialValue:'DOWNLOAD_URL' }]"
                                 @change="downloadTypeChange">
                                    <a-radio-button value="DOWNLOAD_URL">下载链接</a-radio-button>
                                    <a-radio-button value="EXTERNAL_URL">落地页</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-radio-group v-decorator="['appType', { initialValue:'APP_IOS' }]" @change="appTypeChange">
                                <a-radio-button value="" v-if="getFormData('downloadType')=='EXTERNAL_URL' || (projectInfo.length>0&&projectInfo[0].landingType=='LINK')">不限</a-radio-button>
                                <a-radio-button value="APP_IOS">IOS</a-radio-button>
                                <a-radio-button value="APP_ANDROID">安卓</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 v-decorator="['url', {rules:validationRules.url}]" @change="UrlChange" />
                            </a-form-item>
                        </div>
                    </div>    
                    <div class="row-item" v-if="getFormData('downloadType')=='DOWNLOAD_URL'&&getFormData('appType')=='APP_ANDROID'">
                        <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 v-decorator="['adlabPackage', {rules:validationRules.name}]" :disabled="true" />
                        </a-form-item>
                        </div>
                    </div>
                    <div class="row-item" v-if="getFormData('downloadType')=='DOWNLOAD_URL'&&getFormData('appType')=='APP_ANDROID'">
                        <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 v-decorator="['webUrl', {rules:validationRules.url}]" />
                        </a-form-item>
                        </div>
                    </div>
                    <div class="row-item" v-show="getFormData('downloadType')=='EXTERNAL_URL'">
                        <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="['useOpenUrl', { initialValue:'NO' }]" @change="useOpenUrlChange">
                            <a-radio-button value="NO">不启用</a-radio-button>
                            <a-radio-button value="YES">启用</a-radio-button>
                            </a-radio-group>
                        </a-form-item>
                        </div>
                    </div>
                    <div class="row-item" v-show="getFormData('downloadType')=='EXTERNAL_URL'&&getFormData('useOpenUrl')=='YES'">
                        <div class="hint-item"></div>
                        <div class="label-item">
                        <div class="text-item">跳转APP链接</div>
                        <div class="required-item"></div>
                        </div>
                        <div class="input-item">
                        <a-form-item>
                            <a-input v-decorator="['openUrl']" />
                        </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 style="margin-bottom:15px" v-for="(item,index) in LHKaccountInfo" :key="index">
                                <a-radio-button
                                    value="SelectConversionTarget"
                                    @click="SelectConversionTarget(item,index)"
                                    :disabled="!IsURL(getFormData('url'))"
                                    v-show="showIndex<=index"
                                >选择转化目标</a-radio-button>
                                <a-select  style="width: 335px"     v-show="showIndex>index"  @change="APIChange($event,index)">
                                    <a-select-option v-for="item in currentConvertTypes[index]" :key="item.convertId" :value='item.convertId'>
                                        {{item.external_name}}
                                    </a-select-option>
                                </a-select>
                                <span style="margin-left:20px">账户：{{item.title}} </span>
                            </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 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()],

        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:[],
        convertInfo:[],
    }
  },
  watch: {
    
  },
  methods: {
    
    callback(val) {
      console.log(val);
    },

    // 链接地址改变
    UrlChange(e){
      console.log(e.target.value);
      if(this.IsURL(e.target.value)&&this.getFormData('appType')=='APP_ANDROID'&&this.projectInfo[0].landingType=='APP'){
        postAction('/ctop/queryTool/parseInstallPackage',qs.stringify({
          installUrl:e.target.value,
          appType:this.getFormData('appType')
        })).then(res=>{
          console.log(res)
          if(res.success){
            this.form.setFieldsValue({
              adlabPackage:res.result.package
            })
          }else{
            this.$message.error(res.message)
          }
        })
      }
    },
    
    handleOk(e) {
        this.visible=false;
      // this.$router.push('/LaunchHousekeeper/setProjectDirectional')
        this.$router.push({path:'/LaunchHousekeeper/setProjectDirectional'})
       
        
    },
    handleCancel(e) {
        this.visible = false;
    },
    // 直达链接是否启用
    useOpenUrlChange(){
      this.form.setFieldsValue({
        openUrl:''
      })
    },
    // 下载方式改变
    downloadTypeChange(val){
        console.log(val)
        this.showIndex=0;
        if(val.target.value=="EXTERNAL_URL"){
            this.form.setFieldsValue({
                appType:'',
                url:'',
                adlabPackage:'',
                webUrl:'',
            })
        }else{
           this.form.setFieldsValue({
                appType:'APP_IOS',
                url:'',
                adlabPackage:'',
                useOpenUrl:'NO',
                openUrl:'',
            }) 
        }
    },
    // 投放平台改变
    appTypeChange(val){
        this.showIndex=0;
        if(val.target.value=="APP_IOS"){
            this.form.setFieldsValue({
                url:'',
                adlabPackage:'',
                webUrl:'',
            })
        }else{
           this.form.setFieldsValue({               
                url:'',
                     
            }) 
        }
    },
    //  转化目标显示
    SelectConversionTarget(item,index) {
        
        
        let downloadType=this.getFormData('downloadType');
       
        let adlabPackage=this.getFormData('adlabPackage');
        let appType=this.getFormData('appType');

        let downloadUrl='';
        let externalUrl='';
        if(downloadType=='DOWNLOAD_URL'){
            downloadUrl=this.getFormData('url');
            externalUrl='';
        }else{
            externalUrl=this.getFormData('url');
            downloadUrl='';
        }
        if(downloadType=='DOWNLOAD_URL'&&appType=='APP_ANDROID'){
            if(adlabPackage){
            postAction('/ctop/queryTool/queryConvert',qs.stringify({
                accountId:this.LHKaccountInfo[index].value,
                landingType:this.projectInfo[index].landingType,
                downloadType,
                downloadUrl,
                externalUrl,
                toutiaoPackage:adlabPackage,
                appType,
                
            })).then(res=>{
                console.log(res)
                if(res.success){
                  this.showIndex=index+1
                  this.currentConvertTypes[index]=[];
                  res.result.data.forEach(ele=>{
                    if(ele.external_actions.length>0){
                      ele.external_actions.forEach(element=>{
                        if(element.deep_external_action){
                          element.deep_external_action.forEach(i=>{
                            this.currentConvertTypes[index].push(i)
                          })
                        }else{
                          this.currentConvertTypes[index].push(element)
                        }
                      })
                    }
                      
                  })
                
                }else{
                  this.$message.error('网络异常，数据获取失败')
                }
            })
            }else{
                this.$message.error('请先输入应用包名称！')
            }
        }else{
            postAction('/ctop/queryTool/queryConvert',qs.stringify({
                accountId:this.LHKaccountInfo[index].value,
                landingType:this.projectInfo[index].landingType,
                downloadType,
                downloadUrl,
                externalUrl,
                toutiaoPackage:adlabPackage,
                appType,
                
            })).then(res=>{
                console.log(res);
                if(res.success){
                  this.showIndex=index+1;
                  this.currentConvertTypes[index]=[];
                  res.result.data.forEach(ele=>{
                    if(ele.external_actions.length>0){
                      ele.external_actions.forEach(element=>{
                        if(element.deep_external_action){
                          element.deep_external_action.forEach(i=>{
                            this.currentConvertTypes[index].push(i)
                          })
                        }else{
                          this.currentConvertTypes[index].push(element)
                        }
                      })
                    }
                      
                  })
                
                }else{
                  this.$message.error('网络异常，数据获取失败')
                }
            })
        }

        
    },

    // 转化目标改变
    APIChange(val,index,item){
      console.log(val,index,item);
      this.convertIds[index]={
        accountId:this.LHKaccountInfo[index].value,
        convertId:val,

      }
      
      // this.convertInfo[index]={
      //   accountId:this.LHKaccountInfo[index].value,
      //   ...item
      // }
    },
   
    //获取表单的某一个属性值
    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;
              let params=[];
              params=this.convertIds.map((item,index)=>{
                return {
                  ...item,
                  ...values,
                  ...this.projectInfo[index]
                }
              })
              console.log(params)
              postAction('/adlab/Project/setConvert', 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('请正确填写必填项目')
            }
          })
        
      })
      
    },
    

    
  },
  destroyed() {
     sessionStorage.setItem('convertInfo',JSON.stringify(this.convertInfo))
  },
  mounted() {
    this.$bus.$emit('remove', '/LaunchHousekeeper/newProject')
        let projectInfo=sessionStorage.getItem('projectInfo');
        if(projectInfo){
            this.projectInfo=JSON.parse(projectInfo)
        }
        let LHKaccountInfo=sessionStorage.getItem('LHKaccountInfo');
        if(LHKaccountInfo){
            this.LHKaccountInfo=JSON.parse(LHKaccountInfo)
        }
    
  },
}
</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>