<!-- 物料选择组件 -->
<template>
  <div class="container-wrap">
      <div class="container">
        <div class="content">
          <div class="left">
            <div class="title">
              排班面料
            </div>
            <div class="main">
              <my-table
                  ref="table"
                  :data="data2"
                  :columns="columnsV3"
                  :is-show-filter="false"
                  :is-show-page="false"
                  :selected-list="handleData"
                  :select-key="selectKey"
                  :multiple="multiple"
                  :show-flag="modal"
                  :key="renderKey"
                  @on-select="tableSelectChange"
                  @on-select-cancel="tableSelectCancel"
                  @on-select-all-cancel="allCancel"
                  @event-handle="eventHandle"
                  @on-change="changePage"
                  @on-select-all="selectAll"
                  @on-row-click="rowCk"
              ></my-table>
            </div>
          </div>
          <div class="right">
            <div class="title">
              待领面料
            </div>
            <div class="main">
              <my-table
                ref="handleTable"
                :data="data"
                :columns="columns"
                :table-filter="tableFilter"
                :table-page="params"
                :selected-list="handleData"
                :select-key="selectKey"
                :multiple="multiple"
                :show-flag="modal"
                :is-show-filter="false"
                @on-select="tableSelectChange"
                @on-select-cancel="tableSelectCancel"
                @on-select-all-cancel="allCancel"
                @event-handle="eventHandle"
                @on-change="changePage"
                @on-select-all="selectAll"
                :is-show-page="false"
              ></my-table>
            </div>
          </div>
          <div class="handle-list">
            <div class="title">
              已选物料
            </div>
            <div class="main table-3">
              <my-table
                  ref="cfmTable"
                  :key="renderKey"
                  :data="handleData"
                  :columns="columns2"
                  :is-show-page="false"
                  :is-show-filter="false"
                  style="height:auto"
                >
              </my-table>
              <ul>
                <li v-for="(i,index) in restrictedPickingData" :key="index">
                  <div style="width:30%">
                    <span class="cl-blue">推荐卷</span><br>
                    <span>长度</span>{{i.quantity}}m
                  </div>
                  <div>
                    <span>标签值</span>{{i.rfidCode}}<br>
                    <span>位置</span>{{i.areaName || '暂未绑定位置'}}
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="footer">
          <Button type="success" size="large" @click="cfm">领料</Button>
        </div>
      </div>
  </div>
</template>

<script>
import {
  GetV3PlanData,
  GetMaterialCategoryZTree,
  GetV3PlanData2
} from '@/api/integrated'
import MyTable from '@/components/my-table/my-table'
import MyNumberBoardInput from '@/components/my-number-board-input/my-number-board-input'
import axios from 'axios'
import { json } from 'body-parser'

