<template>
  <el-dialog
    append-to-body
    :visible.sync="dialogVisible"
    destroy-on-close
    :show-close="false"
    fullscreen
    @close="close"
  >
    <span slot="title" class="dialog-footer">
      <div class="crud-opts2">
        <span class="el-dialog__title2">木箱分配</span>
      </div>
      <div class="crud-opts-right2" style="display: flex; justify-content: flex-end; align-items: center;">
        <!--左侧插槽-->
        <slot name="left" />
        <el-button type="info" @click="dialogVisible = false">关闭</el-button>
      </div>
    </span>
    <div class="crud-opts2">
      <span class="role-span">分配方案</span>
    </div>
    <el-card class="box-card" shadow="never" :body-style="{padding:'0'}">
      <!--表格1渲染-->
      <el-table
        ref="dtl_table"
        :data="openParam"
        style="width: 100%;"
        max-height="300"
        border
        highlight-current-row
        :row-class-name="tableRowClassName"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        :row-key="row => row.name"
        :span-method="handleSpanMethod"
        handle-row-click
        @row-click="handleRowClick"
      >
        <!-- 列的定义... -->
        <!--        <el-table-column prop="box_group" label="木箱组 " align="center" width="120">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ '' }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column show-overflow-tooltip prop="box_group" label="木箱组" align="center" />
        <el-table-column show-overflow-tooltip prop="quanlity_in_box" label="箱内子卷数" align="center" />
        <el-table-column show-overflow-tooltip prop="container_name" label="子卷号" align="center" />
        <el-table-column show-overflow-tooltip prop="paper_tube_description" label="子卷规格" align="center" />
        <!--        <el-table-column show-overflow-tooltip prop="paper_weight" label="子管重量" align="center" />-->
        <el-table-column show-overflow-tooltip prop="weight" label="子卷重量" align="center" />
        <el-table-column show-overflow-tooltip prop="box_type" label="木箱料号" align="center" />
      </el-table>
    </el-card>
    <div style="margin-bottom: 20px;" />
    <div>
      <span class="role-span">调整分配</span>
    </div>
    <div style="margin-bottom: 10px;" />
    <div class="search-box">
      <el-input
        v-model="searchText"
        placeholder="请输入子卷号"
        class="search-input"
        clearable
        @clear="handleInput"
        @input="handleSearch"
      />

      <span class="crud-opts-right2">
        <el-button
          slot="left"
          class="filter-item"
          type="success"
          icon="el-icon-circle-close"
          size="mini"
          @click="clearSearch()"
        >
          清空
        </el-button>
      </span>
      <span class="crud-opts-right2" style="margin-left: 15px;">
        <el-button
          slot="left"
          class="filter-item"
          type="success"
          icon="el-icon-position"
          size="mini"
          :disabled="isButtonDisabled1"
          @click="transferBoxPackageToMes()"
        >
          回传mes
        </el-button>
      </span>
      <span class="crud-opts-right2" style="margin-left: 15px;">
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          :disabled="isButtonDisabled"
          @click="divStruct()"
        >
          分配木箱规格
        </el-button>
      </span>
    </div>
    <el-card class="box-card" shadow="never" :body-style="{padding:'0'}">
      <el-table
        ref="dis_table"
        :data="filteredData"
        style="width: 100%;"
        max-height="300"
        border
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        :row-style="table2RowStyle"
        @selection-change="handleSelectionChange"
      >
        <!-- 列的定义-->
        <el-table-column type="selection" width="55" />
        <el-table-column show-overflow-tooltip prop="box_group" label="木箱组" align="center" width="130" />
        <el-table-column show-overflow-tooltip prop="container_name" label="子卷号" align="center" />
        <el-table-column show-overflow-tooltip prop="paper_tube_description" label="子卷规格" align="center" />
        <el-table-column show-overflow-tooltip prop="paper_weight" label="子管重量" align="center" />
        <!--        <el-table-column show-overflow-tooltip prop="weight" label="子卷重量" align="center" />-->
        <el-table-column show-overflow-tooltip prop="box_type" label="木箱料号" align="center" />
      </el-table>
    </el-card>
    <MaterDiv
      ref="child"
      :dialog-show.sync="structShow"
      :paper-tube-description="paperTubeDescription"
      :box-type="box_type"
      :sect-prop="sectProp"
      @tableChanged="tableChanged"
    />
  </el-dialog>
</template>

<script>
import CRUD, { crud } from '@crud/crud'
import MaterDiv from '@/views/wms/pdm/sub/MaterDialog.vue'
import crudPackagerelation, { transferBoxPackageToMes } from '@/views/wms/pdm/sub/packagerelation'
import crudSubpackagerelation from '@/views/wms/pdm/sub/packagerelation'

