<template>
  <view class="container safe-area-inset-bottom">
    <image class="bkg" src="~@/static/me/wave.png" mode="widthFix"></image>

    <view class="wrap" v-if="step === 1">
      <view class="year-picker">
        <view class="year-picker__title">报考年份</view>
        <u-input class="year-picker__input"
                 v-model="form.year"
                 type="select"
                 :height="60"
                 border
                 border-color="#b2b2b2"
                 :custom-style="{
                   color: '#6c6f70'
                 }"
                 @click="isShowTime = true"></u-input>
      </view>
      <view class="user-form">
        <view class="user-form__input">
          <u-form :model="form" ref="uForm" :label-style="{ 'font-weight': '500' }" label-width="auto">
            <u-form-item label="学生姓名" required prop="name">
              <u-input v-model="form.name" placeholder="请输入" input-align="right" />
            </u-form-item>
            <u-form-item label="准考证" required prop="examination_number">
              <u-input v-model="form.examination_number" placeholder="请输入" input-align="right" />
            </u-form-item>
            <u-form-item label="毕业学校" required prop="finish_school">
              <u-input v-model="form.finish_school" placeholder="请输入" input-align="right" />
            </u-form-item>
          </u-form>
        </view>
      </view>
      <view class="area-pick">
        <view class="area-pick__title">所在区域</view>
        <view class="area-pick__panel">
          <view v-for="item in areaList" :key="item.id" class="area-item" @click="form.area_id = item.id">
            {{ item.name }}
            <u-icon class="area-item__tag" v-if="form.area_id === item.id " name="checkmark-circle-fill" color="#fff" :size="64" />
          </view>
        </view>
      </view>

      <u-button
          shape="circle"
          ripple
          :custom-style="{
            'background-image': 'linear-gradient(263deg, rgba(31,142,247,0.9) 0%, rgba(17,100,247,0.9981153777569027) 78%, rgba(17,100,247,0.9999999999999999) 78%)',
            height: '76rpx',
            'line-height': '76rpx',
            'margin-top': '110rpx',
            'width': '450rpx',
            'color': '#fff'
          }"
          @click="() => {
            if (form.area_id) {
              stepClick('next')
            } else {
              $u.toast('请选择区域')
            }
          }">下一步</u-button>
    </view>

    <view class="wrap" v-if="step > 1 && step <= (1 + batches.length)">
      <view class="picked-data">
        <view>{{ form.year }}年</view>
        <view>{{ formArea }}</view>
        <view>{{ currentBatch.name }}</view>
      </view>

      <view class="card" v-for="item in currentBatchSub" :key="item.id">
        <view class="card__title">
          <scroll-view scroll-x="true" >
            <view class="batch-sub__title">
              {{ item.name }}
            </view>
          </scroll-view>
        </view>

        <view class="card__body">
          <view class="batch-sub-school" v-for="school in item.batch_sub_schools" :key="school.id">
            <view class="batch-sub-school__name">
              志愿序号 {{ school.number }}
            </view>
            <view class="batch-sub-school__form sub-form1">
              <view class="sub-form1__row sub-form1-title">
                <view class="sub-form1__col1">
                  代码
                </view>
                <view class="sub-form1__col2">
                  学校
                </view>
              </view>
              <view class="sub-form1__row">
                <view class="sub-form1__col1">
                  <u-input v-model="flatForm[`${currentBatch.id}-${item.id}-${school.id}-code`]" :height="50" border border-color="#e0e0e0" input-align="center" :clearable="false"></u-input>
                </view>
                <view class="sub-form1__col2">
                  <u-input v-model="flatForm[`${currentBatch.id}-${item.id}-${school.id}-value`]" :height="50" border border-color="#e0e0e0" input-align="center" :clearable="false"></u-input>
                </view>
              </view>
            </view>

            <view class="batch-sub-school-specialty sub-form2" v-if="school.specialty && school.specialty.length > 0">
              <view class="sub-form2__row sub-form2-title">
                <view class="sub-form2__col1">
                  序号
                </view>
                <view class="sub-form2__col2">
                  代码
                </view>
                <view class="sub-form2__col3">
                  专业
                </view>
              </view>

              <view class="sub-form2__row" v-for="(spec, specIndex) in school.specialty" :key="spec.number">
                <view class="sub-form2__col1">
                  {{ spec.number }}
                </view>
                <view class="sub-form2__col2">
                  <u-input v-model="flatForm[`${currentBatch.id}-${item.id}-${school.id}-${specIndex}-code`]" :height="50" border border-color="#e0e0e0" input-align="center" :clearable="false"></u-input>
                </view>
                <view class="sub-form2__col3">
                  <u-input v-model="flatForm[`${currentBatch.id}-${item.id}-${school.id}-${specIndex}-name`]" :height="50" border border-color="#e0e0e0" input-align="center" :clearable="false"></u-input>
                </view>
              </view>
            </view>

            <view class="batch-sub-is-obey" v-if="item.show_specialty_obey">
              <view>
                其他专业是否服从
              </view>
              <u-radio-group v-model="flatForm[`${currentBatch.id}-${item.id}-specialty`]">
                <u-radio name="1">是</u-radio>
                <u-radio name="0">否</u-radio>
              </u-radio-group>
            </view>
          </view>

          <view class="batch-sub-is-obey" v-if="item.show_school_obey">
            <view>
              其他院校是否服从
            </view>
            <u-radio-group v-model="flatForm[`${currentBatch.id}-${item.id}-school`]">
              <u-radio name="1">是</u-radio>
              <u-radio name="0">否</u-radio>
            </u-radio-group>
          </view>
        </view>
      </view>

      <view class="btns">
        <u-button
            shape="circle"
            ripple
            :custom-style="{
            'background-image': 'linear-gradient(263deg, rgba(31,142,247,0.9) 0%, rgba(17,100,247,0.9981153777569027) 78%, rgba(17,100,247,0.9999999999999999) 78%)',
            height: '76rpx',
            'line-height': '76rpx',
            'margin-top': '110rpx',
            'width': '290rpx',
            'color': '#fff'
          }"
            @click="stepClick('prev')">上一步</u-button>
        <template v-if="step < (batches.length)">
          <u-button
              shape="circle"
              ripple
              :custom-style="{
            'background-image': 'linear-gradient(263deg, rgba(31,142,247,0.9) 0%, rgba(17,100,247,0.9981153777569027) 78%, rgba(17,100,247,0.9999999999999999) 78%)',
            height: '76rpx',
            'line-height': '76rpx',
            'margin-top': '110rpx',
            'width': '290rpx',
            'color': '#fff',
            'margin-left': '64rpx'
          }"
              @click="stepClick('next')">下一步</u-button>
        </template>
        <template v-else>
          <u-button
              shape="circle"
              ripple
              :custom-style="{
            'background-image': 'linear-gradient(263deg, rgba(31,142,247,0.9) 0%, rgba(17,100,247,0.9981153777569027) 78%, rgba(17,100,247,0.9999999999999999) 78%)',
            height: '76rpx',
            'line-height': '76rpx',
            'margin-top': '110rpx',
            'width': '290rpx',
            'color': '#fff',
            'margin-left': '64rpx'
          }"
              @click="isShowModal = true">提交</u-button>
        </template>
      </view>
    </view>

    <u-picker
        v-model="isShowTime"
        mode="time"
        :params="{
					year: true,
					month: false,
					day: false,
					hour: false,
					minute: false,
					second: false
				}"
        @confirm="e => form.year = e.year"></u-picker>
    <u-modal v-model="isShowModal" content="确认提交数据？" show-cancel-button @confirm="submit"></u-modal>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isShowModal: false,
      step: 1,
      isShowTime: false,
      areaList: [],
      form: {
        name: "",
        finish_school: "",
        examination_number: "",
        area_id: "",
        year: new Date().getFullYear().toString(),
        aspiration_id: ""
      },
      config: null,

      currentBatchId: "",
      aspiration: {},
      batchSub: {},

      subForm: [],
      flatForm: {},
    };
  },
  methods: {
    async getBatchSub(batchId) {
      if (!this.subForm.find(i => i.id === batchId)) {
        this.subForm.push({
          batchId,
          name: this.batches.find(j => j.id === batchId)?.name,
          batchSubs: []
        })
      }
      if (this.batchSub.hasOwnProperty(batchId) && this.batchSub[batchId]) {

      } else {
        try {
          const { batchSubs } = await this.$u.api.batchDetail({ id: batchId })
          this.batchSub[batchId] = batchSubs

          const formBatch = this.subForm.find(i => i.batchId === batchId)
          formBatch.batchSubs = batchSubs.map(resSub => ({
            batchSubId: resSub.id,
            name: resSub.name,
            batchSubSchools: resSub.batch_sub_schools.map(subSchool => ({
              batchSubSchoolId: subSchool.id,
              name: subSchool.number,
              code: "",
              value: "",
              specialties: subSchool.specialty?.map((spec, specIndex) => ({
                specialtyId: specIndex,
                code: "",
                value: ""
              }))
            })),
            specialtyObey: "1",
            schoolObey: "1"
          }))
        } catch (err) {
          console.error(err)
        }
      }
      this.currentBatchId = batchId

      const resolveData = (batch) => {
        const myBatchId = batch.batchId
        if (batch.batchSubs && batch.batchSubs.length > 0) {
          batch.batchSubs.forEach(batchSub => {
            const myBatchSubId = batchSub.batchSubId
            if (!this.flatForm.hasOwnProperty(`${myBatchId}-${myBatchSubId}-specialty`)) {
              this.flatForm[`${myBatchId}-${myBatchSubId}-specialty`] = "1"
            }
            if (!this.flatForm.hasOwnProperty(`${myBatchId}-${myBatchSubId}-school`)) {
              this.flatForm[`${myBatchId}-${myBatchSubId}-school`] = "1"
            }

            if (batchSub.batchSubSchools && batchSub.batchSubSchools.length > 0) {
              batchSub.batchSubSchools.forEach(batchSubSchool => {
                const myBatchSubSchoolId = batchSubSchool.batchSubSchoolId
                if (!this.flatForm.hasOwnProperty(`${myBatchId}-${myBatchSubId}-${myBatchSubSchoolId}-value`)) {
                  this.flatForm[`${myBatchId}-${myBatchSubId}-${myBatchSubSchoolId}-value`] = ''
                }
                if (!this.flatForm.hasOwnProperty(`${myBatchId}-${myBatchSubId}-${myBatchSubSchoolId}-code`)) {
                  this.flatForm[`${myBatchId}-${myBatchSubId}-${myBatchSubSchoolId}-code`] = ''
                }

                if (batchSubSchool.specialties && batchSubSchool.specialties.length > 0) {
                  batchSubSchool.specialties.forEach(specialty => {
                    const mySpecialtyId = specialty.specialtyId
                    if (!this.flatForm.hasOwnProperty(`${myBatchId}-${myBatchSubId}-${myBatchSubSchoolId}-${mySpecialtyId}-value`)) {
                      this.flatForm[`${myBatchId}-${myBatchSubId}-${myBatchSubSchoolId}-${mySpecialtyId}-value`] = ''
                    }
                    if (!this.flatForm.hasOwnProperty(`${myBatchId}-${myBatchSubId}-${myBatchSubSchoolId}-${mySpecialtyId}-code`)) {
                      this.flatForm[`${myBatchId}-${myBatchSubId}-${myBatchSubSchoolId}-${mySpecialtyId}-code`] = ''
                    }
                  })
                }
              })
            }
          })
        }
      }
      this.subForm.forEach(batch => resolveData(batch))
    },
    async getConfig () {
      try {
        const { list } = await this.$u.api.batchIndex({
          area_id: this.form.area_id,
          year: this.form.year
        })
        if (list.length > 0) {
          this.form.aspiration_id = list[0].id

          this.aspiration = list[0]
          this.setTitle()
        }
      } catch (err) {
        console.error(err)
      }
    },
    async stepClick(type='next') {
      if (type === 'next') {
        if (this.step === 1 && !this.config) {
          await this.getConfig()
        }
        if (this.step < (1 + this.batches.length)) {
          this.step = this.step + 1
        }
      } else if (type === 'prev') {
        if (this.step > 1) {
          this.step = this.step - 1
        }
      }
      if (this.step > 1) {
        await this.getBatchSub(this.batches[this.step-2]?.id)
      }
    },
    setTitle() {
      uni.setNavigationBarTitle({
        title: `志愿模拟填报 - Step ${this.step}${ this.step !== 1 ? ('/'+(this.batches.length+1)) : '' }`
      })
    },
    async getArea() {
      try {
        const res = await this.$u.api.area()
        this.areaList = res.list
      } catch (err) {
        console.error(err)
      }
    },

    submit () {
      const idName = ['batchId', 'batchSubId', 'batchSubSchoolId', 'specialtyId']
      const linkName = ['batchSubs', 'batchSubSchools', 'specialties']
      for (let key in this.flatForm) {
        let target = null
        let keys = key.split('-')
        for (let i = 0;i < keys.length;i++) {
          const val = keys[i]
          if (i === 1) {
            let myTarget = target.find(j => j[idName[i]] === Number(val))
            if (/school$/.test(key)) {
              if (myTarget.hasOwnProperty('schoolObey')) {
                myTarget['schoolObey'] = this.flatForm[key]
              }
            } else if (/specialty$/.test(key)) {
              if (myTarget.hasOwnProperty('specialtyObey')) {
                myTarget['specialtyObey'] = this.flatForm[key]
              }
            }
          } else if (i === 2) {
            let myTarget = target.find(j => j[idName[i]] === Number(val))
            if (val === 'code') {
              if (myTarget.hasOwnProperty('code')) {
                myTarget['code'] = this.flatForm[key]
              }
            } else if (val === 'value') {
              if (myTarget.hasOwnProperty('value')) {
                myTarget['value'] = this.flatForm[key]
              }
            }
          }
          if (isNaN(Number(val))) {

          } else {
            target = target ? target.find(j => j[idName[i]] === Number(val))[linkName[i]] : this.subForm.find(j => j[idName[i]] === Number(val))[linkName[i]]
          }
        }
      }
      this.$u.api.batchSubmit({
        aspiration_id: this.aspiration.id,
        data: this.subForm,
        name: this.form.name,
        finish_school: this.form.finish_school,
        examination_number: this.form.examination_number,
      }).then(_ => {
        this.$u.route({
          url: '/package_sub/pages/FormSuccess/FormSuccess',
          params: {
            title: "志愿填报",
            redirect: '/pages/list/list'
          }
        })
      })
    }
  },
  computed: {
    formArea() {
      return this.areaList?.find(i => i.id === this.form.area_id)?.name
    },
    batches() {
      return this.aspiration.batchs || []
    },
    currentBatchSub() {
      return this.batchSub[this.currentBatchId]
    },
    currentBatch() {
      return this.batches.find(i => i.id === this.currentBatchId) ?? {}
    }
  },
  watch: {
    step() {
      this.setTitle()
    }
  },
  onShow() {
    this.setTitle()
  },
  created() {
    this.getArea()
  },
}
</script>

