<script lang="ts">
import Vue from 'vue'
import { getFormInfo, submitForm, getLocationList, getJobList } from '@/api/form'
import expoHead from '../components/expoHead.vue'
import { getExpoInfo } from '@/api/expo'
import countryCode from '@/lib/countryCode.json'
import login from '@/views/login/index.vue'
export default Vue.extend({
  name: 'Index',
  components: {
    expoHead
  },
  data() {
    return {
      from_data: [],
      expo_key: '',
      expo_id: '',
      countryCode,
      locationList: [],
      locationPage: 0,
      locationTotal: 1,
      provinceL: [],
      cityL: [],
      jobList: [],
      jobPage: 0,
      jobTotal: 1,
      jobL: [],
      noForm: false,
      loading: false,
      isOk: false
    }
  },
  computed: {
    user() { return this.$store.state.user.user },
    token() { return this.$store.state.user.token }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.expo_key = this.$route.params.url
      const form_data = sessionStorage.getItem('form_cache')
      if (form_data) {
        this.from_data = JSON.parse(form_data)
        this.expo_id = this.from_data.id
      } else {
        getExpoInfo(this.expo_key).then(res => {
          this.from_data = res.data
          this.from_data.images = JSON.parse(res.data.images)
          this.from_data.social_links = JSON.parse(res.data.social_links)
          if (this.from_data.social_links.facebook === '' || this.from_data.social_links.twitter === '' || this.from_data.social_links.linkedin === '') {
            this.from_data.social_links = false
          }
          this.from_data.form_fields.forEach(item => {
            if (item.field_type === 'checkbox') {
              this.$set(item, 'value', [])
            }
          })
          this.expo_id = res.data.id
        }).catch(err => {
          this.noForm = true
        })
      }
    },
    share(way) {
      let url = ''
      let prams = ''
      if (way === 'twitter') {
        url = 'https://twitter.com/intent/tweet'
        prams += ('?url=' + window.location.href)
        prams += ('&text=' + this.from_data.expo_name + ' | ' + this.from_data.content)
      }
      if (way === 'facebook') {
        url = 'https://www.facebook.com/sharer/sharer.php'
        prams += ('?u=' + window.location.href)
        prams += ('&title=' + this.from_data.expo_name)
        prams += ('&quote=' + this.from_data.content)
      }
      if (way === 'linkedin') {
        url = 'https://www.linkedin.com/shareArticle'
        prams += ('?url=' + window.location.href)
        prams += ('&title=' + this.from_data.expo_name)
        prams += ('&summary=' + this.from_data.content)
      }
      window.open(url + encodeURI(prams), '_blank')
    },
    getJob() {
      if (this.loading || this.jobPage >= this.jobTotal) {
        return
      }
      this.loading = true
      getJobList(++this.jobPage, 10).then(res => {
        this.jobList = this.jobList.concat(res.data.data)
        this.jobTotal = res.data.last_page
        this.jobPage = res.data.current_page
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    getLocation() {
      if (this.loading || this.locationPage >= this.locationTotal) {
        return
      }
      this.loading = true
      getLocationList(++this.locationPage, 10).then(res => {
        this.locationList = this.locationList.concat(res.data.data)
        this.locationTotal = res.data.last_page
        this.locationPage = res.data.current_page
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    submit() {
      if (this.token) {
        if (this.loading) {
          return
        }
        this.loading = true
        let hasInvalid = false
        const form_data = {}
        for (let i = 0; i < this.from_data.form_fields.length; i++) {
          if (this.from_data.form_fields[i].field_name) {
            form_data[this.from_data.form_fields[i].field_name] = this.from_data.form_fields[i].value
          } else {
            form_data['field_' + this.from_data.form_fields[i].id] = this.from_data.form_fields[i].value
          }

          if ((this.from_data.form_fields[i].is_required && !this.from_data.form_fields[i].value) ||
              (this.from_data.form_fields[i].field_data.pattern && !this.from_data.form_fields[i].value.match(this.from_data.form_fields[i].field_data.pattern))) {
            hasInvalid = true
            this.from_data.form_fields[i].invalid = true
          } else {
            this.from_data.form_fields[i].invalid = false
          }
        }
        if (hasInvalid) {
          this.$message.error('请正确填写表单')
          window.scrollTo(0, 0)
          this.loading = false
          setInterval(() => {
            for (let i = 0; i < this.from_data.form_fields.length; i++) {
              if ((this.from_data.form_fields[i].is_required && !this.from_data.form_fields[i].value) ||
                (this.from_data.form_fields[i].field_data.pattern && !this.from_data.form_fields[i].value.match(this.from_data.form_fields[i].field_data.pattern))) {
                this.from_data.form_fields[i].invalid = true
              } else {
                this.from_data.form_fields[i].invalid = false
              }
            }
            this.$forceUpdate()
          }, 1000)
        } else {
          submitForm(this.expo_id, form_data).then(res => {
            this.isOk = true
            this.loading = false
          }).catch(err => {
            this.$notify({
              title: '提示',
              message: '提交表单失败：' + err,
              type: 'error'
            })
            this.loading = false
          })
        }
      } else {
        this.$confirm('请先登录', '提示', {
          type: 'warning',
          callback: action => {
            if (action === 'confirm') {
              sessionStorage.setItem('form_cache', JSON.stringify(this.from_data))
              this.$router.push({
                name: 'userRegister',
                query: {
                  expo_key: this.expo_key
                }
              })
            }
          }
        })
      }
    },
    returnWidth(name) {
      if (['email', 'address'].includes(name)) {
        return 6
      }
      if (['id_number', 'mobile'].includes(name)) {
        return 4
      }
      if (['first_name', 'last_name', 'interested_products', 'business_type'].includes(name)) {
        return 3
      }
      return 2
    }
  }
})
</script>

<template>
  <div v-if="noForm" class="no-info">
    <img class="not-found" src="/static/image/404.webp">
    <div class="info">此链接无效，请向管理员咨询。</div>
  </div>
  <div v-else class="body">
    <expo-head :popover_data="from_data" />
    <div class="form">
      <div v-if="isOk" class="form-body ok">
        <div class="icon el-icon-success" />
        <div class="text">表单提交完成</div>
      </div>
      <div v-else class="form-body">
        <div v-for="item in from_data.form_fields" :key="item.id" :style="{gridColumn:'span '+item.field_data.width}" class="form-item">
          <div class="label" :class="[item.is_required?'required':'',item.invalid?'invalid':'']">{{ item.field_label }}</div>
          <el-select v-if="item.field_name==='id_type'" v-model="item.value">
            <el-option value="Passport" label="护照" />
            <el-option value="ID Card" label="身份证" />
          </el-select>
          <el-select v-else-if="item.field_name==='mobile_country_code'" v-model="item.value" filterable>
            <el-option v-for="(code,index) in countryCode" :key="code.country_code+index" :label="'+'+code.phone_code+'('+code.chinese_name+')'" :value="code.phone_code" />
          </el-select>
          <el-popover
            v-else-if="item.field_name==='country'"
            placement="bottom"
            width="260"
            popper-class="popover"
            trigger="click"
            @show="if(locationList.length===0){getLocation()}"
          >
            <div class="cont">
              <div v-for="loca in locationList" :key="loca.id" class="item" @click="item.value=loca.name;from_data.form_fields.push();provinceL=loca.child">
                {{ loca.name }}
              </div>
              <div v-if="locationPage < locationTotal" class="item" @click="getLocation()">加载更多</div>
            </div>
            <el-input slot="reference" :value="item.value" />
          </el-popover>
          <el-popover
            v-else-if="item.field_name==='province'"
            placement="bottom"
            width="260"
            popper-class="popover"
            trigger="click"
          >
            <div class="cont">
              <div v-for="loca in provinceL" :key="loca.id" class="item" @click="item.value=loca.name;from_data.form_fields.push();if(loca.child){cityL=loca.child}else{cityL=[{id:0,name:loca.name}]}">
                {{ loca.name }}
              </div>
              <div v-if="provinceL.length===0" class="item">请先选择国家</div>
            </div>
            <el-input slot="reference" :value="item.value" />
          </el-popover>
          <el-popover
            v-else-if="item.field_name==='city'"
            placement="bottom"
            width="260"
            popper-class="popover"
            trigger="click"
          >
            <div class="cont">
              <div v-for="loca in cityL" :key="loca.id" class="item" @click="item.value=loca.name;from_data.form_fields.push()">
                {{ loca.name }}
              </div>
              <div v-if="cityL.length===0" class="item">请先选择省份</div>
            </div>
            <el-input slot="reference" :value="item.value" />
          </el-popover>
          <el-popover
            v-else-if="item.field_name==='department'"
            placement="bottom"
            width="260"
            popper-class="popover"
            trigger="click"
            @show="if(jobList.length===0){getJob()}"
          >
            <div class="cont">
              <div v-for="job in jobList" :key="job.id" class="item" @click="item.value=job.name;from_data.form_fields.push();jobL=job.child">
                {{ job.name }}
              </div>
              <div v-if="jobPage < jobTotal" class="item" @click="getJob()">加载更多</div>
            </div>
            <el-input slot="reference" :value="item.value" />
          </el-popover>
          <el-popover
            v-else-if="item.field_name==='position'"
            placement="bottom"
            width="260"
            popper-class="popover"
            trigger="click"
          >
            <div class="cont">
              <div v-for="job in jobL" :key="job.id" class="item" @click="item.value=job.name;from_data.form_fields.push()">
                {{ job.name }}
              </div>
              <div v-if="jobL.length===0" class="item">请先选择部门</div>
            </div>
            <el-input slot="reference" :value="item.value" />
          </el-popover>
          <template v-else-if="item.field_name===''">
            <el-input v-if="item.field_type==='input'" v-model="item.value" :placeholder="item.field_data.placeholder" />

            <el-select v-if="item.field_type==='select'" v-model="item.value">
              <option v-for="option in item.field_data.options" :key="option.value" :value="option.value">
                {{ option.label }}
              </option>
            </el-select>

            <el-checkbox-group v-if="item.field_type==='checkbox'" v-model="item.value">
              <el-checkbox v-for="option in item.field_data.options" :key="option.value" :label="option.label" />
            </el-checkbox-group>

            <el-radio-group v-if="item.field_type==='radio'" v-model="item.value">
              <el-radio v-for="option in item.field_data.options" :key="option.value" :label="option.label" />
            </el-radio-group>

            <el-input-number v-if="item.field_type==='number'" v-model="item.value" :max="item.field_data.max" :min="item.field_data.min" :step="item.field_data.step" />

            <el-slider v-if="item.field_type==='slider'" v-model="item.value" :max="item.field_data.max" :min="item.field_data.min" :step="item.field_data.step" />

            <el-input v-if="item.field_type==='textarea'" v-model="item.value" type="textarea" :autosize="{ minRows: item.field_data.minRows, maxRows: item.field_data.maxRows}" :placeholder="item.field_data.placeholder" />

            <el-time-picker v-if="item.field_type==='time'" v-model="item.value" :placeholder="item.field_data.placeholder" />

            <el-time-picker v-if="item.field_type==='timeRange'" v-model="item.value" is-range :start-placeholder="item.field_data.placeholder" :end-placeholder="item.field_data.endPlaceholder" :range-separator="item.field_data.rangeSeparator" />

            <el-date-picker v-if="item.field_type==='date'" v-model="item.value" type="date" :placeholder="item.field_data.placeholder" />

            <el-date-picker v-if="item.field_type==='dateRange'" v-model="item.value" type="daterange" :start-placeholder="item.field_data.placeholder" :end-placeholder="item.field_data.endPlaceholder" :range-separator="item.field_data.rangeSeparator" />
          </template>
          <el-input v-else v-model="item.value" />
        </div>
      </div>
      <div v-if="!isOk" class="button">
        <el-button :disabled="loading" type="primary" @click="submit()">
          提交表单
          <span v-if="loading" class="el-icon-loading" />
        </el-button>
      </div>
      <div class="power-by">
        该表单由主办方{{ from_data.organizer }}创建。
      </div>
    </div>
    <div class="foot">
      <div v-if="from_data.show_official_footer" class="power-by">
        <a target="_blank" href="/">多果表单</a>提供技术支持 by <a target="_blank" href="https://matchexpo.cn/">MatchExpo</a>
      </div>
      <div v-else class="power-by" />
      <div class="share">
        <div class="text">分享至：</div>
        <div class="share-list">
          <!--          <div class="share-icon" @click="share('wechat')">-->
          <!--            <img src="/static/image/icon/wechat.png">-->
          <!--          </div>-->
          <!--          <div class="share-icon" @click="share('qq')">-->
          <!--            <img src="/static/image/icon/qq-zone.png">-->
          <!--          </div>-->
          <div class="share-icon" @click="share('twitter')">
            <img src="/static/image/icon/x.png">
          </div>
          <div class="share-icon" @click="share('facebook')">
            <img src="/static/image/icon/facebook.png">
          </div>
          <div class="share-icon" @click="share('linkedin')">
            <img src="/static/image/icon/linkin.png">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.no-info{
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  .not-found{
    width: 24%;
    margin-top: -8%;
  }
  .info{
    text-align: center;
    font-size: 20px;
    font-weight: bold;
    color: grey;
  }
}
.body{
  width: 100%;
  .foot{
    margin: 16px auto 0;
    max-width: 800px;
    padding: 0 12px 36px;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    justify-content: space-between;
    align-items: center;
    .power-by,a{
      font-size: 16px;
      color: grey;
    }
    .share{
      display: flex;
      align-items: center;
      .share-list{
        display: flex;
        gap: 8px;
        .share-icon{
          cursor: pointer;
          padding: 8px;
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: #EEEEEE;
          img{
            transition-duration: 300ms;
            filter: brightness(0) opacity(0.5);
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
          &:hover{
            background-color: #F4F4F4;
            img{
              filter: brightness(1) opacity(1);
            }
          }

        }
      }
      .text{
        font-size: 16px;
        color: grey;
      }
    }
  }
  .form{
    max-width: 800px;
    border-radius: 8px;
    margin: 16px auto 0;
    padding: 24px;
    box-shadow: 0 0 8px 0 #00000008;
    background: white;
    .power-by{
      margin-top: 16px;
      font-size: 16px;
      color: grey;
    }
    .button{
      margin-top: 12px;
      display: flex;
      justify-content: flex-end;
      @media (max-width:768px)  {
        margin-top: 36px;
         .el-button{
           width: 100%;
           font-size: 18px;
         }
      }
    }
    .desc{
      white-space: pre-wrap;
      color: gray;
      margin-bottom: 32px;
      p{
        margin: 0;
      }
    }
    .form-body{
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      grid-gap: 8px;
      @media (max-width:768px)  {
        display: flex;
        grid-gap: 16px;
        flex-direction: column-reverse;
      }
      &.ok{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 120px 0;
        .icon{
          color: #67C23A;
          font-size: 86px;
        }
        .text{
          margin-top: 24px;
        }
      }
      .form-item{
        div{
          width: 100%;
        }
        .label{
          font-size: 15px;
          color: gray;
          margin-bottom: 8px;
          &.required{
            &::after{
              content: '*';
              color: red;
            }
          }
          &.invalid{
            color: red;
            &::before{
              content: '请正确填写内容！';
              display: block;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}
</style>
<style>
body{
  background: #F9FAFB;
  .popover{
    overflow: hidden;
    padding: 0;
    .cont{
      padding: 8px 0;
      max-height: 220px;
      overflow: auto;
      .item{
        cursor: pointer;
        padding: 8px 16px;
        &:hover{
          background: #F5F7FA;
        }
      }
    }
  }
}
</style>
<style>
#app{
  overflow: auto !important;
}
</style>
