<template>
  <div class='m-container'>
    <!-- <h2>折扣设置</h2> -->
    <div class="m-core">
      <el-form :inline="true"
               :model="searchForm">
        <el-form-item>
          <el-select v-model.trim="searchForm.subjectId"
                     filterable
                     placeholder="请选择声部组合"
                     clearable>
            <el-option-group v-for="group in subjectList"
                             :key="group.label"
                             :label="group.label">
              <el-option v-for="item in group.options"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.chargeTypeId"
                     filterable
                     placeholder="请选择收费类型"
                     clearable>
            <el-option v-for="item in typesList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="danger"
                     @click="search">搜索</el-button>
          <el-button @click="onReSet"
                     type="primary">重置</el-button>
        </el-form-item>
      </el-form>
      <div class='newBand'
           v-permission="'chargeTypeSubjectMapper/insert'"
           @click="createVisible = true">添加</div>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table :data='tableList'
                  :header-cell-style="{background:'#EDEEF0',color:'#444'}">
          <el-table-column align='center'
                           prop="chargeTypeId"
                           label="收费类型">
            <template slot-scope="scope">{{ typesListById[scope.row.chargeTypeId] }}</template>
          </el-table-column>
          <el-table-column align='center'
                           prop="subjectId"
                           label="声部">
            <template slot-scope="scope">{{ subjectListById[scope.row.subjectId] }}</template>
          </el-table-column>
          <el-table-column align='center'
                           prop="goodsDiscountRate"
                           label="折扣(%)">
          </el-table-column>
          <el-table-column align='center'
                           label="操作">
            <template slot-scope="scope">
              <el-button @click="openTypes('update', scope.row)"
                         v-permission="'chargeTypeSubjectMapper/update'"
                         type="text">修改</el-button>
              <el-button @click="onTypesDel(scope.row)"
                         v-permission="'chargeTypeSubjectMapper/del'"
                         type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="pageInfo.total"
                    :page.sync="pageInfo.page"
                    :limit.sync="pageInfo.limit"
                    :page-sizes="pageInfo.page_size"
                    @pagination="getList" />
      </div>
    </div>
    <el-dialog :title="formTitle[formActionTitle]"
               :visible.sync="typeStatus"
               @close="onFormClose('ruleForm')"
               width="500px">
      <el-form :model="form"
               :rules="rules"
               ref="ruleForm">
        <el-form-item label="收费类型"
                      prop="chargeTypeId"
                      :label-width="formLabelWidth">
          <el-select v-model.trim="form.chargeTypeId"
                     filterable
                     disabled
                     placeholder="请选择收费类型"
                     clearable>
            <el-option v-for="item in typesList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="声部选择"
                      v-if="form.classGroupType != 'MIX'"
                      prop="subjectId"
                      :label-width="formLabelWidth">
          <el-select v-model.trim="form.subjectId"
                     filterable
                      disabled
                     placeholder="请选择声部组合"
                     clearable>
            <el-option-group v-for="group in subjectList"
                             :key="group.label"
                             :label="group.label">
              <el-option v-for="item in group.options"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣(%)"
                      prop="goodsDiscountRate"
                      :label-width="formLabelWidth">
          <el-input-number v-model.trim="form.goodsDiscountRate"
                           autocomplete="off"
                           placeholder="请输入折扣 1%-100%"
                           controls-position="right"
                           class="number-input"
                           :min="0"
                           :max="100"
                           :precision="2"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="typeStatus = false">取 消</el-button>
        <el-button type="primary"
                   @click="onTypesSubmit('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="createVisible"
               title="添加折扣商品"
               width="400px">
      <createDiscount @close="createVisible = false"
                      :typesList="typesList"
                      :subjectList="subjectList" />
    </el-dialog>
  </div>
