<template>
  <div>
    <el-form :model="form"
             label-suffix=": "
             ref="form">
      <el-form-item label="所属分部"
                    prop="organId"
                    :rules="[{required: true, message: '请选择所属分部', trigger: 'change'}]"
                    :label-width="formLabelWidth">
        <el-select v-model.trim="form.organId"
                   clearable
                   placeholder="请选择所属分部"
                   filterable>
          <el-option v-for="(item, index) in branchList"
                     :key="index"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="乐团模式"
                    prop="chargeTypeId"
                    :rules="[{required: true, message: '请选择乐团模式', trigger: 'change'}]"
                    :label-width="formLabelWidth">
        <el-select v-model.trim="form.chargeTypeId"
                   clearable
                   placeholder="请选择乐团模式"
                   filterable>
          <el-option v-for="(item, index) in typesList"
                     :key="index"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收费方式名称"
                    prop="name"
                    :rules="[{required: true, message: '请输入收费方式名称', trigger: 'blur'}]"
                    :label-width="formLabelWidth">
        <el-input v-model.trim="form.name"
                  placeholder="请输入收费方式名称"
                  clearable>
        </el-input>
      </el-form-item>
      <div class="class-items">
        <div class="items">
          <div class="items-header">
            <span class="name">课程类型</span>
            <span class="name">是否可选</span>
            <span class="name">课程总时长(分钟)</span>
            <span class="name">现价(元)</span>
            <span class="name">原价(元)</span>
            <span class="ctrl"></span>
          </div>
          <div class="item"
               v-for="(item, index) in form.details"
               :key="index">
            <el-form-item :prop="`details.${index}.courseType`"
                          :rules="[{required: true, message: '请选择课程类型', trigger: 'change'}]">
              <el-select v-model.trim="item.courseType"
                         size="mini"
                         clearable
                         @change="() => courseItemChange(item, index)"
                         filterable>
                <el-option v-for="(item, i) in courseTypes"
                           :key="i"
                           :label="courseType[item.courseType]"
                           :disabled="isOptionDisabled(item.courseType)"
                           :value="item.courseType">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :prop="`details.${index}.isStudentOptional`"
                          :rules="[{required: true, message: '请选择是否可选', trigger: 'change'}]">
              <el-select v-model.trim="item.isStudentOptional"
                         size="mini"
                         clearable
                         filterable>
                <el-option v-for="item in boolOptions"
                           :key="item.label"
                           :label="item.label"
                           :value="String(item.value)">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :prop="`details.${index}.courseTotalMinuties`"
              :rules="[
                { required: true, message: '请输入课程时长', trigger: 'blur' },
              ]">
              <el-input-number size="mini"
                               style="width: 90%!important;"
                               class="number-input"
                               v-model="item.courseTotalMinuties"
                               :controls="false"
                               :precision="0"
                               :min="1"
                               @change="() => courseItemChange(item, index)"
                               placeholder="课程总时长" />
            </el-form-item>
            <el-form-item :prop="`details.${index}.courseCurrentPrice`"
                          :rules="[{required: true, message: '请输入课程现价', trigger: 'blur'}]">
              <el-input-number size="mini"
                               style="width: 90%!important;"
                               class="number-input"
                               v-model="item.courseCurrentPrice"
                               :controls="false"
                               :min="0"
                               placeholder="课程现价" />
            </el-form-item>
            <el-form-item :prop="`details.${index}.courseOriginalPrice`"
                          :rules="[{required: true, message: '请输入课程原价', trigger: 'blur'}]">
              <el-input-number size="mini"
                               style="width: 90%!important;"
                               class="number-input"
                               v-model="item.courseOriginalPrice"
                               :controls="false"
                               :min="0"
                               placeholder="课程原价" />
            </el-form-item>
            <span class="ctrl">
              <i @click="removeItem(index)"
                 v-if="form.details.length > 1"
                 class="el-icon-circle-close" />
            </span>
          </div>
        </div>
        <el-button icon="el-icon-circle-plus-outline"
                   plain
                   class="create-type-button"
                   type="info"
                   size="small"
                   @click="addItem">新增课程类型</el-button>
      </div>
      <el-row>
        <el-col :span="6">
          <el-form-item label="原价"
                        prop="totalOriginalPrice"
                        label-width="50px">
            {{ totalOriginalPrice | moneyFormat}}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="现价"
                        prop="totalCurrentPrice"
                        label-width="50px">
            {{ totalCurrentPrice | moneyFormat}}
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="$listeners.close">取 消</el-button>
      <el-button @click="submit"
                 type="primary">确 定</el-button>
    </span>
  </div>
</template>
<script>
const initItem = {
  courseType: '',
  isStudentOptional: '',
  courseTotalMinuties: '',
  courseOriginalPrice: '',
  courseCurrentPrice: '',
}
import {
  musicGroupOrganizationCourseSettingsAdd,
  musicGroupOrganizationCourseSettingsUpdate,
  getOrganizationCourseUnitPriceSettings
} from '@/api/specialSetting'
import { classTimeList, array2object } from '@/utils/searchArray'
import { queryByMusicGroupOrganizationCourseSettingsId } from '../../../resetTeaming/api'
import { courseType, boolOptions } from '@/constant'
import { objectToOptions } from '@/utils'
import numeral from 'numeral'

