<!--test.vue-->
<template>
  <div class="source-form-top-container" :key="componentKey">
    <div class="source-form-tip-container" v-if="!canWrite">
      <div class="source-form-content-container">
        <van-empty :description="notCanWriteTip" />
      </div>
    </div>
    <van-overlay class="show-success-dialog-container" :class="{ 'is-not-edit': !isEdit }" :show="isShowSuccessDialog" @click="successDialogShow = false">
      <div @click.stop class="show-success-dialog-content-container">
        <img v-if="useSourceFormConfig.submitSuccessImage" :src="useSourceFormConfig.submitSuccessImage" />
        <van-icon class="icon-close-dialog" name="clear" @click="successDialogShow = false" />
      </div>
    </van-overlay>
    <van-form
        class="source-form"
        @submit="onSubmit"
        :style="{
        'background-color': useSourceFormConfig.background
      }"
    >
      <van-field
          v-if="useSourceFormConfig.company"
          v-model.trim="form.company"
          required
          name="公司名称"
          label="公司名称"
          placeholder="请输入准确的公司名称"
      />
      <van-field
          v-if="useSourceFormConfig.name"
          v-model.trim="form.name"
          required
          name="姓名"
          label="姓名"
          placeholder="请输入姓名"
      />
      <van-field
          v-if="useSourceFormConfig.phone"
          v-model.trim="form.phone"
          required
          name="手机号"
          label="手机号"
          placeholder="请输入准确的手机号"
      />
      <van-field name="radio" required label="你希望获得哪个行业的报告" v-if="useSourceFormConfig.source_desc">
        <template #input>
          <div class="custom-radio-type">
            <van-radio-group
                v-model="form.source_desc"
            >
              <van-radio
                  v-for="item in useSourceFormConfig.sourceOptions"
                  :name="item"
                  :key="item"
              >
                <div class="other-input-box" v-if="form.source_desc === '其他' && item === '其他'">
                  <span>{{item}}</span>
                  <van-field
                      v-model.trim="form.source_desc_temp"
                      placeholder="请输入行业"
                  />
                </div>
                <span v-else>{{item}}</span>
              </van-radio>
            </van-radio-group>

          </div>
        </template>
      </van-field>

      <div style="margin: 16px;">
        <van-button round block :type="btnType" :size="size" native-type="submit">{{text}}</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Form, Field, Button, Radio, RadioGroup, Toast, Empty, Overlay, Icon} from 'vant';
import $axios from "@/service/httpServer";

