<!-- 标准零件选型-->
<template>
  <div>
    <vxe-toolbar>
      <template #buttons>
        <div class="ggdy-bts" v-if="pagetype !== 'gyskj'">
          <div class="l-button" @click="addRow">新增行</div>
          <div class="l-button" @click="deletRow">删除行</div>
        </div>
      </template>
    </vxe-toolbar>
    <vxe-table id="bzljtableid" ref='bzljtable' @checkbox-change="selectionChange" @checkbox-all="selectAllChange"
      max-height="400" keep-source :custom-config="{ storage: true }" border show-overflow :data="data.thebzljxzTableData"
      :column-config="{ resizable: true }" :sort-config="{ remote: false }"
      :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="200"
        align="left">
        <template #default="{ row }">
          <span>{{ row.bom_code }}</span>
        </template>
        <template #edit="{ row }">
          <el-select v-model="row.bom_code" v-el-select-loadmore="loadmore" :remote-method="remoteMethod"
            :loading="data.loading" clearable filterable remote placeholder="请选择物料代码"
            @change="bomchange($event, row.indextb)" data-popper-placement="bottom" :disabled="pagetype == 'gyskj'">
            <el-option v-for="item in data.bomlist" :key="item.bom_code" :label="item.bom_code" :value="item.bom_code"
              class="vxe-table--ignore-clear"></el-option>
          </el-select>
        </template>
      </vxe-column>
      <vxe-column field="bom_name" title="零件名称" width="200" align="left">
        <template #default="{ row }">
          <span>{{ row.bom_name }}</span>
        </template>
      </vxe-column>
      <vxe-column field="spec" title="零件规格型号" width="200" align="left">
        <template #default="{ row }">
          <span> {{ row.spec }}</span>
        </template>
      </vxe-column>
      <vxe-column field="molecule" title="用量（分子）" :edit-render="{ autofocus: '.vxe-input--inner' }" width="120"
        align="left">
        <template #edit="{ row }">
          <vxe-input v-model="row.molecule" type="integer" min='0' max="999"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="denominator" title="用量（分母）" :edit-render="{ autofocus: '.vxe-input--inner' }" width="180"
        align="left">
        <template #edit="{ row }">
          <vxe-input v-model="row.denominator" type="integer" min='0' max="999"></vxe-input>
        </template>
      </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, nextTick } from 'vue';
