<!-- Bom-->
<template>
  <div>
    <vxe-toolbar>
      <template #buttons>
        <div class="ggdy-bts">
          <div class="l-button" @click="addRow">新增行</div>
          <div class="l-button" @click="deletRow">删除行</div>
        </div>
      </template>
    </vxe-toolbar>
    <vxe-table id="Bomtableid" ref='Bomtable' @checkbox-change="selectionChange" @checkbox-all="selectAllChange"
      max-height="600" keep-source :custom-config="{ storage: true }" border show-overflow :data="data.theBomxzTableData"
      :column-config="{ resizable: true }" :sort-config="{ remote: false }" :footer-method="footerMethod" show-footer
      :merge-footer-items="data.mergeFooterItems"
      :edit-config="{ trigger: 'click', mode: 'cell', showUpdateStatus: true, showInsertStatus: true }" class="ggdycss">
      <vxe-column type="checkbox" width="50" align="center"></vxe-column>
      <vxe-column type="seq" width="50" title="序号" align="center"></vxe-column>
      <vxe-column field="bom_code" title="物料编码" :edit-render="{ autofocus: '.vxe-input--inner' }" width="250"
        align="left">
        <template #edit="{ row }">
          <vxe-input v-model="row.bom_code" :maxlenth="200"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="bom_name" title="物料名称" :edit-render="{ autofocus: '.vxe-input--inner' }" width="250"
        align="left">
        <template #edit="{ row }">
          <vxe-input v-model="row.bom_name" :maxlenth="200"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="bom_desc" title="物料规格型号" :edit-render="{ autofocus: '.vxe-input--inner' }" width="250"
        align="left">
        <template #edit="{ row }">
          <vxe-input v-model="row.bom_desc" :maxlenth="200"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="molecule" title="分子" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100" align="left">
        <template #edit="{ row }">
          <vxe-input v-model="row.molecule" min='1' type="integer"
            @blur="textinput($event, row.indextb, 'molecule')"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="denominator" title="分母" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100"
        align="left">
        <template #edit="{ row }">
          <vxe-input v-model="row.denominator" min='1' type="integer"
            @blur="textinput($event, row.indextb, 'denominator')"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="price" title="单价" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100" align="left">
        <template #edit="{ row }">
          <vxe-input v-model="row.price" type="number" min='0'
            @blur="checkNum($event, row.indextb, 'price', 8, 4)"></vxe-input>
        </template></vxe-column>
      <vxe-column field="total_price" title="总价" width="110" align="left"> </vxe-column>
      <vxe-column field="remark" title="备注" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
        <template #edit="{ row }">
          <vxe-input v-model.trim="row.remark" :maxlenth="200" />
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>
<script>
import { defineComponent, reactive, getCurrentInstance, onMounted, computed, watch } from 'vue';
import { addBomitem } from '../../utils/lc_data'// 获取人员
export default defineComponent({
  name: 'lcBomtable',
  props: {
    BomxzTableData: {
      type: Array,
      default: []
    },
    projectId: {
      type: Number,
      default: null
    }
  },
  emits: ["update:BomxzTableData"],
  setup (props, context) {
    const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
    const baseUrl = process.env.VUE_APP_API_BASEURL + apiVersion + '/'
    let { proxy } = getCurrentInstance()
    const data = reactive({
      dataKey: new Date().getTime(),
      theBomxzTableData: [],
      enlargeImg: '',
      top: '',
      upLoadUrl: baseUrl + 'project/upload/file',
      upLoadQuery: { type: 'images' },
      bomlist: [],
      loading: false,
      bom_code: '',
      mergeFooterItems: [],
      fileList: [], //上传的文件列表
      multipleSelection: [],// 字段选择显示选中结合
    })
    onMounted(() => {
      setTimeout(() => {
        data.theBomxzTableData = []
        data.theBomxzTableData = props.BomxzTableData ? props.BomxzTableData : []
        listIDX()
        proxy.$refs.Bomtable.loadData(data.theBomxzTableData)
        data.mergeFooterItems = [{ row: 0, col: 1, rowspan: 1, colspan: 5 }]
      }, 1000)
      // 标准零件的下拉交互还没
    })
    watch(() => props.BomxzTableData, (val, preVal) => {
      //val为修改后的值,preVal为修改前的值
      data.theBomxzTableData = val
    }, {
      immediate: true,
      deep: true,
    })
    // 求合
    const sumNum = (list, field) => {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count ? countsetNums83(count, 8, 4) : 0
    }
    // 表尾合计
    const footerMethod = ({ columns, data }) => {
      return [
        columns.map((column, columnIndex) => {
          let arr = []
          if (columnIndex === 0) {
            return '合计'
          }
          ['price', 'total_price'].forEach(el => {
            arr.push(el)
          });
          if (arr.includes(column.property)) {
            return sumNum(data, column.property)
          }
          return null
        })
      ]
    }
    function countsetNums83 (numvValue, integerMax, digits) {
      if (numvValue) {
        let reg;
        numvValue = numvValue + ''
        if (integerMax) {
          reg = new RegExp(`^(\\-)*(\\d{${integerMax}}).*$`); // 通过 integerMax 限制整数位,
          if (!numvValue.includes('.')) {
            numvValue = numvValue.replace(reg, '$1$2');
          }
        }
        if (digits) {
          reg = new RegExp(`^(-)*(\\d*)\\.(\\d{0,${digits}}).*$`); // 通过 digits 限制小数位,
          numvValue = numvValue.replace(reg, '$1$2.$3');
        }
        if (integerMax && digits) {
          reg = new RegExp(`^(-)*(\\d{${integerMax}}).*\\.(\\d{0,${digits}}).*$`);
        } else {
          reg = new RegExp(`^(-)*(\\d*).*\\.(\\d{0,2}).*$`);
        }
        numvValue = numvValue.replace(reg, '$1$2.$3');
        context.emit('update:BomxzTableData', data.theBomxzTableData)
        return parseFloat(numvValue) ? Math.round(parseFloat(numvValue) * Math.pow(10, 3)) / Math.pow(10, 3) : 0
      }
    }
    function setNums83 (numvValue, integerMax, digits, rowIndex) {
      if (numvValue) {
        let reg;
        numvValue = numvValue + ''
        if (integerMax) {
          reg = new RegExp(`^(\\-)*(\\d{${integerMax}}).*$`); // 通过 integerMax 限制整数位,
          if (!numvValue.includes('.')) {
            numvValue = numvValue.replace(reg, '$1$2');
          }
        }
        if (digits) {
          reg = new RegExp(`^(-)*(\\d*)\\.(\\d{0,${digits}}).*$`); // 通过 digits 限制小数位,
          numvValue = numvValue.replace(reg, '$1$2.$3');
        }
        if (integerMax && digits) {
          reg = new RegExp(`^(-)*(\\d{${integerMax}}).*\\.(\\d{0,${digits}}).*$`);
        } else {
          reg = new RegExp(`^(-)*(\\d*).*\\.(\\d{0,2}).*$`);
        }
        numvValue = numvValue.replace(reg, '$1$2.$3');
        if ((rowIndex || rowIndex == 0) && rowIndex != '') {
          data.theBomxzTableData[rowIndex].total_price = parseFloat(numvValue).toFixed(3)
        }
        // return parseFloat(numvValue) ? Math.round(parseFloat(numvValue) * Math.pow(10, 3)) / Math.pow(10, 3) : 0    
        context.emit('update:BomxzTableData', data.theBomxzTableData)
        return parseFloat(numvValue) ? Math.round(parseFloat(numvValue) * Math.pow(10, 3)) / Math.pow(10, 3) : 0
      } else {
        if ((rowIndex || rowIndex == 0) && rowIndex != '') {
          data.theBomxzTableData[rowIndex].total_price = 0
        }
        return 0
      }
    }
    // 输入校验前8侯三
    function checkNum (event, index, key, integerMax, digits) {
      let reg;
      if (integerMax) {
        reg = new RegExp(`^(\\-)*(\\d{${integerMax}}).*$`); // 通过 integerMax 限制整数位,
        if (!event.value.includes('.')) {
          event.value = event.value.replace(reg, '$1$2');
        }
      }
      if (digits) {
        reg = new RegExp(`^(-)*(\\d*)\\.(\\d{0,${digits}}).*$`); // 通过 digits 限制小数位,
        event.value = event.value.replace(reg, '$1$2.$3');
      }
      if (integerMax && digits) {
        reg = new RegExp(`^(-)*(\\d{${integerMax}}).*\\.(\\d{0,${digits}}).*$`);
      } else {
        reg = new RegExp(`^(-)*(\\d*).*\\.(\\d{0,2}).*$`);
      }
      event.value = event.value.replace(reg, '$1$2.$3');
      if (event.value) (
        data.theBomxzTableData[index][key] = parseFloat(event.value).toFixed(3)
      )
      data.theBomxzTableData[index].total_price = setNums83((data.theBomxzTableData[index].molecule / data.theBomxzTableData[index].denominator) * data.theBomxzTableData[index].price, 8, 4, index)
      context.emit('update:BomxzTableData', data.theBomxzTableData)
      // return event.value
    }
    // 选中单行
    function selectionChange (value) {
      data.multipleSelection = value.records
    }
    // 选中全部
    function selectAllChange (value) {
      data.multipleSelection = value.records
    }
    function enlarge (e, row) {
      data.enlargeImg = row.image
      row.enlargeImgShow = true
      data.top = 'top:' + e.clientY + 'px'
    }
    function enlargeOut (row) {
      row.enlargeImgShow = false
      data.enlargeImg = ''
    }
    function remoteMethod (query) {
      if (query !== '') {
        data.loading = true
        setTimeout(() => {
          data.loading = false
          getbzBom(query)
        }, 300)
      } else {
        data.bomlist = []
      }
    }
    function bomchange (val) { }
    // 获取标准零件下拉数据
    function getbzBom (bom_code) {
      proxy.$http.showLoading(false).get('project/data/bom', { page: 1, size: 6000, bom_code: bom_code }).then(r => {
        if (r.errno == 200) {
          data.bomlist = r.data.data
        } else {
          proxy.$message.error(r.errmsg)
        }
      })
    }
    // 重置下标
    function listIDX () {
      if (data.theBomxzTableData && data.theBomxzTableData.length > 0) {
        data.theBomxzTableData.forEach((it, index) => {
          it.indextb = index
        })
      }
    }
    // 新增行
    async function addRow () {
      data.theBomxzTableData.unshift(JSON.parse(JSON.stringify(addBomitem)))
      await proxy.$refs.Bomtable.loadData(data.theBomxzTableData)
      await listIDX()
      context.emit('update:BomxzTableData', data.theBomxzTableData)
    }
    // 删除行
    function deletRow () {
      if (data.multipleSelection && data.multipleSelection.length > 0) {
        proxy.$confirm('是否确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          let newlist = JSON.parse(JSON.stringify(data.theBomxzTableData))
          data.multipleSelection.forEach(it => {
            newlist.forEach((k, theindex) => {
              if (it.indextb == k.indextb) {
                newlist.splice(theindex, 1)
              }
            })
          })
          data.theBomxzTableData = newlist
          listIDX()
          proxy.$refs.Bomtable.loadData(data.theBomxzTableData)
          context.emit('update:BomxzTableData', data.theBomxzTableData)
          proxy.$message({
            type: 'success',
            message: '删除成功',
          })
        }).catch(() => { })
      } else {
        proxy.$message({
          type: 'error',
          message: '请先选择你要删除的行',
        })
      }
    }
    function textinput (event, index, field) {
      data.theBomxzTableData[index][field] = event.value
      data.theBomxzTableData[index].total_price = setNums83((data.theBomxzTableData[index].molecule / data.theBomxzTableData[index].denominator) * data.theBomxzTableData[index].price, 8, 4, index)
      proxy.$refs.Bomtable.loadData(data.theBomxzTableData)
      context.emit('update:BomxzTableData', data.theBomxzTableData)
    }
    return {
      data,
      getbzBom,
      checkNum,
      setNums83,
      textinput,
      countsetNums83,
      selectionChange,
      selectAllChange,
      enlarge,
      enlargeOut,
      remoteMethod,
      bomchange,
      addRow,
      deletRow,
      footerMethod,
      sumNum,
      listIDX
    };
  },
});
</script>

<style lang="scss" scoped>
@import '../../assets/style/lc.scss';
</style>
