ludc
2024-10-17 d02571d59633367ac76b7f58ab38584698b1aa1b
Source/UBCS-WEB/src/components/refer/vciWebReferTable.vue
@@ -1,71 +1,461 @@
<template>
  <avue-input-table :props="props"  :column="column" :on-load="onLoad" v-model="value"  :placeholder="placeholder" ></avue-input-table>
  <div>
    <el-dialog v-dialogDrag
               :height="options.height|| 'auto'" :title="title"
               :visible.sync="visible"
               :width="options.width|| '80%'"
               append-to-body="true"
               class="avue-dialog avue-dialog--top"
               top="0"
               @close="dialogClose">
      <avue-crud ref="referCrud"
                 v-model="value"
                 :data="data"
                 :option="option"
                 :page.sync="page"
                 :table-loading="loading"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @row-click="rowClick"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="icon" slot-scope="scope">
          <i :class="scope.row.icon" style="font-size:24px"></i>
        </template>
      </avue-crud>
      <div class="avue-dialog__footer">
        <div class="avue-dialog__footer--left valueInfo">{{ valueInfo }}</div>
        <el-button @click="escHandler">取 消</el-button>
        <el-button type="primary" @click="setValue">确 定</el-button>
      </div>
    </el-dialog>
    <avue-input v-model="text" :disabled="disabled" :placeholder="title" :readonly="true"
                @click="!disabled && (visible=true)"></avue-input>
  </div>
