<template>
  <div class="m-container1">
    <el-page-header @back="goback" style="padding: 20px" :content="'学校缴费'">
    </el-page-header>
    <div class="payInfoWrap">
      <div class="left">
        <div class="m-core1">
          <el-form :inline="true" :model="form" label-width="120px" ref="form">
            <div class="coreList">
              <payGoodsInfo
                :form="form"
                :courseViewType="courseViewType"
                :organId="organId"
              />
              <payFeeInfo :form="form" @setAllTotal="setAllTotal" />
              <payAddressInfo :form="form" />
              <payBackMoney :form="form" :educationList="educationList" />
            </div>
          </el-form>

          <div style="text-align: center;padding-bottom: 12px">
            <el-button class="submitBtn" @click="onSubmit">确认</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getMusicGroupPaymentCalenderDetail } from "@/api/buildTeam";
import { queryEmployByOrganId } from "@/api/systemManage";
import { musicGroupcreateCalender } from "../api";
import payGoodsInfo from "../goodsModal/payGoodsInfo";
import payFeeInfo from "../goodsModal/payFeeInfo";
import payAddressInfo from "../goodsModal/payAddressInfo";
import payBackMoney from "../goodsModal/payBackMoney";
export default {
  components: {
    payGoodsInfo,
    payFeeInfo,
    payAddressInfo,
    payBackMoney
  },
  data() {
    return {
      baseInfo: null,
      organId: null,
      courseViewType: null,
      educationList: [],
      form: {
        calenderGoodsList: [], // 添加商品
        currentTotalAmount: null, // 付款金额
        calenderFeeJson: {
          discountTotal: 0 // 优惠金额
        },
        contractUrl: "", // 合同链接
        memo: "", // 备注
        calenderAddress: {
          address: "", // 详情地址
          phone: "", // 手机号
          name: "", // 收货人
          province: null,
          city: null,
          region: null
        },
        responsiblePerson: null, // 责任人
        musicGroupCalenderRefundPeriods: [{ refundDate: "", refundAmount: "" }] // 回款周期
      }
    };
  },
  mounted() {
    this.baseInfo = JSON.parse(localStorage.getItem("payMusicBase"));

    this.init();
  },
  methods: {
    async init() {
      this.organId = this.musicGroup?.organId;
      this.courseViewType = this.baseInfo?.musicGroup?.courseViewType;

      this.getEmploy();

      if (this.$route.query.calenderId) {
        // 说明是修改  查缴项目详情
        this.initDetail = true;
        await getMusicGroupPaymentCalenderDetail({
          id: this.$route.query.calenderId
        }).then(res => {
          if (res.code == 200) {
            const result = res.data || {};
            this.$set(this.form, "calenderGoodsList", result.goods || []);

            this.$set(
              this.form,
              "musicGroupCalenderRefundPeriods",
              result.calenderRefundPeriods
            );
            // 设置责任人
            if (
              result.calenderRefundPeriods &&
              result.calenderRefundPeriods.length > 0
            ) {
              this.$set(
                this.form,
                "responsiblePerson",
                result.calenderRefundPeriods[0].responsiblePerson
              );
            }
            let calenderFeeJson = result.calender?.calenderFeeJson;
            if (calenderFeeJson) {
              calenderFeeJson = JSON.parse(calenderFeeJson);
              this.$set(this.form, "calenderFeeJson", calenderFeeJson);
            }
            this.$set(this.form, "contractUrl", result.calender?.contractUrl);
            this.$set(this.form, "memo", result.calender?.memo);
            this.$set(this.form, "calenderAddress", result.address);
          }
        });
      }
    },
    setAllTotal(val) {
      this.form.calenderFeeJson.allTotal = val;
      if (this.form.calenderFeeJson.discountTotal) {
        this.form.currentTotalAmount =
          this.form.calenderFeeJson.allTotal -
          this.form.calenderFeeJson.discountTotal;
      } else {
        this.form.currentTotalAmount = this.form.calenderFeeJson.allTotal;
      }
      this.$set(this.form, "currentTotalAmount", this.form.currentTotalAmount);
    },
    getEmploy() {
      try {
        queryEmployByOrganId({
          organId: this.organId,
          rows: 99999,
          demissionflag: 0
        }).then(res => {
          this.educationList = res.data?.rows || [];
        });
      } catch (e) {
        conosle.log(res, "res");
      }
    },
    goback() {
      let query = { ...this.$route.query };
      query.calenderId = null;
      if (query.type == "resetTeam") {
        this.$store.dispatch("delVisitedViews", this.$route);
        this.$router.push({
          path: "/business/resetTeaming",
          query
        });
      } else if (query.type == "look") {
        this.$store.dispatch("delVisitedViews", this.$route);
        this.$router.push({
          path: "/business/resetTeaming",
          query
        });
      } else if (
        query.type == "teamDraft" ||
        query.type == "feeAudit" ||
        query.type == "FEE_AUDIT_FAILED"
      ) {
        this.$store.dispatch("delVisitedViews", this.$route);
        this.$router.push({
          path: "/business/resetTeaming",
          query
        });
      }
    },
    onSubmit() {
      console.log(this.formatData());
      this.$refs.form.validate(async isok => {
        if (!isok) return;
        let obj = this.formatData();
        if (this.form.calenderGoodsList.length <= 0) {
          this.$message.error("请至少选择一个采购商品");
          return;
        }
        let total = 0;
        this.form.musicGroupCalenderRefundPeriods.forEach(item => {
          total += item.refundAmount * 1;
        });
        if (total != this.form.currentTotalAmount) {
          this.$message.error("付款金额与回款金额不一致,请重新设置");
          return;
        }

        try {
          const res = await musicGroupcreateCalender(obj);
          if (res.code == 200) {
            this.$message.success("创建缴费成功");
            this.goback();
          }
          if (res.code == 207) {
            await this.$confirm(
              res.msg || `当前乐团存在未排课的缴费项目，请再次确认操作`,
              "提示",
              {
                type: "warning"
              }
            );
            obj.confirmCreate = true;
            await musicGroupcreateCalender(obj);
            this.$message.success("创建缴费成功");
            this.goback();
          }
        } catch (e) {
          console.log(e);
        }
      });
    },
    formatData() {
      let calenderFeeJson = this.form.calenderFeeJson;
      const musicGroupCalenderRefundPeriods =
        this.form.musicGroupCalenderRefundPeriods || [];
      musicGroupCalenderRefundPeriods.forEach(period => {
        period.responsiblePerson = this.form.responsiblePerson;
      });
      return {
        payUserType: "SCHOOL",
        memo: this.form.memo,
        musicGroupId: this.$route.query.id,
        calenderFeeJson: JSON.stringify(calenderFeeJson),
        musicGroupCalenderRefundPeriods,
        currentTotalAmount: this.form.currentTotalAmount,
        contractUrl: this.form.contractUrl,
        calenderAddress: this.form.calenderAddress,
        calenderGoodsList: this.form.calenderGoodsList
      };
    },
    scrollView(object) {
      console.log(object);
      for (const i in object) {
        let dom = this.$refs[i];
        // 这里是针对遍历的情况（多个输入框），取值为数组
        if (Object.prototype.toString.call(dom) !== "[object Object]") {
          if (dom) {
            dom = dom[0];
          }
        }

        // 第一种方法（包含动画效果）
        dom.$el.scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: "center",
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: "smooth"
        });
        break; // 跳出循环了
      }
    }
  },
  computed: {
    musicGroup() {
      return this.baseInfo?.musicGroup;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/views/resetTeaming/modals/pay.scss";
.memoWrap {
  // width: calc(100% - 860px);
  width: 860px;
  .memoWrapItem {
    display: block;
    ::v-deep .el-form-item__content {
      display: inline-block;
      width: calc(100% - 140px);
    }
  }
}
.Wall {
  height: 15px;
  background-color: #f2f2f2;
}
::v-deep .el-form-item__label:before {
  content: "" !important;
  position: absolute;
  color: transparent;
  margin-right: 4px;
}
.payInfoWrap {
  .submitBtn {
    // width: 121px;
    // height: 41px;
    background: var(--color-primary);
    border-radius: 7px;
    // margin: 20px auto;
    // line-height: 40px;
    color: #fff;
    text-align: center;
    cursor: pointer;
  }
  .baseWrap {
    padding: 20px;
    background-color: #fff;
  }
  .baseWrapFixed {
    top: 105px;
    left: 215px; // 205
    position: fixed;
    background-color: #fff;
    width: calc(100% - 220px);
    z-index: 100;
    padding: 20px;
    box-shadow: rgba(0, 0, 0, 0.05) 0px 2px 3px 3px;
  }
  .left {
    ::v-deep .el-checkbox {
      padding: 8px 10px 7px 10px;
      border-radius: 4px;
    }
    ::v-deep .el-checkbox .el-checkbox__inner {
      border-radius: 50%;
      border: 1px solid var(--color-primary);
      width: 16px;
      height: 16px;
      &:after {
        height: 8px;
        left: 5px;
      }
    }
    ::v-deep .el-checkbox__inner:hover {
      background-color: var(--color-primary);
    }
    ::v-deep .el-checkbox.is-checked {
      border-color: #fff;
      color: #fff;
    }
    .payTitle {
      display: flex;
      flex-direction: row;
      align-items: center;
      font-size: 18px;
      font-weight: 600;
      color: #1a1a1a;
      height: 25px;
      margin-bottom: 15px;
      p {
        line-height: 25px;
      }
      .squrt {
        width: 3px;
        height: 16px;
        background: var(--color-primary);
        margin-right: 8px;
        position: relative;
        top: -1px;
        border-radius: 2px;
      }
      .payContext {
        color: var(--color-primary);
        border: 1px solid var(--color-primary);
        font-size: 14px;
        line-height: 22px;
        border-radius: 3px;
        padding: 0 5px;
        margin-left: 12px;
      }
    }
    .checkWrap {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      .checkBtn.active {
        border: 1px solid var(--color-primary);
      }
      .checkBtn {
        position: relative;
        background-color: #fefefe;
        margin-right: 12px;
        padding: 0 22px;
        display: flex;
        flex-direction: row;
        align-items: center;
        border-radius: 6px;
        border: 1px solid #dfe8ec;
        cursor: pointer;
        height: 84px;
        width: 251px;
        overflow: hidden;
        &:hover {
          border: 1px solid var(--color-primary);
        }
        p {
          height: 41px;
          line-height: 41px;
        }
        .checkLeft {
          width: 60px;
          height: 60px;
          margin-right: 16px;
          img {
            width: 100%;
          }
        }
        .checkRight {
          p {
            height: 26px;
            font-size: 19px;
            font-weight: 600;
            color: #1a1a1a;
            line-height: 26px;
          }
          .checkSubTitle {
            font-size: 14px;
            font-weight: 400;
            color: var(--color-primary);
            line-height: 20px;
          }
        }
        .checTriangle {
          border-bottom: 44px solid var(--color-primary);
          border-left: 44px solid transparent;
          position: absolute;
          right: 0;
          bottom: 0;
          width: 0;
          height: 0;
          img {
            width: 19px;
            height: 16px;
            position: absolute;
            top: 22px;
            right: 5px;
          }
        }
      }
      // .checkBtn.disabled {
      //   cursor: not-allowed;
      //   color: #d9d9d9;
      //   background-color: #f2f2f2 !important;
      //   ::v-deep .el-checkbox__inner {
      //     background-color: #fff !important;
      //     border-color: #d9d9d9;
      //     color: #fff;
      //     &::after {
      //       border-color: #d9d9d9;
      //     }
      //   }
      //   &:hover {
      //     background-color: #f2f2f2 !important;
      //     color: #d9d9d9;
      //     ::v-deep .el-checkbox__inner {
      //       background-color: #fff !important;
      //     }
      //   }
      // }
    }
  }
}
.coreList {
  // margin: 14px;
}
</style>
<style lang="less" scoped>
::v-deep .el-dialog__body {
  padding: 15px 0 0;
}
.empty {
  background-color: #fff;
  padding-bottom: 20px;
}
</style>
