廖井涛
2024-04-25 ed6f35069824d71ee6da599a328d865eb0c58550
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
<script setup>
import {computed, onMounted, reactive, ref, watch} from "vue"
import {filterChanged} from "@/hook"
import {useI18n} from "vue-i18n"
import {ElMessage, ElMessageBox,} from "element-plus"
import request from "@/utils/request"
import {useRouter,useRoute} from "vue-router"
const { t } = useI18n()
const router = useRouter()
const route = useRoute()
let rowClickIndex = ref(null)
const xGrid = ref()
const gridOptions = reactive({
  border:  "full",//表格加边框
  keepSource: true,//保持源数据
  align: 'center',//文字居中
  stripe:true,//斑马纹
  rowConfig: {isCurrent: true, isHover: true,height: 30},//鼠标移动或选择高亮
  id: 'OrderList',
  showFooter: true,//显示脚
  scrollY:{ enabled: true },//开启虚拟滚动
  showOverflow:true,
 
  columnConfig: {
   // resizable: true,
    useKey: true
  },
  filterConfig: {   //筛选配置项
                    //remote: true  //远端筛选
  },
  // customConfig: {
  //   storage: true
  // },
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    showStatus: true
  },//表头参数
  columns:[
    // {field: 'buildingNumber',width:120,  title: '楼号',editRender: { name: 'input'},filters:[{ data: '' }],slots: { filter: 'num1_filter'}, sortable: true,filterMethod:filterChanged},
    {field: 'alias', title:'其他加工',minWith:'130'},
    {field: 'price',  title:'单价',editRender: { name: 'input'}},
    {field: 'quantity',  title:'数量' },
    {field: 'money', slots:{default:'default'},  title:'金额'}
  ],
  //表单验证
  editRules: {
    price: [
      {
        validator ({ cellValue }) {
          const regex = /^(0(\.\d{1,2})?|([1-9]\d{0,4})(\.\d{1,2})?|99999(\.9{1,2})?)$/
          if (cellValue && !regex.test(cellValue) ) {
            return new Error(t('basicData.msg.range99999Dec2') )
          }
        }
      }
    ],
    quantity: [
      {
        validator ({ cellValue }) {
          const regex = /^(0(\.\d{1,2})?|([1-9]\d{0,4})(\.\d{1,2})?|99999(\.9{1,2})?)$/
          if (cellValue && !regex.test(cellValue) ) {
            return new Error(t('basicData.msg.range99999Dec2') )
          }
        }
      }
    ]
 
  },
  toolbarConfig: {
    buttons: [
      {'code': 'add', 'name': '新增',status: 'primary'},
      {'code': 'delete', 'name': '删除',status: 'primary'}
    ],
 
 
    // import: false,
    // export: true,
    // print: true,
    // zoom: true,
    // custom: true
  }
  ,
  //table body实际数据
  footerMethod ({ columns, data }) {//页脚函数
    return[
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return t('basicData.total')+':'
        }
        const footList = ['quantity']
        if (footList.includes(column.field)) {
          return sumNum(data, column.field)
        }
        if(column.field==='money'){
          let count = 0
          data.forEach(item => {
            count+=countAmount(item)
          })
          return parseFloat(count.toFixed(2))
        }
        return ''
      })
    ]
  }
 
})
const gridEvents = {
  async toolbarButtonClick({code}) {
    const $grid = xGrid.value
    if ($grid) {
      switch (code) {
        case 'add': {
          addColumn()
          break
        }
        case 'delete': {
          if(rowClickIndex.value === null){
            ElMessage.warning('请先单击选择行')
            return
          }
          deleteColum(rowClickIndex.value.id)
          rowClickIndex.value = null
          break
        }
      }
    }
  },
  cellClick({ row }){
    rowClickIndex.value = row
  }
}
 
const sumNum = (list, field) => {
  let count = 0
  list.forEach(item => {
    count += Number(item[field])
  })
  return count.toFixed(2)==='NaN' ? null : parseFloat(count.toFixed(2))
}
 
//用于接收父组件参数
let prop = defineProps({
  otherMoney:{}
})
onMounted(()=>{
  xGrid.value.reloadData(prop.otherMoney)
})
watch(prop,(newVal)=>{
  xGrid.value.reloadData(prop.otherMoney)
})
 
const countAmount = (row) => {
  const price = row.price===null?0:row.price
  const quantity = row.quantity===null?0:row.quantity
  return parseFloat((row.price * row.quantity).toFixed(2))
}
 
 
const validate = async () => {
  const errMap = await xGrid.value.validate(true)
  if (errMap) {
    ElMessage.error(`校验不通过!`)
    return false
  }
  return true
}
defineExpose({
  validate
})
 
 
const addColumn = () => {
  ElMessageBox.prompt( '新增列名:', {
    confirmButtonText: '新增',
    cancelButtonText: '取消',
    inputPattern:/^.{1,20}$/,
    inputErrorMessage: '请输入20个字符以内的且不为空的字符',
  })
    .then(({ value }) => {
      request.post('/basicOtherMoney/save',{alias:value}).then(res=>{
        if (res.code==='200' && res.data!==false){
          ElMessage.success('新增成功')
          setTimeout(()=>{
            window.location.reload()
          },1500)
 
        }else{
          ElMessage.error('新增失败,不能重复添加或超过100条列')
        }
      })
    })
 
}
 
const deleteColum = (id) => {
  ElMessageBox.confirm(
      '确认删除此列名?',
      'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        request.post(`/basicOtherMoney/deleteById/${id}`,).then(res=>{
          if (res.code==='200' && res.data!==false){
            ElMessage.success('删除成功')
            setTimeout(()=>{
              window.location.reload()
            },1500)
          }else{
            ElMessage.error('删除失败')
          }
        })
      })
 
}
 
</script>
 
<template>
  <div style="height: 100%;width: 100%">
    <vxe-grid
        @filter-change="filterChanged"
        ref="xGrid"
        max-height="350px"
        :width="'100%'"
        v-bind="gridOptions"
        v-on="gridEvents"
    >
      <template #default="{ row }">
        <span>{{ countAmount(row) }} </span>
      </template>
    </vxe-grid>
 
  </div>
 
 
</template>
 
<style scoped>
 
</style>