<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 in courseTypes"
                            :key="item.courseType"
                            :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="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"
                :precision="0"
                :min="1"
                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"
                :precision="0"
                :min="1"
                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 } from '@/utils/searchArray'
import { courseType, boolOptions } from '@/constant'
import { objectToOptions }  from '@/utils'
import numeral from 'numeral'

const plusNum = (items = [], key) => {
  let money = 0
  const _items = items.filter(item => !item.isStudentOptional)
  for (const item of _items) {
    money += parseFloat(parseFloat(item[key] || 0).toFixed(2) || 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: {},
    }
  },
  computed: {
    totalOriginalPrice() {
      return plusNum(this.form.details, 'courseOriginalPrice')
    },
    totalCurrentPrice() {
      return plusNum(this.form.details, 'courseCurrentPrice')
    }
  },
  watch: {
    rowDetail() {
      this.updateForm()
    },
    async 'form.chargeTypeId'() {
      try {
        const res = await getOrganizationCourseUnitPriceSettings({
          chargeTypeId: this.form.chargeTypeId,
          rows: 9999
        })
        const d = {}
        this.courseTypes = res.data.rows
        for (const item of this.courseTypes) {
          d[item.courseType] = item
        }
        this.courseTypesByType = d
      } catch (error) {}
    }
  },
  mounted() {
    this.updateForm()
  },
  methods: {
    courseItemChange(item, index) {
      if (item.courseType) {
        const active = this.courseTypesByType[item.courseType] || {}
        const _list = this.form.details
        _list[index] = {
          ...item,
          courseCurrentPrice: Math.ceil(active.unitPrice * (item.courseTotalMinuties || 1)),
          courseOriginalPrice: Math.ceil(active.unitPrice * (item.courseTotalMinuties || 1))
        }
        this.$set(this.form, `details`, [..._list])
      }
    },
    updateForm() {
      if (this.rowDetail) {
        const { organId, classTimeList, chargeTypeId, name, details } = this.rowDetail
        this.form = {
          organId,
          classTimeList,
          chargeTypeId,
          name,
          details: details.map(item => ({
            ...item,
            isStudentOptional: String(item.isStudentOptional)
          }))
        }
      } 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) {}
        }
      })
    }
  },
}
</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>