const DEFAULT_SOURCE_CONFIG = {
  background: 'transparent',
  source: 'default-source-h5',
  name: true,
  phone: true,
  company: true,
  source_desc: true,
  sourceOptions: [
    '建筑工程',
    '信息技术',
    '弱电安防',
    '医疗卫生',
    '服务采购',
    '其他'
  ],
  // 提交限制
  submitCountState: -1,
  submitTimeState: -1,
  submitSuccessState: -1,
  submitTime: [],
  submitSuccessTip: '提交成功',
  submitCountMaxTip: '您已提交该表单',
  submitTimeBeforeTip: '该表单暂未开始填写',
  submitTimeAfterTip: '该表单已结束填写',
}

	export default {
    name: 'DsSourceForm',
    components: {
        [Overlay.name]: Overlay,
        [Empty.name]: Empty,
        [Icon.name]: Icon,
        [Form.name]: Form,
        [Field.name]: Field,
        [Radio.name]: Radio,
        [RadioGroup.name]: RadioGroup,
        [Button.name]: Button
    },
    data() {
      return {
        componentKey: 1,
        successDialogShow: false,
        form: {
          name: '',
          phone: '',
          company: '',
          source_desc: '',
          source_desc_temp: ''
        }
      }
    },
		props: {
      api: {
        type: String,
        default: '/salesLeads/official/notLogin'
      },
      btnType:{
        type:String,
        default:'info'
      },
      text: {
        type: String,
        default: '提 交'
      },
      size:{
        type:String,
        default:'large'
      },
      sourceFormConfig: {
        type:Object,
        default: () => {
          return DEFAULT_SOURCE_CONFIG
        }
      }
		},
    computed: {
      isShowSuccessDialog () {
        if (this.useSourceFormConfig.submitSuccessState !== 0) {
          return false
        }
        if (this.isEdit) {
          return true
        }
        return this.successDialogShow
      },
      isEdit () {
        return location.href.indexOf('/#/editor?id') !== -1
      },
      useSourceFormConfig () {
        return Object.assign({}, DEFAULT_SOURCE_CONFIG, this.sourceFormConfig)
      },
      canWrite () {
        let result = true
        if (this.needCheckWriteCount && this.hasCacheWrite) {
          result = false
        }
        if (!this.canTimeing) {
          result = false
        }
        return result
      },
      notCanWriteTip () {
        // 判断表单填写限制、表单过期限制
        let tip = ''
        if (this.needCheckTime) {
          if (!this.isTimeStart) {
            tip = this.useSourceFormConfig.submitTimeBeforeTip
          } else if (this.isTimeEnd) {
            tip = this.useSourceFormConfig.submitTimeAfterTip
          }
        }

        if (this.needCheckWriteCount) {
          if (this.hasCacheWrite) {
            tip = this.useSourceFormConfig.submitCountMaxTip
          }
        }
        return tip
      },
      needCheckWriteCount () {
        return this.useSourceFormConfig.submitCountState !== -1
      },
      needCheckTime () {
        return this.useSourceFormConfig.submitTimeState !== -1
      },
      canTimeing () {
        if (!this.needCheckTime) {
          return true
        }
        return this.isTimeStart && !this.isTimeEnd
      },
      hasCacheWrite () {
        console.log(this.componentKey, 'update key')
        if (this.isEdit) {
          return true
        }
        let result = false
        try {
          result = localStorage.getItem(window._pageData._id) === '1'
        } catch (e) {
          console.warn(e)
        }
        return result
      },
      isTimeStart () {
        console.log(this.componentKey, 'update key')
        if (this.sourceFormConfig.submitTime[0]) {
          return Date.now() >= this.sourceFormConfig.submitTime[0]
        } else {
          return true
        }
      },
      isTimeEnd () {
        console.log(this.componentKey, 'update key')
        if (this.sourceFormConfig.submitTime[1]) {
          return Date.now() >= this.sourceFormConfig.submitTime[1]
        } else {
          return false
        }
      },
    },
    methods: {
      updateComponent () {
        this.componentKey = Date.now()
      },
      saveCache () {
        try {
          localStorage.setItem(window._pageData._id, '1')
        } catch (e) {
          console.warn(e)
        }
      },
      submitSuccessCallback () {
        this.saveCache()
        this.updateComponent()
        switch (this.useSourceFormConfig.submitSuccessState) {
          case -1: {
            Toast(this.useSourceFormConfig.submitSuccessTip)
            break
          }
          case 0: {
            if (this.useSourceFormConfig.submitSuccessImage) {
              this.successDialogShow = true
            } else {
              Toast(this.useSourceFormConfig.submitSuccessTip)
            }
            break
          }
          case 1: {
            if (this.useSourceFormConfig.submitSuccessURL) {
              location.href = this.useSourceFormConfig.submitSuccessURL
            } else {
              Toast(this.useSourceFormConfig.submitSuccessTip)
            }
            break
          }
        }
      },
      onSubmit (values) {
        console.log(values)
        Toast.loading({
          duration: 0,
          forbidClick: true
        });
        const params = Object.assign({
          source: this.useSourceFormConfig.source,
          origin: location.href
        }, this.form, {
          source_desc: this.form.source_desc === '其他' ? this.form.source_desc_temp : this.form.source_desc
        })

        console.log('source-params', params)
        $axios.post(location.origin + this.api, JSON.stringify(params), {
          headers: {
            'Content-Type': 'application/json;charset=utf-8'
          }
        }).then(res => {
          console.log('res', res)
          Toast.clear()
          if (res.data) {
            this.submitSuccessCallback()
          } else {
            Toast(res.error_msg || '太火爆了，请稍后重试')
          }

        }).catch(() => {
          Toast.clear()
          Toast('太火爆了，请稍后重试')
        })
      }
    }
	}
</script>

<style lang="scss" scoped>
.other-input-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  span {
    flex-shrink: 0;
  }
}
.custom-radio-type {
  display: flex;
  flex-direction: column;
}
.source-form {
  max-width: 375px;
  margin: 0 auto;
  width: 100%;
  height: 100%;
  padding: 16px 0;

  ::v-deep {
    .van-cell {
      flex-direction: column;
      background-color: inherit;
    }
    .van-field__label {
      width: 100%;
    }
    .van-radio {
      height: 44px;
    }
  }
}
.source-form-top-container {
  position: relative;
}

.show-success-dialog-container {
  display: flex;
  align-items: center;
  justify-content: center;
  &.is-not-edit {
    height: 100vh;
    width: 100vw;
  }
}
.show-success-dialog-content-container {
  max-width: 80%;
  img {
    max-width: 100%;
    border-radius: 12px;
  }
}

.icon-close-dialog {
  color: #fff;
  font-size: 24px;
}
.source-form-tip-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
  .source-form-content-container {
    background-color: #fff;
  }
}
</style>
