<template>
  <view class="collect-information">
    <step-register />

    <!-- 地区负责人信息 （づ￣3￣）づ╭～ -->
    <view class="area-principal-information">
      <view class="information-title"> 地区负责人信息（承办人） </view>
      <view class="information-form">
        <view class="information-form-item">
          <view class="information-form-label">承办地区</view>
          <view class="information-form-filed">
            <view class="filed-input-view" @click="selectArea">
              <text
                :class="[
                  form.district.startsWith('请')
                    ? `placeholder-class`
                    : 'select-after-text text-Ellipsis',
                ]"
                style="width: 438rpx"
              >
                {{ form.district }}
              </text>
              <van-icon name="arrow-down" />
            </view>
          </view>
        </view>
        <view class="information-form-item">
          <view class="information-form-label">详细地址 </view>
          <view class="information-form-filed">
            <input
              class="filed-input"
              placeholder="选填"
              placeholder-class="placeholder-class"
              :value="form.detailAddress"
              @input="(e) => changeForm(e, 'detailAddress')"
            />
            <image
              class="close-icon"
              :src="staticImg.closeIcon"
              v-if="form.detailAddress"
              @click="clearFormItem('detailAddress')"
            />
          </view>
        </view>
        <view class="information-form-item">
          <view class="information-form-label">承办单位</view>
          <view class="information-form-filed">
            <input
              class="filed-input"
              placeholder="请输入承办单位"
              placeholder-class="placeholder-class"
              :value="form.unit"
              @input="(e) => changeForm(e, 'unit')"
            />
            <image
              class="close-icon"
              :src="staticImg.closeIcon"
              v-if="form.unit"
              @click="clearFormItem('unit')"
            />
          </view>
        </view>
        <view class="information-form-item">
          <view class="information-form-label">承办人</view>
          <view class="information-form-filed">
            <input
              class="filed-input"
              placeholder="请输入承办人姓名"
              placeholder-class="placeholder-class"
              :value="form.unitPrincipal"
              @input="(e) => changeForm(e, 'unitPrincipal')"
            />
            <image
              class="close-icon"
              :src="staticImg.closeIcon"
              v-if="form.unitPrincipal"
              @click="clearFormItem('unitPrincipal')"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 参赛园所信息 -->
    <view class="school-information" @click="handleGoSchoolInfo">
      <view class="information-title"> 参赛园所信息 </view>
      <view v-if="form.schoolList.length === 0" class="school-add-area">
        <view class="school-add-button">
          <image class="plus-icon" :src="staticImg.plusIcon" />
          <text>添加参赛园所</text>
          <image class="plus-arrow" :src="staticImg.arrow" />
        </view>
      </view>
      <view v-else class="school-have-area">
        <view class="school-add-button">
          <image class="plus-icon" :src="staticImg.plusIcon" />
          <text>参赛园所（{{ form.schoolList.length }}）</text>
          <image class="plus-arrow" :src="staticImg.arrow" />
        </view>
      </view>
    </view>

    <!-- 预定物料包数量 -->
    <view class="pre-material-package">
      <view class="information-title pre-material-package-title">
        预定物料包数量 <view class="tip">（50套起订） </view>
      </view>
      <view class="material-package-information">
        <view
          class="material-package-item"
          v-for="material in form.materialList"
          :key="material.materialName"
        >
          <view class="material-package-item-label">
            <van-checkbox
              :value="material.isShow"
              shape="square"
              @change="onChange(material.materialName)"
            >
              <view class="material-package-item-label-left">
                <view class="label-prefix">赛事标准物料包</view
                ><view class="clazz">({{ material.materialName }})</view>
              </view>
            </van-checkbox>
          </view>
          <view v-if="material.isShow" class="material-count">
            <input
              class="material-input"
              type="number"
              :min="50"
              :value="material.number"
              @change="changeMaterialNumber(material, $event.target.value)"
            />
            套
          </view>
        </view>
      </view>
    </view>

    <step-tabbar
      :totalSchool="totalSchool"
      :totalPeople="totalPeople"
      :submitIsShow="submitIsShow"
      @handleSubmit="submitAgentRegister"
    />

    <!-- 地区选择 -->
    <van-action-sheet
      class="area-picker"
      :show="showAreaPicker"
      @click-overlay="showAreaPicker = false"
    >
      <van-area
        :area-list="areaList"
        :value="code"
        @confirm="confirmArea"
        @cancel="cancelArea"
      />
    </van-action-sheet>

    <!-- 提交成功弹窗 -->
    <van-overlay :show="show" @click="handleReturnHome">
      <view class="wrapper" @click.stop>
        <view class="block">
          <image
            :src="staticImg.closeBtn"
            class="closeBtn"
            @click="handleReturnHome"
          />
          <image :src="staticImg.submitSucess" class="submitSucess" />
          <view class="promptText">参与信息提交完成！</view>
          <view class="returnHome" @click="handleReturnHome">返回首页</view>
        </view>
      </view>
    </van-overlay>
  </view>
</template>

