<template>
  <div>
    <div class="searchBox">
      <span>商品类型：{{ getGoodsType(goodsItem.goodsType) }}</span>
      <span>教育类型：{{ goodsItem.educationName }}</span>
      <span
        >培训项目：{{
          goodsItem.projectName + "/" + goodsItem.businessName
        }}</span
      >
      <el-form
        :inline="true"
        :model="formData"
        size="small"
        style="display: inline"
      >
        <el-form-item
          v-for="(item, index) in formList"
          :key="index"
          :label="item.label"
        >
          <el-select
            v-if="item.scope === 'select'"
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            size="small"
          >
            <el-option
              v-for="(items, indexs) in item.options"
              :key="indexs"
              :label="items.label"
              :value="items.value"
            ></el-option>
          </el-select>
          <el-input
            v-else
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="search"
            >查询</el-button
          >
          <el-button size="small" @click="init">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div id="tableList">
      <div class="headerNavTool" v-if="navText.headShow !== false">
        <div class="leftIndexText">
          {{ navText.title }} <strong>{{ navText.index }}</strong>
          {{ navText.ch }}
        </div>
        <div class="rightBtnBox">
          <el-button
            size="medium"
            type="primary"
            @click="openMatchingDialog(null, 'multiple')"
            >匹配商品</el-button
          >
          <el-button
            size="medium"
            @click="openAddStudentDialog()"
            type="primary"
            >新增学员</el-button
          >
          <el-button
            size="medium"
            @click="openImportStudentDialog()"
            type="primary"
            >导入学员</el-button
          >
          <el-button size="medium" @click="handleDelete(null)" type="primary"
            >批量删除</el-button
          >
        </div>
      </div>
      <el-table
        ref="tableList"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        max-height="500"
        fit
        border
        :header-cell-style="{
          'text-align': 'center',
          'background-color': '#eee',
          color: '#333',
          fontSize: '14px',
        }"
        :cell-style="{
          'text-align': 'center',
        }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          fixed="left"
        ></el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="staffName" label="姓名" width="100">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.staffName"
              placeholder="请输入"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.idCard"
              placeholder="请输入"
              @blur="validateInput($event, 'idCard')"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="手机号码" width="150">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.telephone"
              placeholder="请输入"
              @blur="validateInput($event, 'telephone')"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="degree" label="学历" width="120">
          <template slot-scope="scope">
            <el-select v-model="scope.row.degree" placeholder="请选择">
              <el-option
                v-for="item in degreeTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value.toString()"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="companyName" label="所属公司" width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.companyName"
              placeholder="请输入"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="subjectId"
          label="科目/类型/年份/商品/单价"
          width="450"
        >
          <template slot-scope="scope">
            <div
              v-for="(item, index) in scope.row.subjectIdsList"
              :key="item.subjectId"
              :style="{
                'border-top': index == 0 ? '' : '1px solid #dfe6ec',
              }"
              class="subject"
            >
              <div class="title">
                {{ item.subjectNames }}
              </div>
              <div class="content">
                <div
                  v-for="subItem in item.goodsIdsList"
                  :key="subItem.goodsId"
                >
                  <el-checkbox
                    v-model="subItem.checked"
                    style="margin-right: 6px"
                  >
                    {{ changeGoodsType(subItem.goodsType) }}
                    {{ subItem.year }} / {{ subItem.goodsName }} /
                    <span style="color: red">￥{{ subItem.standPrice }}</span>
                  </el-checkbox>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="handle" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="openMatchingDialog(scope.row, 'edit')"
              >匹配商品</el-button
            >
            <el-button type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
        <!-- 暂无数据 -->
        <template slot="empty">
          <div style="margin: 30px">
            <div>
              <img
                style="width: 60px; height: 60px"
                src="@/assets/404_images/wuyuxaog.png"
                alt=""
              />
            </div>
            <el-button
              @click="openImportStudentDialog()"
              type="primary"
              size="small"
              >导入学员</el-button
            >
          </div>
        </template>
      </el-table>
      <!-- <pagination
        :total="total"
        :pageSize="formData.pageSize"
        :currentPage="formData.pageNum"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      /> -->
    </div>
    <div class="footetLine"></div>
    <div class="footerOrder">
      <div class="left">
        共<span class="blueColor">{{ this.navText.index }}</span
        >人，信息错误<span class="redColor">{{ "0" }}</span
        >人，匹配商品<span class="blueColor">{{
          matchingGoodsNum("peopleNum")
        }}</span
        >人
      </div>
      <div class="right">
        已选商品<span class="blueColor">{{ matchingGoodsNum("goodsNum") }}</span
        >个；总价<span class="redColor">
          ￥<span style="font-size: 28px; margin-right: 20px">
            {{ matchingGoodsNum("totalPrice").toFixed(2) }}
          </span>
        </span>
        <!-- <el-button plain>保存草稿</el-button> -->
        <el-button type="primary" @click="submitResult">提交结算</el-button>
      </div>
    </div>

    <!-- 新增学员弹窗 -->
    <addStudentDialog
      ref="addStudentDialog"
      :degree-type-list="degreeTypeList"
      @handle-add-student="handleAddStudent"
    />
    <!-- 导入学员弹窗 -->
    <importStudentDialog
      ref="importStudentDialog"
      :degree-type-list="degreeTypeList"
      @handle-import-data="handleImportData"
    />
    <!-- 匹配弹窗 -->
    <matchingDialog
      ref="matchingDialog"
      @handle-matching-data="handleMatchingData"
    />
    <!-- 订单结算弹窗 -->
    <orderResultDialog ref="orderResultDialog" />
  </div>
