<template>
  <view>
    <uv-popup ref="popup" mode="bottom" bgColor="none" :zIndex="1000000" @change="onPopupChange">
      <view class="popup__view" v-if="isShow">
        <view class="flex header">
          <view class="title">新增记录</view>
          <button class="btn" @click="close">关闭</button>
        </view>
        <view class="form">
          <uv-form 
            ref="form"
            :model="form"
            errorType="toast"
          >
            <view class="form-item">
              <uv-form-item prop="experienceId" :customStyle="formItemStyle">
                <view class="form-item-label">
                  <image class="icon" src="@/pages_order/static/icon-require.png" mode="widthFix"></image>
                  关联项目
                </view>
                <view class="form-item-content">
                  <view class="flex row" @click="openRelatePojectPicker">
                    <view v-if="form.experienceId" class="text">{{ projectDesc }}</view>
                    <view v-else class="text placeholder">请选择关联项目</view>
                    <uv-icon name="arrow-right" color="#C6C6C6" size="32rpx"></uv-icon>
                  </view>
                  <reloateProjectPopup ref="reloateProjectPopup" :options="projects" @confirm="onRelateProjectChange"></reloateProjectPopup>
                </view>
              </uv-form-item>
            </view>
            <!-- <view class="form-item">
              <uv-form-item prop="processScore" :customStyle="formItemStyle">
                <view class="flex row">
                  <view class="form-item-label">行程</view>
                  <view class="form-item-content">
                    <formRate v-model="form.processScore"></formRate>
                  </view>
                </view>
              </uv-form-item>
            </view>
            <view class="form-item">
              <uv-form-item prop="spotScore" :customStyle="formItemStyle">
                <view class="flex row">
                  <view class="form-item-label">景点</view>
                  <view class="form-item-content">
                    <formRate v-model="form.spotScore"></formRate>
                  </view>
                </view>
              </uv-form-item>
            </view>
            <view class="form-item">
              <uv-form-item prop="teacherScore" :customStyle="formItemStyle">
                <view class="flex row">
                  <view class="form-item-label">导师</view>
                  <view class="form-item-content">
                    <formRate v-model="form.teacherScore"></formRate>
                  </view>
                </view>
              </uv-form-item>
            </view> -->
            <view class="form-item">
              <uv-form-item prop="images" :customStyle="formItemStyle">
                <view class="form-item-label">上传图片</view>
                <view class="form-item-content">
                  <formUpload v-model="form.images"></formUpload>
                </view>
              </uv-form-item>
            </view>
            <view class="form-item" v-for="(item, index) in configList.experienceQuestionList" :key="item.id">
              <uv-form-item :prop="`texts[${index}]`" :customStyle="formItemStyle">
                <view class="form-item-label">
                  <image class="icon" src="@/pages_order/static/icon-require.png" mode="widthFix"></image>
                  {{ item.question }}
                </view>
                <view class="form-item-content">
                  <formTextarea v-model="form.texts[index]"></formTextarea>
                </view>
              </uv-form-item>
            </view>
          </uv-form>
        </view>
        <view class="footer">
          <button class="flex btn" @click="onPublish">发布</button>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script>
	import { mapState } from 'vuex'

  import reloateProjectPopup from '@/pages_order/components/reloateProjectPopup.vue'
  import formTextarea from '@/pages_order/components/formTextarea.vue'
  import formUpload from '@/pages_order/components/formUpload.vue'
  import formRate from '@/pages_order/components/formRate.vue'

  export default {
    components: {
      reloateProjectPopup,
      formTextarea,
      formUpload,
      formRate,
    },
    data() {
      return {
        isShow: false,
        form: {
          experienceId: null,
          // processScore: null,
          // spotScore: null,
          // teacherScore: null,
          images: [],
          texts: [],
        },
        projects: [],
      }
    },
    computed: {
			...mapState(['userInfo', 'configList']),
      projectDesc() {
        const { experienceId } = this.form
        const target = this.projects?.find?.(item => item.id === experienceId)

        return target?.name || ''
      },
    },
    methods: {
      async fetchProjectOptions() {
        try {
          const records = (await this.$fetch('queryExperienceList', { pageNo: 1, pageSize: 1000, }))?.records

          this.projects = records.map(item => {
            return {
              id: item.id,
              name: item.activityTitle || item.activityId_dictText || ''
            }
          })
        } catch (err) {

        }
      },
      setRules() {
        const rules =  {
          'experienceId': {
            type: 'string',
            required: true,
            message: '请选择关联项目',
          },
          'texts': {
            type: 'array',
            required: true,
            message: '请完整回答',
            validator: (rule, value, callback) => {
              
              if (value.every(val => !!val)) {
                return true
              }

              return false
            },
          },
        }

			  this.$refs.form.setRules(rules)
      },
      async open() {

        await this.fetchProjectOptions()

        console.log('projects', this.projects)
        console.log('experienceQuestionList', this.configList.experienceQuestionList)

        const texts = this.configList.experienceQuestionList.map(() => '')

        this.form = {
          experienceId: null,
          // processScore: null,
          // spotScore: null,
          // teacherScore: null,
          images: [],
          texts,
        }

        this.$refs.popup.open()
      },
      close() {
        this.$refs.popup.close()
      },
      onPopupChange(e) {
        this.isShow = e.show

        // todo: need settimeout?
        setTimeout(() => {
          this.setRules()
        }, 800)
      },
      openRelatePojectPicker() {
        this.$refs.reloateProjectPopup.open(this.form.experienceId || null)
      },
      onRelateProjectChange(id) {
        this.form.experienceId = id
      },
      async onPublish() {
        try {
          await this.$refs.form.validate()

          const {
            experienceId,
            // processScore,
            // spotScore,
            // teacherScore,
            images,
            texts,
          } = this.form

          const params = {
            // todo: check
            userId: this.userInfo.id,
            experienceId,
            image: images.join(','), 
            content: texts.join('\r\n')
          }

          await this.$fetch('addExperience', params)

          uni.showToast({
            icon: 'success',
            title: '发布成功',
          });

          this.$emit('submitted')

          this.close()

        } catch (err) {
          console.log('onSave err', err)
        }
      },
    },
  }
