<template>
  <div class="newPlan">
    <a-form :form="form">
      <div class="moduler">
        <div class="moduler-title">选择账户</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-tree-select
                    v-model="accountIds"
                    show-search
                    style="width: 600px;height:30px"
                    :dropdownMatchSelectWidth='true'
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"              
                    tree-checkable
                    searchPlaceholder='请输入账户关键字搜索'
                    :show-checked-strategy="SHOW_PARENT"
                    placeholder="请选择项目和账户或搜索账户关键字"
                    treeNodeFilterProp="title"
                    :allowClear="true"
                    @change="treeChange"
                    @search="treeSearch"
                    @select="treeSelect"                        
                    :maxTagCount='1'    
                    :tree-data="treeData"
                    :filterOption='filterOption'
                >
              
                </a-tree-select>
            </div>
          </div>
        </div>
      </div>
      <!-- 投放范围 -->
      <div class="moduler">
        <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="['deliveryRange', { initialValue:'DEFAULT' }]">
                  <a-radio-button value="DEFAULT">默认</a-radio-button>
                  <a-radio-button value="UNION">
                    穿山甲
                    <a-tooltip>
                      <template slot="title">基于4亿日活跃用户大数据积累，顶尖AI智能推荐技术，今日头条与最广泛的合作伙伴携手打造全新移动生态联盟</template>
                      <a-icon type="question-circle" />
                    </a-tooltip>
                  </a-radio-button>
                </a-radio-group>
              </a-form-item>
            </div>
          </div>        
        </div>
      </div>
        <!-- 推广目的 -->
        <div class="moduler">
            <div class="moduler-title">请选择推广目的</div>
            
            <div class="row-item">
                <div class="hint-item">
                    <a-tooltip>
                    <template slot="title">
                        <span>应用推广：提升应用的下载、安装、激活、付费</span>
                        <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-radio-group   v-decorator="['landingType',{initialValue:'APP' }]" @change="landingTypeChange">
                        <a-radio-button value="APP">应用推广</a-radio-button>
                        <a-radio-button value="LINK">销售线索收集</a-radio-button>                                   
                    </a-radio-group>
                    </a-form-item>
                </div>
            </div>        
           
        </div>
        <!-- 投放方式 -->
        <div class="moduler">
            <div class="moduler-title">请选择投放方式</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-radio-group v-decorator="['adTarget', { initialValue:'CPA' }]">
                  <a-radio-button value="CPA" >优先成本</a-radio-button>
                  <a-radio-button value="COST">优先跑量</a-radio-button>
                  <a-radio-button value="PUSH">激进抢量</a-radio-button>
                 </a-radio-group> 
              </a-form-item>
            </div>
          </div>  
            
        </div>
        <!-- 基础信息 -->
        <div class="moduler">
            <div class="moduler-title">请设置基本信息</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-model="name"  allow-clear />
               </a-form-item>
            </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>
    </a-form>
    <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 { TreeSelect } from 'ant-design-vue';
import qs from 'qs'
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
// import selectCheckAll from './toutiaoTime'

