<template>
  <div>
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="原乐器" prop="name">
        <span>{{originalMusicalGoods}}</span>
      </el-form-item>
      <el-form-item label="原教辅" prop="name">
        <span>{{originalAccessoriesGoods}}</span>
      </el-form-item>
      <el-form-item label="更改声部" prop="name">
        <el-select
          style="width: 100%!important"
          v-model="form.subjectId"
          clearable
          @change="subjectChange"
          placeholder="请选择声部"
        >
          <el-option
            v-for="item in voiceList"
            :key="item.subjectId"
            :label="item.subjectName"
            :value="item.subjectId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="更改乐器" prop="name">
        <el-select
          style="width: 100%!important"
          v-model="form.musicalGoods"
          clearable
          @change="musicalGoodsChange"
          placeholder="请选择乐器"
        >
          <el-option
            v-for="item in musicalGoods"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="activeAccessories.length || groupList.length" label="更换教辅" prop="name">
        <accessories
          :list.sync="activeAccessories"
          :groupList.sync="groupList"
          @change="accessoriesChange"
        />
        <!-- <el-select style="width: 100%" v-model="form.accessories" clearable placeholder="请选择教辅">
          <el-option
            v-for="item in accessories"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="支付差价" prop="name">
        <span style="color: red;">{{ spread }}元</span>
      </el-form-item>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
      style="text-align: right;"
    >
      <el-button
        @click="$listeners.close"
      >取 消</el-button>
      <el-button
        @click="cancel"
        type="danger"
        v-if="detail.subjectChange"
      >取消订单</el-button>
      <el-button
        type="primary"
        @click="submit"
      >确 定</el-button>
    </div>
  </div>
</template>
<script>
import { getStudentOriginal, getSubjectGoodsAndInfo, subjectChangeAdd, subjectChangeCancel } from '@/api/buildTeam'
import accessories from './accessories'

const formatAllGoods = (data, kitGroupPurchaseType) => {

  const accessories = []
  const accessoriesById = {}
  const musicalGoods = []
  const musicalGoodsById = {}
  const groupList = []
  const groupListById = {}

  const accessoriesByGoods = {}

  if (data) {
    const { musicGroupSubjectGoodsGroupList } = data

    const types = {}

    for (const item of musicGroupSubjectGoodsGroupList) {
      if (!types[item.type]) {
        types[item.type] = []
      }
      types[item.type].push(item)
    }

    const typesKeys = Object.keys(types)

    for (const key of typesKeys) {
      for (const item of types[key]) {
        if (key === 'INSTRUMENT') {
          let json = {}
          try {
            json = JSON.parse(item.kitGroupPurchaseTypeJson)
          } catch (error) {}
          const _item = {
            ...item,
            kitGroupPurchaseTypePrice: json[kitGroupPurchaseType]
          }
          musicalGoods.push(_item)
          musicalGoodsById[item.id] = _item
          if (!types.ACCESSORIES) {
            if (!accessoriesByGoods[item.id]) {
              accessoriesByGoods[item.id] = []
            }
            const acs = item.goodsList[0].goodsList ? item.goodsList[0].goodsList : []
            for (const goods of acs) {
              accessoriesByGoods[item.id].push(goods)
              accessoriesById[goods.id] = goods
            }
          }
        } else if (item.type === 'ACCESSORIES') {
          groupList.push(item)
          groupListById[item.id] = item
        }
      }
    }
  }

  return {
    accessories,
    accessoriesById,
    musicalGoods,
    musicalGoodsById,
    groupList,
    groupListById,
    accessoriesByGoods
  }
}