<script>
import {
  submitAgentRegister,
  getAgentRegisterLastInfo,
} from "@/api/competition.js";
import StepRegister from "./component/step-register.vue";
import StepTabbar from "./component/step-tabbar.vue";
import { areaList } from "@vant/area-data";
import Tip from "@/utils/tip.js";

const staticImg = {
  closeIcon: require("@/static/competitionRegister/common/close-icon.png"),
  plusIcon: require("@/static/competitionRegister/common/plus-icon.png"),
  submitSucess: require("@/static/competitionRegister/common/submitSucess.png"),
  closeBtn: require("@/static/competitionRegister/common/closeBtn.png"),
  arrow: require("@/static/competitionRegister/common/arrow.png"),
};

export default {
  name: "collect-information",
  components: {
    StepRegister,
    StepTabbar,
  },
  data() {
    return {
      show: false, // 提交成功弹窗
      showAreaPicker: false,
      staticImg,
      areaList: Object.freeze(areaList),
      form: {
        competitionChildId: "",
        district: "请选择所在地区",
        detailAddress: "",
        unit: "",
        unitPrincipal: "",
        materialList: [
          { id: 1, materialName: "小班", number: 50, isShow: true },
          { id: 2, materialName: "中班", number: 50, isShow: true },
          { id: 3, materialName: "大班", number: 50, isShow: true },
        ],
        schoolList: [],
      },
    };
  },
  computed: {
    submitIsShow() {
      let state = false;
      if (
        this.form.district !== "请选择所在地区" &&
        this.form.unit !== "" &&
        this.form.unitPrincipal !== "" &&
        this.form.schoolList.length !== 0
      ) {
        state = true;
      }
      return state;
    },
    totalSchool() {
      return this.form.schoolList.length || 0;
    },
    totalPeople() {
      let count = 0;
      this.form.schoolList.forEach((item) => {
        count += item.totalPerson * 1;
      });
      return count;
    },
  },
  onLoad(options) {
    if (options && options.competitionId) {
      this.form.competitionChildId = options.competitionId;
    }
  },
  async onReady() {
    await this.getAgentRegisterLastInfo();
  },
  onShow() {
    uni.getStorage({
      key: "formData",
      success: (res) => {
        console.log("success", res.data);
        this.form = res.data;
      },
      fail: (res) => {
        console.log(res, "fail");
      },
    });
  },
  methods: {
    // 查询上一次报名基本信息
    async getAgentRegisterLastInfo() {
      const { data, msg, status } = await getAgentRegisterLastInfo();
      if (status === 200 && data) {
        // console.log(data, "getAgentRegisterLastInfo");
        const obj = {
          district: data.district,
          unit: data.unit,
          unitPrincipal: data.unitPrincipal,
          detailAddress: data.detailAddress,
        };
        Object.assign(this.form, obj);
        // console.log(this.form, "form");
      }
    },
    changeMaterialNumber(key, value) {
      key.number = value;
      this.$forceUpdate();
    },
    // 去添加园所
    handleGoSchoolInfo() {
      uni.setStorage({
        key: "formData",
        data: this.form,
        success: () => {
          console.log("form保存成功");
        },
      });
      uni.redirectTo({
        url: `/pages/competitionRegister/addSchool`,
      });
    },
    // 预料包数量小于50时，强制改成50  @blur="handleInputBlur(material, $event.target.value)"
    // handleInputBlur(material, value) {
    //   if (value * 1 < 50) {
    //     // this.$set(this.form.materialList[material.id - 1], "number", 50);
    //     this.form.materialList[material.id - 1].number = 50;
    //     this.form.materialList[material.id - 1].isShow = false;
    //     this.$nextTick(() => {
    //       this.form.materialList[material.id - 1].isShow = true;
    //     });
    //   }
    // },
    // 返回首页
    handleReturnHome() {
      uni.reLaunch({
        url: "/pages/user/index",
      });
      this.show = false;
    },
    onChange(val) {
      this.form.materialList.forEach((item) => {
        if (item.materialName === val) item.isShow = !item.isShow;
      });
    },
    beforeSubmit() {
      let total = 0;
      this.form.materialList.map((item) => {
        if (item.isShow) total += item.number * 1;
      });
      if (total < 50) {
        Tip.error("预定物料包数量总和不得低于50套");
        return false;
      } else {
        return true;
      }
    },
    // 提交海选报名
    async submitAgentRegister() {
      if (!this.beforeSubmit()) return;
      const materialList = this.form.materialList.filter((item) => {
        if (item.isShow) {
          return item;
        }
      });
      const params = {
        ...this.form,
        materialList,
      };
      const { data, msg, status } = await submitAgentRegister(params);
      if (status === 200) {
        this.show = true;
        uni.removeStorage({
          key: "formData",
          success: function(res) {
            console.log("已经移除内存中的schoolList");
          },
        });
      } else {
        Tip.error(msg);
      }
    },
    // 清空表单项
    clearFormItem(key) {
      this.form[key] = "";
    },
    // 改变表单项
    changeForm(e, key) {
      console.log(e, key);
      const value = e.detail.value;
      this.form[key] = value;
    },
    // 取消地区
    cancelArea() {
      this.showAreaPicker = false;
    },
    // 确认地区
    confirmArea(e) {
      const { values } = e.detail;
      this.form.district = values.map((item) => item.name).join(",");
      this.showAreaPicker = false;
    },
    // 选择地区
    selectArea() {
      this.showAreaPicker = !this.showAreaPicker;
    },
  },
};
</script>

