<template>
  <div class='main-content'>
    <el-row type='flex'>
      <el-col :span='16'>
        <el-row type='flex'>
          <el-form label-width='120px' size='small'>
            <el-form-item label='字典项标签'>
              <el-input v-model.trim='searchParams.dictLabel' class='query-form-input' />
            </el-form-item>
          </el-form>
          <div style='padding-left: 10px'>
            <el-button type='primary' @click='searchFn(false)' size='small'>搜索</el-button>
            <el-button @click='resetFn' size='small'>清空</el-button>
          </div>
        </el-row>
      </el-col>
      <el-col :span='8'>
        <el-row type='flex' justify='end'>
          <el-button type='primary' size='small' @click='addFn(tableData.length)'>新增</el-button>
          <el-button type='danger' size='small' @click='batchDelFn'>批量删除</el-button>
        </el-row>
      </el-col>
    </el-row>
    <el-row type='flex' justify='space-between'>
      <el-table ref='dictionaryOptionTable' tripe border tooltip-effect='dark' height='400' :data='tableData'>
        <el-table-column type='selection' width='40' />
        <el-table-column label='字典项标签' header-align='center' align='center' prop='dictLabel'>
          <template slot-scope='scope'>
            <el-form class='dict-label-form' :ref="'dictLabelForm' + scope.$index" :model='formData' :rules='rules'>
              <el-form-item prop='dictLabel'>
                <el-input v-model.trim='formData.dictLabel' size='small' v-if='editIndex === scope.$index' />
                <span v-else>{{ scope.row['dictLabel'] }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label='字典项值' header-align='center' align='center' prop='dictValue'>
          <template slot-scope='scope'>
            <el-input v-model.trim='formData.dictValue' size='small' v-if='editIndex === scope.$index' />
            <span v-else>{{ scope.row['dictValue'] }}</span>
          </template>
        </el-table-column>
        <el-table-column label='排序号' header-align='center' align='center' prop='ord'>
          <template slot-scope='scope'>
            <el-input-number v-model='formData.ord' size='small' v-if='editIndex === scope.$index'></el-input-number>
            <span v-else>{{ scope.row['ord'] }}</span>
          </template>
        </el-table-column>
        <el-table-column label='操作' header-align='center' align='center' prop='operation'>
          <template slot-scope='scope'>
            <div v-if='editIndex === scope.$index'>
              <el-button type='success' size='small' @click='submitFn(scope.$index)'>确定</el-button>
              <span style='margin-right: 5px'></span>
              <el-button plain type='primary' size='small' @click='cancelFn(scope.$index)'>取消</el-button>
            </div>
            <div v-else>
              <el-button type='primary' size='small' @click='editFn(scope.row, scope.$index)'>编辑</el-button>
              <span style='margin-right: 5px'></span>
              <el-button type='danger' size='small' @click='delFn(scope.row)'>删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
  </div>
</template>

<script>
import {
  fetchDictionaryOptionPage,
  createDictionaryOption,
  updateDictionaryOption,
  removeDictionaryOption
} from '@api/upms/api-dictionary';

export default {
  name: 'Dictionary-Option',
  props: {
    dictId: {
      type: String,
      default: '0'
    }
  },
  watch: {
    dictId() {
      this.searchFn();
    }
  },
  data() {
    return {
      searchParams: Object.assign({}, this.$dialogSearch),
      tableData: [],
      editIndex: -1,
      formData: {},
      defaultData: {
        dictLabel: '',
        dictValue: '',
        ord: 99
      },
      rules: {
        dictLabel: [{ required: true, message: '请输入字典项标签', trigger: 'blur' }]
      }
    };
  },
  methods: {
    searchFn(isReset = false) {
      let vm = this;
      if (isReset) {
        vm.searchParams = Object.assign(vm.searchParams, vm.$dialogSearch);
      }
      vm.editIndex = -1;
      vm.searchParams.dictId = vm.dictId;
      fetchDictionaryOptionPage(vm.searchParams).then(
        (res) => {
          vm.tableData = res.data;
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    resetFn() {
      let vm = this;
      vm.searchParams = Object.assign({}, this.$dialogSearch);
      vm.searchFn();
    },
    addFn(index) {
      let vm = this;
      if (index > 0 && vm.editIndex !== -1) {
        if (!vm.tableData[index - 1].id) {
          return;
        }
        vm.$refs['dictLabelForm' + (index - 1)].validateField('dictLabel', (error) => {
          if (!error) {
            vm.formData = Object.assign({}, vm.defaultData, { dictId: vm.dictId });
            vm.tableData.push(vm.formData);
            vm.editIndex = index;
          }
        });
      } else {
        vm.formData = Object.assign({}, vm.defaultData, { dictId: vm.dictId });
        vm.tableData.push(vm.formData);
        vm.editIndex = index;
      }
    },
    editFn(row, index) {
      let vm = this;
      if (!vm.tableData[vm.tableData.length - 1].id) {
        vm.$refs['dictLabelForm' + (vm.tableData.length - 1)].validateField('dictLabel', (error) => {
          if (!error) {
            vm.editIndex = index;
          }
        });
      } else {
        vm.formData = Object.assign({}, row);
        vm.editIndex = index;
      }
    },
    cancelFn(index) {
      let vm = this;
      vm.editIndex = -1;
      if (!vm.tableData[index].id) {
        vm.tableData.pop();
      } else {
        vm.$refs['dictLabelForm' + index].resetFields();
      }
    },
    submitFn(index) {
      let vm = this;
      vm.$refs['dictLabelForm' + index].validate((valid) => {
        if (valid) {
          let formData = vm.formData;
          formData.dictId = vm.dictId;
          if (formData.id) {
            updateDictionaryOption(formData).then(
              (res) => {
                vm.searchFn(true);
              },
              (error) => {
                vm.$notify.error({
                  title: error.data.msg,
                  message: error.data.data
                });
                vm.editIndex = -1;
              }
            );
          } else {
            createDictionaryOption(formData).then(
              (res) => {
                vm.searchFn(true);
              },
              (error) => {
                vm.$notify.error({
                  title: error.data.msg,
                  message: error.data.data
                });
                vm.editIndex = -1;
              }
            );
          }
        }
      });
    },
    delFn(row) {
      let vm = this;
      vm.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        let ids = [row.id];
        removeDictionaryOption({ ids: ids }).then(
          (res) => {
            vm.searchFn(true);
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          }
        );
      });
    },
    batchDelFn() {
      let vm = this;
      let rows = vm.$refs.dictionaryOptionTable.selection;
      if (!rows || rows.length === 0) {
        vm.$message.warning('请选择要删除的记录');
        return;
      }
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        let ids = rows.map((row) => row.id);
        removeDictionaryOption({ ids: ids }).then(
          (res) => {
            vm.searchFn(true);
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          }
        );
      });
    }
  },
  mounted() {
    this.searchFn();
  }
};
</script>

<style lang='less' scoped>
.dict-label-form {
  .el-form-item {
    margin: 0;
  }
}
</style>