export default {
  name: 'material_maintenance',
  components: {
    MyTable,
    MyNumberBoardInput
  },
  watch: {
    value: {
      handler (n) {
        this.modal = n
      },
      immediate: true
    },
    modal (n) {
      this.$emit('input', n)
    },
    treeData: {
      handler (newVal, oldVal) {
        this.initData(this.treeData)
      },
      deep: true
    }
  },
  props: {
    // 已选数据
    selectedList: {
      type: Array,
      default () {
        return []
      }
    },
    /* 数据回填所根据的key */
    selectKey: {
      type: String,
      default: 'code'
    },
    /* 是否单选 */
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否显示表单
    value: {
      type: Boolean,
      default: false,
      require: true
    }
  },
  data () {
    return {
      modal: false,
      categoryCode: '',
      columns2: [
        {
          title: '物料名称',
          key: 'name',
          minWidth: 150
        },
        {
          title: '数量',
          minWidth: 100,
          render: (h, params) => {
            let that = this
            return h(MyNumberBoardInput, {
              props: {
                min: 1,
                value: that.handleData[params.row._index].quantity
              },
              on: {
                'on-change'(val){
                  console.log('???????val', val)
                  that.handleData[params.row._index].quantity = Number.parseFloat(val)
                  console.log(that.handleData[params.row._index].quantity)
                  if (that.handleData[params.row._index].stockQty < that.handleData[params.row._index].quantity) {
                    that.$Message.error('输入数量不可大于实时库存')
                  }
                  that.handleArea(params.row._index)
                }
              }
            })
          }
        },
        {
          title: '操作',
          width: 80,
          align: 'center',
          render: (h, params) => {
            let that = this
            return h('Icon', {
              props: {
                type: 'ios-trash',
                size: 24,
                color: 'red'
              },
              style: {
                cursor: 'pointer'
              },
              on: {
                click(e) {
                  e.stopPropagation()
                  that.handleData.splice(params.row._index, 1)
                  that.handleDelArea(params.row.name)
                  that.renderKey = new Date().getTime()
                  that.$refs.handleTable.handleCancel(params.row.code)
                  that.$refs.table.handleCancel(params.row.code)
                }
              }
            })
          }
        }
      ],
      columnsV3: [
        {
          title: '物料名称',
          key: 'name',
          minWidth: 200,
          render:(h,p)=>{
            if(p.row.icon == 'xian'){
              return h('div',[
                h('span',{
                  style:{
                    padding:'5px',
                    background:"red",
                    margin:"0 5px",
                    borderRadius:"5px",
                    color:"#fff"
                  },
                },'限'),
                h('span',{},p.row.name)
              ])
            }else{
              return h('div',[
              h('span',{},p.row.name)
            ])
            }
            
          }
        },
        {
          title: '排班面积',
          key: 'canTakeQty',
          minWidth: 150
        }
      ],
      columns: [
        {
          type: 'selection',
          width: 60
        },
        {
          title: '物料名称',
          key: 'name',
          minWidth: 150
        },
        {
          title: '实时库存',
          key: 'stockQty',
          minWidth: 150
        },
        {
          title: '门幅',
          key: 'width',
          minWidth: 150
        },
        {
          title: '可领用数量',
          key: 'canTakeQty',
          minWidth: 150,
          render: (h, params) => {
            return h('span', {
              style: {
                color: params.row.canTakeQty > 0 ? 'green' : 'red'
              }
            }, params.row.canTakeQty)
          }
        }
      ],
      tableFilter: [
        {
          name: 'Input',
          value: 'key',
          placeholder: '请输入关键字'
        },
        {
          name: 'Button',
          type: 'primary',
          text: '查询',
          e: 'search'
        }
      ],
      params: {
        pageIndex: 1,
        pageSize: 20,
        total: 0,
        categoryCode: this.$store.state.materialCategoryId
      },
      data: [],
      data2: [],
      handleData: [],
      checkedList: [],
      renderKey: new Date().getTime(),
      restrictedPickingData:[]
    }
  },
  methods: {
    rowCk(row){
      const v = this
      console.log(row)
      if(row == false){
        v.data = v.dataCopy
      }else{
        const msg = []
        for (let i = 0; i < v.dataCopy.length; i++) {
          const element = v.dataCopy[i];
          if(element.name.indexOf(row.name) != -1){
            msg.push(element)
          }
        }
        v.data = msg
      }
      
    },
    //查询限定领料
    getRestrictedPicking(){
      const v = this
      axios.post('/cloudApi/stockDetail/restrictedPicking',{jobNo:window.localStorage.getItem('jobNo')}).then(res=>{
        for (let i = 0; i < res.data.data.length; i++) {
          const element = res.data.data[i];
          this.data2.push({
            name:element.materialName,
            canTakeQty:element.availableArea,
            icon:"xian"
          })
          this.data.push({
            name:element.materialName,
            stockQty:element.totalArea,
            width:element.materialWidth,
            canTakeQty:element.quantity || '未匹配到合适的物料',
            _checked:true,
            _disabled: true,
            bgRed:true,
          })
        }

        v.restrictedPickingData = res.data.data
        this.dataCopy = JSON.parse(JSON.stringify(this.data))
        console.log(this.dataCopy)
      })
    },
    handlePageChange () {
      let arr = []
      this.handleData.forEach(item => {
        this.data2.forEach(data => {
          if (item.name.split('-')[0] === data.name) {
            arr.push(data.name)
          }
        })
      })
      Array.from(new Set(arr)).forEach(item => {
        this.handleDelArea(item)
      })
      console.log('??????处理的数据')
      console.log(Array.from(new Set(arr)))
    },
    /* 处理排班面积数量 删除已选数据时自动计算可领用数量 */
    handleDelArea (name) {
      let findObj = this.data2.find(item => name.split('-')[0] === item.name)
      if (findObj) {
        /* 当前勾选的所有相关面料的数量 */
        let quantity = 0
        this.handleData.filter(item => item.name.split('-')[0] === findObj.name).forEach(dataItem => {
          quantity += dataItem.quantity
        })

        this.data.forEach(item => {
          if (item.name.split('-')[0] === findObj.name) {
            let canApplyNum = (findObj.canTakeQty - (quantity * item.width / 100)) / (item.width / 100)
            console.log('计算可领用数量')
            console.log(canApplyNum)
            this.$set(item, 'oldCanTakeQty', item.canTakeQty)
            this.$set(item, 'canTakeQty', canApplyNum.toFixed(1))
          }
        })
      }
    },
    /* 处理排班面积数量 自动计算可领用数量 */
    handleArea(index, defultNum) {
      let data = this.handleData[index]
      console.log('当前操作数据')
      console.log(data)
      /* 当前勾选的面料是否需要特殊处理 */
      let findObj = this.data2.find(item => data.name.split('-')[0] === item.name)
      if (findObj && (data.quantity || data.quantity === 0)) {
        console.log('获取到排班物料')
        console.log(findObj)
        /* 当前勾选的所有相关面料的数量 */
        let quantity = 0
        if (defultNum) {
          quantity = defultNum
        } else {
          this.handleData.filter(item => item.name.split('-')[0] === findObj.name).forEach(dataItem => {
            quantity += dataItem.quantity
          })
        }
        console.log('处理总数量')
        console.log(quantity)

        this.data.forEach(item => {
          if (item.name.split('-')[0] === findObj.name) {
            let canApplyNum = (findObj.canTakeQty - (quantity * item.width / 100)) / (item.width / 100)
            console.log('计算可领用数量')
            console.log(canApplyNum)
            this.$set(item, 'oldCanTakeQty', item.canTakeQty)
            this.$set(item, 'canTakeQty', canApplyNum.toFixed(1))
          }
        })
        console.log('处理后的data')
        console.log(this.data)
      }
    },
    cfm () {
      // this.$refs.table.clear()
      // this.modal = false
      this.$emit('getselectedList', this.handleData,this.restrictedPickingData)
      console.log(this.handleData)
    },
    cancel () {
      this.$refs.table.clear()
      this.modal = false
    },
    getTree () {
      GetMaterialCategoryZTree().then(res => {
        if (res.code === 0) {
          this.treeData = res.result
        }
      })
    },
    
    getList () {
      this.params.jobNo = window.localStorage.getItem('jobNo')
      GetV3PlanData2(this.params).then(res => {
        if (res.code === 0) {
          this.data = res.result.allMaterialList.list
          this.params.total = res.result.allMaterialList.totalCount
          this.data2 = res.result.v3DataList
          this.data.forEach(item => {
            item.name = item.materialName
            item.code = item.materialCode
          })
          this.getRestrictedPicking()
          this.handlePageChange()
          console.log('??????????')
          console.log(this.data)
        }
      })
      // GetOutMaterialPageList(this.params).then(res => {
      //   if (res.code === 0) {
      //     this.data = res.result.list
      //     this.params.total = res.result.totalCount
      //   }
      // })
      // GetUserTakeMaterialRankList().then(res => {
      //   if (res.code === 0) {
      //     this.data2 = res.result
      //     this.data2.forEach(item => {
      //       item.name = item.materialName
      //       item.code = item.materialCode
      //     })
      //   }
      // })
    },
    initData (array) {
      array.forEach(item => {
        item.title = item.name
        if (item.children) {
          this.initData(item.children)
        }
      })
    },
    allCancel(data) {
      data.forEach(data => {
        this.handleData.forEach((item, index) => {
          if (data.code === item.code) {
            this.handleData.splice(index, 0)
          }
        })
      })
    },
    // 获取表格选中数据
    tableSelectChange (selection, row) {
      if (this.handleData.length < 1 && row.code) {
        this.handleData.push({ ...row, quantity: 0})
        // this.handleArea(this.handleData.length - 1, 1)
      } else {
        let isExist = false
        this.handleData.forEach(item => {
          if (item.code === row.code) {
            isExist = true
          }
        })
        if (!isExist && selection.length > 0 && row.code) {
          this.handleData.push({ ...row, quantity: 0})
          // this.handleArea(this.handleData.length - 1, 1)
        }
      }
    },
    selectAll(selection) {
      selection.forEach(data => {
        let isExist = false
        this.handleData.forEach(item => {
          if (item.code === data.code) {
            isExist = true
          }
        })
        if (!isExist) {
          this.handleData.push({ ...data, quantity: 0})
        }
      })
    },
    tableSelectCancel(selection, row) {
      console.log('??????????/row')
      console.log(row)
      console.log(selection)

      // this.handleData.forEach((item, index) => {
      //   if (item.code === row.code) {
      //     this.handleData.splice(index, 1)
      //   }
      // })
      console.log('handleData-----')
      console.log(this.handleData)
    },
    changePage (pageIndex) {
      this.params.pageIndex = pageIndex
      this.getList()
    },
    // 检索条件事件处理
    eventHandle (option) {
      switch (option._evnet) {
        case 'search':
          this.params.pageIndex = 1
          this.params.key = option.key
          this.getList()
          break
      }
    },
    // 选择物料分类 显示物料列表
    treeCheck (data) {
      this.categoryCode = data.value
      this.params.categoryCode = data.value
      this.getList()
    }
  },
  mounted () {
    this.getList()
    this.getTree()
    
  }
}
</script>

