<template>
  <div>
    <el-form :model="form" :rules="rules" ref="form" label-width="110px">
      <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="subjectId"
        :rules="[
          { required: true, message: '请选择更改声部', trigger: 'change' }
        ]"
      >
        <el-select
          style="width: 100%!important"
          v-model="form.subjectId"
          clearable
          v-if="!changeInfo"
          @change="subjectChange"
          placeholder="请选择声部"
        >
          <el-option
            v-for="item in filterVoiceList"
            :key="item.subjectId"
            :label="item.subjectName"
            :value="item.subjectId">
          </el-option>
        </el-select>
        <span v-else>{{changeSubjectName}}</span>
      </el-form-item>
      <el-form-item
        label="更改乐器"
        prop="musicalGoods"
        :rules="[
          { required: true, message: '请选择更改乐器', trigger: 'change' }
        ]"
      >
        <el-select
          style="width: 100%!important"
          v-model="form.musicalGoods"
          clearable
          v-if="!changeInfo"
          @change="musicalGoodsChange"
          placeholder="请选择乐器"
        >
          <el-option
            label="自备乐器"
            value="OWNED">
          </el-option>
          <el-option
            v-for="item in musicalGoods"
            :key="item.goodsIdList"
            :label="item.name"
            :value="item.goodsIdList">
          </el-option>
        </el-select>
        <span v-else-if="changeInfo && changeInfo.changeMusicalGoods">{{changeInfo.changeMusicalGoods.name}}</span>
      </el-form-item>
      <el-form-item
        v-if="changeInfo || (form.musicalGoods && musicalGoodsById[form.musicalGoods] && musicalGoodsById[form.musicalGoods].kitGroupPurchaseTypeJsonParse)" label="乐器提供方式" prop="type"
        :rules="[
          { required: true, message: '请选择乐器提供方式', trigger: 'change' }
        ]"
      >
        <el-radio-group v-if="!changeInfo" v-model="form.type">
          <el-radio
            :label="key"
            v-for="(item, key) in musicalGoodsById[form.musicalGoods].kitGroupPurchaseTypeJsonParse"
            :key="key"
          >{{`${kitGroupPurchaseTypeFormater[key]} ${(musicalGoodsById[form.musicalGoods][typeAndprice[key]] || 0) > 0 ? musicalGoodsById[form.musicalGoods][typeAndprice[key]] + '元' : '免费'}`}}</el-radio>
        </el-radio-group>
        <span v-else-if="changeInfo && changeInfo.kitGroupPurchaseType">{{kitGroupPurchaseTypeFormater[changeInfo.kitGroupPurchaseType]}}</span>
      </el-form-item>
      <el-form-item v-if="(activeAccessories.length || groupList.length) || changeInfo" label="更换教辅" prop="name">
        <accessories
          :list.sync="activeAccessories"
          :groupList.sync="groupList"
          @change="accessoriesChange"
          v-if="!changeInfo"
        />
        <span v-else-if="changeInfo">{{changeAccessoriesGoods}}</span>
        <!-- <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" v-if="changeInfo">
        <div class="viewlink">
          <el-tooltip class="item" effect="dark" :content="copyLink" placement="top">
            <span class="link">{{copyLink}}</span>
          </el-tooltip>
          <el-popover
            placement="top"
            width="220"
            trigger="click">
            <div class="left-code">
              <div id="qrcode"
                  class="qrcode code"
                  ref="qrCodeUrl"></div>
              <p class="code-url"
                v-if="copyLink">{{ copyLink }} <el-link @click="copyUrl(copyLink)" class="linkbtn" type="primary">复制</el-link></p>
            </div>
            <el-button type="primary" class="btn" slot="reference" @click="onCreateQRCode">二维码</el-button>
          </el-popover>
        </div>
      </el-form-item>
      <el-form-item label="支付差价" prop="name">
        <span style="color: red;" v-if="!changeInfo">{{ spread | moneyFormat }}元</span>
        <span style="color: red;" v-else>{{ editSpread | moneyFormat }}元</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-permission="'subjectChange/cancel'"
        v-if="changeInfo && changeInfo.status !== 1"
      >取消订单</el-button>
      <el-button
        type="primary"
        v-if="!changeInfo"
        v-permission="'subjectChange/add'"
        @click="submit"
      >确 定</el-button>
    </div>
  </div>