import { addbzljitem } from '../../utils/lc_data'// 获取人员
export default defineComponent({
  name: 'lcbzljtable',
  props: {
    bzljxzTableData: {
      type: Array,
      default: []
    },
    projectId: {
      type: Number,
      default: null
    },
    pagetype: {
      type: String,
      default: null
    }
  },
  emits: ["update:bzljxzTableData"],
  directives: {
    // 下拉框懒加载（el-select-loadmore是自定义的指令，使用时前面加v-）
    'el-select-loadmore': {
      // el:使用自定义指令的元素（下拉框），
      bind (el, binding) {
        // 下拉框下拉的框
        const SELECTWRAP_DOM = el.querySelector(
          '.el-select-dropdown .el-select-dropdown__wrap'
        );
        // 增加滚动监听，
        SELECTWRAP_DOM.addEventListener('scroll', function () {
          let { proxy } = getCurrentInstance()
          // scrollHeight:当前所有选项的高度
          // scrollTop:滚动的距离
          // clientHeight:下拉框的高度
          const condition = proxy.scrollHeight - proxy.scrollTop <= proxy.clientHeight;
          // 当滚动条滚动到最底下的时候执行接口加载下一页
          if (condition) {
            binding.value();
          }
        });
      }
    }
  },
  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({
      querys: '',// 远程搜索输入的内容
      selectLoading: false,//select加载
      stopLoading: false,// 最后一次加载之后，不再加载
      pageData: {// 懒加载相关参数，这里代表从第一条数据开始加载，一次加载十项
        page: 1,
        size: 50,
        bom_code: ''
      },
      dataKey: new Date().getTime(),
      thebzljxzTableData: [],
      enlargeImg: '',
      top: '',
      upLoadUrl: baseUrl + 'project/upload/file',
      upLoadQuery: { type: 'images' },
      bomlist: [],
      loading: false,
      bom_code: '',
      fileList: [], //上传的文件列表
      multipleSelection: [],// 字段选择显示选中结合
    })
    onMounted(() => {
      setTimeout(() => {
        data.thebzljxzTableData = props.bzljxzTableData
        listIDX()
        proxy.$refs.bzljtable.loadData(data.thebzljxzTableData)
      }, 1200)
    })
    // 重置下标
    function listIDX () {
      if (data.thebzljxzTableData && data.thebzljxzTableData.length > 0) {
        data.thebzljxzTableData.forEach((it, index) => {
          it.indextb = index
        })
      }
    }
    // 输入校验前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');
      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)
      //   }, 800)
      // } else {
      //   data.bomlist = []
      // }
      data.querys = query;// 保存搜索内容
      let querys = {};
      // 有内容则搜索
      if (query !== '') {
        querys = {
          page: 1,
          size: 50,
          bom_code: query
        };
      } else {
        // 没有内容搜10
        querys = {
          page: 1,
          size: 50,
          bom_code: query
        };
        // 重置懒加载
        data.stopLoading = false;
        data.pageData = {// 懒加载相关参数，这里代表从第一条数据开始加载，一次加载二十项
          page: 1,
          size: 50,
          bom_code: query
        };
      }
      // 调用接口
      data.selectLoading = true;
      proxy.$http.showLoading(false).get('project/data/bom', querys).then(r => {
        if (r.errno == 200) {
          data.bomlist = r.data.data
          proxy.$forceUpdate()
        } else {
          proxy.$message.error(r.errmsg)
        }
      }).finally(() => {
        data.selectLoading = false;
      })
    }
    // 物料选择
    function bomchange (val, index) {
      proxy.$http.showLoading(false).get('project/data/bom', { page: 1, size: 1, bom_code: val }).then(r => {
        if (r.errno == 200) {
          if (r.data.data && r.data.data.length > 0) {
            let item = r.data.data[0]
            data.thebzljxzTableData[index].bom_name = item.bom_name
            data.thebzljxzTableData[index].spec = item.spec
            data.thebzljxzTableData[index].id = item.id
          }

        } else {
          proxy.$message.error(r.errmsg)
        }
      })
    }
    // 获取标准零件下拉数据
    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
          proxy.$forceUpdate()
        } else {
          proxy.$message.error(r.errmsg)
        }
      })
    }
    function getTypeOption (querys) {
      if (data.querys != '' && data.querys != undefined) {
        return;
      }
      data.selectLoading = true;
      props.$http.showLoading(false).get('project/data/bom', querys)
        .then(r => {
          if (r.errno == 200) {
            data.bomlist = r.data.data
          }
          // 如果某次返回值是[]，表示已经加载完了，不必再加载
          if (data.bomlist.length == 0) {
            data.stopLoading = true;
            return;
          }
        }).finally(() => {
          this.selectLoading = false;
        });
    }
    // 新增行
    async function addRow () {
      data.thebzljxzTableData.unshift(JSON.parse(JSON.stringify(addbzljitem)))
      await proxy.$refs.bzljtable.loadData(data.thebzljxzTableData)
      await listIDX()
      // proxy.$refs.bzljtable.insert(addbzljitem) // 从前面新增
      context.emit('update:bzljxzTableData', data.thebzljxzTableData)
    }
    // 删除行
    function deletRow () {
      if (data.multipleSelection && data.multipleSelection.length > 0) {
        proxy.$confirm('是否确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          let newlist = JSON.parse(JSON.stringify(data.thebzljxzTableData))
          data.multipleSelection.forEach(it => {
            newlist.forEach((k, theindex) => {
              if (it.indextb == k.indextb) {
                newlist.splice(theindex, 1)
              }
            })
          })
          data.thebzljxzTableData = newlist
          listIDX()
          proxy.$refs.bzljtable.loadData(data.thebzljxzTableData ? data.thebzljxzTableData : [])
          context.emit('update:bzljxzTableData', data.thebzljxzTableData)
          proxy.$message({
            type: 'success',
            message: '删除成功',
          })
          data.multipleSelection = []
        }).catch(() => { })
      } else {
        proxy.$message({
          type: 'error',
          message: '请先选择你要删除的行',
        })
      }
    }
    function updtaddata (list) {
      data.thebzljxzTableData = list
      proxy.$refs.bzljtable.loadData(list ? list : [])
    }

    function loadmore () {
      if (!data.stopLoading) {
        data.pageData.page++;// 搜索下一页
        getTypeOption(data.pageData);//调用接口获取下拉框数据
      }
    }
    return {
      data,
      getbzBom,
      loadmore,
      checkNum,
      selectionChange,
      selectAllChange,
      enlarge,
      enlargeOut,
      remoteMethod,
      updtaddata,
      getTypeOption,
      bomchange,
      addRow,
      deletRow,
      listIDX
    };
  },
});
</script>

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