<template>
  <div class='m-container'>
    <!-- <h2>收费类型设置</h2> -->
    <div class="m-core">
      <div @click="onBranchOperation('create')"
           class='newBand'>添加</div>
      <div class="tableWrap">
        <el-table :data="dataList"
                  :header-cell-style="{background:'#EDEEF0',color:'#444'}">
          <el-table-column prop="price"
                           label="收费标准">
          </el-table-column>
          <el-table-column prop="name"
                           label="分部名称">
            <template slot-scope="scope">
              {{ scope.row.branchNames | joinArray(',') }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="操作">
            <template slot-scope="scope">
              <el-button @click="onBranchOperation('update', scope.row)"
                         type="text">修改</el-button>
              <el-button @click="onBranchDelete(scope.row)"
                         type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog :title="formTitle[formActionTitle]"
                 :visible.sync="branchStatus"
                 @close="onFormClose('ruleForm')"
                 width="500px">
        <el-form :model="form"
                 :rules="rules"
                 ref="ruleForm">
          <el-form-item label="收费标准"
                        prop="price"
                        :label-width="formLabelWidth">
            <el-input type="number"
                      @mousewheel.native.prevent
                      v-model.trim="form.price"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="所选分部"
                        prop="branchIds"
                        :label-width="formLabelWidth">
            <el-select v-model.trim="form.branchIds"
                       clearable
                       filterable
                       multiple>
              <el-option v-for="(item, index) in branchList"
                         :key="index"
                         :label="item.label"
                         :value="item.value"
                         :disabled="item.disabled">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="branchStatus = false">取 消</el-button>
          <el-button @click="onTypesSubmit('ruleForm')"
                     type="primary">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import pagination from '@/components/Pagination/index'
import store from '@/store'
import { branchQueryPage } from '@/api/specialSetting'
import { sysConfigList, sysConfigUpdate } from '@/api/generalSettings'
export default {
  components: { pagination },
  name: 'charges',
  data () {
    return {
      id: null,
      dataList: [],
      branchList: [], // 分部列表
      formActionTitle: 'create',
      formTitle: {
        create: '添加分部收费标准',
        update: '修改分部收费标准'
      },
      branchStatus: false,
      formLabelWidth: '100px',
      form: {
        branchIds: [],
        price: null,
      },
      rules: {
        price: [{ required: true, message: '请输入收费标准', trigger: 'blur' }],
        branchIds: [{ required: true, message: '请选择分部', trigger: 'change' }]
      },
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    onTypesSubmit (formName) { // 添加数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 分部名称
          let form = this.form
          let params = JSON.parse(JSON.stringify(this.dataList))
          let branchNames = []
          this.branchList.forEach(item => {
            if (form.branchIds.includes(item.value)) {
              branchNames.push(item.label)
            }
          })
          if (this.formActionTitle == 'create') {
            params.push({
              price: form.price,
              branchIds: form.branchIds,
              branchNames: branchNames
            })
            sysConfigUpdate({
              id: this.id,
              paranValue: JSON.stringify(params)
            }).then(res => {
              if (res.code == 200) {
                this.$message.success('添加成功')
                this.branchStatus = false
                this.getList()
              }
            })
          } else if (this.formActionTitle == 'update') {
            let tempUpdate = params.map(item => {
              if (item.id == form.id) {
                item = {
                  price: form.price,
                  branchIds: form.branchIds,
                  branchNames: branchNames
                }
              }
              delete item.id
              return item
            })

            sysConfigUpdate({
              id: this.id,
              paranValue: JSON.stringify(tempUpdate)
            }).then(res => {
              if (res.code == 200) {
                this.$message.success('修改成功')
                this.branchStatus = false
                this.getList()
              }
            })
          }
        } else {
          return false;
        }
      })
    },
    onBranchDelete (row) {

      let tempBranch = JSON.parse(JSON.stringify(this.dataList))
      tempBranch.splice(row.id, 1)

      let temp = tempBranch.map(item => {
        delete item.id
        return item
      })
      sysConfigUpdate({
        id: this.id,
        paranValue: JSON.stringify(temp)
      }).then(res => {
        if (res.code == 200) {
          this.$message.success('删除成功')
          this.getList()
        }
      })
    },
    onBranchOperation (type, row) {
      this.branchStatus = true
      this.formActionTitle = type
      if (type == 'update') {
        this.branchList.forEach(item => {
          if (row.branchIds.includes(item.value)) {
            item.disabled = false
          }
        })
        this.form = row
      }
    },
    async getList () {
      // 获取所有分部
      let branchList = await branchQueryPage({ rows: 9999, page: 1 })
      if (branchList.code == 200) {
        branchList = branchList.data.rows
      }
      // 获取对应配置
      let sysConfig = await sysConfigList({ group: 'organ_course_fee' })
      if (sysConfig.code == 200) {
        this.id = sysConfig.data[0].id
        sysConfig = sysConfig.data[0].paranValue ? JSON.parse(sysConfig.data[0].paranValue) : []
      }

      let tempList = []
      let tempBranch = []
      let sysBranchIds = []
      sysConfig.forEach((item, index) => {
        item.id = index
        tempList.push(item)
        sysBranchIds = sysBranchIds.concat(item.branchIds)
      })

      // 过滤数据
      branchList.forEach((item, index) => {
        // 判断是否有同意
        let params = {
          label: item.name,
          value: item.id
        }
        if (sysBranchIds.includes(item.id)) {
          params.disabled = true
        } else {
          params.disabled = false
        }
        tempBranch.push(params)
      })
      this.branchList = tempBranch
      this.dataList = tempList
    },
    onFormClose (formName) { // 关闭弹窗重置验证
      this.form = {
        price: null,
        branchIds: []
      }
      this.$refs[formName].resetFields()
    },
  }
}
</script>
<style lang="scss" scoped>
/deep/.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;
}
/deep/.el-select {
  width: 98% !important;
}

/deep/.el-table {
  display: inline-block;
}
</style>