<template>
  <div class="sale-details-container order-mc-bg main-container" :style="{height:heightNum + 'px!important'}">
    <div class="sale-details-btn-group">
      <toolBtn @actionhandel="actionhandel" :btnType="btnType" :isDisable="isDisableTop"></toolBtn>
    </div>
    <div class="sale-details-base-info">
      <div class="search-group">
        <el-form :inline="true">
          <el-row :gutter="2">
            <el-col :span="4">
              <el-form-item label="组织" class="search-group-one">
                <el-select v-model="searchGroup.orgId" placeholder>
                  <el-option
                    v-for="item in orgList"
                    :key="item.id"
                    :label="item.name"
                    @click="againRequest($event,item.id,'orgId')"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="物料编码">
                <el-select
                  v-model="searchGroup.materialId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="(query)=>{matterCodeChange(query,'materialId')}"
                >
                  <el-option
                    v-for="item in matterallCodelist"
                    :key="item.id"
                    :label="item.number"
                    :value="item.id"
                    @click="selectMatter(item.id);againRequest($event,item.id,'materialId',item.bomId);"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" v-if="type === 'just'">
              <el-form-item label="BOM版本">
                <el-select v-model="searchGroup.bomId" placeholder>
                  <el-option
                    v-for="item in bomVersionList"
                    :key="item.id"
                    :label="item.name"
                    @click="againRequest($event,item.id,'bomId')"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label="不显示失效物料" class="search-group-invalid">
                <el-checkbox
                  v-model="searchGroup.noShowEffect"
                  key="noShowEffect"
                  @click="againRequest($event,searchGroup.noShowEffect,'noShowEffect')"
                ></el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label="不显示供应商承担物料" class="search-group-supplier">
                <el-checkbox
                  v-model="searchGroup.noShowSupplier"
                  key="noShowSupplier"
                  @click="againRequest($event,searchGroup.noShowSupplier,'noShowSupplier')"
                ></el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- ref="bomInfoTree" -->
      <div class="tableData">
        <vxe-table
          ref="xTable"
          :key="isRender"
          show-overflow
          :row-config="{isHover: true, useKey: true}"
          :column-config="{resizable: true}"
          :tree-config="{transform: true, rowField: 'id', parentField: 'parentId', line: true,expandAll:true}"
          :data="tableData"
          v-loading="isLoading"
          :height="tableHeight"
          :scroll-y="{enabled: false}"
        >
          <vxe-column field="level" title="BOM层级" tree-node :width="200" fixed="left"></vxe-column>
          <vxe-column field="materialNumber" title="物料编码" :width="200"></vxe-column>
          <vxe-column field="specification" title="规格型号" :width="200"></vxe-column>
          <vxe-column field="materialName" title="物料名称" :width="200"></vxe-column>
          <vxe-column v-if="this.$route.query.type === 'just'" field="materialProperty" title="物料属性" :width="200"></vxe-column>
          <vxe-column v-else field="unitName" title="父项单位" :width="200"></vxe-column>
          <vxe-column field="subUnitName" :title="this.$route.query.type === 'just' ? '子单位' : '子项子单位'" :width="200"></vxe-column>
          <vxe-column field="numerator" title="用量:分子" :width="200"></vxe-column>
          <vxe-column field="denominator" title="用量:分母" :width="200"></vxe-column>
          <vxe-column field="ffixscrapqty" title="损耗率%" :width="200"></vxe-column>
          <vxe-column field="isEffect" title="是否失效" :width="200">
            <template #default="{ row }">
              <span>{{ row.id != -1 && row.id != 0 ? row.isEffect ? '是' : '否' : '' }}</span>
            </template>
          </vxe-column>
          <vxe-column field="remark" title="位置号/模号/备注" :width="200"></vxe-column>
          <vxe-column field="isKeyComponent" title="是否关键件" :width="200">
            <template #default="{ row }">
              <span>{{ row.id != -1 && row.id != 0 ? row.isKeyComponent ? '是' : '否' : '' }}</span>
            </template>
          </vxe-column>
          <vxe-column field="materialBear" title="物料承担方" :width="200"></vxe-column>
          <vxe-column field="bomVersion" title="BOM版本" :width="200"></vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'BomJustCheckbackCheck',
  data() {
    return {
      isDisableTop: false,
      heightNum: 0,
      tableHeight: 0,
      isRender: 0,
      orgList: [], // 供应组织
      matterallCodelist: [], // 物料编码
      bomVersionList: [],
      isLoading: false,
      searchGroup: {
        orgId: '',
        materialId: '',
        bomId: null,
        noShowSupplier: true,
        noShowEffect: true
      },
      // 's-p-t-g8', 
      btnType: [
        'add',
        'out-export',
        'push-order',
        'copy',
        'submit',
        'revoke',
        'audit',
        'de-approval',
        'delete',
        'push-down',
        'operation',
        'query',
        'save',
        'split-order',
        'print-aterial-list',
        'finish',
        'close-case',
        'de-excute-start',
        'de-excute-finish',
        'de-close',
        's-p-t-g1',
        's-p-t-g2',
        's-p-t-g3',
        's-p-t-g4',
        's-p-t-g7',
        'close'
      ], // 不需要显示的顶部按钮类型
      isDisable: false,
      isEdit: false, //是否可编辑
      tableData: [],
      type: '',
      excelData:[]
    }
  },
  computed: {
    ...mapState({
      // 获取当前组织
      orgId: state => (state && state.user ? state.user.orgId : null),
      orgIdArr: state => (state ? state.user.orgIdArr : null)
    })
  },
  watch: {},
  created() {
    this.type = this.$route.query.type
    this.heightNum = document.documentElement.clientHeight - (40 + 30 + 16 + 16)
    this.tableHeight = document.documentElement.clientHeight - (40 + 30 + 24 + 41 + 28 + 24 + 12 + 16)
    this.orgList = this.orgIdArr
    this.Init(this.$route.query.id, this.$route.query.type, this.$store.state.org.orgId, this.$route.query.name)
    if (this.$route.query.type === 'just') {
      this.$topNavTagRename('BOM正查')
    }
    if (this.$route.query.type === 'back') {
      this.$topNavTagRename('BOM反查')
    }
  },
  methods: {
    Init(id, type, orgId, name) {
      // 组织 物料编码 携带值
      this.searchGroup.orgId = orgId
      this.matterCodeChange(name, 'init')
      this.bomJustBackCheck(id, type, orgId,null,true,true)
    },
    // BOM正查反查
    bomJustBackCheck(id, type, orgId, bomId, noShowSupplier, noShowEffect) {
      let pathName = type === 'just' ? 'MaterialBom/MaterialBomSearch' : 'MaterialBom/MaterialBomSearchInverted'
      if(id){
        this.isLoading = true
        this.$http
          .post(pathName, {
            materialId: id,
            orgId: orgId,
            bomId: bomId ? bomId : null,
            noShowEffect: noShowEffect ? noShowEffect : false,
            noShowSupplier: noShowSupplier ? noShowSupplier : false
          })
          .then(res => {
            if (res.status === 200) {
              this.tableData = res.data
              this.isRender++
              // this.$nextTick(() => this.$refs.bomInfoTree.setAllTreeExpand(true))
              this.isLoading = false
            }
          })
      }
      
    },
    // 物料模糊匹配
    matterCodeChange(val, init) {
      let id = this.$store.state.org.orgId
      let key = 'Number'
      this.$http
        .showLoading(false)
        .post('SysConfig/GetMaterial', { name: val, file: key, orgId: id })
        .then(res => {
          if (res.status === 200) {
            this.matterallCodelist = res.data
            // 第一次进入携带获取的值 物料编码 BOM版本
            if (init && init === 'init') {
              let result = this.matterallCodelist.filter(it => {
                return it.id == this.$route.query.id
              })
              if(result[0]){
                this.searchGroup.materialId = result[0].id
                this.selectMatter(this.searchGroup.materialId)
                this.searchGroup.bomId = result[0].bomId
              }
            }
          }
        })
    },
    // 用户切换选择物料,获取BOM版本
    selectMatter(val) {
      let result = this.matterallCodelist.filter(it => it.id === val)
      if (result) {
        this.bomVersionList = result[0].bomList
      }
    },
    // 选择切换重新获取BOM信息
    againRequest(e, val, key, bomId) {
      // 切换物料编码 获取BOM版本
      if (key === 'materialId') {
        this.searchGroup.bomId = bomId
      }
      if (key === 'noShowEffect' || key === 'noShowSupplier') {
        // 复选框 阻止冒泡事件 只让checkbox触发一次
        if (e.target.tagName !== 'INPUT') return
        this.searchGroup[key] = !val
      } else {
        this.searchGroup[key] = val
      }
      this.bomJustBackCheckCom()
    },
    // 顶部公共按钮操作
    actionhandel(type) {
      // 防重
      this.isDisableTop = true
      setTimeout(() => {
        this.isDisableTop = false
      }, 2000)
      if (type == 'refresh') {
        this.bomJustBackCheckCom()
      }
      if (type == 'out-export'){
        this.exportExcel()
      }
    },
    // 正反查请求
    bomJustBackCheckCom() {
      this.bomJustBackCheck(
        this.searchGroup.materialId,
        this.$route.query.type,
        this.searchGroup.orgId,
        this.searchGroup.bomId,
        this.searchGroup.noShowSupplier,
        this.searchGroup.noShowEffect
      )
    },
    exportExcel(){
      let tempList = this.matterallCodelist.filter(it => it.id === this.searchGroup.materialId)
      let firstName = tempList.length > 0 ? tempList[0].number : '物料'
      let lastName = this.$route.query.type == 'just' ? '正查' : '反查'
      this.excelData = []
      import('@/vendor/Export2Excel').then(excel => {
        let changeStringHeader = this.$route.query.type == 'just' ? '物料属性' : '父项单位'
        let changeStringValue = this.$route.query.type == 'just' ? 'materialProperty' : 'unitName'
        let changeStringUnitName = this.$route.query.type == 'just' ? '子单位' : '子项子单位'
        const tHeader = ['BOM层级','物料编码','规格型号','物料名称',changeStringHeader,changeStringUnitName,'用量：分子','用量：分母','损耗率%','是否失效','位置号/模号/备注','是否关键件','物料承担方','BOM版本'] //这边放excel的头部信息  
        const filterVal = ['level','materialNumber','specification','materialName',changeStringValue,'subUnitName','numerator','denominator','ffixscrapqty','isEffect','remark','isKeyComponent','materialBear','bomVersion']//这边是excel头部信息对应的字段  
        const list = this.tableData
        this.formatJson(filterVal, list)
        this.excelData.forEach((el,ind) => {
          this.excelData[ind].forEach((ele,indx) => {
            if(ind == 0){
              this.excelData[ind][indx] = this.excelData[ind][indx] || this.excelData[ind][indx] == 0 ? this.excelData[ind][indx] : null
              this.excelData[ind][indx] = this.excelData[ind][indx] + '' == 'false' ? null : this.excelData[ind][indx]
            }else if( indx == 9 || indx == 11){
              this.excelData[ind][indx] = this.excelData[ind][indx] ? '是' : '否'
            }
          });
        });
        excel.export_json_to_excel({
          header: tHeader,
          data: this.excelData,
          filename: firstName + lastName,
          autoWidth: true
        })
      })
    },
    formatJson(filterVal, jsonData) {
      jsonData.map((v, index) => {
        let tempArr = []
        filterVal.map(j => {
          if (j != 'children') {
            if (j === 'date') {
              tempArr.push(v[j].replace(/T/g, ' '))
            } else {
              tempArr.push(v[j])
            }
          } else {
            //如果有children进行递归
            this.formatJson(filterVal, v.children)
          }
        });
        this.excelData.push(tempArr)
      });
    },
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/style/saleOrder/saleOrderCommon.scss';
@import '@/assets/style/saleOrder/orderDetails.scss';
@import '@/assets/style/materialBom/bom.scss';
</style>