<!--物料分类新增/编辑 -->
<template>
  <div :style="{height:heightNum + 'px!important'}" class="sale-details-container order-mc-bg main-container">
    <div class="sale-details-btn-group">
      <!-- 顶部按钮 -->
      <toolBtn :btnType="btnType" @actionhandel="actionhandel"></toolBtn>
    </div>
    <div class="sale-details-base-info">
      <el-tabs style="margin-bottom:8px;" type="border-card">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息">
          <div class="base-info-form-box">
            <el-form :model="pagefromData" label-width="80px" ref="form">
              <el-row :gutter="10" style="margin-bottom: 20px;">
                <el-col :span="4">
                  <el-form-item :required="true" class="Iisshow" label="分类编码">
                    <el-input
                      :disabled="pagefromData.id ? true :false"
                      :maxlength="6"
                      onkeyup="value=value.replace(/[^\w\-]/g,'')"
                      placeholder="分类编码"
                      v-model.trim="pagefromData.number"
                    ></el-input>
                    <div :data-clipboard-text="pagefromData.number" @click="saleOrderCopy" class="copyBtn">
                      <i class="el-icon-document-copy" />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item :required="true" class="item-bt-s Iisshow" label="分类名称">
                    <el-input :maxlength="255" v-model.trim="pagefromData.name"></el-input>
                    <div :data-clipboard-text="pagefromData.name" @click="saleOrderCopy" class="copyBtn">
                      <i class="el-icon-document-copy" />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="4">
                  <el-form-item class="item-bt-s" label="父级分类名称">
                    <el-select
                      :loading="loading"
                      :remote-method="getDropDownAddOrEdit"
                      @change="parentClassChange"
                      clearable
                      filterable
                      placeholder="请输入分类编码/名称"
                      remote
                      reserve-keyword
                      v-model="pagefromData.parentId"
                    >
                      <el-option
                        :key="index"
                        :label="item.number + '/' + item.name "
                        :value="item.id"
                        class="f-12"
                        v-for="(item,index) in dropDownList"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item class="Iisshow" label="父级分类等级">
                    <el-input :maxlength="255" disabled placeholder="父项分类编码获取" v-model="grade"></el-input>
                    <div :data-clipboard-text="grade" @click="saleOrderCopy" class="copyBtn">
                      <i class="el-icon-document-copy" />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 明细信息 -->
    <div class="sale-details-tell-info">
      <div class="tell-info-row-title">
        <h3>明细信息</h3>
        <div class="long-line-bx">
          <div class="long-line"></div>
        </div>
      </div>
      <!-- 明细工具栏 -->
      <!-- <div :class="calendarFlag == true?'img-onlyRead':''" class="tell-info-button-group"> -->
      <!-- @copyRow="bottomCopyRow"  
      @copyCellcolumn="copyCellcolumn" -->
      <div class="tell-info-button-group">
        <DetailsOperation
          :detailBtn="detailBtn"
          :deviationSelectArr="selectRowIndexArr"
          @deleteRow="selectDeleteRow"
          @insertObj="getInsertInfo"
        ></DetailsOperation>
      </div>
      <!-- 表格信息-->
      <div class="tell-info-table">
        <el-table
          :cell-class-name="tableCellClassName"
          :data="pagefromData.chinds"
          :header-cell-class-name="mustAfter"
          :header-cell-style="headerBg"
          @cell-click="getRowCol"
          @select="selectRow"
          @select-all="selectRowAll"
          @selection-change="handleSelectionChange"
          border
          max-height="400"
          ref="multipleTable"
          style="width: 50%;font-size:12px;"
        >
          <el-table-column align="center" fixed type="selection" width="40" />
          <el-table-column prop="number">
            <template #header>
              <span class="iconfont icon-bianji1 iconfont-mg"></span>子项分类编码
            </template>
            <template #default="scope">
              <el-input
                :id="'number'+scope.$index"
                :maxlength="6"
                onkeyup="value=value.replace(/[^\w\-]/g,'')"
                placeholder="子项分类编码"
                style="wdith:200px"
                v-if="scope.row.isnumbershow"
                v-model.trim="scope.row.number"
              ></el-input>
              <span v-else>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name">
            <template #header>
              <span class="iconfont icon-bianji1 iconfont-mg"></span>子项分类名称
            </template>
            <template #default="scope">
              <el-input
                :disabled="parseInt(infoleve)  === 4"
                :id="'name'+scope.$index"
                :maxlength="255"
                placeholder="请输入"
                v-if="scope.row.isnameshow"
                v-model.trim="scope.row.name"
              ></el-input>
              <span v-else>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { orderCopy,bottomAddRow } from '@/utils/takeMethods.js'
