<template>
  <div class="newAppId">
    
        <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">                    
                    <!-- <Treeselect :appId.sync="accountId" :multiple="false" request="2" reqUrl='/ctop/projectMember/getProjectAccountByUserId'  ref="treeSelect" style="margin-bottom:8px;width:580px " /> -->
                   
                    <Treeselect :appId.sync="accountId" :multiple="false"  request="2,4"   ref="treeSelect" style="margin-bottom:8px;width:600px " />               
              
                </div>
            </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-radio-group  v-model="platform" >
                            <a-radio-button :value="1">Android应用刚下载</a-radio-button>
                            <a-radio-button :value="3">IOS应用下载</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">
                
              <uploadFile
                  :value.sync="urlListImage.url"
                  :checkFile="fileWater"
                  @overUpload="overUploadImage"
                  @removeUpload="deleteImage"
                  :fileCount="1"
                  uploadType="image"
                  :disabled="!accountId"
              />
                
            </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 :href="attachmentUrl" style="margin-right:20px;display:block" v-if="attachmentUrl">{{attachmentName}}</a>
                    <a-upload
                        name="file"
                        :multiple="false"
                        :action="uploadAction"
                        :headers="tokenHeader"
                        :file-list="fileList"
                        :showUploadList="false"
                        :beforeUpload="beforeUpload"
                        @change="handleChange"
                        style="margin-right:20px"
                        
                        >
                            <a-button :disabled="!accountId&&!urlListImage.url || loadDisabled">
                            <a-icon type="upload" />
                                {{loadDisabled?'上传中,请稍后':'文件上传'}}
                            </a-button>
                    </a-upload>

            </div>
          </div>  
            
        </div>
    
      <div class="moduler">
        <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>
</template>

<script>
import Vue from 'vue'
import {ACCESS_TOKEN} from "@/store/mutation-types";
import moment from 'moment'
import { getAction, postAction, downFile, downFilePost } from '@/api/manage'
import Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'
import { TreeSelect } from 'ant-design-vue';
import qs from 'qs'
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
// import selectCheckAll from './toutiaoTime'
import BMF from 'browser-md5-file'
import uploadFile from '@/components/uploadFile.vue'

var str = ""
for (let i = 0; i < 7*48; i++) {
 str+='0'
  
}
const fileSuffix = [
  'xlsx',
  'xls',
  'zip'
]
export default {
    components: {
       
        Treeselect,
        uploadFile,
    },
    data() {
        return {
          platform:1,
            urlListImage: {
                url: '', 
                md5:'',
                signature:'',
              imageToken:'',
            },
            attachmentName:'',
            attachmentUrl:'',
            treeData:[],
            accountId:undefined,
           
            goNextloading:false,
            goPlanShowloading:false,
            
            fileList:[],
            isEidt:false,
            loadDisabled:false,
            tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
            uploadAction:'',
            imageinfo:{
              signature:'',
              imageToken:'',
            }

        }
    },
    watch: {
        accountId(n,o){
          this.urlListImage={
                url: '',
                signature:'',
                imageToken:'',
          }
          this.fileList=[];
          this. attachmentName='';
            this.attachmentUrl='';
        }
    },
    methods: {
    
        fileWater(file) {
            console.log(file)
            var bmf = new BMF()
            var that = this
            
            this.urlListImage = {
                url: '',
                md5: '',
                
            }
            
            return new Promise( (resolve, reject)=> {
                bmf.md5(file, (err, md5) => {
                  that.urlListImage.name=file.name
                  that.urlListImage.md5=md5
                  that.urlListImage.size=file.size
                })
                resolve()
            })
        },
        deleteImage(urls) {
            console.log(urls, this.urlListImage.url)
            this.urlListImage.url='';
            
        },
        overUploadImage(urlAll) {
            console.log(urlAll)
            var that = this
            that.material = []
            that.imageArrList = []
            var img
            if (urlAll.length > 0) {
                urlAll.forEach((ele,index)=>{

                    this.urlListImage.url=ele.url
                    postAction('/ai/aiKuaiShouAppInfo/uploadAppIconImage',{
                      accountId:this.accountId,
                      url:'http:'+this.urlListImage.url
                    }).then(res=>{
                      this.urlListImage.signature=res.signature
                      this.urlListImage.imageToken=res.imageToken
                    })
                })
                
            } else {}
        },
        addImage(item) {
            this.addImageVisible = true
            this.addImageData = item
        },
        
        //获取表单的某一个属性值
        getFormData(className) {
        return this.form.getFieldValue(className)
        },
       
        goBack() {
            this.$router.replace('/autoLaunch/appIdList')
            this.$bus.$emit('remove', '/autoLaunch/newAppId')
        },
    
       
        //请求项目和账户内容
        accountHttp(){
            this.treeData=[];
            this.accountIds=[];
            getAction('/ctop/projectMember/getProjectAccountByUserId?mediaType=2', {}).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)
                        
                    }
            }
            })
        },

        
        beforeUpload(file) {
            // ${this.form.project}
            if (process.env.NODE_ENV == 'development') { 
                this.uploadAction= `/jeecg-boot/ai/aiKuaiShouAppInfo/importAppExcel?accountId=${this.accountId}&platform=${this.platform}&imageToken=${this.urlListImage.imageToken}`
            } 
            else if (process.env.NODE_ENV == 'debug') { 
            } 
            else if (process.env.NODE_ENV == 'production') { 

              this.uploadAction= `${this.axios.defaults.baseURL}/ai/aiKuaiShouAppInfo/importAppExcel?accountId=${this.accountId}&platform=${this.platform}&imageToken=${this.urlListImage.imageToken}`
            }

            this.loadDisabled = true
            const size = (Number(file.size) / (1024 * 1024)).toFixed(2)
            const fileName = file.name
            const fileStrArr = fileName.split('.')
            const suffix = fileStrArr[fileStrArr.length - 1]

            let result = fileSuffix.some((item) => {
                return item === suffix
            })

            if (!result) {
                this.$message.error('不支持该文件类型')
                this.loadDisabled = false
                return false
            }

            // if (size > 10) {
            //     this.$message.error('文件不能大于10MB')
            //     this.loadDisabled = false
            //     return false
            // }
            
        },
        handleChange(info) {
            console.log(info)
            let fileList = [...info.fileList];

            // 1. Limit the number of uploaded files
            //    Only to show two recent uploaded files, and old ones will be replaced by the new
            fileList = fileList.slice(-2);

            // 2. read from response and show file link
            fileList = fileList.map(file => {
                if (file.response) {
                    // Component will show file.url as link
                    file.url = file.response.url;
                }
                return file;
            });
            if(fileList.length>0){
                this.fileList = [
                    {
                        ...fileList[fileList.length-1]
                    }
                ]
            }else{
                this.fileList=[]
            }
            // this.loadDisabled = false 
            // this.$message.success('文件导入成功，异步创建中，请稍后查看...')
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList)
            }
            if (info.file.status === 'done') {
                
                this.loadDisabled = false 
                if(info.file.response.code==0){
                  this.$message.success(info.file.response.message)
                  this.$router.replace('/autoLaunch/appIdList')
                  this.$bus.$emit('remove', '/autoLaunch/newAppId')
                }else{
                  this.$message.error(info.file.response.message)
                }
                
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name}上传失败`)
                this.loadDisabled = false
            }

            // console.log(this.form)
        },
        
    },
    
  mounted() {
    this.accountHttp()
   
  },
}
</script>
<style lang="scss">
.newAppId{
  .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>
.newAppId {
  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>