</template>
<script>
import QRCode from 'qrcodejs2'
import copy from 'copy-to-clipboard'
import numeral from 'numeral'
import { getStudentOriginal, getSubjectGoodsAndInfo, subjectChangeAdd, subjectChangeCancel, getChangeInfo } from '@/api/buildTeam'
import { vaildStudentUrl } from '@/utils/validate'
import accessories from './accessories'
import { kitGroupPurchaseType } from '@/constant'

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 = {}
          let courseJson = {}
          try {
            json = JSON.parse(item.kitGroupPurchaseTypeJson)
          } catch (error) {}
          try {
            courseJson = JSON.parse(item.coursePurchaseTypeJson)
          } catch (error) {}
          // if (json[kitGroupPurchaseType] !== undefined) {
            const _item = {
              ...item,
              kitGroupPurchaseTypeJsonParse: json,
              kitGroupPurchaseTypePrice: json[kitGroupPurchaseType] || 0,
              coursePurchaseTypeJsonTypePrice: courseJson[kitGroupPurchaseType] || 0,
              _calculated_price: (kitGroupPurchaseType === 'FREE' ? 0 : (kitGroupPurchaseType === 'LEASE' ? item.depositFee : item.price))
            }
            musicalGoods.push(_item)
            musicalGoodsById[item.goodsIdList] = _item
            if (!types.ACCESSORIES) {
              if (!accessoriesByGoods[item.goodsIdList]) {
                accessoriesByGoods[item.goodsIdList] = []
              }
              const acs = item.goodsList[0].goodsList ? item.goodsList[0].goodsList : []
              for (const goods of acs) {
                accessoriesByGoods[item.goodsIdList].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
  }
}

const typeAndprice = {
  GROUP: 'price',
  LEASE: 'depositFee',
}