export default {
  name: 'AddClassificationSet',
  data() {
    return {
      detailBtn: ['copy', 'allIn'],
      btnType: ['save', 'copy', 'revoke', 's-p-t-g3', 's-p-t-g4', 's-p-t-g5'],
      dropDownList: [], // 父级分类名称下拉
      infoleve: '', //基本信息的父级分类等级
      grade: '',
      detailsleve: '', // 明细里面的等级
      // 明细下级分类
      pagechinds: {
        id: 0, // id
        seq: 0, // 序号
        number: '', // 编码
        name: null // 名称
      },
      loading: false,
      pagefromData: {
        id: 0, // 单据的id
        parentId: null, //上级Id
        name: '', // 名称
        number: '', // 编码
        level: null, //级别 1 2 3 默认是1级
        chinds: []
      },
      pageAction: this.$route.query && this.$route.query.type ? this.$route.query.type : '', // 判断到该页面的操作状态
      addRow: {},
      selectRowIndexArr: [],
      selectRowIndex: '', // 当前 选择行
      heightNum: 0
    }
  },
  computed: {
    ...mapState({
      orgIdArr: state => (state ? state.user.orgIdArr : null)
    })
  },
  created() {
    this.heightNum = document.documentElement.clientHeight - (40 + 30 + 16 + 16)
    this.actionType = this.$route.query.type
    this.$route.query.type === 'add' ? this.$topNavTagRename('新增物料分类') : this.$topNavTagRename('编辑物料分类')
    this.addRow = JSON.parse(JSON.stringify(this.pagechinds))
    this.pagefromData.chinds = [JSON.parse(JSON.stringify(this.pagechinds))]
    this.Init()
  },
  mounted() {},
  methods: {
    // 星星--头部必填ico显示
    mustAfter(obj) {
      let arry = [1, 2]
      if (arry.indexOf(obj.columnIndex) !== -1) {
        return 'must'
      }
    },
    Init() {
      this.InItEditorCopy()
    },
    // 初始化--编辑或者详情
    InItEditorCopy() {
      // 如果是复制，编辑，查看--过来的新增订单
      if (this.$route.query && this.$route.query.type !== 'add' && this.$route.query.productId) {
        this.getProductInfo(this.$route.query.productId)
      }
    },
    // 获取物料分类详情
    getProductInfo(id) {
      this.$http.get('MaterialGroup/Get/' + id).then(res => {
        if (res.status === 200) {
          this.pagefromData = JSON.parse(JSON.stringify(res.data))
          this.infoleve = parseInt(res.data.level) - 1
          if (this.infoleve) {
            this.grade = this.infoleve + '级'
          } else {
            this.grade = ''
          }
          console.log(res.data)
          this.getDropDownAddOrEdit(res.data.parentName)
          if (res.data.chinds && res.data.chinds.length === 0) {
            this.pagefromData.chinds = [JSON.parse(JSON.stringify(this.pagechinds))]
            this.pagefromData.chinds.forEach((it, index) => {
              this.pagefromData.chinds[index].seq = index
            })
          }
        }
      })
    },
    // 父级名称下拉选择监听
    parentClassChange(id) {
      if (id) {
        let itarry = this.dropDownList.filter(it => {
          return it.id === id
        })[0]
        this.infoleve = parseInt(itarry.level)
        if (this.infoleve) {
          this.grade = this.infoleve + '级'
        } else {
          this.grade = ''
        }
      } else {
        this.infoleve = null
      }
    },
    //物料分类新增和编辑页下拉列表
    getDropDownAddOrEdit(val) {
      console.log(val)
      let newVal = encodeURIComponent(val)
      const _this = this
      if (val !== '') {
        _this.loading = true
        setTimeout(() => {
          _this.loading = false
          this.$http.get('MaterialGroup/GetDropDownAddOrEdit/' + newVal).then(res => {
            _this.dropDownList = res.data
            if (_this.$route.query.productId) {
              _this.dropDownList.forEach((it, index) => {
                if (it.id === parseInt(_this.$route.query.productId)) {
                  _this.dropDownList[index].disabled = true
                }
              })
            }
            console.log('物料分类新增和编辑页下拉列表', res, _this.dropDownList, _this.$route.query.productId)
          })
        }, 200)
      } else {
        this.dropDownList = []
      }
    },
    //顶部按钮操作栏
    actionhandel(type) {
      // 点击新增
      if (type === 'add') {
        this.$router.push({ name: 'AddClassificationSet', query: { type: 'add', id: '', sjtag: Math.random() * 36 } })
      }
      //点击提交
      if (type === 'submit') {
        this.submitPageData()
      }
    },
    // 提交
    submitPageData() {
      let data = {
        id: this.pagefromData.id, // 单据的id
        number: this.pagefromData.number,
        parentId: this.pagefromData.parentId, //上级Id
        name: this.pagefromData.name, // 名称
        level: this.pagefromData.parentId ? parseInt(this.infoleve) + 1 : 1, //级别 1 2 3 默认是1级
        chinds: []
      }
      if (data.level === 4) {
        data.chinds = []
      } else {
        this.pagefromData.chinds.forEach((it, index) => {
          if (it.name || it.name === 0) {
            data.chinds.push({
              id: it.id, // id
              seq: index, // 序号
              number: it.number, // 编码
              level: this.pagefromData.parentId ? parseInt(this.infoleve) + 2 : 2,
              name: it.name // 名称
            })
          }
        })
        if (this.pagefromData.chinds && this.pagefromData.chinds.length > 0 && !this.pagefromData.chinds[0].name) {
          data.chinds = []
        }
      }
      this.$http.post('MaterialGroup/Commit', data).then(res => {
        if (res.status === 200) {
          this.pagefromData = JSON.parse(JSON.stringify(res.data))
          if (res.data.chinds && res.data.chinds.length === 0) {
            this.pagefromData.chinds = [JSON.parse(JSON.stringify(this.pagechinds))]
          }
          this.$message.success({ message: '提交成功', showClose: true })
          this.$route.meta.title = '编辑物料分类'
        }
      })
    },
    // 失焦处理
    selectBlur(){
      this.pagefromData.chinds.forEach(el => {
        el.isnumbershow = false,
        el.isnameshow = false
      })
    },
    // 表头
    headerBg({ rowIndex, columnIndex }) {},
    arrangeData() {
      let newDetails = this.pagefromData.chinds.map((v, index) => {
        return { ...v, seq: index }
      })
      this.pagefromData.chinds = newDetails
      if (this.pagefromData.chinds) {
        let newDetails = this.pagefromData.chinds.map((v, index) => {
          return { ...v, seq: index }
        })
        this.pagefromData.chinds = newDetails
        // 清空明细选中
        this.$refs.multipleTable.clearSelection()
        this.selectRowIndexArr = []
      }
    },
    // 插入的行
    getInsertInfo() {
      this.pagefromData.chinds = bottomAddRow(this.pagefromData.chinds,JSON.parse(JSON.stringify(this.addRow)))
      this.$nextTick(()=>{
        this.$refs.multipleTable.$refs.bodyWrapper.scrollTop = this.$refs.multipleTable.$refs.bodyWrapper.scrollHeight
      })
      this.selectBlur()
      // if (data.insertTopVal != 0) {
      //   for (let i = 0; i < parseInt(data.insertTopVal); i++) {
      //     this.pagefromData.chinds.splice(this.selectRowIndex, 0, JSON.parse(JSON.stringify(this.addRow)))
      //     this.selectRowIndex = parseInt(this.selectRowIndex) + 1
      //   }
      // }
      // if (parseInt(data.insertBottomVal) != 0) {
      //   for (let i = 0; i < data.insertBottomVal; i++) {
      //     var num = this.selectRowIndex + 1
      //     this.pagefromData.chinds.splice(num, 0, JSON.parse(JSON.stringify(this.addRow)))
      //   }
      // }
      this.arrangeData()
    },
    // 向下复制行
    // bottomCopyRow(data) {
    //   // 判断行数
    //   if (this.selectRowIndexArr.length == 1) {
    //     const tableArr = JSON.parse(JSON.stringify(this.pagefromData.chinds[this.selectRowIndex]))
    //     tableArr.id = 0
    //     var insertNum = this.selectRowIndex + 1
    //     this.pagefromData.chinds.splice(insertNum, 0, tableArr)
    //     this.arrangeData()
    //   } else {
    //     this.$message.error({ message: '请勾选一条行,在操作', showClose: true })
    //   }
    // },
    // 删除行
    selectDeleteRow(data) {
      if (this.selectRowIndexArr.length === this.pagefromData.chinds.length) {
        this.$message.error({ message: '至少保留一条设置项', showClose: true })
        return
      }
      if (this.selectRowIndexArr.length === 0) {
        this.$message.error({ message: '请勾选删除', showClose: true })
        return
      }
      // 不能为空
      if (this.pagefromData.chinds.length > 1 && this.selectRowIndexArr.length < this.pagefromData.chinds.length) {
        this.selectRowIndexArr.sort(function(a,b){return a - b})
        this.selectRowIndexArr.forEach(k => {
          this.pagefromData.chinds.forEach((l, index) => {
            if (k === l.seq) {
              this.pagefromData.chinds.splice(index, 1)
            }
          })
        })
        this.arrangeData()
      } else {
        this.$message.error({ message: '至少保留一行!', showClose: true })
      }
    },
    // // 批量填充
    // copyCellcolumn(data) {
    //   console.log('批量填充', data)
    // },
    // 订单号 复制按钮
    saleOrderCopy() {
      orderCopy()
    },

    // 选择的行
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    // 明细选择行的数据处理
    selectdataSet(selection, row) {
      this.multipleSelection = []
      this.multipleSelection = selection
      if (row) {
        this.selectRowIndex = row.seq
      }
      if (selection && selection.length > 0) {
        this.selectRowIndex = selection[0].seq
      }
      if (selection.length != 0) {
        this.selectRowIndexArr = selection.map(it => {
          return it.seq
        })
      } else {
        this.selectRowIndexArr = []
      }
    },
    //注意这里是解构
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex
      column.index = columnIndex
    },
    getRowCol(row, column, cell, event) {
      // 处理表格下拉框输入框显示隐藏
      this.pagefromData.chinds.forEach((it, index) => {
        Object.assign(it, { isnumbershow: false, isnameshow: false })
      })
      var showtagarry = ['isnumbershow', 'isnameshow']
      var parentshowtagarry = ['number', 'name']
      showtagarry.forEach((k, idx) => {
        if (column.property == parentshowtagarry[idx]) {
          this.pagefromData.chinds[row.index][k] = true
          this.$nextTick(_ => {
            if (document.getElementById(column.property + row.index)) {
              document.getElementById(column.property + row.index).focus()
            }
          })
        }
      })
    },
    // 选择全部明细(全选)
    selectRowAll(selection) {
      this.selectdataSet(selection)
    },
    // 选择的行（单选）
    selectRow(selection, row) {
      this.selectdataSet(selection)
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/style/saleOrder/saleOrderCommon.scss';
@import '@/assets/style/saleOrder/orderDetails.scss';
@import '@/assets/style/materialBom/bom.scss';
@import '@/assets/style/saleOrder/common.scss';
</style>