<style lang="scss">

.container {
  position: relative;
  min-height: 100vh;
  width: 100vw;
  background: #eaf8fe;

  .bkg {
    width: 100vw;
    position: fixed;
    top: 0;
    left: 0;
  }

  .wrap {
    z-index: 3;
    position: relative;
    padding-top: 40rpx;

    .year-picker {
      background: #fff;
      display: flex;
      align-items: center;
      margin: 0 24rpx;
      padding: 32rpx 75rpx 32rpx 60rpx;
      border-radius: 20rpx;
      filter: drop-shadow(-2.179rpx 3.355rpx 2.5rpx rgba(208, 209, 209, 0.3));

      &__title {
        font-size: 30rpx;
        text-transform: uppercase;
        color: #333333;
        font-weight: 500;
      }

      &__input {
        flex: 1;
        margin-left: 32rpx;
      }
    }
    .user-form {
      background: #fff;
      display: flex;
      align-items: center;
      margin: 40rpx 24rpx 0;
      padding: 32rpx 75rpx 32rpx 46rpx;
      border-radius: 20rpx;
      filter: drop-shadow(-2.179rpx 3.355rpx 2.5rpx rgba(208, 209, 209, 0.3));

      &__title {
        font-size: 30rpx;
        text-transform: uppercase;
        color: #333333;
        font-weight: 500;
      }

      &__input {
        flex: 1;
        margin-left: 32rpx;
      }
    }

    .area-pick {
      margin: 0 24rpx;

      &__title {
        font-size: 30rpx;
        text-transform: uppercase;
        color: #333333;
        font-weight: 500;
        padding: 42rpx 0 38rpx 60rpx;
      }

      &__panel {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-gap: 22rpx 28rpx;

        $colors: linear-gradient(0deg, #309cfe 0%, #58e5ff 100%),
        linear-gradient(0deg, #309cfe 0%, #58e5ff 100%),
        linear-gradient(0deg, #2f69fd 0%, #51bcfe 100%),
        linear-gradient(0deg, #2f69fd 0%, #51bcfe 100%),
        linear-gradient(0deg, #2941fc 0%, #587bff 100%),
        linear-gradient(0deg, #2941fc 0%, #587bff 100%),
        linear-gradient(0deg, #280bb7 0%, #5776fe 100%),
        linear-gradient(0deg, #280bb7 0%, #5776fe 100%);

        .area-item {
          border-radius: 15rpx;
          font-size: 46rpx;
          text-transform: uppercase;
          color: #ffffff;
          font-weight: 500;
          text-align: center;
          padding: 60rpx 0;
          filter: drop-shadow(0 4rpx 2rpx rgba(0, 0, 0, 0.3));
          position: relative;
          overflow: hidden;

          &::before {
            content: '';
            opacity: 0.302;
            width: 192rpx;
            height: 192rpx;
            border-radius: 96rpx;
            background-image: linear-gradient(0deg, #309cfe 0%, #58c2ff 100%);
            position: absolute;
            top: -140rpx;
            right: -38rpx;
          }

          &::after {
            content: '';
            opacity: 0.149;
            width: 192rpx;
            height: 192rpx;
            border-radius: 96rpx;
            background-color: #b9e1fd;
            position: absolute;
            bottom: -148rpx;
            left: -44rpx;
          }

          &__tag {
            z-index: 4;
            position: absolute;
            top: 10rpx;
            right: 10rpx;
          }
        }

        @for $i from 1 through length($colors) {
          .area-item:nth-child(n + #{$i}) {
            background: nth($colors, $i);
          }
        }
      }
    }
    .picked-data {
      display: flex;
      align-items: center;
      border-radius: 20rpx;
      filter: drop-shadow(-2.179rpx 3.355rpx 2.5rpx rgba(208,209,209,0.3));
      background-color: rgba(255, 255, 255, 0.5);
      margin: 20rpx 24rpx 0;
      padding: 26rpx  160rpx;

      & > view {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        text-transform: uppercase;
        color: #333333;
        font-weight: bold;
        white-space: nowrap;
      }
      & > view + view {
        margin-left: 10rpx;
      }
    }

    .card {
      margin: 28rpx 24rpx 0;
      border-radius: 20rpx;
      filter: drop-shadow(-2.179rpx 3.355rpx 2.5rpx rgba(208,209,209,0.3));
      background-color: #ffffff;

      &__title {
        background: #fbf1e8;
        border-radius: 20rpx 20rpx 0 0;
        padding: 0 16rpx;
      }
      &__body {
        padding: 48rpx 30rpx 70rpx 30rpx;
      }
    }
    .batch-sub {

      &__title {
        text-align: center;
        font-size: 28rpx;
        text-transform: uppercase;
        color: #e77817;
        font-weight: 500;
        padding: 30rpx 20rpx;
        word-break: keep-all;
        white-space: nowrap;
      }

      &-is-obey {
        display: flex;
        align-items: center;
        margin-top: 40rpx;

        & > view:nth-child(1) {
          font-size: 24rpx;
          text-transform: uppercase;
          color: #333333;
          font-weight: 500;
          margin-right: 110rpx;
        }
      }
    }
  }
}
.btns {
  display: flex;
  align-items: center;
  justify-content: center;
}
.batch-sub-school {
  margin-top: 40rpx;

  &:nth-child(1) {
    margin-top: 0;
  }
  &__name {
    font-size: 28rpx;
    line-height: 36rpx;
    text-transform: uppercase;
    color: #333333;
    font-weight: 500;
  }
  .sub-form1 {
    &-title {
      font-size: 24rpx;
      line-height: 36rpx;
      text-transform: uppercase;
      color: #333333;
      font-weight: 500;
      margin: 28rpx 0;
      text-align: center;
    }
    &__row {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    &__col1 {
      flex-basis: 29%;
    }
    &__col2 {
      flex-basis: 67.5%;
    }
  }

  .sub-form2 {
    &-title {
      font-size: 24rpx;
      line-height: 36rpx;
      text-transform: uppercase;
      color: #333333;
      font-weight: 500;
      margin: 28rpx 0;
      text-align: center;
    }
    &__row {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    &__col1 {
      flex-basis: 14.8%;
      font-size: 28rpx;
      text-transform: uppercase;
      color: #333333;
    }
    &__col2 {
      flex-basis: 29%;
    }
    &__col3 {
      flex-basis: 48.9%;
    }
  }
  .sub-form2__row + .sub-form2__row {
    margin-top: 22rpx;
  }
}

</style>