<style lang="less" scoped>
@import "@/utils/utils.less";

.collect-information {
  padding-bottom: 200rpx;
  .area-principal-information {
    padding: 0 32rpx;
    box-sizing: border-box;
    margin-top: 50rpx;
    .information-form {
      .information-form-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 28rpx;
        .information-form-label {
          font-size: 30rpx;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #666666;
        }
        .information-form-filed {
          width: 530rpx;
          height: 88rpx;
          background: #ffffff;
          box-shadow: 0rpx 0rpx 44rpx 0rpx rgba(226, 226, 226, 0.58);
          border-radius: 20rpx;
          padding-left: 32rpx;
          padding-right: 32rpx;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .filed-input-view {
            height: 88rpx;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-right: 28rpx;
            box-sizing: border-box;
          }
          .filed-input {
            width: 408rpx;
            height: 88rpx;
          }
          .close-icon {
            width: 26rpx;
            height: 28rpx;
            display: block;
          }
          .placeholder-class {
            font-size: 30rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #d1d1d1;
          }
          .select-after-text {
            font-size: 30rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #333333;
          }
        }
      }
    }
  }

  .school-information {
    padding: 0 32rpx;
    box-sizing: border-box;
    margin-top: 60rpx;
    .school-add-area {
      .school-add-button {
        width: 686rpx;
        height: 108rpx;
        border-radius: 20rpx;
        border: 4rpx dashed rgba(0, 91, 255, 0.3);
        display: flex;
        justify-content: center;
        align-items: center;
        .plus-icon {
          width: 42rpx;
          height: 40rpx;
          object-fit: cover;
        }
        .plus-arrow {
          width: 18rpx;
          height: 28rpx;
          object-fit: cover;
        }
        text {
          margin-left: 20rpx;
          margin-right: 10rpx;
          height: 34rpx;
          line-height: 34rpx;
          font-size: 34rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #4679ff;
        }
      }
    }
    .school-have-area {
      .school-add-button {
        width: 686rpx;
        height: 108rpx;
        border-radius: 20rpx;
        background: #ffffff;
        box-shadow: 0px 0px 22px 0px rgba(226, 226, 226, 0.58);
        display: flex;
        justify-content: center;
        align-items: center;
        .plus-icon {
          width: 42rpx;
          height: 40rpx;
          object-fit: cover;
        }
        .plus-arrow {
          width: 18rpx;
          height: 28rpx;
          object-fit: cover;
        }
        text {
          margin-left: 22rpx;
          height: 34rpx;
          line-height: 34rpx;
          font-size: 34rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #4679ff;
        }
      }
    }
  }

  .pre-material-package {
    margin-top: 60rpx;
    padding: 0 32rpx;
    box-sizing: border-box;
    .pre-material-package-title {
      width: 100%;
      height: 56rpx;
      display: flex;
      align-items: center;
      .tip {
        font-size: 30rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #fe6573;
      }
    }
    .material-package-information {
      width: 686rpx;
      height: 300rpx;
      background: #ffffff;
      box-shadow: 0rpx 0rpx 44rpx 0rpx rgba(226, 226, 226, 0.58);
      border-radius: 20rpx;
      padding: 34rpx 30rpx;
      box-sizing: border-box;
      .material-package-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        height: 64rpx;
        .material-package-item-label {
          display: flex;
          .material-package-item-label-left {
            display: flex;
            font-size: 28rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #666666;
            .label-prefix {
              color: #666;
              margin-right: 10rpx;
            }
            .clazz {
              color: #5f87f0;
            }
          }
        }
        .material-count {
          display: flex;
          align-items: center;
          .material-input {
            width: 120rpx;
            height: 64rpx;
            border-radius: 10rpx;
            border: 2rpx solid #e3e3e3;
            margin-right: 14rpx;
            text-align: center;
          }
        }
      }
    }
  }

  .information-title {
    font-size: 44rpx;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    margin-bottom: 40rpx;
  }

  .area-picker {
    width: 100vw;
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.block {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  margin-top: -100rpx;
  width: 686rpx;
  height: 576rpx;
  background: #ffffff;
  border-radius: 20rpx;
  .closeBtn {
    position: absolute;
    top: 40rpx;
    right: 40rpx;
    width: 24rpx;
    height: 24rpx;
    object-fit: cover;
  }
  .submitSucess {
    width: 334rpx;
    height: 336rpx;
    object-fit: cover;
  }
  .promptText {
    width: 234rpx;
    height: 36rpx;
    font-size: 26rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 36rpx;
  }
  .returnHome {
    margin-top: 32rpx;
    width: 278rpx;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ffffff;
    background: linear-gradient(130deg, #466efc 0%, #84bdfc 100%);
    border-radius: 84rpx;
    text-align: center;
  }
}
</style>
