<template>
  <div class="p20">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>

      <el-form-item label="落地页名称" prop="name">
        <el-input v-model="ruleForm.name" style="width:300px" />
      </el-form-item>

      <el-form-item label="背景图素材" prop="bgUrl">
        <Upload :file-count="1" @imgUrlChange="bgUrlChange" />
      </el-form-item>

      <el-form-item v-if="ruleForm.bgUrl" label="添加按钮素材" prop="btnUrl">
        <Upload :file-count="1" @imgUrlChange="btnUrlChange" />
      </el-form-item>

      <el-form-item v-if="ruleForm.bgUrl" label="添加按钮位置">
        <el-radio-group v-model="radio" @change="radioChange">
          <el-radio :label="1">底部悬浮</el-radio>
          <el-radio :label="2">居中悬浮</el-radio>
          <el-radio :label="3">自定义</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label=" ">

        <div class="bgBox">
          <div id="dragDiv" class="btnBox"></div>
        </div>

      </el-form-item>

      <el-form-item label="配置支付链接">
        <el-input v-model="ruleForm.paymentUrl" />
      </el-form-item>

      <el-form-item label=" ">
        <el-button type="primary" @click="savePage">创建落地页</el-button>
        <el-button type="primary" @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
v-if="dialogVisible"
v-model="dialogVisible"
destroy-on-close
title="选择获客链接"
width="70%"
      :before-close="handleClose"
>
      <div>
        <List :is-only-read="true" @getlandingPageInfo="getPageInfo" />
      </div>
      <template #footer>
        <div class="dialog-footer" style="margin-top:50px">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script>
import Upload from './upload.vue'
import { updatePage, savePage, getPageDetail } from '@/api/page.js'