var str = ""
for (let i = 0; i < 7*48; i++) {
 str+='0'
  
}
export default {
  components: {
    // selectCheckAll,
    // newDirectedPackage,
  },
  data() {
    return {
        LHKaccountInfo:{},
        treeValue: [],
        treeData: [],
        SHOW_PARENT,
        accountIds:[],
        name: '',
        form: this.$form.createForm(this),

        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,
            }],
        },
        
    }
  },
  watch: {
    
  },
  methods: {
    // //项目改变后的事件
    treeChange(val) {
      // console.log(this.treeData)
      console.log(val)
      this.accountIds = [];
      //选择一个后禁用其他
      if(val.length==1){
          if(val[0]*1){
            let selectindex=0
              this.treeData.forEach((ele,index)=>{                   
                  if(ele.children){
                     ele.children.map((item,ind)=>{
                            if(item.value==val[0]){
                                selectindex=index;
                            }
                      })
                  }                   
              });
              // console.log(selectindex)
              if(selectindex ||selectindex==0){
                this.treeData.forEach((ele,index)=>{
                    if(index!=selectindex){
                         ele.disableCheckbox = true;
                         if(ele.children){
                              ele.children.map((item,ind)=>{
                                   item.disableCheckbox = true;
                              })
                         }
                    }
                })
              }
              
          }else{
            //  console.log(1)
              this.treeData.forEach((ele,index)=>{
                    if(ele.value!=val[0]){
                         ele.disableCheckbox = true;
                         
                         if(ele.children){
                              ele.children.forEach((item,ind)=>{
                                   item.disableCheckbox = true;
                              })
                         }
                    }
                    
              })
          }
          // console.log(this.mediaId)
          
      }

        if(val.length==0){
            this.treeData.forEach((ele,index)=>{              
                    ele.disableCheckbox = false;
                    
                    if(ele.children){
                        ele.children.forEach((item,ind)=>{
                            item.disableCheckbox = false;
                        })
                    }
                
            });
            
        }
      if(val){
        val.forEach((ele,index)=>{
          if(ele*1){
              this.accountIds.push(ele)
          }else{              
              let projectArr=this.treeData.filter((item)=>{
                  return item.value==ele
              });
              // console.log(projectArr)
              projectArr[0].children.forEach((element)=>{
                 this.accountIds.push(element.value)
              })
          }


        })       
      }
      
     console.log(this.accountIds);
      let LHKaccountInfo=[]
      this.accountIds.forEach(item=>{
          this.treeData.forEach(element=>{
            element.children.forEach(ele=>{
              if(item==ele.value){
                LHKaccountInfo.push(ele)
              }
            })
          })
      })

      sessionStorage.setItem('LHKaccountInfo',JSON.stringify(LHKaccountInfo))
    },
    treeSearch(){
    },
    treeSelect(){
    },
    
    filterOption(input, option){
      console.log(input, option)
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
    },
 

    //请求项目和账户内容
    accountHttp(){
        this.treeData=[];
        this.accountIds=[];
        getAction('/ctop/projectMember/getProjectAccountByUserId?mediaType=1', {}).then(res => {
        if(res.success){
                // console.log(res);
                if(res.result){
                    res.result.forEach((element,index) => {
                    if(element){                  
                        this.treeData.push({});                    
                        this.treeData[index].title=element.project.projectName +'_('+ element.project.advertiserName +')';
                        this.treeData[index].value='project'+element.project.projectId;
                        this.treeData[index].key=element.project.projectId;
                        this.treeData[index].mediaId=element.project.mediaId;
                        this.treeData[index].children=[];
                                            
                        if(element.account.length){
                        element.account.forEach((ele,i)=>{
                            this.treeData[index].children.push({});
                            this.treeData[index].children[i].title=ele.userName+'_'+ele.authName+'_'+element.project.projectName;
                            this.treeData[index].children[i].value=ele.accountId;
                            this.treeData[index].children[i].key=ele.accountId;
                        })
                            
                        }                           
                    }      
                    });
                    // console.log(this.treeData)
                    
                }
        }
        })
    },

    
    handleOk(e) {
        this.visible=false;
        this.$router.replace({path:'/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'),
      })
    },
    
    //推广目的改变
    landingTypeChange(e){
        console.log(e.target)
        if(e.target.value=='APP'){            
            this.name=`应用推广_${moment().format('MM_DD_HH:SS')}`           
        }else if(e.target.value=='LINK'){            
            this.name=`销售线索收集_${moment().format('MM_DD_HH:SS')}`           
        }
    },
    
    // 验证网址
    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/newProject')
    },
    
    // 保存并新建创意
    goNext() {
      this.$nextTick(()=>{
        if (this.name) {
           let LHKaccountInfo=sessionStorage.getItem('LHKaccountInfo');
            if(LHKaccountInfo){
                this.LHKaccountInfo=JSON.parse(LHKaccountInfo)
            }
          this.form.validateFields((err, values) => {
            if (!err) {

              console.log('Received values of form: ', values)
              // console.log(this.names)
              this.goNextloading=true;
              values.accountIds = this.accountIds
              values.name=this.name
              postAction('/adlab/Project/create', {                
                ...values,
              }).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('网络开小差了，等会再试试')
                }
              })
            }else{
              this.$message.error('请正确填写必填项目')
            }
          })
        }else{
            this.$message.error('请输入投放项目名称')
        }
      })
      
    },
    

    
  },
  
  mounted() {
    this.accountHttp()
    // this.$bus.$emit('remove', '/modules/BatchCreate/newGroup')
    let namepart='';
    if(this.getFormData('landingType')=='APP'){
        namepart='应用推广'
    }else{
        namepart='销售线索收集'
    }
    
    this.name ='[项目]'+ namepart + moment().format('MM_DD_hh:mm') ;

    
  },
}
</script>
<style lang="scss">
.newPlan{
  .ant-btn-danger {
    background-color: #ff4d4f !important; 
  }
}


.ant-tooltip-inner,
.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: 9px;
    }
    .row-item .label-item {
      position: relative;
      align-items: flex-start;
      align-self: flex-start;
      line-height: 20px;
      height: 20px;
      margin-top: 10px;
      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;
      }
    }
  }
  .opt {
    text-align: right;
  }
}
</style>