export default {
  name: 'DivDialog',
  components: { MaterDiv },
  mixins: [crud()],
  dicts: ['io_bill_status'],
  props: {
    props: {
      parentMethod: {
        type: Function,
        default: () => {
        }
      }
    },
    dialogShow: {
      type: Boolean,
      default: false
    },
    openParam: {
      type: Array,
      default: () => {
        return []
      }
    },
    saleOrderName: {
      type: String,
      default: null
    },
    billType: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      isButtonDisabled: false, // 木箱规格分配按钮
      isButtonDisabled1: true, // 手动同步MES按钮
      searchText: '',
      box_type: '',
      // 存储搜索前的选中状态
      previousSelection: [],
      // 存储搜索后的选中状态
      currentSelection: [],
      // 上面表格选中的
      upSelection: [],
      // 取消选中
      cancelSelection: [],
      multipleSelection: [],
      dialogVisible: false,
      stor_id: '',
      sect_id: '',
      sectProp: null,
      paperTubeDescription: '',
      bucketProp: {},
      structShow: false,
      bucketObj: null,
      bucketShow: false,
      sects: [],
      sect_val: null,
      form: {
        checked: null,
        sale_order_name: null,
        tableMater: []
      },
      storlist: [],
      pointlist: [],
      rules: {}
    }
  },
  computed: {
    filteredData() {
      if (this.searchText.trim() === '') {
        return this.openParam
      } else {
        // 过滤数据
        return this.openParam.filter(row =>
          row.container_name.toLowerCase().includes(this.searchText.toLowerCase())
        )
      }
    }
  },
  watch: {
    dialogShow: {
      handler(newValue, oldValue) {
        this.dialogVisible = newValue
      }
    }
  },
  methods: {
    handleSearch() {
      debugger
      this.multipleSelection = this.multipleSelection.filter(i => {
        return this.$refs.dis_table.selection.includes(i)
      })
      this.currentSelection = [...this.$refs.dis_table.selection]
    },
    // 处理清除搜索条件事件
    clearSearch() {
      this.searchText = ''
      this.currentSelection.push(...this.previousSelection)
      this.multipleSelection.push(...this.currentSelection)
      this.multipleSelection = this.getMultipleSelection(this.multipleSelection)
      console.log('multipleSelection1:', this.multipleSelection)
      this.multipleSelection.forEach(row => {
        this.table2RowStyle(row)
      })
      console.log('multipleSelection2:', this.multipleSelection)
      const table2 = this.$refs.dis_table
      table2.clearSelection()
      const selectedRows = this.multipleSelection
      selectedRows.forEach(row => {
        table2.toggleRowSelection(row)
      })
      // this.$refs.dis_table.clearSelection()
      // this.multipleSelection.forEach(row => {
      //   this.$refs.dis_table.toggleRowSelection(row,true);
      // });
    },
    clearSearch1() {
      console.log('dis_table1:', this.$refs.dis_table)
      console.log('dis_table2:', this.$refs['dis_table'])
      console.log('multipleSelection:', this.currentSelection)
      const table2 = this.$refs.dis_table
      table2.clearSelection()
      const selectedRows = this.multipleSelection
      selectedRows.forEach(row => table2.toggleRowSelection(row))
      // this.$refs.dis_table.clearSelection()
      // this.multipleSelection.forEach(row => {
      //   this.$refs.dis_table.toggleRowSelection(row,true);
      // });
    },
    handleInput(value) {
      this.clearSearch1()
    },
    table2RowStyle({ row }) {
      if (this.currentSelection.includes(row)) {
        if (row.box_group !== '0') {
          return { background: 'orange' } // 修改颜色
        }
      }
      if (this.multipleSelection.includes(row)) {
        if (row.box_group !== '0') {
          return { background: 'orange' } // 修改颜色
        }
      }
    },
    getMultipleSelection(multipleSelection) {
      return multipleSelection.reduce((acc, item) => {
        const existingItem = acc.find(existing => existing.container_name === item.container_name)
        if (!existingItem) {
          acc.push(item)
        }
        return acc
      }, [])
    },
    // 表格1的分组处理
    handleSpanMethod({ row, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        if (row.box_group !== null) {
          const sortedData = [...this.openParam].sort((a, b) => a.box_group.localeCompare(b.box_group))
          const currentIndex = sortedData.findIndex(item => item === row)
          const isFirstRow = currentIndex === 0 || sortedData[currentIndex - 1].box_group !== row.box_group
          return {
            rowspan: isFirstRow ? sortedData.filter(item => item.box_group === row.box_group).length : 0,
            colspan: 1
          }
        } else {
          return { rowspan: 1, colspan: 1 }
        }
      }
    },
    // 表格1的行点击事件
    handleRowClick(scope) {
      debugger
      // 按钮禁用
      this.isButtonDisabled = !!(scope.status !== '99')
      this.isButtonDisabled1 = scope.status === '99'
      const table2 = this.$refs.dis_table
      const table2Data = Array.from(this.openParam)
      const groupValue = scope.box_group === '0' ? scope.container_name : scope.box_group
      const selectedRows = table2Data.filter(row => (row.container_name == groupValue) || (row.box_group === groupValue && row.box_group !== null && row.box_group !== '0'))
      table2.clearSelection()
      selectedRows.forEach(row => table2.toggleRowSelection(row))
      this.box_type = ''
      // 给木箱料号赋值
      this.box_type = scope.box_type
    },
    // 表格2的行点击事件
    handleSelectionChange(selection) {
      debugger
      if (selection.length > 0) {
        this.isButtonDisabled = !selection.every(item => item.status === '99')
        this.isButtonDisabled1 = selection.some(item => item.status === '99')
        this.box_type = ''
        // 给木箱料号赋值
        const box_type = selection.filter(item => item.box_type !== '' && item.box_type !== null)
        if (box_type.length > 0) {
          this.box_type = box_type[0].box_type
        }
        this.currentSelection = selection
        if (!this.searchText) {
          this.previousSelection = selection
        }
      } else {
        debugger
        if (!this.searchText) {
          this.cancelSelection = []
          this.cancelSelection = [...this.currentSelection]
          this.table2RowStyle({ row: this.currentSelection })
        }
      }
    },
    toDelete(data) {
      this.$set(data, 'pop', true)
      // data.pop = true
    },
    close() {
      this.clearSelection()
      this.form.tableMater = []
      this.form.dtl_row = null
      this.sectProp = null
      this.$emit('update:dialogShow', false)
      this.$emit('AddChanged')
      this.crud.refresh()
      this.$refs['form2'].resetFields()
    },
    // 清除选中项
    clearSelection() {
      this.previousSelection = []
      this.multipleSelection = []
      this.currentSelection = []
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    async tableChanged(row) {
      debugger
      this.form.tableMater = this.currentSelection
      if (this.currentSelection.length > row.num) {
        this.crud.notify('子卷数量超过木箱的最大装卷数！', CRUD.NOTIFICATION_TYPE.WARNING)
        return
      }
      debugger
      this.form.checked = row.material_code
      this.form.sale_order_name = this.saleOrderName
      await crudPackagerelation.updateEntityList(this.form)
      debugger
      const queryParam = { sale_order_name: this.saleOrderName, type: '0' }
      const res = crudSubpackagerelation.queryContainerization(queryParam)
      this.openParam = res.content
      this.clearSelection()
      this.form.tableMater = []
      this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$emit('childEvent')
    },
    divStruct() {
      debugger
      if (this.currentSelection.length > 0 && this.$refs.dis_table.selection.length > 0) {
        debugger
        const weightList = this.currentSelection.filter(item => item.weight === '0' || item.weight === null)
        if (weightList.length > 0) {
          this.crud.notify('该子卷重量不能为空，请检查子卷的分切计划信息！', CRUD.NOTIFICATION_TYPE.WARNING)
          return
        }
        const descriptionList = this.currentSelection.filter(item => item.paper_tube_description !== null && item.paper_tube_description !== '')
        if (descriptionList.length === 0) {
          this.crud.notify('未查询到该子卷的规格信息，请检查子卷的分切计划信息！', CRUD.NOTIFICATION_TYPE.WARNING)
          return
        }
        const paper_tube_description = descriptionList[0].paper_tube_description
        const descriptionsAreSame = this.currentSelection.every(item => item.paper_tube_description === paper_tube_description)
        if (descriptionsAreSame) {
          // 给木箱料号赋值
          const box_type = this.currentSelection.filter(item => item.box_type !== '' && item.box_type !== null)
          if (box_type.length > 0) {
            this.box_type = ''
            this.box_type = box_type[0].box_type
          }
          this.paperTubeDescription = paper_tube_description
          this.structShow = true
          this.$refs.child.getMsg(false)
        } else {
          this.crud.notify('子卷规格不一致！', CRUD.NOTIFICATION_TYPE.WARNING)
        }
      } else {
        this.crud.notify('请选中子卷信息！', CRUD.NOTIFICATION_TYPE.WARNING)
      }
    },
    transferBoxPackageToMes() {
      this.form.tableMater = this.currentSelection
      crudPackagerelation.transferBoxPackageToMes(this.form).then(r => {
        this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      })
    },
    doCancel(data) {
      this.$set(data, 'pop', false)
    }
  }
}
</script>

<style>
.crud-opts2 {
  padding: 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts2 .el-dialog__title2 {
  line-height: 24px;
  font-size: 20px;
  color: #303133;
}

.search-box {
  margin-bottom: 10px;
}

.search-input {
  width: 200px;
}

.clear-icon {
  cursor: pointer;
}

.crud-opts2 .role-span {
  padding: 10px 0px 10px 0px;
}

.crud-opts2 .crud-opts-form {
  padding: 10px 0px 0px 20px;
}

.input-with-select {
  background-color: #fff;
}
</style>