export default {
  components: { Upload },
  name: 'CreatePage',
  props: {
    ruleForm: {
      type: Object,
      default: () => ({
        bgUrl: '',
        btnPosition: 0,
        btnStyle: '',
        btnUrl: '',
        name: '',
        paymentUrl: ''
      })
    }
  },
  data() {
    return {
      isEdit: false,
      radio: 1,
      dialogVisible: false,

      rules: {
        name: [
          { required: true, message: '请输入落地页名称!', trigger: 'blur' },
          { min: 1, max: 150, message: '长度在 1 到 150 个字符', trigger: 'blur' }
        ],
        bgUrl: [
          { required: true, message: '请上传背景图', trigger: 'blur' }
        ],
        btnUrl: [
          { required: true, message: '请上传按钮图', trigger: 'blur' }
        ],
        paymentUrl: [
          { required: true, message: '请填写支付链接', trigger: 'blur' }
        ]
      },
      btnInfo: {
        width: 0,
        height: 0,
        url: ''
      },
      bgInfo: {
        width: 0,
        height: 0,
        url: ''
      },
      pageData: {},
      btnData: {},

      prevHandleMouseDown: null,
      prevHandleMouseMove: null
    }
  },

  watch: {
    radio(val) {
      // 获取需要拖动的元素和它的父元素
      const dragDiv = document.getElementById('dragDiv')
      const bgBox = document.getElementsByClassName('bgBox')[0]

      // 初始化拖动状态和相关变量
      let isDragging = val === 3

      let offsetX = 0; let offsetY = 0

      if (val !== 3) {
        dragDiv.removeEventListener('mousedown', this.prevHandleMouseDown)
        document.removeEventListener('mousemove', this.prevHandleMouseMove)
        return
      }

      // 鼠标移动事件处理函数
      function handleMousemove(event) {
        // console.log('-----------move', isDragging);
        if (!isDragging) return
        event.preventDefault()
        // 计算拖动元素的新位置并更新样式
        var currentX = event.clientX - offsetX
        var currentY = event.clientY - offsetY
        // 确保拖动元素不会移出父元素的边界
        var dragDivRect = dragDiv.getBoundingClientRect()
        var bgBoxRect = bgBox.getBoundingClientRect()

        var newLeft = Math.max(0, Math.min(currentX, bgBoxRect.width - dragDivRect.width))
        var newTop = Math.max(0, Math.min(currentY, bgBoxRect.height - dragDivRect.height))
        // dragDiv.style.left = newLeft + 'px';
        // dragDiv.style.top = newTop + 'px';
        dragDiv.style.left = (newLeft / bgBoxRect.width) * 100 + '%'
        dragDiv.style.top = (newTop / bgBoxRect.height) * 100 + '%'
      }

      function handleMouseDown(event) {
        // console.log('-----------down', isDragging);
        isDragging = true
        offsetX = event.clientX - dragDiv.offsetLeft
        offsetY = event.clientY - dragDiv.offsetTop
        event.preventDefault()
        document.addEventListener('mousemove', handleMousemove)
        document.addEventListener('mouseup', () => {
          isDragging = false
          document.removeEventListener('mousemove', handleMousemove)
        })
      }
      dragDiv.addEventListener('mousedown', handleMouseDown)
      this.prevHandleMouseDown = handleMouseDown
      this.prevHandleMouseMove = handleMousemove
    }
  },

  mounted() {
    // 如果是编辑页面，则获取链接详情
    if (this.$route.params.id && this.$route.params.id !== 'undefined') {
      this.isEdit = true
      // 查询落地页详情
      this.getPageDetail(this.$route.params.id)
    } else if (this.ruleForm.id) {
      this.isEdit = true
      // 查询落地页详情
      this.getPageDetail()
    }
  },
  methods: {
    async readImg(val, type) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = val
        img.onload = function() {
          const width = img.width
          const height = img.height
          resolve({ width, height, url: val })
        }
        img.onerror = function() {
          reject(new Error('图片加载失败'))
        }
      })
    },

    async getPageDetail(id) {
      let pageData = {}
      if (id) {
        pageData = (await getPageDetail({ id }))
      } else {
        pageData = { data: this.ruleForm }
      }

      // 赋值
      this.ruleForm.id = pageData.data.id
      this.ruleForm.name = pageData.data.name
      this.ruleForm.bgUrl = pageData.data.bgUrl
      this.ruleForm.btnUrl = pageData.data.btnUrl
      this.ruleForm.paymentUrl = pageData.data.paymentUrl
      this.radio = pageData.data.btnPosition
      this.pageData = pageData.data

      // 等待读取文图片的尺寸
      const bgData = await this.readImg(pageData.data.bgUrl, 1)
      this.bgInfo = {
        width: bgData.width,
        height: bgData.height,
        url: bgData.url
      }
      this.bgStyleChange()

      if (pageData.data.btnUrl) {
        const btnData = await this.readImg(pageData.data.btnUrl, 2)
        this.btnInfo = {
          width: btnData.width,
          height: btnData.height,
          url: btnData.url
        }
        if (this.radio !== 3) {
          this.btnStyleChange()
        } else {
          const el = document.getElementById('dragDiv')
          // 获取 this.pageData.btnStyle 中的style部分
          // const styleStr = this.pageData.btnStyle.match(/style="(.*?)"/)[1];
          const styleStr = this.pageData.btnStyle
          const newStyleStr = styleStr.replace(/&quot;/g, '')
          el.style = newStyleStr
        }
      }
      this.$refs.ruleFormRef.validate()
    },

    handleClose() {
      this.dialogVisible = false
    },

    bgUrlChange(url, height, width) {
      if (this.btnInfo.url) {
        if (width < this.btnInfo.width || height < this.btnInfo.height) {
          return this.$message.error('图片尺寸不能小于按钮图尺寸')
        }
      }

      this.$set(this.ruleForm, 'bgUrl', url)
      this.$nextTick(() => {
        this.$refs.ruleFormRef.validateField('bgUrl')
      })
      this.bgInfo = {
        width,
        height,
        url
      }
      this.bgStyleChange()
    },

    bgStyleChange() {
      const bgDiv = document.getElementsByClassName('bgBox')[0]
      // 设置bgDiv的行内样式 不存储
      bgDiv.style.width = `${this.bgInfo.width}px`
      bgDiv.style.height = `${this.bgInfo.height}px`
      bgDiv.style.backgroundImage = `url('${this.bgInfo.url}')`
      bgDiv.style.position = 'relative'
      bgDiv.style.overflow = 'hidden'
    },

    btnUrlChange(url, height, width) {
      if (width > this.bgInfo.width || height > this.bgInfo.height) {
        return this.$message.error('图片尺寸不能大于背景图尺寸')
      }
      this.$set(this.ruleForm, 'btnUrl', url)
      this.$nextTick(() => {
        this.$refs.ruleFormRef.validateField('btnUrl')
      })
      this.btnInfo = {
        // width: width / this.bgInfo.width * 100,
        width,
        height,
        url
      }
      this.btnStyleChange()
    },

    btnStyleChange() {
      const btnDiv = document.getElementsByClassName('btnBox')[0]
      btnDiv.style.width = `${this.btnInfo.width}px`
      btnDiv.style.height = `${this.btnInfo.height}px`
      // btnDiv.style.width = `${this.btnInfo.width /  this.bgInfo.width * 100}px`;
      // btnDiv.style.height = `${this.btnInfo.height}px`;

      btnDiv.style.backgroundImage = `url('${this.btnInfo.url}')`
      btnDiv.style.position = 'absolute'
      if (this.radio === 1) {
        btnDiv.style.bottom = '0px'
        btnDiv.style.left = '50%'
        btnDiv.style.transform = 'translate(-50%, 0)'
      }
      if (this.radio === 2) {
        btnDiv.style.top = '50%'
        btnDiv.style.left = '50%'
        btnDiv.style.transform = 'translate(-50%, -50%)'
      }
      if (this.radio === 3) {
        btnDiv.style.left = '0px'
        btnDiv.style.top = '0px'
        btnDiv.style.transform = 'translate(0, 0)'
      }
    },

    // 对话框提交
    submit() {
      this.dialogVisible = false
      this.$refs.ruleFormRef.validateField('linkId')
    },

    // 表格选择结果
    getPageInfo(val) {
      if (!val) return
      const data = JSON.parse(JSON.stringify(val))
      data.members = JSON.parse(data.members)
      this.linkInfo = data
    },

    radioChange() {
      const btnDiv = document.getElementsByClassName('btnBox')[0]
      // 清除该元素的全部行内样式
      btnDiv.style.cssText = ''
      this.btnStyleChange()
    },

    savePage() {
      this.$refs.ruleFormRef.validate(async(valid) => {
        if (valid) {
          // 加密
          // if (!this.ruleForm.btnUrl) {
          //   return this.$message.error('请先填写表单！');
          // }
          if (!this.ruleForm.bgUrl) {
            return this.$message.error('请先填写表单！')
          }
          // if (!this.ruleForm.linkId) {
          //   return this.$message.error('请先填写表单！');
          // }

          // 获取div中的内容 需要存储 用于定位
          // const dragDiv = document.getElementById('dragDiv')
          // 只存储样式
          const btnHtml = document.getElementsByClassName('bgBox')[0].innerHTML
          const styleStr = btnHtml.match(/style="(.*?)"/) ? btnHtml.match(/style="(.*?)"/)[1] : ''
          const data = {
            id: this.ruleForm.id,
            name: this.ruleForm.name,
            bgUrl: this.ruleForm.bgUrl,
            btnStyle: styleStr || '',
            btnUrl: this.ruleForm.btnUrl || '',
            paymentUrl: this.ruleForm.paymentUrl,
            btnPosition: this.radio
          }
          const ret = this.isEdit ? await updatePage(data) : await savePage(data)
          if (ret.code === 0) {
            this.$emit('submit')
            this.$message.success('操作成功！')
            this.goBack()
          } else {
            this.$message.error(`操作失败！${ret.msg}`)
          }
        } else {
          this.$message.error('请完成表单！')
        }
      })
    },
    goBack() {
      this.$store.dispatch('delView', this.$route)
      this.$router.push('/foundation/page')
    }
  }
}

</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.p20 {
  padding: 20px;
}
</style>