</template>
<script>
import {validatenull} from "@/util/validate";
import {getList, getLazyList, getTableDefinedUrl} from "@/api/refer/table";
export default {
  name: "vciWebReferTable",
  props:["referConfig","value"],
  props: ["referConfig", "value", "text", "title", "disabled", "referType"],
  data() {
    return {
      placeholder:this.referConfig.placeholder || '请选择数据',
      column:{
        children:{
          border: true,
          column: [{
            label: '姓名',
            width: 120,
            search:true,
            prop: 'name'
          }, {
            label: '性别',
            search:true,
            prop: 'sex'
          }],
        },
      },
      visible: false,
      options: this.referConfig.options || {},
      isMuti: ("true" == this.referConfig.options.isMuti || this.referConfig.options.isMuti == true || this.referConfig.options.muti == true) ? true : false,
      props: {
        value: this.referConfig.valueField || this.referConfig.options.valueField || 'oid',
        label: this.referConfig.textField || this.referConfig.options.textField || "name"
      },
      url: this.referConfig.options.url || '/api/ubcs-code/mdmEngineController/defaultReferDataGrid',
      tableDefinedUrl: '',//平台表格地址
      copyParam: ['referBo', 'textField', 'valueField', 'displayTable', 'whereSql', 'queryScheme'],
      query: {},
      loading: false,
      page: {
        layout: this.referType === "master" ? "total,pager,prev, next,jumper" : "total,pager,prev, next,jumper,sizes",
        pageSize: 10,
        currentPage: 1,
        total: this.referConfig.options.data ? this.referConfig.options.data.length : 0
      },
      data: this.referConfig.options.data || [],
      selectionList: [],
      option: {
        addBtn: false,
        columnBtn: false,
        height: this.referConfig.options.height ? this.referConfig.options.height : 475,
        calcHeight: 30,
        tip: false,
        menu: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        border: true,
        index: true,
        selection: true,
        reserveSelection: true,
        dialogClickModal: false,
        highlightCurrentRow: true,
        rowKey: 'oid',
        rowParentKey: 'parentSaleProduct',
        column: []
      }
    };
  },
  created() {
    this.getParams();
  },
  mounted() {
    if (this.referConfig.options.tableConfig && this.referConfig.options.tableConfig.page) {
      this.page.pageSize = this.referConfig.options.tableConfig.page.limit || this.referConfig.options.tableConfig.page.pageSize;
      this.page.currentPage = this.referConfig.options.tableConfig.page.page || this.referConfig.options.tableConfig.page.currentPage;
    } else if (!validatenull(this.referConfig.options.limit)) {
      this.page.pageSize = this.referConfig.options.limit;
    } else if (this.referConfig.options.tableConfig && !validatenull(this.referConfig.options.tableConfig.limit)) {
      this.page.pageSize = this.referConfig.options.tableConfig.limit;
    }
    this.$nextTick(() => {
      this.$refs.referCrud.doLayout()
    })
  },
  computed: {
    valueInfo: function () {
      return this.text ? ("已设置的值为[" + this.text + "]") : '未设置值'
    }
  },
  methods: {
    onLoad({page, value, data}, callback) {
      //首次加载去查询对应的值
      if (value) {
        this.$message.success('首次查询' + value)
        callback({
          id: '0',
          name: '张三',
          sex: '男'
        })
        return
    escHandler() {
      this.visible = false;
      this.$refs.referDefalutCrud.refreshTable()
    },
    dialogClose() {
      this.visible = false;
      this.$refs.referDefalutCrud.refreshTable()
    },
    getParams: function () {
      var queryParams = {};
      if (this.options.extraParams) {
        queryParams = this.options.extraParams;
      }
      if (data) {
        this.$message.success('搜索查询参数' + JSON.stringify(data))
      if (this.options.useFormKey && this.options.formValues) {
        //使用表单上的字段来过滤
        queryParams['conditionMap["' + (this.options.paramForFormKey ? this.options.paramForFormKey : this.options.useFormKey) + '"]'] = this.options.formValues[this.options.useFormKey];
      }
      if (page) {
        this.$message.success('分页参数' + JSON.stringify(page))
      if (this.options.where) {
        for (var key in this.options.where) {
          queryParams['conditionMap["' + key + '"]'] = this.options.where[key];//新
        }
      }
      //分页查询信息
      callback({
        total: 2,
        data: [{
          id: '0',
          name: '张三',
          sex: '男'
        }, {
          id: '1',
          name: '李四',
          sex: '女'
        }]
      for (var i = 0; i < this.copyParam.length; i++) {
        queryParams[this.copyParam[i]] = this.options[this.copyParam[i]];
      }
      queryParams["isMuti"] = this.isMuti;
      queryParams.muti = this.isMuti;
      if (!queryParams['referBo']) {
        queryParams['referBo'] = this.options['referBo'] || this.options['referType'];
      }
      queryParams['referType'] = queryParams['referBo']
      if (this.options.initSort) {
        queryParams['order'] = this.options.initSort.type;//方法
        queryParams['sort'] = this.options.initSort.field;//字段
      }
      if (this.options.sortField) {
        queryParams['sort'] = this.options.sortField;//字段
      }
      if (this.options.sortType) {
        queryParams['order'] = this.options.sortType;//方法
      }
      if (this.options.conditionParams) {
        //说明是扩展属性
        for (var key in this.options.conditionParams) {
          queryParams['conditionMap["' + key + '"]'] = this.options.conditionParams[key];//新的方式
        }
      }
      if (this.options.sourceDataParams) {
        //说明是扩展属性
        for (var key in this.options.sourceDataParams) {
          if (key && key.constructor === Object) return;
          queryParams['sourceData["' + key + '"]'] = this.options.sourceDataParams[key];//新的方式
        }
      }
      if (this.options.replaceParams) {
        //说明是扩展属性
        for (var key in this.options.replaceParams) {
          if (key && key.constructor === Object) return;
          queryParams['replaceMap["' + key + '"]'] = this.options.replaceParams[key];//新的方式
        }
      }
      var paramsData = {};
      //为了处理单引号和双引号的
      if (queryParams) {
        for (var key in queryParams) {
          paramsData[key.replace(/"/g, "'")] = queryParams[key];
        }
      }
      if (this.options.displayTable) {
        //说明是使用平台的表格
        getTableDefinedUrl({
          btmType: (this.options.referBo || this.options.referType),
          code: this.options.displayTable,
          isMuti: this.isMuti
        }, this.tableDefinedUrl).then(result => {
          console.log('result', result)
          if (result.success) {
            var queryScheme = result.querySchema;
            if (!validatenull(queryScheme) && validatenull(this.options.queryScheme)) {
              this.options.queryScheme = queryScheme;
            }
            paramsData['queryScheme'] = this.options.queryScheme;
            if (result.showIndex) {
              this.option.index = true;
            }
            if (result.showCheckbox) {
              this.option.selection = true
            }
            var referColumn = "";
            if (result.columns) {
              this.option.column = result.columns.map(item => {
                if (item.field.indexOf(".") > -1) {
                  referColumn += item.field + ",";
                  item.field = item.field.replace(".", "_");
                }
                if (!validatenull(item.enumCode)) {
                  //是枚举的内容
                  item.type = 'select';
                  item.dicUrl = "/api/ubcs-omd/enum/dictionary?code=" + item.enumCode;
                  item.dicData = item.enumMap;
                  item.dataType = "String";
                  item.search = true;
                  item.props = {
                    label: "itemName",
                    value: "itemValue"
                  };
                  item.rules = [{
                    required: true,
                    message: "请输入" + item.field,
                    trigger: "blur"
                  }];
                }
                item.formatter = function (d) {
                  if (d[item.field] != undefined) {
                    return d[item.field]
                  } else if (d.data[item.field] != undefined) {
                    return d.data[item.field]
                  } else {
                    return ''
                  }
                };
                return {
                  ...item,
                  label: item.title,
                  prop: item.field,
                  search: true
                }
              })
            }
            paramsData['referColumn'] = referColumn;
            if (result.limit > 0) {
              this.page.pageSize = result.limit;
              this.page.currentPage = 1
            }
            if (this.options.isTreeGrid) {
              //表格树加上配置
            }
            this.params = paramsData;
          } else {
            this.$message.error(result.msg);
          }
        });
      } else {
        //说明是自定义的表格
        var tableConfig = this.options.tableConfig;
        if (!tableConfig) {
          this.$message.error('没有定义参照的表格配置');
        }
        if (!paramsData) {
          paramsData = {
            currentUserReferModelKey: this.options.currentUserReferModelKey,
            currentUserReferMethodKey: this.options.currentUserReferMethodKey
          };
        } else {
          paramsData['currentUserReferModelKey'] = this.options.currentUserReferModelKey;
          paramsData['currentUserReferMethodKey'] = this.options.currentUserReferMethodKey;
        }
        if (this.options.tableConfig && this.options.tableConfig.cols && this.options.tableConfig.cols.length > 0) {
          //说明传递了的
          this.option.column = this.options.tableConfig.cols.map(item => {
            if (item.field != 'LAY_TABLE_INDEX' && item.field != 'LAY_CHECKED') {
              let formatter = item.template || item.templet;
              if (typeof formatter == "string" && formatter != '') {
                formatter = eval("(" + formatter + ")")
              } else {
                formatter = function (d) {
                  if (d[item.field] != undefined) {
                    return d[item.field]
                  } else if (d.data[item.field] != undefined) {
                    return d.data[item.field]
                  } else {
                    return ''
                  }
                }
              }
              return {
                ...item,
                label: item.title,
                prop: item.field,
                formatter: formatter,
                sortable: item.sort,
                hide: item.hidden,
                search: this.options.tableConfig.queryColumns.some(qItem => {
                  return qItem.field == item.field
                })
              }
            }
          })
        }
        if (this.options.isTreeGrid) {
          //表格树加上配置
        }
      }
      this.params = paramsData;
    },
    setValue() {
      if (this.selectionList.length == 0) {
        this.$message.warning('没有选择数据');
        return false;
      } else if (this.selectionList.length > 1 && !this.isMuti) {
        this.$message.warning('每次只能选择一条数据');
        return false;
      }
      var value = [];
      var text = [];
      var isMutiValue = (this.props.value.indexOf(",") > -1);
      var isMutiRaw = (this.props.label.indexOf(",") > -1);
      var _that = this
      this.selectionList.forEach((item, _index) => {
        if (isMutiValue) {
          var valueFieldArray = _that.props.value.split(",");
          valueFieldArray.forEach((_itemField, _indexField) => {
            let itemValue = item[_itemField];
            if (itemValue == undefined || itemValue == null) {
              itemValue = item['data'][_itemField]
            }
            value.push(itemValue + (_that.referConfig.valueSep ? _that.referConfig.valueSep : ' '));
          })
        } else {
          let itemValue = item[_that.props.value];
          if (itemValue == undefined || itemValue == null) {
            itemValue = item['data'][_that.props.value]
          }
          value.push(itemValue);
        }
        if (isMutiRaw) {
          var rawFieldArray = _that.props.label.split(",");
          rawFieldArray.forEach((_itemField, _indexField) => {
            let itemText = item[_itemField];
            if (itemText == undefined || itemText == null) {
              itemText = item['data'][_itemField]
            }
            text.push(itemText + (_that.referConfig.textSep ? _that.referConfig.textSep : ' '));
          })
        } else {
          let itemText = item[_that.props.label];
          if (itemText == undefined || itemText == null) {
            itemText = item['data'][_that.props.label]
          }
          text.push(itemText);
        }
      })
      let mapFields = this.referConfig.fieldMap || {};
      try {
        if (!validatenull(this.options.mapFields)) {
          mapFields = Object.assign(this.referConfig.fieldMap, JSON.parse(this.options.mapFields));
        }
      } catch (e) {
      }
      this.value = value.join(',');
      this.text = text.join(',')
      this.$emit("setValue", {
        field: this.referConfig.field,
        showField: this.referConfig.showField,
        value: this.value,
        text: this.text,
        rawData: this.selectionList,
        fieldMap: mapFields
      });
      this.visible = false;
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    rowClick(row) {
      this.$refs.referCrud.toggleSelection();
      this.$refs.referCrud.toggleRowSelection(row); //选中当前行
      this.selectionList = [row]
    },
    selectionChange(list) {
      if (!this.isMuti && list.length > 1) {
        const nowVal = list.shift();
        this.$refs.referCrud.toggleRowSelection(nowVal, false);
      }
      this.selectionList = list
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.referCrud.toggleSelection();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      if (this.url) {
        this.loading = true;
        var query = {}
        if (this.query) {
          for (var key in this.query) {
            query['conditionMap["' + key + '"]'] = this.query[key];
          }
        }
        getList(Object.assign(params, this.params, this.query, query), page.currentPage, page.pageSize, this.url).then(res => {
          let data = []
          if (res.data.records) {
            data = res.data.records
            this.page.total = res.data.total;
          } else {
            data = res.data.data.records;
            this.page.total = res.data.data.total;
          }
          this.data = data.map(item => {
            item.data = item.data || {}
            return {
              ...item
            }
          })
          this.loading = false;
          this.selectionClear();
        }).catch(error => {
          this.$message.error(error);
          this.loading = false;
        });
      }
    }
  }
}
</script>
<style scoped>
.valueInfo {
  float: left;
  border: 1px solid #E9E7E7;
  display: inline-block;
  vertical-align: middle;
  padding: 9px 15px;
  line-height: 1;
}
</style>