</script>

<style lang="scss" scoped>

  .popup__view {
    width: 100vw;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background: #FFFFFF;
    border-top-left-radius: 32rpx;
    border-top-right-radius: 32rpx;
  }

  .header {
    position: relative;
    width: 100%;
    padding: 24rpx 0;
    box-sizing: border-box;
    border-bottom: 2rpx solid #EEEEEE;

    .title {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 34rpx;
      line-height: 1.4;
      color: #181818;
    }

    .btn {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 32rpx;
      line-height: 1.4;
      color: #8B8B8B;
      position: absolute;
      top: 26rpx;
      left: 40rpx;
    }

  }
  
  .form {
    max-height: 75vh;
    padding: 32rpx 40rpx;
    box-sizing: border-box;
    overflow-y: auto;

    &-item {
      padding: 8rpx 0 6rpx 0;
      
      & + & {
        padding-top: 24rpx;
        border-top: 2rpx solid #EEEEEE;
      }

      &-label {
        margin-bottom: 14rpx;
        display: flex;
        align-items: center;
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 26rpx;
        line-height: 1.4;
        color: #181818;

        .icon {
          margin-right: 8rpx;
          width: 16rpx;
          height: auto;
        }
      }

      &-content {
    
        .text {
          padding: 2rpx 0;
          font-family: PingFang SC;
          font-weight: 400;
          font-size: 32rpx;
          line-height: 1.4;

          &.placeholder {
            color: #C6C6C6;
          }
        }

      }
    }
  }


  .row {
    justify-content: space-between;

    .form-label {
      margin: 0;
    }
  }

  .footer {
    width: 100%;
    padding: 32rpx 40rpx;
    box-sizing: border-box;
    border-top: 2rpx solid #F1F1F1;

    .btn {
      width: 100%;
      padding: 14rpx 0;
      box-sizing: border-box;
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 36rpx;
      line-height: 1.4;
      color: #FFFFFF;
      background-image: linear-gradient(to right, #21FEEC, #019AF9);
      border: 2rpx solid #00A9FF;
      border-radius: 41rpx;
    }
  }

</style>