export default {
  props: ['detail', 'musicGroupId', 'voiceList'],
  components: {
    accessories
  },
  data() {
    return {
      typeAndprice,
      kitGroupPurchaseTypeFormater: kitGroupPurchaseType,
      changeInfo: null,
      oldAllMoney: 0,
      accessories: [],
      accessoriesByid: {},
      musicalGoods: [],
      musicalGoodsById: {},
      groupList: [],
      groupListById: {},
      accessoriesByGoods: {},
      selectAccessories: [],
      selectAccessoriesMoney: 0,
      kitGroupPurchaseTypePrice: 0,
      coursePurchaseTypeJsonTypePrice: 0,
      form: {
        subjectId: '',
        accessories: '',
        musicalGoods: '',
        type: '',
      },
      rules: {},
      item: {},
      originalMusicalGoods: '',
      originalAccessoriesGoods: '',
      originalAccessoriesPrice: 0,
      originalMusicalPrice: 0,
      originalCourseFee: 0,
      musicGroupSubjectPlanFee: 0,
      musicalPrice: 0,
    }
  },
  watch: {
    detail() {
      if (this.detail) {
        this.fetchDetail()
      }
    },
    'form.musicalGoods'() {
      this.$set(this.form, 'type', '')
    },
    'form.type'() {
      this.musicalGoodsChange(this.form.musicalGoods)
    }
  },
  computed: {
    copyLink() {
      if (this.changeInfo) {
        return vaildStudentUrl() + '/#/change-voice?id=' + this.changeInfo.id
      }
      return ''
    },
    filterVoiceList() {
      return this.voiceList.filter(item => item.subjectId !== this.detail.actualSubjectId)
    },
    activeAccessories() {
      const { musicalGoods } = this.form || {}
      return musicalGoods ? this.accessoriesByGoods[musicalGoods] || [] : []
    },
    changeSubjectName() {
      let name = ''
      if (this.item.changeSubjectId) {
        for (const item of this.voiceList) {
          if (item.subjectId === this.item.changeSubjectId) {
            name = item.subjectName
            break
          }
        }
      }
      return name
    },
    changeAccessoriesGoods() {
      const subjectChange = this.changeInfo || {}
      const items = (subjectChange.changeAccessoriesGoods || []).map(item => item.name).join(',')
      return items || '未选择教辅'
    },
    editSpread() {
      const data = this.changeInfo || {}
      const payed = (data.originalAccessoriesPrice || 0) + (data.originalCourseFee || 0) + (data.originalMusicalPrice || 0)
      // console.log(payed, data.changeMusicalPrice, data.changeAccessoriesPrice, data.changeCourseFee, {...data})
      return (data.changeMusicalPrice || 0) + (data.changeAccessoriesPrice || 0) + (data.changeCourseFee || 0) - payed
    },
    spread() {
      const money = (
        this.numFormat(
          this.musicalPrice +
          this.selectAccessoriesMoney +
          this.musicGroupSubjectPlanFee -
          this.originalAccessoriesPrice -
          this.originalMusicalPrice -
          this.originalCourseFee -
          this.coursePurchaseTypeJsonTypePrice -
          this.kitGroupPurchaseTypePrice
        )
      )
      // console.log(
      //   this.item.kitGroupPurchaseType,
      //   '乐器价格', this.musicalPrice,
      //   '已选附件价格', this.selectAccessoriesMoney,
      //   '选择课程费用', this.musicGroupSubjectPlanFee,
      //   '原附件价格', this.originalAccessoriesPrice,
      //   '原乐器价格', this.originalMusicalPrice,
      //   '原课程费用', this.originalCourseFee,
      //   '原课程减免费用', this.coursePurchaseTypeJsonTypePrice,
      //   '乐器减免费用', this.kitGroupPurchaseTypePrice,
      //   '结果价格', money
      // )
      return money
    }
  },
  mounted() {
    if (this.detail && this.detail.id) {
      this.fetchDetail()
    }
  },
  methods: {
    copyUrl(url) {
      copy(url)
      this.$message.success('复制成功')
    },
    async fetchDetail() {
      const setRes = res => {
        const { data } = res
        this.item = data || {}
        if (data) {
          this.$set(this.form, 'type', this.item.kitGroupPurchaseType)
          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()
        }
      }
      if (this.detail.subjectChange) {
        await getChangeInfo({
          id: this.detail.subjectChange.id
        })
        .then(res => {
          setRes(res)
          this.changeInfo = res.data
        })
      } else {
        this.changeInfo = this.detail.subjectChange
        await getStudentOriginal({
          musicGroupId: this.musicGroupId,
          studentId: this.detail.studentId,
        })
        .then(setRes)
      }
    },
    async subjectChange(id) {
      this.$set(this.form, 'musicalGoods', '')
      let data = null
      if (id) {
        await getSubjectGoodsAndInfo({
          musicGroupId: this.musicGroupId,
          subjectId: id,
        })
        .then(res => {
          data = res.data
          this.musicGroupSubjectPlanFee = res.data.musicGroupSubjectPlan.fee
        })
      } else {
        this.musicGroupSubjectPlanFee = 0
      }
      const items = formatAllGoods(data, this.item.kitGroupPurchaseType)
      for (const key in items) {
        if (items.hasOwnProperty(key)) {
          const item = items[key]
          this[key] = item
        }
      }
      this.musicalGoodsChange()
    },
    musicalGoodsChange(val) {
      const item = this.musicalGoodsById[val]
      if (item) {
        this.musicalPrice = this.numFormat(item[typeAndprice[this.form.type]] || 0)
        // this.kitGroupPurchaseTypePrice = this.numFormat(item[typeAndprice[this.form.type]] || 0)
        this.coursePurchaseTypeJsonTypePrice = this.numFormat(item.coursePurchaseTypeJsonTypePrice)
        this.types = item.kitGroupPurchaseTypeJsonParse
      } else {
        this.musicalPrice = 0
        // this.kitGroupPurchaseTypePrice = 0
        this.coursePurchaseTypeJsonTypePrice = 0
        this.$set(this.form, 'type', '')
      }
    },
    accessoriesChange(ids, money) {
      this.selectAccessories = ids
      this.selectAccessoriesMoney = money
    },
    numFormat(num) {
      let _num = parseFloat(num)
      if (isNaN(_num)) {
        _num = 0
      }
      return parseFloat(_num.toFixed(2))
    },
    onCreateQRCode () {
      setTimeout(() => {
        this.$refs.qrCodeUrl.innerHTML = '';
        this.qrcode = new QRCode(this.$refs.qrCodeUrl, {
          width: 200,
          height: 200,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        })
        this.qrcode.makeCode(this.copyLink)
        this.codeUrl = this.copyLink
      }, 500)
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          subjectChangeAdd({
            changeCourseFee: this.numFormat(this.musicGroupSubjectPlanFee - this.coursePurchaseTypeJsonTypePrice),
            changeAccessories: this.selectAccessories.join(','),
            changeAccessoriesPrice: this.numFormat(this.selectAccessoriesMoney),
            changeMusicalPrice: this.numFormat(this.musicalPrice),
            originalCourseFee: this.originalCourseFee,
            originalMusicalPrice: this.originalMusicalPrice,
            originalMusical: this.item.originalMusical,
            originalAccessories: this.item.originalAccessories,
            originalAccessoriesPrice: this.originalAccessoriesPrice,
            cooperationOrganId: this.item.cooperationOrganId,
            kitGroupPurchaseType: (this.form.musicalGoods === 'OWNED' ? this.form.musicalGoods : this.form.type),
            musicGroupId: this.musicGroupId,
            studentId: this.detail.studentId,
            changeMusical: (this.form.musicalGoods === 'OWNED' ? 0 : 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.$listeners.submited()
              this.$message.success('提交成功!')
            })
        }
      })
    },
    cancel() {
      this.$confirm('是否确认取消订单?', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        subjectChangeCancel({
          id: this.detail.subjectChange.id
        })
        .then(res => {
          this.$listeners.close()
          this.$listeners.submited()
          this.$message.success('取消成功!')
        })
      })
    }
  },
}
</script>
<style lang="less" scoped>
  .viewlink{
    display: flex;
    .link{
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      display: block;
      white-space: nowrap;
    }
    .btn{
      width: 100px;
      margin-left: 20px;
    }
  }
  .left-code{
    height: 255px;
    .code-url{
      margin-top: 10px;
      .linkbtn{
        margin-top: 0;
        margin-bottom: 0;
        font-size: 12px;
      }
    }
  }
</style>
