<!--基础数据-->
<template>
  <div
    style="display: flex; flex-direction: column; height: 100%"
    class="systemBase"
  >
    <div class="base-data-container">
      <div class="base-data-left">
        <div class="common-title-div">导航树</div>
        <el-tree
          v-loading="dataLoading"
          ref="baseDataTree"
          :data="baseDataTree"
          :style="{ height: tableHeight1 + 'px' }"
          highlight-current
          node-key="id"
          @node-click="nodeClick"
        >
        </el-tree>
      </div>
      <div class="base-data-table">
        <div class="common-title-div">
          基础数据
          <div class="common-operation-button-div">
            <el-button
              icon="el-icon-circle-plus-outline"
              type="primary"
              size="mini"
              @click="addBaseData"
              v-loading.fullscreen.lock="operateLoading"
              v-privilege="activeMenu + 'ADD'"
              >新增</el-button
            >
            <el-button
              icon="el-icon-edit"
              type="primary"
              size="mini"
              @click="modifyBaseData"
              v-loading.fullscreen.lock="operateLoading"
              v-privilege="activeMenu + 'UPDATE'"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-check"
              @click="enableBaseData"
              v-loading.fullscreen.lock="operateLoading"
              v-privilege="activeMenu + 'RECOVERY'"
              >启用</el-button
            >
            <el-button
              size="mini"
              type="danger"
              plain
              icon="el-icon-remove-outline"
              @click="discardBaseData"
              v-loading.fullscreen.lock="operateLoading"
              v-privilege="activeMenu + 'ABOLISH'"
              >废除</el-button
            >
          </div>
        </div>
        <div class="common-table-div">
          <el-table
            v-loading="dataLoading"
            :row-class-name="tableRowClassName"
            ref="baseDataTable"
            border
            highlight-current-row
            @selection-change="handleSelectionChange"
            :data="table.list"
            @row-click="rowChange"
            :height="tableHeight"
            :exchangeFilterMap="{
              validFlag: { '0': '无效', '1': '有效' },
              isEditFlag: { '0': '可编辑', '1': '不可编辑' },
              isCreateSubclaseFlag: { '0': '可添加', '1': '不可添加' },
            }"
            :icore-filter-flag="icoreFilterFlag"
          >
            <el-table-column
              type="index"
              label="序号"
              fixed="left"
              align="center"
            ></el-table-column>
            <el-table-column
              type="selection"
              width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              min-width="150px"
              :show-overflow-tooltip="true"
              sortable
              label="基础数据编码"
              align="left"
              prop="baseCode"
            ></el-table-column>
            <el-table-column
              min-width="150px"
              :show-overflow-tooltip="true"
              sortable
              label="基础数据名称"
              align="left"
              prop="baseName"
            ></el-table-column>
            <el-table-column
              min-width="150px"
              :show-overflow-tooltip="true"
              sortable
              label="快速检索码"
              align="left"
              prop="pBaseCode"
            ></el-table-column>
            <el-table-column
              min-width="120px"
              :show-overflow-tooltip="true"
              sortable
              prop="isEditFlag"
              label="可编辑"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.isEditFlag == 0">可编辑</span>
                <span v-else-if="scope.row.isEditFlag == 1">不可编辑</span>
              </template>
            </el-table-column>
            <el-table-column
              min-width="120px"
              :show-overflow-tooltip="true"
              sortable
              prop="isCreateSubclaseFlag"
              label="允许添加子类"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.isCreateSubclaseFlag == 0">可添加</span>
                <span v-else-if="scope.row.isCreateSubclaseFlag == 1"
                  >不可添加</span
                >
              </template>
            </el-table-column>
            <el-table-column
              min-width="150px"
              :show-overflow-tooltip="true"
              sortable
              label="拼音助记码"
              align="left"
              prop="mnemonicCode"
            ></el-table-column>
            <el-table-column
              min-width="200px"
              :show-overflow-tooltip="true"
              sortable
              label="备注"
              align="left"
              prop="memo"
            ></el-table-column>
            <el-table-column
              min-width="120px"
              :show-overflow-tooltip="true"
              prop="validFlag"
              sortable
              label="状态"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.validFlag == 1">有效</span>
                <span v-else-if="scope.row.validFlag == 0">无效</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="common-foot-style">
          <el-pagination
            v-loading="dataLoading"
            @size-change="pageSizeChange"
            @current-change="pageCurrentChange"
            :current-page="page.pageNum"
            :page-sizes="[100, 500, 1000]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.totalPage"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- <div ref="editTitle" class="common-title-div">编辑区
    </div> -->
    <div ref="editDiv" class="commom-edit-div">
      <el-form
        ref="baseData"
        label-width="70px"
        :inline="true"
        :rules="ruleValidate"
        :model="baseData"
      >
        <el-form-item prop="baseCode" label="数据编号">
          <el-input
            v-model="baseData.baseCode"
            clearable
            size="small"
            placeholder="请输入"
            style="width: 120px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="baseName" label="数据名称">
          <el-input
            v-model="baseData.baseName"
            clearable
            size="small"
            placeholder="请输入"
            @blur="myBlur"
            style="width: 120px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pBaseCode" label="检索码">
          <el-input
            v-model="baseData.pBaseCode"
            clearable
            size="small"
            placeholder="请输入"
            style="width: 120px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="isEditFlag" label="编辑状态">
          <el-select
            v-model="baseData.isEditFlag"
            filterable
            collapse-tags
            size="small"
            style="width: 120px"
          >
            <el-option
              v-for="(item, index) in editState"
              :key="index"
              :label="item.label"
              :value="item.state"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="isCreateSubclaseFlag" label="添加子类">
          <el-select
            v-model="baseData.isCreateSubclaseFlag"
            filterable
            collapse-tags
            size="small"
            style="width: 120px"
          >
            <el-option
              v-for="(item, index) in editChildren"
              :key="index"
              :label="item.label"
              :value="item.state"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="mnemonicCode" label="助记码">
          <el-input
            v-model="baseData.mnemonicCode"
            clearable
            size="small"
            placeholder="请输入"
            style="width: 120px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="memo" label="备注">
          <el-input
            v-model="baseData.memo"
            clearable
            size="small"
            placeholder="请输入"
            style="width: 120px"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  combaseinfos
} from '../../../utils/api.js';
import {
  getCookie
} from '@/utils/util.js';
import {
  cookieUserId,
  cookieUserName
} from '@/config/config.js';
import {
  discard,
  Recovery,
  add,
  modify
} from '../../../utils/httpRequest.js';
import pinyinUtils from '../../../utils/pinyin/pinyinUtils.js';
import { recordChange } from '~/utils/utils'