<style lang="scss" scoped>
.table-3 .table-content{
  height: auto!important;
  
}
.table-3{
  ul{
    color: #6E6E6E;
    li{
      background: #FFE7E7;
      border-bottom: 1px solid #DDDCDC;
      display: flex;
      text-align: left;
      padding: 0 10px;
      line-height: 30px;
      span{
        display: inline-block;
        width: 50px;
      }
      .cl-blue{
        color: #0268FF;
        font-weight: bold;
      }
    }
  }
}
.container-wrap {
  width: 100%;
  height: 100%;
  .container {
    height: 100%;
    overflow: hidden;
    .content {
      padding: 10px;
      display: flex;
      justify-content: space-between;
      height: calc(100% - 60px);
      .left, .right, .handle-list {
        height: 100%;
        overflow: auto;
        box-shadow: 3px 3px 5px rgba(57, 57, 57, 0.8);
        background-color: #FFFFFF;
        border-radius: 5px;
        .title {
          padding: 5px 0;
          background-color: #2c3034;
          font-size: 18px;
          font-weight: bold;
          text-align: center;
          color: #FFFFFF;
        }
        .main {
          box-sizing: border-box;
          padding: 10px;
          height: calc(100% - 48px);
          overflow: auto
        }
      }
      .left {
        margin-right: 15px;
        flex: 1;
        min-width: 400px;
        .main {
          overflow-x: hidden;
        }
      }
      .right {
        margin-right: 15px;
        flex: 2;
        min-width: 500px;
      }
      .handle-list {
        flex: 1;
        min-width: 400px;
      }
    }
  }
  .footer {
    padding: 10px 0;
    /deep/ .ivu-btn-large {
      border-radius: 20px;
      font-weight: bold;
      width: 150px;
    }
  }
}
/deep/ .ivu-tree {
  ul {
    text-align: left;
  }
}
</style>
