<template>
  <div>
    <paymentCycle
      ref="cycle"
      :form="cycle"
      :isUserType="true"
      :isCommon="true"
      :isDisabled="true"
      :hideMoney="true"
    />
    <otherform :form="other" ref="other" />
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="dialogVisible = true">一键修改差价</el-button>
      <el-button type="primary" @click="init">还原差价</el-button>
    </div>
    <el-table
      :data="dataList"
      :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
      max-height="300px"
    >
      <el-table-column
        prop="userId"
        align="center"
        width="120"
        label="学员编号"
      ></el-table-column>
      <el-table-column
        prop="username"
        align="center"
        width="120"
        label="学员姓名"
      ></el-table-column>
      <el-table-column prop="phone" align="center" width="120" label="课程类型">
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.courseList"
            :key="index"
            class="courseDiv"
          >
            {{ item.courseType | coursesType }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="原班级剩余课程价值">
        <template slot-scope="scope">
          <div>
            <div
              class="courseDiv"
              v-for="(item, index) in scope.row.courseList"
              :key="index"
            >
              {{ item.subCourseAmount }}
              <!-- <el-input v-model="item.courseCurrentPrice"></el-input> -->
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="subjectNames"
        align="center"
        label="主班级剩余课程价值"
      >
        <template slot-scope="scope">
          <div>
            <div
              class="courseDiv"
              v-for="(item, index) in scope.row.courseList"
              :key="index"
            >
              <!-- <el-input v-model="item.courseOriginalPrice"></el-input> -->
              {{ item.masterSubCoursePrice}}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="subjectNames" align="center" label="需补交差价">
        <template slot-scope="scope">
          <div>
            <div
              class="courseDiv"
              v-for="(item, index) in scope.row.courseList"
              :key="index"
            >
              <el-input v-model="item.courseCurrentPrice" type="number"></el-input>
              <!-- {{item.courseOriginalPrice}} -->
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="一键修改差价" :visible.sync="dialogVisible" append-to-body width="500px" v-if="dialogVisible">
      <calenderStudentList :conrseTypeList='conrseTypeList' ref='calenderStudentList'/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setAllprice"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Vue from "vue";
import paymentCycle from "@/views/resetTeaming/modals/payment-cycle";
import otherform from "@/views/resetTeaming/modals/other";
import { getTimes } from "@/utils";
import { spanGroupMergeClassSplitClassAffirm } from "@/api/buildTeam";
import { courseType, filterCourseType } from "@/constant";
import descriptions from "@/components/Descriptions";
Vue.use(descriptions);
import calenderStudentList from './resetCourseMasker'
export default {
  props: [
    "studentIds",
    "masterClassGroupId",
    "classGroupStudents",
    "classList",
    "mergeInfo",
  ],
  components: {
    paymentCycle,
    otherform,
    calenderStudentList
  },
  data() {
    return {
      activeNames: [],
      mergeInfoList: [],
      cycle: {
        paymentAmount: null,
        paymentPattern: null,
      },
      other: {},
      dataList: [],
      copyList: {},
      conrseTypeList: [],
      filterCourseType,
      dialogVisible:false
    };
  },
  mounted() {
    // console.log(this.studentIds, this.masterClassGroupId, this.classGroupStudents)
    // for (let item in this.mergeInfo) {
    //   this.activeNames.push(item);
    // }
    this.init();
  },
  methods: {
    init() {
      this.coypList = this.$helpers.lodash.cloneDeep(this.mergeInfo);
      this.mergeInfoList = [];
      for (let merge in this.coypList) {
        this.mergeInfoList = this.mergeInfoList.concat(this.coypList[merge]);
      }
      this.concatCourseLst(this.mergeInfoList);
    },
    getCLassName(key) {
      let str = "";
      this.classList.forEach((classes) => {
        if (classes.id == key) {
          str = classes.name;
        }
      });
      return str;
    },
    async submit() {
      let flag = false;
      let isNumber = false;
      const lodash = this.$helpers.lodash

      this.dataList.forEach(stu=>{
        stu.courseList.forEach(course=>{
          if(!(course.courseCurrentPrice+'')){
            flag = true
          }
          if(!lodash.isNumber(course.courseCurrentPrice*1) || course.courseCurrentPrice*1<0){
            isNumber = true
          }
        })
      })
      if(isNumber){
        this.$message.error('请填写正确的补交差价')
        return
      }
      if(flag){
        this.$message.error('请填写完成的缴费信息')
        return
      }
      let obj = {};
      let some = this.getData();
      if (some) {
        obj.musicGroupPaymentCalenderDtos = [some];
      } else {
        return;
      }

      obj.classGroupIds = this.classList.map((classes) => {
        return classes.id;
      });
      obj.masterClassGroupId = this.masterClassGroupId;
      obj.classGroupStudents = this.classGroupStudents;
      obj.studentIds = this.studentIds;
      try {
        const reset = await spanGroupMergeClassSplitClassAffirm(obj);
        this.$message.success(reset.msg);
        // 1.关闭弹窗
        // 2.清空合并班
        // 3.刷新列表
        this.$emit("refresh");
      } catch (e) {
        console.log(e);
      }
    },
    getForms() {
      const { $refs: refs } = this;
      // [refs.base, refs.eclass, refs.cycle, ...(refs.cycles || []), refs.other, refs.payment]
      return [refs.cycle, refs.other]
        .filter((item) => !!item)
        .map((item) => item.$refs.form || item);
    },
    getData() {
      const forms = this.getForms();
      const valided = [];
      for (const form of forms) {
        form.validate((valid) => {
          if (valid) {
            valided.push(form);
          }
        });
      }
      if (valided.length === forms.length) {
        const { leixing, ...rest } = {
          ...this.form,
          ...this.other,
        };

        if (this.$refs.cycle) {
          const {
            paymentDate,
            paymentValid,
            paymentPattern,
            ...other
          } = this.cycle;
          rest.paymentPattern = paymentPattern;
          rest.payUserType = "STUDENT";
          rest.paymentType = "SPAN_GROUP_CLASS_ADJUST";
          rest.musicGroupPaymentCalenderStudentDetails = this.mergeInfoList;
          rest.musicGroupPaymentDateRangeList = [
            {
              ...other,
              ...getTimes(paymentDate, [
                "startPaymentDate",
                "deadlinePaymentDate",
              ]),
              ...getTimes(paymentValid, [
                "paymentValidStartDate",
                "paymentValidEndDate",
              ]),
            },
          ];
        }
        const data = {
          ...rest,
        };
        return data;

        // 说明验证通过
      } else {
        this.$message.error("请填写必要信息");
        return null;
      }
    },
    concatCourseLst(arr) {
      let data = {};
      arr.forEach((some) => {
        if (data[some.userId]) {
          // data[some.userId].push(some)
          data[some.userId].courseList.push(some);
        } else {
          data[some.userId] = {};
          data[some.userId].userId = some.userId;
          data[some.userId].username = some.username;
          data[some.userId].courseList = [];
          data[some.userId].courseList.push(some);
        }
      });
      this.dataList = Object.values(data);
      this.getNewClassType(this.dataList[0]?.courseList);
    },
    getNewClassType(arr) {
      this.conrseTypeList = arr.map((item) => {
        return {
          type:item.courseType,
          typeName:this.filterCourseType[item.courseType]+'补缴',
          price:''
        }
      });

    },
    setAllprice(){
      this.$refs.calenderStudentList.$refs.visitForm.validate(res=>{
        if(res){
          this.mergeInfoList.forEach(merge=>{
            this.conrseTypeList.forEach(courseType=>{
              if(merge.courseType == courseType.type){
                // 修改为新值
                merge.courseCurrentPrice = courseType.price
              }
            })
          })
           this.$refs.calenderStudentList.$refs.visitForm.resetFields();
           this.dialogVisible = false
          // this.conrseTypeList
          // this.mergeInfoList

        }
      })

    }
  },
};
</script>
<style lang="scss" scoped>
.courseDiv {
  height: 45px;
  line-height: 45px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
/deep/ .header {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
  // margin-bottom: 10px;
  > span:first-child {
    display: flex;
    &::before {
      content: "";
      display: block;
      width: 5px;
      background-color: #14928a;
      margin-right: 10px;
      border-radius: 2px;
      height: 48px;
    }
  }
  .icon {
    font-size: 18px;
    font-weight: normal;
    margin-right: 20px;
  }
  /deep/.el-collapse-item__wrap {
    border-bottom: none !important;
  }
}
</style>