let userId = getCookie(cookieUserId)
let userName = getCookie(cookieUserName)
export default {
  data () {
    var baseCodeVerify = (rule, value, callback) => {
      if (this.baseData.baseCode) {
        if (this.baseData.baseCode.length % 3 === 0) {
          callback();
        } else {
          callback(new Error('请按照编码规则进行输入！'));
        }
      } else {
        callback();
      }
    };
    const baseCodeIsNum = (rule, value, callback) => {
      const age = /^[0-9]*$/
      if (!age.test(this.baseData.baseCode)) {
        callback(new Error('编码只能为数字！'))
      } else {
        callback()
      }
    }
    var pBaseCodeVerify = (rule, value, callback) => {
      if (this.baseData.pBaseCode) {
        if (this.baseData.pBaseCode.length % 3 === 0) {
          callback();
        } else {
          callback(new Error('请按照编码规则进行输入！'));
        }
      } else {
        callback();
      }
    };
    const pBaseCodeIsNum = (rule, value, callback) => {
      const age = /^[0-9]*$/
      if (!age.test(this.baseData.pBaseCode)) {
        callback(new Error('检索码只能为数字！'))
      } else {
        callback()
      }
    }
    return {
      dataLoading: false,
      operateLoading: false,
      table: {
        list: []
      },
      baseDataTree: [],
      editState: [{
        label: '可编辑',
        state: '0'
      },
      {
        label: '不可编辑',
        state: '1'
      }
      ],
      editChildren: [{
        label: '可添加',
        state: '0'
      },
      {
        label: '不可添加',
        state: '1'
      }
      ],
      page: {
        pageSize: 500,
        pageNum: 1,
        totalPage: 0
      },
      multipleSelection: [],
      treeLoading: false,
      baseData: {
        baseCode: '',
        baseName: '',
        isEditFlag: '0',
        mnemonicCode: '',
        pBaseCode: '',
        isCreateSubclaseFlag: '0',
        memo: '',
        createManName: '',
        createManNo: '',
        createTime: ''
      },
      baseData2: {},
      ruleValidate: {
        baseCode: [{
          required: true,
          message: '数据编号不能为空',
          trigger: ['blur', 'change']
        },
        { required: true, validator: baseCodeIsNum, trigger: 'blur' },
        { required: true, validator: baseCodeVerify, trigger: 'blur' },
        ],
        baseName: [{
          required: true,
          message: '数据名称不能为空',
          trigger: 'change'
        }],
        pBaseCode: [{
          required: true,
          message: '快速检索码不能为空',
          trigger: 'change'
        },
        { required: true, validator: pBaseCodeIsNum, trigger: 'blur' },
        { required: true, validator: pBaseCodeVerify, trigger: 'blur' },]
      },
      tableHeight: 0,
      tableHeight1: 0,
      selectBaseCodeNo: '',
      icoreFilterFlag: true,
      activeMenu: '',
      oldObj: {}
    }
  },
  created () {
    this.tableHeight = window.innerHeight - 320 > 500 ? window.innerHeight - 320 : 500;
    this.tableHeight1 = window.innerHeight - 220 > 400 ? window.innerHeight - 220 : 400;
    this.activeMenu = window.top.localStorage.getItem('activeMenu')
  },
  mounted () {
    this.getBaseDataList();
    this.getBaseDataList2();
  },
  methods: {
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    rowChange (row, column, event) {
      let row1 = Object.assign({}, row)
      if (row1.isEditFlag === '0') {
        this.baseData = row1;
        this.oldObj = { ...row1 }
        this.baseData2 = row1;
      } else {
        this.$message.warning('该条数据不可修改！')
      }
    },
    // 新增
    addBaseData () {
      let _this = this;
      _this.$refs['baseData'].validate((valid) => {
        // 新增日志参数
        const param = {
          createManNo: userId,
          createManName: userName,
          operationPage: '基础数据配置页面',
          operationFunction: "新增",
          operationId: _this.baseData.baseCode,
          operationPredictionNo: '',
          operationCarnNo: '',
          operationBeforeFix: '',
          operationAfterFix: ''
        }
        if (valid) {
          _this.operateLoading = true;
          add(combaseinfos, {
            id: _this.baseData.baseCode,
            baseCode: _this.baseData.baseCode,
            baseName: _this.baseData.baseName,
            isEditFlag: _this.baseData.isEditFlag,
            mnemonicCode: _this.baseData.mnemonicCode,
            pBaseCode: _this.baseData.pBaseCode,
            isCreateSubclaseFlag: _this.baseData.isCreateSubclaseFlag,
            memo: _this.baseData.memo,
            createManName: '',
            createManNo: '',
            createTime: ''
          }, async (e) => {
            _this.operateLoading = false;
            if (!e) {
              const log = await this.axios.post('pass/systemBase/v1/meterbaseoperationlogs/addList', [param], { individualType: 'json' })
              if (!log.succeed) {
                this.$message.error('新增日志保存失败');
              }
              _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              _this.getBaseDataList();
              _this.getBaseDataList2();
            }
          })
        }
      });
    },
    // 修改
    modifyBaseData () {
      let _this = this;

      // 记录修改的内容
      const { oldStr, newStr } = recordChange(this.oldObj, this.baseData)

      const param = {
        createManNo: userId,
        createManName: userName,
        operationPage: '基础数据配置页面',
        operationFunction: "修改",
        operationId: this.baseData.id,
        operationPredictionNo: '',
        operationCarnNo: '',
        operationBeforeFix: oldStr,
        operationAfterFix: newStr
      }

      _this.$refs['baseData'].validate((valid) => {
        if (valid) {
          _this.operateLoading = true;
          // _this.baseData.id = _this.baseData2.baseCode;
          modify(combaseinfos + _this.baseData.baseCode + '/', _this.baseData, async (e) => {
            _this.operateLoading = false;
            if (!e) {
              const log = await this.axios.post('pass/systemBase/v1/meterbaseoperationlogs/addList', [param], { individualType: 'json' })
              if (!log.succeed) {
                this.$message.error('修改日志保存失败');
              }
              _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
            }
            _this.getBaseDataList();
            _this.getBaseDataList2();
          });
        }
      });
    },
    // 启用
    enableBaseData () {
      this.operateLoading = true;
      // 启用日志参数
      let logList = []
      this.multipleSelection.forEach(item => {
        const param = {
          createManNo: userId,
          createManName: userName,
          operationPage: '基础数据配置页面',
          operationFunction: "启用",
          operationId: item.id,
          operationPredictionNo: '',
          operationCarnNo: '',
          operationBeforeFix: '',
          operationAfterFix: ''
        }
        logList.push(param)
      })
      Recovery(combaseinfos + 'Recovery', this.multipleSelection, async (e) => {
        this.operateLoading = false;
        if (!e) {
          const log = await this.axios.post('pass/systemBase/v1/meterbaseoperationlogs/addList', [...logList], { individualType: 'json' })
          if (!log.succeed) {
            this.$message.error('启用日志保存失败');
          }
          this.getBaseDataList();
        }
      });
    },
    // 作废
    discardBaseData () {
      // 作废日志参数
      let logList = []
      this.multipleSelection.forEach(item => {
        const param = {
          createManNo: userId,
          createManName: userName,
          operationPage: '基础数据配置页面',
          operationFunction: "作废",
          operationId: item.id,
          operationPredictionNo: '',
          operationCarnNo: '',
          operationBeforeFix: '',
          operationAfterFix: ''
        }
        logList.push(param)
      })
      this.operateLoading = true;
      discard(combaseinfos + 'abolish', this.multipleSelection, async (e) => {
        this.operateLoading = false;
        if (!e) {
          const log = await this.axios.post('pass/systemBase/v1/meterbaseoperationlogs/addList', logList, { individualType: 'json' })
          if (!log.succeed) {
            this.$message.error('作废日志保存失败');
          }
          this.getBaseDataList();
        }
      });
    },
    nodeClick (item) {
      this.selectBaseCodeNo = item.baseCode;
      this.page.pageNum = 1
      this.getBaseDataList();
    },
    pageSizeChange (size) {
      this.page.pageSize = size;
      this.getBaseDataList();
    },

    pageCurrentChange (index) {
      this.page.pageNum = index;
      this.getBaseDataList();
    },
    getBaseDataList () {
      this.dataLoading = true;
      this.axios.get(combaseinfos + '?pageNum=' + this.page.pageNum + '&pageSize=' + this.page.pageSize +
        '&pBaseCode=' + this.selectBaseCodeNo)
        .then(res => {
          this.dataLoading = false;
          this.table.list = res.data.list;
          this.page.totalPage = res.data.total;
        }).catch(e => {
          this.dataLoading = false;
        });
    },
    getBaseDataList2 () {
      this.axios.get(combaseinfos + 'noPage')
        .then(res => {
          this.initTree(res.data);
        });
    },
    tableRowClassName ({
      row,
      rowIndex
    }) {
      if (row.validFlag !== '1') {
        return 'error-row2';
      }
      return '';
    },
    initTree (data) {
      var list = [];
      var parentList = [];
      for (var i = 0; i < data.length; i++) {
        data[i].children = [];
        data[i].label = data[i].baseName;
        if (data[i].pBaseCode === '' || data[i].pBaseCode === null) {
          parentList.push(data[i]);
        } else {
          list.push(data[i]);
        }
      }
      this.getChildren(parentList, list);
      this.baseDataTree = parentList;
    },
    getChildren (parentList, list) {
      for (var i = 0; i < parentList.length; i++) {
        var childrenList = [];
        for (var j = 0; j < list.length; j++) {
          if (parentList[i].baseCode === list[j].pBaseCode) {
            parentList[i].children.push(list[j]);
            childrenList.push(list[j]);
          }
        }
        if (childrenList.length > 0) {
          this.getChildren(childrenList, list);
        }
      }
    },
    myBlur () {
      if (this.baseData.baseName) {
        this.baseData.mnemonicCode = pinyinUtils.initial(this.baseData.baseName);
      }
    }
  }
}
</script>

<style lang="less">
.base-data-container {
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid #d5d5d5;
  padding-bottom: 10px;
  flex: 1;
}

.base-data-left {
  width: 20%;
  display: flex;
  flex-direction: column;
}

.base-data-table {
  width: 80%;
  border-left: 1px solid #d5d5d5;
  display: flex;
  flex-direction: column;
}

.public-function-div {
  font-size: 16px;
  padding: 10px 20px;
  border-bottom: 1px solid #d5d5d5;
  position: relative;
}

.el-tree {
  overflow-x: hidden !important;
}

.el-tree-node {
  .el-tree-node__label {
    border-bottom: 0;
  }
}

.el-select {
  width: 100%;
}
</style>