const plusNum = (items = [], key) => {
  let money = 0
  for (const item of items) {
    if (item) {
      money += item[key] || 0
    }
  }
  return money
}

const initForm = {
  organId: '',
  classTimeList: '',
  chargeTypeId: '',
  name: '',
  details: [{}],
}

export default {
  name: 'modal-chargesForm',
  props: ['branchList', 'typesList', 'rowDetail'],
  data () {
    return {
      form: { ...initForm },
      formLabelWidth: '120px',
      courseType,
      courseTypeOptions: objectToOptions(courseType),
      boolOptions: objectToOptions(boolOptions),
      courseTypes: [],
      courseTypesByType: {},
      loading: false,
    }
  },
  computed: {
    totalOriginalPrice () {
      return plusNum(this.form.details, 'courseOriginalPrice')
    },
    totalCurrentPrice () {
      return plusNum(this.form.details, 'courseCurrentPrice')
    },
    classTimeList() {
      return array2object(classTimeList)
    }
  },
  watch: {
    rowDetail: {
      deep: true,
      handler () {
        this.updateForm()
      },
    },
    async 'form.organId' () {
      this.FetchOrganizationCourseUnitPriceSettings()
    },
    async 'form.chargeTypeId' () {
      this.FetchOrganizationCourseUnitPriceSettings()
    },
  },
  mounted () {
    this.updateForm()
  },
  methods: {
    async FetchOrganizationCourseUnitPriceSettings () {
      if (this.loading) {
        return
      }
      this.loading = true
      try {
        if (this.form.organId && this.form.chargeTypeId) {
          this.$set(this.form, 'details', [{}])
          const res = await getOrganizationCourseUnitPriceSettings({
            chargeTypeId: this.form.chargeTypeId,
            organId: this.form.organId,
            rows: 9999
          })
          const d = {}
          this.courseTypes = res.data.rows
          for (const item of this.courseTypes) {
            d[item.courseType] = item
          }
          this.courseTypesByType = d

        }
      } catch (error) { }
      this.loading = false
    },
    courseItemChange (item, index) {
      if (item.courseType) {
        const active = this.courseTypesByType[item.courseType] || {}
        const _list = this.form.details
        const price = Math.round(numeral((active.unitPrice || 1)).multiply((item.courseTotalMinuties || 1)).value())
        _list[index] = {
          ...item,
          courseCurrentPrice: price,
          courseOriginalPrice: price
        }
        this.$refs.form.validateField(`details.${index}.courseTotalMinuties`)
        this.$set(this.form, `details`, [..._list])
      }
    },
    async updateForm () {
      if (this.rowDetail) {
        const { organId, classTimeList, chargeTypeId, name } = this.rowDetail
        this.form = {
          organId,
          classTimeList,
          chargeTypeId,
          name,
        }
        try {
          const res = await queryByMusicGroupOrganizationCourseSettingsId({
            id: this.rowDetail.id
          })
          this.$set(this.form, 'details', res.data.map(item => ({
            ...item,
            isStudentOptional: String(item.isStudentOptional)
          })))
        } catch (error) { }
      } else {
        this.form = { ...initForm }
      }
    },
    isOptionDisabled (key) {
      const selected = this.form.details.map(item => item.courseType)
      return selected.includes(key)
    },
    addItem () {
      const _items = [...this.form.details, {}]
      this.form.details = _items
    },
    removeItem (index) {
      const _items = [...this.form.details]
      _items[index] = null
      this.form.details = _items.filter(item => !!item)
    },
    submit () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            if (this.rowDetail) {
              const res = await musicGroupOrganizationCourseSettingsUpdate({
                id: this.rowDetail.id,
                ...this.form
              })
              this.$message.success('更新成功')
            } else {
              const res = await musicGroupOrganizationCourseSettingsAdd(this.form)
              this.$message.success('提交成功')
            }
            this.$listeners.close()
            this.$listeners.submited()
          } catch (error) { }
        }
      })
    },
    validatorCourseTotalMinuties(index, item) {
      return (rule, value, callback) => {
        const { courseType } = item
        if (courseType && value && this.classTimeList[courseType] &&  value < this.classTimeList[courseType]) {
          callback(new Error(`单节课不得少于${this.classTimeList[courseType]}分钟`))
          return
        }
        callback()
      }
    }
  },
}
</script>
<style lang="less" scoped>
.dialog-footer {
  display: block;
  text-align: right;
}
.items {
  .items-header,
  .item {
    display: flex;
    > .el-form-item,
    > span {
      width: 100%;
      text-align: center;
      padding: 0 10px;
      &.ctrl {
        width: 300px;
      }
    }
  }
  .items-header {
    background-color: #f1f1f1;
    padding: 10px 0;
    margin-bottom: 10px;
    > span {
      line-height: 26px;
    }
  }
}
.create-type-button {
  width: 100%;
  margin-bottom: 20px;
}
.ctrl {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 26px;
  i {
    cursor: pointer;
    font-size: 18px;
  }
}
</style>
