<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body width="80%">
    <el-form ref="dataForm" :rules="rules" :model="caseTypeForm" label-well-code="right" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="类型名称" prop="typeDetailName">
            <el-input v-model.trim="caseTypeForm.typeDetailName" type="text" placeholder="必填" maxlength="25" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型编码" prop="typeDetailCode">
            <el-input v-model.trim="caseTypeForm.typeDetailCode" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="立案标准" prop="typesTime">
          <el-row class="table-title">
            <!-- <el-col :span="6"><div class="title-header"><i class="el-icon-menu"/>数据列表</div></el-col> -->
            <el-col :span="18" :offset="6" class="edit_btns">
              <el-button v-if="hasPerm('/caseType/addTypesTime')" class="edit_btn" size="small" @click="addRow">添加立案标准</el-button>
            </el-col>
          </el-row>
          <el-table
            ref="typesTimeTable"
            :data="caseTypeForm.typesTime"
            :header-cell-style="{'font-size':'14px'}"
            :cell-style="{'vertical-align':'middle'}"
            class="table"
            size="mini"
            border>
            <el-table-column type="index" align="center"/>
            <el-table-column prop="name" label="立案标准" align="center">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.edit" :prop=" 'typesTime.' + scope.$index + '.name' " :rules="rules.name">
                  <el-input v-model="scope.row.name" class="table-textarea" type="textarea" maxlength="50" autosize show-word-limit/>
                </el-form-item>
                <span v-else style="margin-left: 10px">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="结案标准" align="center">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.edit" :prop=" 'typesTime.' + scope.$index + '.description' " :rules="rules.description">
                  <el-input v-model="scope.row.description" class="table-textarea" type="textarea" maxlength="50" autosize show-word-limit/>
                </el-form-item>
                <span v-else style="margin-left: 10px">{{ scope.row.description }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="day" label="时限" align="center" width="250%">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.edit" :prop=" 'typesTime.' + scope.$index + '.day' " :rules="rules.day">
                  <el-input v-model="scope.row.day" size="mini" style="width:20%"/>天
                  <el-input v-model="scope.row.hours" size="mini" style="width:20%"/>小时
                  <el-input v-model="scope.row.minutes" size="mini" style="width:20%"/>分钟
                </el-form-item>
                <span v-else style="margin-left: 10px">{{ scope.row.day }}天{{ scope.row.hours }}小时{{ scope.row.minutes }}分钟</span>
              </template>
            </el-table-column>
            <el-table-column prop="deptId" label="默认部门" align="center">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.edit" :prop=" 'typesTime.' + scope.$index + '.deptId' " :rules="rules.deptId">
                  <dept-select v-model="scope.row.deptId" :need-top="deptShowTop" :dept-show="deptShow" dept-type="03" placeholder="选择权属单位" @deptChange="(v)=>changeDept(v,scope.row)"/>
                </el-form-item>
                <span v-else>{{ scope.row.deptName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="option" label="操作" align="center">
              <template slot-scope="scope">
                <el-button v-if="scope.row.edit" class="table-button" type="text" @click="saveRow(scope.row)">保存</el-button>
                <el-button v-else class="table-button" type="text" @click="editRow(scope.row)">编辑</el-button>
                <el-button v-if="scope.row" class="table-button" type="text" @click="deleteRow(scope.$index,scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCaseTypesTime, getMaxDetailCode, addCaseDetailType, addCaseTypesTime, updateCaseDetailType, updateCaseTypesTime, deleteCaseTypesTime } from '@/api/busAdmin/caseType'
import DeptSelect from '@/components/DeptSelect'

export default {
  name: 'EditCaseType',
  components: { DeptSelect, getCaseTypesTime, addCaseDetailType, addCaseTypesTime, updateCaseDetailType, updateCaseTypesTime, deleteCaseTypesTime },
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      textMap: {
        update: '编辑',
        create: '新增'
      },
      caseTypeForm: {
        id: '',
        eorc: '',
        typeDetailName: '',
        typeDetailCode: '',
        typeId: '',
        deptName: '',
        deptId: '',
        typesTime: []
      },
      rules: {
        typeDetailName: [{ required: true, message: '类型名称不能为空', trigger: ['blur', 'change'] }],
        typeDetailCode: [{ required: true, message: '类型编码不能为空', trigger: ['blur', 'change'] }],
        name: [{ required: true, message: '立案标准不能为空', trigger: ['blur', 'change'] }],
        description: [{ required: true, message: '结案标准不能为空', trigger: ['blur', 'change'] }],
        deptId: [{ required: true, message: '默认部门不能为空', trigger: ['blur', 'change'] }]
      },
      deptShowTop: false, // 权属单位下拉是否显示顶级
      deptShow: true
    }
  },
  methods: {
    initDialog: function(option) {
      this.dialogStatus = option.dialogStatus
      this.dialogFormVisible = option.dialogFormVisible

      if (this.dialogStatus === 'create') {
        // 清空需要填写的属性
        this.resetForm()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        // 公共的、从上一页传来的属性
        this.caseTypeForm.eorc = option.eorc
        this.caseTypeForm.typeId = option.typeId
        this.caseTypeForm.typesTime = []
        getMaxDetailCode(this.caseTypeForm.typeId).then(response => {
          // 默认编码
          this.caseTypeForm.typeDetailCode = response.data.maxTypeDetailCode
        })
      } else if (this.dialogStatus === 'update') {
        // 公共的、从上一页传来的属性
        this.caseTypeForm.eorc = option.eorc
        this.caseTypeForm.typeId = option.typeId
        this.caseTypeForm.typesTime = []

        const row = option.row
        this.caseTypeForm.typeDetailName = row.typeDetailName
        this.caseTypeForm.typeDetailCode = row.typeDetailCode
        this.caseTypeForm.id = row.id
        this.fetchTypesTime()
      }
    },
    fetchTypesTime() {
      this.caseTypeForm.typesTime = []
      console.log(this.caseTypeForm.id)
      getCaseTypesTime(this.caseTypeForm.id).then(response => {
        response.data.rows.forEach(element => {
          const typeTime = {
            id: element.id,
            name: element.name,
            description: element.description,
            day: element.day,
            hours: element.hours,
            minutes: element.minutes,
            deptId: element.deptId,
            deptName: element.deptName,
            detailId: element.detailId,
            typeId: element.typeId,
            edit: false
          }
          this.caseTypeForm.typesTime.push(typeTime)
        })
      })
    },
    resetForm() {
      this.caseTypeForm = {
        id: '',
        eorc: '',
        typeDetailName: '',
        typeDetailCode: '',
        typeId: '',
        deptName: '',
        deptId: '',
        typesTime: []
      }
    },
    addRow() {
      if (this.checkBeforeAdd()) {
        this.caseTypeForm.typesTime.push({
          detailId: this.caseTypeForm.id,
          typeId: this.caseTypeForm.typeId,
          edit: true
        })
      }
    },
    editRow(row) {
      if (this.hasPerm('/caseType/updateTypesTime')) {
        row.edit = true
      } else {
        this.$message.warning('没有权限')
      }
    },
    checkRow(row) {
      if (!row.name) {
        this.$message.error('立案标准不能为空')
        return false
      } else if (!row.description) {
        this.$message.error('结案标准不能为空')
        return false
      } else if (!row.day && !row.hours && !row.minutes) {
        this.$message.error('时限不能为空')
        return false
      } else if (!row.deptId) {
        this.$message.error('默认部门不能为空')
        return false
      } else {
        return true
      }
    },
    saveRow(row) {
      if (this.checkRow(row)) {
        row.day = row.day ? row.day : 0
        row.hours = row.hours ? row.hours : 0
        row.minutes = row.minutes ? row.minutes : 0

        // 编辑状态下-> 如果id为null，添加立案标准；如果id不为null，更新立案标准
        if (this.dialogStatus === 'update') {
          if (row.id) {
            updateCaseTypesTime(row).then(response => {
              if (response.code === 200) {
                this.$message.success('保存成功')
                row.edit = false
                this.fetchTypesTime()
              } else {
                this.$message.error('保存失败')
              }
            })
          } else {
            console.log(JSON.stringify([row]))
            addCaseTypesTime(JSON.stringify([row])).then(response => {
              if (response.code === 200) {
                this.$message.success('保存成功')
                row.edit = false
                this.fetchTypesTime()
              } else {
                this.$message.error('保存失败')
              }
            })
          }
          // 更新状态下，提交时批量保存
        } else if (this.dialogStatus === 'create') {
          row.edit = false
        }
      }
    },
    deleteRow(index, row) {
      // 1 提示框
      // 2 如果是从数据库中获取的立案标准（row.id不为空），调用后台删除接口；否则直接删除
      this.$confirm(
        '确定要删除吗？',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        if (row.id) {
          if (this.hasPerm('/caseType/deleteTypesTime')) {
            deleteCaseTypesTime(row.id).then(response => {
              if (response.code === 200) {
                this.$message.success('删除成功')
                this.fetchTypesTime()
              } else {
                this.$message.error('删除失败')
              }
            })
          } else {
            this.$message.warning('没有权限')
          }
        } else {
          this.caseTypeForm.typesTime.splice(index, 1)
        }
      })
    },
    checkBeforeAdd() {
      var unsave = 0
      this.caseTypeForm.typesTime.forEach(item => {
        if (item.edit === true) {
          unsave += 1
        }
      })
      if (unsave > 0) {
        this.$message.error('有未保存数据，请先保存')
        return false
      } else {
        return true
      }
    },
    changeDept(v, row) {
      row.deptName = v.name
    },
    cancel() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    },
    saveData() {
      this.caseTypeForm.typesTime.forEach(row => {
        this.saveRow(row)
      })
      if (this.dialogStatus === 'create') {
        this.createData()
      } else if (this.dialogStatus === 'update') {
        this.updateData()
      }
    },
    createData() {
      console.log('create data')
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log('create valid success')
          // 1.添加小类，返回id
          console.log(this.caseTypeForm)
          addCaseDetailType(this.caseTypeForm).then(response1 => {
            if (response1.code === 200) {
              // 2.更新全部立案标准的detailId
              const detailId = response1.data.id
              this.caseTypeForm.typesTime.forEach(row => {
                row.detailId = detailId
              })
              // 3.批量添加立案标准
              console.log(this.caseTypeForm.typesTime)
              addCaseTypesTime(JSON.stringify(this.caseTypeForm.typesTime)).then(response2 => {
                if (response2.code === 200) {
                  this.$message.success('添加成功')
                  this.$emit('watchChild')
                  this.dialogFormVisible = false
                } else {
                  this.$message.error('立案标准添加失败')
                }
              })
            } else {
              this.$message.error('小类添加失败')
            }
          })
        } else {
          console.log('create valid error')
        }
      })
    },
    updateData: function() {
      console.log('update data')
      console.log(this.caseTypeForm)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log('update valid success')
          // 只需要更新小类，立案标准在每次保存时已更新
          updateCaseDetailType(this.caseTypeForm).then(response => {
            if (response.code === 200) {
              this.$message.success('更新成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
            } else {
              this.$message.error('更新失败')
            }
          })
        } else {
          console.log('update valid error')
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  $tableTitleHeight:46px;
  .table{
    margin-bottom: 20px;
    font-size: 14px;
  }
  .pagination-container{
    margin-bottom: 50px;
  }
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btns{
    .edit_btn{
      float:right;
      margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
    }
  }
  .table-input{
    display: block;
  }
  .el-input__count-inner, .el-input__count{
    line-height: initial !important
  }
  .table-textarea{
    vertical-align: middle;
  }
</style>