</template>
<script>
import pagination from '@/components/Pagination/index'
import { chargeTypeList, subjectListTree, insertChargeTypeSubjectMapper, updateChargeTypeSubjectMapper, delChargeTypeSubjectMapper, chargeTypeSubjectMapper } from '@/api/specialSetting'
import createDiscount from './modals/create-discount'
export default {
  name: 'typesManager',
  components: { pagination, createDiscount },
  data () {
    return {
      tableList: [],
      typesList: [],
      typesListById: {},
      subjectList: [], // 声部列表
      subjectListById: {}, // 声部列表
      formActionTitle: 'create',
      formTitle: {
        create: '添加折扣',
        update: '修改折扣'
      },
      createVisible: false,
      typeStatus: false, // 添加教学点
      formLabelWidth: '100px',
      form: {
        name: null, //
        subjectId: null,
        goodsDiscountRate: null,
      },
      searchForm: {
        subjectId: null,
        chargeTypeId: null,
      },
      rules: {
        chargeTypeId: [{ required: true, message: '请选择收费类型', trigger: 'blur' }],
        subjectId: [{ required: true, message: '请选择声部组合', trigger: 'change' }],
        goodsDiscountRate: [{ required: true, message: '请输入折扣', trigger: 'blur' }],
      },
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      }
    }
  },
  mounted () {
    this.getList()
    this.getChargeTypeList()
    this.getSubjectTree()
  },
  methods: {
    search () {
      this.pageInfo.page = 1;
      this.getList();
    },
    onReSet () {
      this.searchForm = {
        subjectId: null,
        chargeTypeId: null,
      };
      this.search();
    },
    onTypesSubmit (formName) { // 添加数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formActionTitle == 'create') {
            if (this.form.id) { // 判断有没有Id，如果有则删除
              delete this.form.id
            }
            insertChargeTypeSubjectMapper(this.form).then(res => {
              this.messageTips('添加', res)
            })
          } else if (this.formActionTitle == 'update') {
            updateChargeTypeSubjectMapper([this.form]).then(res => {
              this.messageTips('修改', res)
            })
          }
        } else {
          return false;
        }
      })
    },
    messageTips (title, res) {
      if (res.code == 200) {
        this.$message.success(title + '成功')
        this.typeStatus = false
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
    },
    async onTypesDel (row) {
      try {
        await this.$confirm('是否删除此条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        delChargeTypeSubjectMapper({ id: row.id }).then(res => {
          this.messageTips('删除', res)
        })
      } catch (error) { }
    },
    getChargeTypeList () {
      chargeTypeList({
        rows: 9999,
        page: 1
      }).then(res => {
        if (res.code == 200) {
          const typesListById = {}
          res.data.rows.forEach(item => {
            typesListById[item.id] = item.name
            this.typesList.push({
              label: item.name,
              value: item.id
            })
          })
          this.typesListById = typesListById
        }
      })
    },
    getList () {
      chargeTypeSubjectMapper({
        rows: this.pageInfo.limit,
        page: this.pageInfo.page,
        ...this.searchForm
      }).then(res => {
        let result = res.data
        this.tableList = result.rows
        // if (res.code == 200) {
        //   result.data.rows.forEach(row => {
        //     let subjectname = [],
        //       subjectIds = []
        //     row.subjects.forEach(item => {
        //       subjectname.push(item.name)
        //       subjectIds.push(item.id)
        //     })
        //     row.subjectName = subjectname
        //     row.subjectIds = subjectIds
        //   })
        //   this.tableList = result.rows
        this.pageInfo.total = result.total
        // }
      })
    },
    openTypes (type, row) {
      this.typeStatus = true
      this.formActionTitle = type
      // 修改的时候赋值
      if (type == 'update') {
        this.form = {
          id: row.id,
          chargeTypeId: row.chargeTypeId,
          subjectId: row.subjectId,
          goodsDiscountRate: row.goodsDiscountRate,
        }
      }
    },
    onFormClose (formName) { // 关闭弹窗重置验证
      this.form = {
        name: null, // 作业模块名称
        subjectId: null,
        goodsDiscountRate: null,
      }
      this.$refs[formName].resetFields()
    },
    getSubjectTree () { // 获取声部列表
      subjectListTree({
        delFlag: 0,
        rows: 9999
      }).then(res => {
        const subjectListById = {}
        let result = res.data
        if (res.code == 200) {
          let tempArray = []
          result.rows.forEach((item, index) => {
            let subject = []
            if (item.subjects) {
              item.subjects.forEach(s => {
                subjectListById[s.id] = s.name
                subject.push({
                  value: s.id,
                  label: s.name
                })
              })
            }

            tempArray[index] = {
              label: item.name,
              options: subject
            }
          })
          this.subjectListById = subjectListById
          this.subjectList = tempArray
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
/deep/.el-date-editor.el-input {
  width: 100% !important;
}
.el-select {
  width: 100% !important;
}
.number-input {
  /deep/ .el-input__inner {
    text-align: left;
  }

  width: 100%;
}
</style>