</template>
    
<script>
import addStudentDialog from "./addStudentDialog.vue";
import importStudentDialog from "@/views/orderManagement/shopMall/goodsMatching/importStudentDialog";
import matchingDialog from "@/views/orderManagement/shopMall/goodsMatching/matchingDialog";
import orderResultDialog from "./orderResultDialog.vue";
import { getDegreeTypeList } from "@/views/companyManagement/component/typeList";
import { mapGetters } from "vuex";
export default {
  components: {
    addStudentDialog,
    importStudentDialog,
    matchingDialog,
    orderResultDialog,
  },
  data() {
    return {
      loading: false, //当前表单加载是否加载动画
      navText: {
        title: "学员列表",
        index: 0,
        ch: "条",
      },
      //搜索
      formList: [
        {
          prop: "matchingStates",
          placeholder: "商品匹配",
          scope: "select",
          options: [
            {
              label: "已匹配",
              value: 1,
            },
            {
              label: "待匹配",
              value: 2,
            },
          ],
        },
        {
          prop: "searchItem",
          placeholder: "请输入姓名/身份证号/手机号码",
        },
      ],
      formData: {
        pageSize: 10,
        pageNum: 1,
      },
      goodsItem: {}, // 商品下单信息
      tableData: [], //表单数据
      multipleSelection: [], // 多选选中数据
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      degreeTypeList: getDegreeTypeList(), // 获取学历类型列表
      copyTableData: [],
      isSearch: false,
      tableDataTemp: [], // 备份列表数据
    };
  },
  computed: {
    //获取商品类型
    getGoodsType: function () {
      return function (goodsType) {
        var str = "";
        switch (goodsType) {
          case 1:
            str = "课程";
            break;
          case 2:
            str = "题库";
            break;
          case 6:
            str = "直播";
            break;
          case 10:
            str = "商品包";
            break;
          default:
            break;
        }
        return str;
      };
    },
    /**
     * 转换匹配商品类型
     */
    changeGoodsType() {
      return function (goodsType) {
        var str = "";
        switch (goodsType) {
          case 1:
            str = "课：";
            break;
          case 2:
            str = "题：";
            break;
          case 6:
            str = "直：";
            break;
          default:
            break;
        }
        return str;
      };
    },
    // 匹商品数量or价格or人数
    matchingGoodsNum: function () {
      return function (type) {
        let numObj = { peopleNum: 0, goodsNum: 0, totalPrice: 0 };
        let hasCheckedItem = false; // 用来标记是否有 checked 的商品
        this.tableData.forEach((item) => {
          if (!item.subjectIdsList || !item.subjectIdsList.length) {
            return;
          }
          item.subjectIdsList.forEach((subItem) => {
            if (!subItem.goodsIdsList || !subItem.goodsIdsList.length) {
              return;
            }
            subItem.goodsIdsList.forEach((i) => {
              if (i.checked) {
                numObj.goodsNum++;
                numObj.totalPrice += Number(i.standPrice);
                hasCheckedItem = true;
              }
            });
          });
          if (hasCheckedItem) {
            numObj.peopleNum++;
            // 重置 hasCheckedItem，当前 item 已经处理
            hasCheckedItem = false;
          }
        });
        return numObj[type];
      };
    },
  },
  watch: {
    tableData: {
      handler() {
        this.navText.index = this.tableData.length;
        console.log("---------tableData变化----------");
        var obj = {};
        let arrs = this.tableData;
        for (let i = 0; i < arrs.length; i++) {
          if (!obj[arrs[i].idCard]) {
            obj[arrs[i].idCard] = true;
          } else {
            arrs.splice(i, 1);
            i--;
          }
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.goodsItem = JSON.parse(localStorage.getItem("goodsItem"));
    if (this.$route.query.type === "default") {
      this.getDafaultStudent();
    }
  },
  methods: {
    // 获取默认学员列表
    getDafaultStudent() {
      this.loading = true;
      const params = {};
      if (this.goodsItem.goodsType && this.goodsItem.goodsType != 10) {
        params.goodsId = this.goodsItem.goodsId;
      } else {
        params.configId = this.goodsItem.configId;
      }
      this.$api
        .dafaultStudent(params)
        .then((res) => {
          res.rows.forEach((item) => {
            this.changeDefaultData(item);
          });
          this.navText.index = this.total;
          this.tableData = res.rows;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 改变默认数据
    changeDefaultData(item) {
      if (item.courseSubjectList && item.courseSubjectList.length > 0) {
        item.subjectIdsList = item.courseSubjectList.map((subjectItem) => {
          const {
            id: subjectId,
            subjectName: subjectNames,
            goodsVoList,
          } = subjectItem;
          if (goodsVoList && goodsVoList.length) {
            goodsVoList.forEach((i) => {
              i.checked = true;
            });
          }
          return {
            subjectId,
            subjectNames,
            goodsIdsList: goodsVoList || [],
          };
        });
        delete item.courseSubjectList;
      }
    },
    validateInput(event, type) {
      console.log(event.target.value, "----event----");
      // return;
      var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!reg.test(event.target.value) && type == 'idCard') {
        this.$message.warning("身份证格式不正确!");
        event.target.value = "";
      }
      var regPhone = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!regPhone.test(event.target.value) && type == 'telephone') {
        this.$message.warning("手机号码格式不正确!");
        event.target.value = "";
      }
    },
    openAddStudentDialog() {
      console.log(this.goodsItem, "---------");
      this.$refs.addStudentDialog.openBoxs(this.goodsItem.educationTypeId);
    },
    openImportStudentDialog() {
      this.$refs.importStudentDialog.openBoxs(this.goodsItem);
    },
    openMatchingDialog(row, type) {
      let datas = [];
      if (type === "multiple" && !row) {
        if (!this.multipleSelection.length) {
          this.$message.warning("请勾选需要匹配的选项");
          return;
        }
        datas = this.multipleSelection;
      } else {
        datas = [row];
      }
      console.log(datas, "----datas---------");
      this.$refs.matchingDialog.openBoxs(datas, this.goodsItem.businessId);
    },
    // 操作回调的导入数据
    handleImportData(datas) {
      datas.forEach((item) => {
        this.changeDefaultData(item);
      });
      this.tableData = this.tableData.concat(datas);
    },
    // 操作回调的新增学员数据
    handleAddStudent(data) {
      this.tableData.push(data);
    },
    // 操作回调的匹配商品数据
    handleMatchingData(datas) {
      for (let i = 0; i < this.tableData.length; i++) {
        datas.forEach((item) => {
          if (item.idCard == this.tableData[i].idCard) {
            this.$set(this.tableData[i], "subjectIdsList", item.subjectIdsList);
          }
        });
      }
    },
    // 提交结算弹窗
    submitResult() {
      if (!this.navText.index) {
        this.$message.warning("请添加学员");
        return;
      }
      if (!this.matchingGoodsNum("goodsNum")) {
        this.$message.warning("请完成匹配商品");
        return;
      }
      this.$refs.orderResultDialog.openBoxs({
        goodsItem: this.goodsItem,
        tableData: this.tableData,
      });
    },
    search() {
      if (!this.isSearch) {
        this.tableDataTemp = JSON.parse(JSON.stringify(this.tableData));
      } else {
        this.tableData = JSON.parse(JSON.stringify(this.tableDataTemp));
      }
      this.tableData = this.tableData.filter((item) => {
        const searchMatches =
          item.idCard.includes(this.formData.searchItem) ||
          item.staffName.includes(this.formData.searchItem) ||
          item.telephone.includes(this.formData.searchItem);
        const matchingStateMatches =
          (this.formData.matchingStates === 1 &&
            item.subjectIdsList.length > 0) ||
          (this.formData.matchingStates === 2 && !item.subjectIdsList.length);
        // 如果同时设置了searchItem和matchingStates，则需要两者都匹配
        if (this.formData.searchItem && this.formData.matchingStates) {
          return searchMatches && matchingStateMatches;
        }
        // 如果只设置了searchItem或matchingStates，则只需满足相应条件
        return searchMatches || matchingStateMatches;
      });
      this.isSearch = true;
    },
    init() {
      this.formData = {};
      if (this.isSearch) {
        this.tableData = this.tableDataTemp;
      }
      this.isSearch = false;
    },
    handleDelete(row) {
      if (!this.multipleSelection.length && !row) {
        this.$message.warning("请勾选需要删除的选项");
        return;
      }
      this.$confirm(
        row
          ? `确定删除此内容？内容删除后将无法恢复！`
          : `此操作将永久删除所勾选的${this.multipleSelection.length}条数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          const ids = row
            ? [row.idCard]
            : this.multipleSelection.map((item) => item.idCard);
          console.log(ids, "ids");
          this.tableData = this.tableData.filter(
            (item) => !ids.includes(item.idCard)
          );
        })
        .catch(() => {});
    },
    //多选操作回调
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
    },
    handleSizeChange(v) {
      this.formData.pageSize = v;
      this.formData.pageNum = 1;
      this.search();
    },
    handleCurrentChange(v) {
      this.formData.pageNum = v;
      this.search();
    },
  },
};
</script>
    
<style lang="less" scoped>
#tableList {
  padding: 16px 16px 16px;
  border-radius: 8px;
  box-shadow: 0px 0px 9px 1px rgba(28, 41, 90, 0.1);
  background: #ffffff;
  .headerNavTool {
    height: 72px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: -16px;
    .rightBtnBox {
      display: flex;
      align-items: center;
    }
  }
}
.footetLine {
  z-index: 999;
  position: fixed;
  bottom: 88px;
  right: 0;
  left: 0;
  border: 1px solid #f4f4f4;
}
.footerOrder {
  z-index: 999;
  position: fixed;
  bottom: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #ffffff;
  padding: 25px 30px 25px;
  // box-shadow: 3px -1px 1px 1px #f4f4f4;
  .blueColor {
    color: #1890ff;
  }
  .redColor {
    color: red;
  }
}
.subject {
  display: flex;
  align-items: stretch;
  padding: 10px 0;
  .title {
    min-width: 100px;
    max-width: 100px;
    text-align: center;
    align-self: center;
  }
  .content {
    text-align: left;
    padding-left: 10px;
    margin-left: 10px;
    border-left: 1px solid #dfe6ec;
  }
}
.searchBox {
  padding: 16px 10px 0 16px;
  margin: 0 0 10px 0;
  border-radius: 8px;
  box-shadow: 0px 0px 9px 1px rgba(28, 41, 90, 0.1);
  background: #ffffff;
  color: #333;
  font-size: 14px;
  line-height: 33px;
  span:nth-child(2) {
    margin: 0 20px;
  }
  span:nth-child(3) {
    margin-right: 10%;
  }
}
/deep/.el-button {
  border-radius: 8px;
}
</style>
    
    