<template>
  <div>
    <a-modal
      title="编辑应用"
      :visible="application"
      @ok="handleOk"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      width="800px"
    >
      <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
        <a-form :form="form">
          <!-- <selectTable :projectId.sync="projectId" ref="selectTable" :requireCheck="true"></selectTable> -->
          <a-form-item
            label="项目名称"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
          >
            <a-input
              disabled
              v-decorator="[
                'projectName',
                {
                  rules: [{ required: true }],
                },
              ]"
            />
          </a-form-item>
          <a-form-item
            label="设备类型"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
          >
            <a-radio-group v-model="appType" @change="changePlatform" disabled>
              <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 v-if="appType == 'android'"> -->
          <a-form-item
            label="推广类型"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
          >
            <a-radio-group v-model="platform" disabled>
              <a-radio value="1">应用下载</a-radio>
              <a-radio value="2">网页游戏</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            label="上传应用"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
          >
            <a-radio-group v-model="uploadType">
              <a-radio-button value="1" disabled>本地上传</a-radio-button>
              <a-radio-button value="2">填写链接</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            label="上传文件"
            v-if="uploadType == '1'"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
          >
            <!-- <a-upload name="file" :file-list="fileList" :before-upload="beforeUpload" @change="handleChange">
              <a-button><a-icon type="upload" />文件上传</a-button>
            </a-upload> -->
            <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="(!projectId && !fileUrl) || loadDisabled">
                <a-icon type="upload" />
                {{ loadDisabled ? '上传中,请稍后' : '文件上传' }}
              </a-button>
            </a-upload>
            <a @click="downLoadFile">文件格式下载</a>
          </a-form-item>

          <a-form-item
            v-if="uploadType == '2'"
            label="下载链接"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
          >
            <a-input
              placeholder="请填写应用下载链接"
              v-decorator="[
                'url',
                {
                  rules: [{ required: true, validator: handleConfirmValue }],
                },
              ]"
            />
          </a-form-item>

          <a-form-item
            label="应用包名"
            v-if="uploadType == '2' && appType == 'android'"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
          >
            <a-input
              v-decorator="[
                'packageName',
                {
                  rules: [{ required: true, message: '请填写正确的应用包名称' }],
                },
              ]"
              placeholder="请填写包名称，如com.smile.gifmaker"
            />
          </a-form-item>

          <a-form-item
            label="应用名称"
            v-if="uploadType == '2'"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
          >
            <a-input
              v-decorator="[
                'appName',
                {
                  rules: [{ required: true, message: '请填写应用名称' }],
                },
              ]"
              placeholder="请填写应用名称"
            />
          </a-form-item>

          <a-form-item
            label="上传图标"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
            v-if="application"
          >
            <uploadFile
              v-if="application"
              :value.sync="fileUrl"
              :multiple="false"
              :fileCount="1"
              uploadType="image"
              @overUpload="overUpload"
              :size="100"
            ></uploadFile>
            <p class="upload-txt-rules">文件格式：支持上传png/jpg/jpeg图片,尺寸450*450,小于100kb</p>
          </a-form-item>

          <a-form-item
            label="应用标记"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
            v-if="uploadType == '2'"
          >
            <a-input
              v-decorator="[
                'appVersion',
                {
                  rules: [{ required: true, message: ' ' }, { validator: checkAppVersion }],
                },
              ]"
              placeholder="请填写应用标记，必填且不可重复，如快手-5.6.1.66"
            />
          </a-form-item>
          <!-- <a-form-item>
            <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
              <a-button htmlType="submit" type="primary">提交</a-button>
              <a-button style="margin-left: 8px">保存</a-button>
            </a-form-item>
          </a-form-item> -->
          <a-form-item
            label=""
            :labelCol="{ span: 5 }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 }, offset: 5 }"
            v-if="uploadType == '2' && appType == 'android'"
          >
            <a-checkbox-group v-decorator="['useSdk']">
              <a-checkbox :value="0"> 该应用已接入快手广告监测SDK </a-checkbox>
            </a-checkbox-group>
          </a-form-item>
          <a-form-item
            label="隐私政策链接"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
            v-if="uploadType == '2' && appType == 'android'"
          >
            <a-input
              v-decorator="[
                'appPrivacyUrl',
                {
                  rules: [{ required: true, message: '请填写隐私政策链接' }, { validator: handleConfirmValue }],
                },
              ]"
              placeholder="请填写隐私政策链接"
            />
          </a-form-item>

          <a-form-item
            label="监测链接"
            :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
            v-if="uploadType == '2' && appType == 'android'"
          >
            <a-input v-decorator="['trackUrl']" placeholder="请填写监测链接" />
          </a-form-item>
        </a-form>
      </a-card>
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { deleteAction, postAction, getAction, downFilePost, downFile } from '@/api/manage'
import uploadFile from './uploadFile.vue'
import { mapActions, mapGetters } from 'vuex'
import BMF from 'browser-md5-file'
import selectTable from '@/views/modules/Statistics/components/selectPagination.vue'
import pick from 'lodash.pick'
const fileSuffix = ['xlsx', 'xls', 'zip']
export default {
  name: 'BaseForm',
  components: {
    uploadFile,
    selectTable,
  },
  data() {
    return {
      loadDisabled: false,
      projectId: '',
      accountId: '',
      fileList: [],
      fileUrl: '',
      accountList: {},
      appType: 'android', //设备类型
      platform: '1', //应用类型   ： 1 Android 应用下载，2： Android 网页游戏，3： iOS 应用下载， 4：iOS 网页游戏
      uploadType: '2', //上传类型 1 本地上传 2 填写链接
      appVersion: '', //应用标记
      appName: '', // 应用名称
      packageName: '', //应用包名
      file: '', // 上传文件
      imageUrl: '', // 上传图标链接链接
      downloadUrl: '', //下载链接
      showUploadFile: true,
      showDownLoad: false,
      showUpload: true,
      showAndroid: true,
      showIOS: false,
      customDomain: '',
      acceptVideo: '/*.apk,/*.png,/*.jpg,/*.jpeg,/*.mp4',
      accessKeyId: 'LTAIbNbqWzSOklQV',
      accessKeySecret: '1rkPz7JNoXk8sJevPaeYHWqfkQXBGh',
      region: 'oss-cn-beijing',
      bucket: 'ctop-media',
      form: this.$form.createForm(this),
      url: {
        insertTemplateUrl: '/kuaishouAppPackage/fillInLink',
        userAllocationList: '/ctop/userAllocation/list',
      },
      application: false,
      confirmLoading: false,
      imageToken: '',
      uploadAction: '/kuaishouAppPackage/importAppExcel',
      tokenHeader: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
      appId: null,
    }
  },
  methods: {
    checkAppVersion(rule, value, callback) {
      if (value != '') {
        if (this.projectId) {
          let params = {}
          params.projectId = this.projectId
          params.appVersion = value
          getAction('/kuaishouAppPackage/checkAppVersion', params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback(res.message)
            }
          })
        }
      } else {
        callback('应用标记必填')
      }
    },
    overUpload(file) {
      console.log(file)
    },
    downLoadFile() {
      downFile('/kuaishouAppPackage/exportAppTemplate').then((res) => {
        let blob = new Blob([res], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        })
        let downloadElement = document.createElement('a')
        let href = window.URL.createObjectURL(blob) //创建下载的链接
        downloadElement.href = href
        downloadElement.download = '应用模板' //下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() //点击下载
        document.body.removeChild(downloadElement) //下载完成移除元素
        window.URL.revokeObjectURL(href) //释放掉blob对象
      })
    },
    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 == 200) {
          this.application = true
          this.$emit('getDataList')
          this.$message.success(info.file.response.message)
        } 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)
    },
    beforeUpload(file) {
      // this.cosUpload(file)
      if (process.env.NODE_ENV == 'development') {
        this.uploadAction = `/jeecg-boot/kuaishouAppPackage/importAppExcel?projectId=${this.projectId}&platform=${
          this.appType == 'ios' ? +this.platform + 2 : +this.platform
        }&imageUrl=${this.fileUrl}`
      } else if (process.env.NODE_ENV == 'debug') {
      } else if (process.env.NODE_ENV == 'production') {
        this.uploadAction = `${this.axios.defaults.baseURL}/kuaishouAppPackage/importAppExcel?projectId=${
          this.projectId
        }&platform=${this.appType == 'ios' ? +this.platform + 2 : +this.platform}&imageUrl=${this.fileUrl}`
      }
      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
      }
    },
    cosUpload(file) {
      let that = this
      let date = new Date()
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let timeElse = new Date().getTime()
      let arr = file.name.split('.')
      let str = ''
      for (let i = 0; i < arr.length; i++) {
        if (i === arr.length - 1) {
        } else {
          if (i === arr.length - 2) {
            str += arr[i]
          } else {
            str += arr[i] + '.'
          }
        }
      }
      cos.putObject(
        {
          Bucket: 'media-1301855440',
          Region: 'ap-chongqing',
          // 存储桶所在地域，必须字段
          Key: that.appType + '/' + y + '-' + MM + '-' + d + '/' + str + '-' + timeElse + '.' + arr[arr.length - 1],
          StorageClass: 'STANDARD',
          Body: file, // 上传文件对象
        },
        function (err, data) {
          if (err) {
            that.$message.error('上传失败!!!' + err)
            return
          }
          that.loadingElse = false
          that.fileList.push({
            uid: file.name,
            name: file.name,
            status: 'done',
            url: '//' + data.Location,
          })
          if (that.fileList.length > 1) {
            that.fileList = that.fileList.slice(-1)
          }
          const isZip = file.type.includes('zip') || file.type.includes('text')
          const fileOvesize = file.size > 1024 * 1024 * 1024
          if (!isZip) {
            that.$message.error('只能上传zip格式的文件或者txt文件')
            return
          }
          if (fileOvesize) {
            that.$message.error('文件大小不能超过1G')
            return
          }
          that.handleMd5(file)
        }
      )
    },
    handleMd5(file) {
      let bmf = new BMF()
      let that = this
      return new Promise(function (resolve, reject) {
        bmf.md5(file, (err, md5) => {
          // getAction('kuaishouPopulationPackage/checkPopulationPackage', { signature: md5 })
          //   .then((result) => {
          //     if (result.code === 200) {
          that.personNameDisabled = false
          that.personResourceDisabled = false
          resolve()
          //   } else if (result.code === 201) {
          //     that.$message.error(result.message)
          //     that.personForm.name = result.result.orientationName
          //     that.personForm.resource = result.result.type
          //     that.personNameDisabled = true
          //     that.personResourceDisabled = true
          //     reject()
          //   }
          // })
          // .catch((error) => {
          //   console.log(error, 'eeee')
          //   reject()
          // })
        })
      })
    },
    handleOk() {
      this.handleSubmit()
    },
    handleCancel() {
      this.form.resetFields()
      this.imageUrl = ''
      this.fileUrl = ''
      this.platform = '1'
      this.application = false
      this.uploadType = '2'
    },
    showApplication(val) {
      this.application = true
      this.appId = val.id
      getAction('/kuaishouAppPackage/queryById', { id: val.id }).then((res) => {
        //   'appIconUrl',
        if (res.success) {
          this.fileUrl = res.result.appIconUrl
          this.appType = res.result.platform > 2 ? 'ios' : 'android'
          this.platform = res.result.platform > 2 ? res.result.platform - 2 + '' : res.result.platform + ''
          res.result.useSdk = res.result.useSdk ? (res.result.useSdk == 0 ? [] : [0]) : null
          this.projectId = res.result.projectId
          if (this.appType == 'android') {
            this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(res.result, 'url', 'packageName', 'appPrivacyUrl', 'useSdk', 'trackUrl', 'appName', 'projectName')
              )
              setTimeout(() => {
                this.form.setFieldsValue(pick(res.result, 'appVersion'))
              }, 150)
            })
          } else {
            setTimeout(() => {
              this.form.setFieldsValue(pick(res.result, 'url', 'appVersion', 'projectName'))
            }, 100)
            setTimeout(() => {
              this.form.setFieldsValue(pick(res.result, 'appName'))
            }, 150)
          }
        }
      })
    },
    handleConfirmValue(rule, value, callback) {
      if (/(http|https):\/\/([\w.]+\/?)\S*/.test(value) && value != '') {
        callback()
      } else {
        callback('链接不能为空且开头为http://或https://')
      }
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    changePlatform() {
      // this.form.resetFields()
      // if (this.appType == 'android') {
      //   this.showAndroid = true
      //   this.showIOS = false
      //   this.platform = '1'
      // } else {
      //   this.showAndroid = false
      //   this.showIOS = true
      //   this.showDownLoad = true
      //   this.platform = '1'
      // }
    },

    handleSubmit() {
      //   console.log('设备类型：' + this.appType)
      //   console.log('应用类型：' + this.platform)
      //   console.log('上传类型：' + this.uploadType)
      //   console.log('应用标记：' + this.appVersion)
      //   console.log('应用名称：' + this.appName)
      //   console.log('包名称：' + this.packageName)
      //   console.log('文件地址：' + this.file)
      //   console.log('图片地址：' + this.imageUrl)
      //   e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.fileUrl && this.projectId) {
            this.confirmLoading = true
            let params = {}
            params.projectId = this.projectId
            if (this.uploadType == '1') {
              this.url.insertTemplateUrl = '/kuaishouAppPackage/importAppExcel'
              params.platform = this.appType == 'ios' ? +this.platform + 2 : +this.platform
              params.imageUrl = this.fileUrl
            } else {
              this.url.insertTemplateUrl = '/kuaishouAppPackage/fillInLink'
              params = { ...values }
              params.useSdk = params.useSdk ? (params.useSdk.length > 0 ? 1 : 0) : null
              params.id = this.appId
              params.projectId = this.projectId
              params.appIconUrl = this.fileUrl
              params.platform = this.appType == 'ios' ? +this.platform + 2 : +this.platform
            }
            postAction(this.url.insertTemplateUrl, params).then((res) => {
              this.confirmLoading = false
              if (res.success) {
                this.$message.success('修改成功')
                this.handleCancel()
                this.$emit('getDataList')
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            this.$message.error('请填写必填项')
          }
        }
      })
    },

    onChange(value) {
      console.log(value)
    },
  },
  created: function () {
    let params = {}
    params.pageSize = '1000'
    params.mediaId = '2'
    params.userId = this.userInfo().id
    getAction(this.url.userAllocationList, params).then((res) => {
      if (res.success) {
        this.accountList = res.result.records
      }
    })
  },
}
</script>
