<template>
  <div class="cart">
    <Header></Header>
    <section class="section">
      <div class="container">
        <div class="section__header">
          <div class="cart-icon">
            <i class="img el-icon-shopping-cart-2"></i>
          </div>
          <div class="title">
            我的购物车
            <span class="number">
              {{ goodsList.length ? `(${goodsList.length}) ` : "" }}
            </span>
          </div>
          <div class="total">
            <div class="total__number">
              已选
              <span>{{ multipleSelection.length }}件</span>
              商品
            </div>
            <div class="total__price">
              总金额：
              <span>￥{{ total | toFixed }}</span>
            </div>
          </div>
          <div class="pay-btn" @click="pay">去支付</div>
        </div>
        <div class="section__body">
          <el-table
            ref="multipleTable"
            :data="goodsList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="60"
            >
            </el-table-column>
            <el-table-column label="商品信息" header-align="center">
              <template slot-scope="scope">
                <div class="goods">
                  <div class="goods__img">
                    <img
                      :src="$tools.splitImgHost(scope.row.coverUrl, true, 213)"
                      alt=""
                    />
                  </div>
                  <div class="goods__info">
                    <div class="title">
                      {{ scope.row.goodsName }}

                      <span class="note">60学时</span>
                      <span class="note">继续教育</span>
                    </div>
                    <div class="desc">
                      项目类型-业务层级
                      <span class="note">
                        报名截止时间：{{ scope.row.date }}
                      </span>
                    </div>
                    <div
                      class="selection"
                      v-if="
                        scope.row.templateType == 'class' &&
                        scope.row.goodsType == 1
                      "
                    >
                      <el-select
                        class="select"
                        v-model="scope.row.gradeId"
                        placeholder="请选择班级"
                        size="small"
                        @click.native="selectClick(scope.row, 'class')"
                      >
                        <el-option
                          v-for="item in scope.row.gradeList"
                          :key="item.gradeId"
                          :label="item.className"
                          :value="item.gradeId"
                        >
                        </el-option>
                      </el-select>
                    </div>

                    <div
                      class="selection"
                      v-if="
                        scope.row.templateType == 'apply' &&
                        scope.row.goodsType == 1
                      "
                    >
                      <el-select
                        v-model="scope.row.educationId"
                        placeholder="请选择考期"
                        size="small"
                        @click.native="selectClick(scope.row, 'exam')"
                      >
                        <el-option
                          v-for="item in scope.row.examineList"
                          :key="item.educationId"
                          :label="item.examineName"
                          :value="item.educationId"
                        >
                        </el-option>
                      </el-select>
                      <el-cascader
                        size="small"
                        :props="props"
                        :ref="'cascader' + scope.$index"
                        :options="provinceList"
                        v-model="scope.row.area"
                        @change="areaChange(scope.row, scope.$index)"
                        clearable
                        placeholder="请选择报考地区"
                      ></el-cascader>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="金额"
              header-align="center"
              align="center"
              width="120"
            >
              <template slot-scope="scope">
                <a class="goods_price"> ￥{{ scope.row.standPrice }} </a>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="编辑"
              width="120"
              header-align="center"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <a @click="del(scope.row)">删除</a>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="section__footer">
          <div class="title">
            <el-checkbox v-model="checked" @change="allCheckChange(checked)"
              >全选</el-checkbox
            >
          </div>
          <div class="total">
            <div class="total__number">
              已选
              <span>{{ multipleSelection.length }}件</span>
              商品
            </div>
            <div class="total__price">
              总金额：
              <span>￥{{ total | toFixed }}</span>
            </div>
          </div>
          <div class="pay-btn" @click="pay">去支付</div>
        </div>
      </div>
    </section>

    <ToolBar></ToolBar>
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from "@/components/footer/index";
import Header from "@/components/header/index";
import ToolBar from "@/components/toolbar/index";
import { mapMutations } from "vuex";
export default {
  name: "login",
  components: {
    Footer,
    Header,
    ToolBar,
  },
  data() {
    return {
      checked: false,
      multipleSelection: [],
      goodsList: [],
      total: 0,
      provinceList: [],
      props: {
        lazy: true,
        lazyLoad: this.lazyLoad,
      },
    };
  },
  mounted() {
    this.getProvinceList();
    this.cartList();
  },
  methods: {
    ...mapMutations(["setCheckGoodsList"]),
    areaChange(row, index) {
      console.log(row);
      let node = this.$refs["cascader" + index].getCheckedNodes()[0]; //选中的根节点
      console.log(node);
      row.applyAreas = {
        areaName: node.parent.label,
        areaId: node.parent.value,
        cityId: node.value,
        cityName: node.label,
      };
    },
    lazyLoad(node, resolve) {
      const { level } = node;
      console.log(node);
      if (level == 0) {
        // this.$request.getProvinceList().then((res) => {
        //   const nodes = res.rows.map((item) => ({
        //     value: item.areaId,
        //     label: `${item.areaName}`,
        //     leaf: level >= 1,
        //   }));
        //   resolve(nodes);
        // });
      } else if (level == 1) {
        this.$request.getCityList({ parentId: node.value }).then((res) => {
          const nodes = res.rows.map((item) => ({
            value: item.areaId,
            label: `${item.areaName}`,
            leaf: level >= 1,
          }));
          resolve(nodes);
        });
      }
    },
    /**
     * 点击select获取对应列表
     */
    selectClick(row, type) {
      if (type == "class") {
        //选择班级
        console.log(row);
        if (!row.gradeList.length) {
          this.$request.goodsGradeList({ goodsId: row.goodsId }).then((res) => {
            row.gradeList = res.rows;
            if (row.gradeList.length == 0) {
              let item = {
                className: "系统分班",
                gradeId: 0,
              };

              row.gradeList.push(item);
            }
          });
        }
      } else if (type == "apply") {
        //选择考试地点
      } else if (type == "exam") {
        //选择考期
        this.$request
          .getExamineList({ projectId: row.projectId })
          .then((res) => {
            row.examineList = res.rows;
          });
      }
    },
    /**
     * 获取所有省份
     */
    getProvinceList() {
      this.$request.getProvinceList().then((res) => {
        this.provinceList = res.rows.map((item) => ({
          value: item.areaId,
          label: `${item.areaName}`,
          leaf: false,
        }));
      });
    },
    /**
     * 全选和取消全选
     */
    allCheckChange(val) {
      if (val) {
        this.goodsList.forEach((row, i) => {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    /**
     * 获取购物车列表
     */
    cartList() {
      this.$request.cartList().then((res) => {
        res.rows.forEach((item) => {
          item.area = [];
          item.gradeId = "";
          item.gradeList = [];
          item.examDate = "";
          item.examineList = [];
        });
        this.goodsList = res.rows;
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;

      if (
        this.multipleSelection.length > 0 &&
        this.multipleSelection.length == this.goodsList.length
      ) {
        this.checked = true;
      } else {
        this.checked = false;
      }

      this.caculate();
    },

    caculate() {
      this.total = 0;

      this.multipleSelection.forEach((item) => {
        this.total += item.standPrice;
      });
    },
    pay() {
      if (this.$refs.multipleTable.selection.length == 0) {
        this.$message({
          message: "请选择商品",
          type: "warning",
        });

        return;
      }

      for (let i = 0; i < this.$refs.multipleTable.selection.length; i++) {
        let item = this.$refs.multipleTable.selection[i];

        if (item.templateType == "class" && item.goodsType == 1) {
          if (!item.gradeId && item.gradeId !== 0) {
            this.$message({
              message: "请选择班级",
              type: "warning",
            });
            return;
          }
        }

        if (item.templateType == "apply" && item.goodsType == 1) {
          // if (!item.applyAreas.areaName) {
          // 	uni.showModal({
          // 		title: '提示',
          // 		content: '请选择报考地区',
          // 		showCancel: false
          // 	});
          // 	return false;
          // }
          if (!item.applyAreas.areaName) {
            this.$message({
              message: "请选择考期",
              type: "warning",
            });
            return false;
          }
        }
      }

      let selectGoodsList = JSON.parse(
        JSON.stringify(this.$refs.multipleTable.selection)
      );
      selectGoodsList.forEach((item) => {
        if (item.goodsType == 1) {
          if (item.templateType == "class") {
            let goodsInputData = {
              type: "class",
              gradeId: item.gradeId,
              gradeJson: JSON.stringify(
                item.gradeList.find((grade) => grade.gradeId == item.gradeId)
              ),
            };
            item.goodsInputData = goodsInputData;
          }
          if (item.templateType == "apply") {
            let goodsInputData = {
              type: "apply",
              applyAreasJson: JSON.stringify(item.applyAreas),
              examDateJson: JSON.stringify(
                item.examineList.find(
                  (exam) => exam.educationId == item.educationId
                )
              ),
            };
            item.goodsInputData = goodsInputData;
          }
        }
      });

      this.setCheckGoodsList(selectGoodsList);

      this.$router.push({
        path: "/payment",
      });
    },
    del(row) {
      this.$confirm("确认删除商品？")
        .then((_) => {
          this.$request.cartDelete(row.id).then((res) => {
            this.$message.con;
            this.cartList();
          });
        })
        .catch((_) => {});
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.cart {
  .section {
    &__header {
      height: 80px;
      background: #ebf3ff;
      display: flex;
      align-items: center;
      padding: 0 20px;

      .cart-icon {
        width: 40px;
        height: 40px;
        background: #3f8dfd;
        box-shadow: 0px 0px 9px 1px rgba(63, 141, 253, 0.3);
        border-radius: 50%;
        text-align: center;
        line-height: 40px;

        .img {
          vertical-align: middle;
          display: inline-block;
          color: #fff;
          font-size: 24px;
        }
      }

      .title {
        font-size: 30px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333333;
        flex: 1;
        margin-left: 20px;

        .number {
          font-size: 24px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #333333;
        }
      }

      .total {
        display: flex;
        &__number {
          span {
            font-size: 24px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #333333;
          }
        }

        &__price {
          margin-left: 20px;
          span {
            font-size: 24px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #ff3b30;
          }
        }
      }

      .pay-btn {
        cursor: pointer;
        width: 80px;
        height: 40px;
        background: #ff3b30;
        border-radius: 20px;
        text-align: center;
        line-height: 40px;
        color: #fff;
        margin-left: 20px;
      }
    }

    &__body {
      .goods {
        display: flex;
        &__img {
          width: 213px;
          height: 120px;
          background: #000;
        }

        &__info {
          margin-left: 10px;
          flex: 1;

          .title {
            margin-top: 10px;
            font-size: 16px;
            font-family: Microsoft YaHei;
            font-weight: bold;
            color: #333333;
            .note {
              margin-left: 10px;
              padding: 1px 5px;
              border: 1px solid #333333;
              border-radius: 4px;
              font-size: 12px;
              font-family: Microsoft YaHei;
              font-weight: 400;
              color: #333333;
            }
          }

          .desc {
            margin-top: 10px;
            font-size: 14px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #333333;
            .note {
              font-size: 14px;
              font-family: Microsoft YaHei;
              font-weight: 400;
              color: #999999;
            }
          }

          .selection {
            margin-top: 10px;
            width: 5f00px;

            .select {
              width: 400px;
            }
          }
        }
      }

      .goods_price {
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        color: #ff3b30;
      }
    }

    &__footer {
      height: 80px;
      background: #ffffff;
      display: flex;
      align-items: center;
      padding: 0 20px;

      .cart-icon {
        width: 40px;
        height: 40px;
        background: #3f8dfd;
        box-shadow: 0px 0px 9px 1px rgba(63, 141, 253, 0.3);
        border-radius: 50%;
      }

      .title {
        font-size: 30px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333333;
        flex: 1;
      }

      .total {
        display: flex;
        &__number {
          span {
            font-size: 24px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #333333;
          }
        }

        &__price {
          margin-left: 20px;
          span {
            font-size: 24px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #ff3b30;
          }
        }
      }

      .pay-btn {
        cursor: pointer;
        width: 80px;
        height: 40px;
        background: #ff3b30;
        border-radius: 20px;
        text-align: center;
        line-height: 40px;
        color: #fff;
        margin-left: 20px;
      }
    }
  }
}
</style>