export default {
  props: ['detail', 'musicGroupId', 'voiceList'],
  components: {
    accessories
  },
  data() {
    return {
      oldAllMoney: 0,
      accessories: [],
      accessoriesByid: {},
      musicalGoods: [],
      musicalGoodsById: {},
      groupList: [],
      groupListById: {},
      accessoriesByGoods: {},
      selectAccessories: [],
      selectAccessoriesMoney: 0,
      kitGroupPurchaseTypePrice: 0,
      form: {
        subjectId: '',
        accessories: '',
        musicalGoods: '',
      },
      rules: {},
      item: {},
      originalMusicalGoods: '',
      originalAccessoriesGoods: '',
      originalAccessoriesPrice: 0,
      originalMusicalPrice: 0,
      originalCourseFee: 0,
      musicGroupSubjectPlanFee: 0,
      musicalPrice: 0,
    }
  },
  watch: {
    detail() {
      if (this.detail) {
        console.log(this.detail, this.voiceList)
        this.fetchDetail()
      }
    },
  },
  computed: {
    activeAccessories() {
      const { musicalGoods } = this.form
      return musicalGoods ? this.accessoriesByGoods[musicalGoods] || [] : []
    },
    spread() {
      return (
        this.musicalPrice +
        this.selectAccessoriesMoney +
        this.musicGroupSubjectPlanFee -
        this.originalAccessoriesPrice -
        this.originalMusicalPrice -
        this.originalCourseFee -
        this.kitGroupPurchaseTypePrice
      )
    }
  },
  mounted() {
    if (this.detail) {
      this.fetchDetail()
    }
  },
  methods: {
    fetchDetail() {
      getStudentOriginal({
        musicGroupId: this.musicGroupId,
        studentId: this.detail.studentId,
      })
      .then(res => {
        const { data } = res
        this.item = data
        if (data) {
          this.originalAccessoriesPrice = data.originalAccessoriesPrice
          this.originalMusicalPrice = data.originalMusicalPrice
          this.originalCourseFee = data.originalCourseFee
          this.originalMusicalGoods = data.originalMusicalGoods && data.originalMusicalGoods.name
          this.originalAccessoriesGoods = (data.originalAccessoriesGoods || []).map(item => item.name).join()
        }
      })
    },
    subjectChange(id) {
      this.$set(this.form, 'musicalGoods', '')
      getSubjectGoodsAndInfo({
        musicGroupId: this.musicGroupId,
        subjectId: id,
      })
      .then(res => {
        this.musicGroupSubjectPlanFee = res.data.musicGroupSubjectPlan.fee
        const items = formatAllGoods(res.data, this.item.kitGroupPurchaseType)
        for (const key in items) {
          if (items.hasOwnProperty(key)) {
            const item = items[key]
            this[key] = item
          }
        }
      })
    },
    musicalGoodsChange(val) {
      const item = this.musicalGoodsById[val]
      console.log(item)
      this.musicalPrice = this.numFormat(item.price)
      this.kitGroupPurchaseTypePrice = this.numFormat(item.kitGroupPurchaseTypePrice)
    },
    accessoriesChange(ids, money) {
      console.log(ids, money)
      this.selectAccessories = ids
      this.selectAccessoriesMoney = money
    },
    numFormat(num) {
      let _num = parseFloat(num)
      if (isNaN(_num)) {
        _num = 0
      }
      return Math.floor(_num * 100) / 100
    },
    submit() {
      subjectChangeAdd({
        changeCourseFee: this.numFormat(this.musicGroupSubjectPlanFee),
        changeAccessories: this.selectAccessories.join(','),
        changeAccessoriesPrice: this.numFormat(this.selectAccessoriesMoney),
        changeMusicalPrice: this.numFormat(this.musicalPrice - this.kitGroupPurchaseTypePrice),
        originalCourseFee: this.originalCourseFee,
        originalMusicalPrice: this.originalMusicalPrice,
        originalMusical: this.item.originalMusical,
        originalAccessories: this.item.originalAccessories,
        originalAccessoriesPrice: this.originalAccessoriesPrice,
        cooperationOrganId: this.item.cooperationOrganId,
        kitGroupPurchaseType: this.item.kitGroupPurchaseType,
        musicGroupId: this.musicGroupId,
        studentId: this.detail.studentId,
        changeMusical: this.form.musicalGoods,
        originalCost: this.item.originalCost,
        organId: this.item.organId,
        originalSubjectId: this.detail.actualSubjectId,
        changeSubjectId: this.form.subjectId,
      })
        .then(res => {
          this.$listeners.close()
          this.$message({
            type: 'success',
            message: '提交成功!'
          })
        })
    },
    cancel() {
      this.$confirm('是否确认取消订单?', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        subjectChangeCancel({
          id: this.item.id
        })
        .then(res => {
          this.$message({
            type: 'success',
            message: '取消成功!'
          })
        })
      })
    }
  },
}
</script>
<style lang="less" scoped>

</style>
