<template>
  <el-dialog
    append-to-body
    :visible.sync="dialogVisible"
    destroy-on-close
    :show-close="false"
    fullscreen
    @close="close"
    @open="open"
  >

    <span slot="title" class="dialog-footer">
      <div class="crud-opts2">
        <span class="el-dialog__title2">入库分配</span>
        <span class="crud-opts-right2">
          <!--左侧插槽-->
          <slot name="left" />
          <el-button slot="left" type="info" @click="dialogVisible = false">关闭</el-button>
        </span>
      </div>
    </span>
    <div class="crud-opts2">
      <span class="role-span">入库明细项</span>
    </div>
    <el-card class="box-card" shadow="never" :body-style="{padding:'0'}">
      <!--表格渲染-->
      <el-table
        ref="dtl_table"
        :data="this.openParam"
        style="width: 100%;"
        max-height="300"
        border
        highlight-current-row
        :row-class-name="tableRowClassName"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        @row-click="clcikRow"
      >
        <el-table-column prop="bill_status" label="状态" align="center" width="110px">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.bill_status"
              class="filter-item"
              :disabled="true"
            >
              <el-option
                v-for="item in dict.io_bill_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="box_no" width="250" label="木箱号" align="center" />
        <el-table-column show-overflow-tooltip prop="material_code" label="物料编码" align="center" />
        <el-table-column show-overflow-tooltip prop="material_name" label="物料名称" align="center" />
        <el-table-column show-overflow-tooltip prop="pcsn" label="子卷号" align="center" />
        <el-table-column show-overflow-tooltip prop="plan_qty" :formatter="crud.formatNum3" label="重量" align="center" />
        <!--        <el-table-column show-overflow-tooltip prop="assign_qty" :formatter="crud.formatNum3" label="已分配数量"
                         align="center"/>
        <el-table-column show-overflow-tooltip prop="unassign_qty" :formatter="crud.formatNum3" label="未分配数量"
                         align="center"/>-->
        <el-table-column show-overflow-tooltip prop="qty_unit_name" label="单位" align="center" />
        <el-table-column show-overflow-tooltip prop="source_bill_type_name" label="源单类型" align="center" />
        <el-table-column show-overflow-tooltip prop="source_bill_code" label="源单编号" align="center" />
      </el-table>
    </el-card>
    <el-card class="box-card" shadow="never" :body-style="{padding:'20px 20px 0 20px'}">
      <el-form ref="form2" :inline="true" :model="form" :rules="rules" size="mini">
        <!--<el-form-item label="载具号" prop="storagevehicle_code">
          <el-input v-model="form.storagevehicle_code" placeholder="载具号" style="width: 200px" @blur="vehicleCheck"/>
        </el-form-item>
        <el-form-item label="桶号" prop="bucketunique">
          <el-input
            v-model="form.bucketunique"
            placeholder="桶号"
            disabled
            class="input-with-select"
            style="width: 200px"
          >
            <el-button slot="append" icon="el-icon-search" @click="dialogBucket"/>
          </el-input>
        </el-form-item>
        <el-form-item label="放入重量" prop="storage_qty">
          <el-input-number
            v-model="form.storage_qty"
            style="width: 200px"
            disabled
            placeholder="放入重量"
            controls-position="right"
            :controls="false"
            :min="0"
            :precision="3"
          />
        </el-form-item>-->
        <el-form-item label="入库点" prop="point_code">
          <el-select
            v-model="form.point_code"
            clearable
            placeholder="请选择"
            class="filter-item"
            style="width: 200px;"
          >
            <el-option
              v-for="item in pointlist"
              :key="item.point_code"
              :label="item.point_name"
              :value="item.point_code"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="crud-opts2">
      <span class="role-span">载具物料明细</span>
      <div class="crud-opts-form">
        <el-form ref="form" :inline="true" :model="form" size="mini">
          <el-form-item label="库区" prop="gender5">
            <el-cascader
              placeholder="请选择"
              :options="sects"
              :props="{ checkStrictly: true }"
              clearable
              @change="sectQueryChange"
            />
          </el-form-item>
          <el-form-item prop="checked">
            <el-checkbox v-model="form.checked">自动分配货位</el-checkbox>
          </el-form-item>
        </el-form>
      </div>
      <span class="crud-opts-right2">
        <!--左侧插槽-->
        <slot name="left" />
        <!--<el-button
          slot="left"
          class="filter-item"
          type="warning"
          icon="el-icon-check"
          size="mini"
          @click="insertvehicle()"
        >
          装入托盘
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="confirmvehicle()"
        >
          组盘确认
        </el-button>-->
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="divStruct()"
        >
          分配货位
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="unDivStruct()"
        >
          取消分配
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-delete"
          size="mini"
          @click="divPoint()"
        >
          设置起点
        </el-button>
      </span>
    </div>
    <el-card class="box-card" shadow="never" :body-style="{padding:'0'}">
      <!--表格渲染-->
      <el-table
        ref="dis_table"
        :data="form.tableMater"
        style="width: 100%;"
        max-height="300"
        border
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
      >
        <el-table-column show-overflow-tooltip type="index" label="序号" align="center" />
        <el-table-column show-overflow-tooltip prop="box_no" width="250" label="木箱号" align="center" />
        <el-table-column show-overflow-tooltip prop="material_code" label="物料编码" align="center" />
        <el-table-column show-overflow-tooltip prop="material_name" label="物料名称" align="center" />
        <el-table-column show-overflow-tooltip prop="pcsn" label="子卷号" align="center" />
        <el-table-column show-overflow-tooltip prop="plan_qty" :formatter="crud.formatNum3" label="重量" align="center" />
        <el-table-column show-overflow-tooltip prop="point_code" label="入库点" align="center" />
        <el-table-column show-overflow-tooltip prop="struct_code" label="货位" align="center" />
        <!--<el-table-column align="center" label="操作" width="190" fixed="right">
          <template slot-scope="scope">
            <el-popover v-model="scope.row.pop" placement="top" width="180" trigger="manual">
              <p>{{ '是否确认删除桶明细？' }}</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="doCancel(scope.row)">取消</el-button>
                <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope.$index, form.tableMater)">确定</el-button>
              </div>
              <el-button slot="reference" :disabled="scope.row.struct_code !== '' && scope.row.struct_code" type="danger" icon="el-icon-delete" size="mini" @click="toDelete(scope.row)" />
            </el-popover>
          </template>
        </el-table-column>-->
      </el-table>
    </el-card>

    <StructDiv ref="child" :dialog-show.sync="structShow" :sect-prop="sectProp" @tableChanged="tableChanged" />

  </el-dialog>
</template>

<script>
import CRUD, { crud } from '@crud/crud'
import crudSectattr from '@/views/wms/basedata/st/sect/sectattr'
import StructDiv from '@/views/wms/pub/StructDialog'
import crudRawAssist from '@/views/wms/st/inbill/rawassist'
import crudPoint from '@/views/wms/sch/point/point'
import crudUserStor, { getSect } from '@/views/wms/basedata/st/userStor/userStor'

export default {
  name: 'DivDialog',
  components: { StructDiv },
  mixins: [crud()],
  dicts: ['io_bill_status'],
  props: {
    dialogShow: {
      type: Boolean,
      default: false
    },
    bussConfig: {
      type: Object
    },
    openParam: {
      type: Array,
      default: () => {
        return []
      }
    },
    billType: {
      type: String,
      default: null
    },
    storId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      stor_id: '',
      sect_id: '',
      sectProp: null,
      bucketProp: {},
      structShow: false,
      bucketObj: null,
      bucketShow: false,
      sects: [],
      sect_val: null,
      form: {
        dtl_row: null,
        bucketunique: '',
        storage_qty: '',
        point_code: null,
        storagevehicle_code: '',
        checked: true,
        tableMater: []
      },
      storlist: [],
      pointlist: [],
      rules: {}
    }
  },
  watch: {
    dialogShow: {
      handler(newValue, oldValue) {
        this.dialogVisible = newValue
      }
    }
  },
  methods: {
    open() {
      crudUserStor.getSect({ 'stor_id': this.storId}).then(res => {
        this.sects = res.content
      })

      const area_type = '1585164789083148288'

      crudPoint.getPoint({ 'area_type': area_type }).then(res => {
        this.pointlist = res
      })
    },
    toDelete(data) {
      data.pop = true
    },
    close() {
      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()
    },
    clcikRow(row, column, event) {
      this.form.dtl_row = row
      crudRawAssist.getIODtl({ 'bill_code': this.form.dtl_row.bill_code }).then(res => {
        this.openParam = res
        this.form.dtl_row = res[row.index]
      })
      crudRawAssist.getDisDtl(row).then(res => {
        this.form.tableMater = res
      })
    },
    vehicleCheck() {
      if (!this.form.dtl_row) {
        this.crud.notify('请选择一条入库明细', CRUD.NOTIFICATION_TYPE.INFO)
        this.form.storagevehicle_code = ''
        return
      }
      crudRawAssist.checkVehicle({
        'storagevehicle_code': this.form.storagevehicle_code,
        'dis_num': this.form.tableMater.length,
        'iostorinv_id': this.form.dtl_row.iostorinv_id
      }).then(res => {

      }).catch(err => {
        this.form.storagevehicle_code = ''
      })
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    insertvehicle() {
      if (!this.form.dtl_row) {
        this.crud.notify('请选择一条入库明细', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      if (!this.form.storagevehicle_code) {
        this.crud.notify('请输入托盘号', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      // 判断是否选择了桶号
      if (this.bucketObj) {
        if (!(this.bucketObj.status === '01')) {
          this.crud.notify('请校验桶状态！', CRUD.NOTIFICATION_TYPE.INFO)
          return
        }
        const dis_dtl = JSON.parse(JSON.stringify(this.bucketObj))
        // 判断选择的桶是否已经被选过
        const flag = this.form.tableMater.some(mater => mater.bucketunique === dis_dtl.bucketunique)
        if (!flag) {
          const flag = this.form.tableMater.some(mater => mater.storagevehicle_code !== this.form.storagevehicle_code)
          if (flag) {
            this.crud.notify('存在不同载具号', CRUD.NOTIFICATION_TYPE.INFO)
            return
          }
          dis_dtl.storagevehicle_code = this.form.storagevehicle_code
          dis_dtl.pop = false
          this.form.tableMater.splice(this.form.tableMater.length, 0, dis_dtl)
          if (this.form.dtl_row.assign_qty) {
            this.form.dtl_row.assign_qty = parseFloat(this.form.dtl_row.assign_qty) + parseFloat(this.form.storage_qty)
          } else {
            this.form.dtl_row.assign_qty = parseFloat(this.form.storage_qty)
          }
          if (parseFloat(this.form.dtl_row.unassign_qty) - parseFloat(this.form.storage_qty) > 0) {
            this.form.dtl_row.unassign_qty = parseFloat(this.form.dtl_row.unassign_qty) - parseFloat(this.form.storage_qty)
          } else {
            this.form.dtl_row.unassign_qty = 0
          }
          this.openParam.splice(this.form.dtl_row.index, 1, this.form.dtl_row)
        }
        if (flag) {
          this.crud.notify('该桶已被加入明细中', CRUD.NOTIFICATION_TYPE.INFO)
        }
      } else {
        this.crud.notify('请选择桶号', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
    },
    confirmvehicle() {
      if (this.form.tableMater.length <= 0) {
        this.crud.notify('至少添加一条载具明细', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      const carrier_no = this.form.tableMater[0].storagevehicle_code
      const flag = this.form.tableMater.every(mater => mater.storagevehicle_code === carrier_no)
      if (!flag) {
        this.crud.notify('请选择唯一载具进行组盘！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      const flag2 = this.form.tableMater.some(mater => mater.point_code !== this.form.point_code && mater.point_code)
      if (flag2) {
        this.crud.notify('请选择相同入库点！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      crudRawAssist.confirmvehicle(this.form).then(res => {
        crudRawAssist.getIODtl({ 'bill_code': this.form.dtl_row.bill_code }).then(res => {
          this.openParam = res
        })
        crudRawAssist.getDisDtl(this.form.dtl_row).then(res => {
          this.form.tableMater = res
          this.crud.notify('组盘成功！', CRUD.NOTIFICATION_TYPE.SUCCESS)
        })
      })
    },
    deleteRow(index, rows) {
      // 如果桶状态不是生成调后台逻辑
      if (rows[index].status !== '01') {
        crudRawAssist.deleteDisDtl(rows[index]).then(res => {
          crudRawAssist.getIODtl({ 'bill_code': this.form.dtl_row.bill_code, 'open_flag': '1' }).then(res => {
            this.openParam = res
          })
          crudRawAssist.getDisDtl(this.form.dtl_row).then(res => {
            this.form.tableMater = res
          })
          rows[index].pop = false
        }).catch(err => {
          rows[index].pop = false
          return
        })
      }
      this.form.dtl_row.assign_qty = parseFloat(this.form.dtl_row.assign_qty) - parseFloat(rows[index].storage_qty)
      this.form.dtl_row.unassign_qty = parseFloat(this.form.dtl_row.unassign_qty) + parseFloat(rows[index].storage_qty)
      this.openParam.splice(this.form.dtl_row.index, 1, this.form.dtl_row)
      rows.splice(index, 1)
    },
    sectQueryChange(val) {
      this.sectProp = val
      if (val.length === 1) {
        this.stor_id = val[0]
        this.sect_id = ''
      }
      if (val.length === 0) {
        this.sect_id = ''
        this.stor_id = ''
      }
      if (val.length === 2) {
        this.stor_id = val[0]
        this.sect_id = val[1]
      }
    },
    tableChanged(row) {
      // 新增一行物料时，给行进行赋值
      for (let i = 0; i < this.form.tableMater.length; i++) {
        this.form.tableMater[i].struct_code = row.struct_code
        this.form.tableMater[i].sect_id = row.sect_id
        this.form.tableMater[i].struct_id = row.struct_id
        this.form.tableMater[i].struct_name = row.struct_name
        this.form.tableMater[i].sect_code = row.sect_code
        this.form.tableMater[i].sect_name = row.sect_name
        this.form.tableMater.splice(i, 1, this.form.tableMater[i]) // 通过splice 替换数据 触发视图更新
      }
      crudRawAssist.divStruct(this.form).then(res => {
        crudRawAssist.getIODtl({ 'bill_code': this.form.dtl_row.bill_code, 'open_flag': '1' }).then(res => {
          this.openParam = res
        })
        this.form.tableMater = []
      })
    },
    bucketChange(row) {
      debugger
      this.bucketObj = row
      this.form.bucketunique = row.bucketunique
      this.form.storage_qty = row.storage_qty
    },
    divPoint() {
      if (!this.form.point_code) {
        this.crud.notify('请选择入库点', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      debugger
      if (this.form.tableMater.length === 0) {
        this.crud.notify('请先选择一条明细！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      crudRawAssist.divPoint(this.form).then(res => {
        crudRawAssist.getIODtl({ 'bill_code': this.form.dtl_row.bill_code, 'open_flag': '1' }).then(res => {
          this.openParam = res
        })
        crudRawAssist.getDisDtl(this.form.dtl_row).then(res => {
          this.form.tableMater = res
          this.crud.notify('设置起点成功！', CRUD.NOTIFICATION_TYPE.SUCCESS)
        })
      })
    },
    divStruct() {
      if (this.form.tableMater.length === 0) {
        this.crud.notify('请先选择一条明细！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      // 如果勾选了，直接跳后台
      if (this.form.checked) {
        if (!this.sect_id) {
          this.crud.notify('请先选择区域！', CRUD.NOTIFICATION_TYPE.INFO)
          return
        }
        this.form.sect_id = this.sect_id
        this.form.stor_id = this.stor_id
        this.form.is_pc = '1'
        crudRawAssist.divStruct(this.form).then(res => {
          crudRawAssist.getIODtl({ 'bill_code': this.form.dtl_row.bill_code, 'open_flag': '1' }).then(res => {
            this.openParam = res
          })
          crudRawAssist.getDisDtl(this.form.dtl_row).then(res => {
            this.form.tableMater = res
            this.crud.notify('分配货位成功！', CRUD.NOTIFICATION_TYPE.SUCCESS)
          })
        })
      } else {
        this.structShow = true
        this.$refs.child.getMsg(false)
      }
    },
    doCancel(data) {
      data.pop = false
    },
    unDivStruct() {
      if (this.form.tableMater.length <= 0) {
        this.crud.notify('不存在载具明细！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      const flag = this.form.tableMater.some(mater => !mater.struct_code)
      if (flag) {
        this.crud.notify('明细存在未分配货位！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      // 如果勾选了，直接跳后台
      if (this.form.checked) {
        crudRawAssist.unDivStruct(this.form).then(res => {
          crudRawAssist.getIODtl({ 'bill_code': this.form.dtl_row.bill_code, 'open_flag': '1' }).then(res => {
            this.openParam = res
          })
          crudRawAssist.getDisDtl(this.form.dtl_row).then(res => {
            this.form.tableMater = res
            this.crud.notify('取消分配成功！', CRUD.NOTIFICATION_TYPE.SUCCESS)
          })
        })
      } else {
        this.structShow = true
        this.$refs.child.getMsg(false)
      }
    },
    dialogBucket() {
      if (!this.form.dtl_row) {
        this.crud.notify('请选择一条入库明细', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      /* const material_dtl_scode = this.form.dtl_row.material_dtl_scode
      let type = ''
      if (material_dtl_scode.slice(0, 4) === '0903') {
        type = '01'
      }
      if (material_dtl_scode.slice(0, 4) === '0904') {
        type = '02'
      }
      if (material_dtl_scode.slice(0, 6) === '090202') {
        type = '04'
      }
      if (material_dtl_scode.slice(0, 6) === '090201') {
        type = '03'
      }*/
      const bucket = {
        'material_code': this.form.dtl_row.material_code,
        'pcsn': this.form.dtl_row.pcsn,
        'quality_scode': this.form.dtl_row.quality_scode,
        'ivt_level': this.form.dtl_row.ivt_level,
        'is_active': this.form.dtl_row.is_active,
        // 'storagevehicle_type': type,
        'bucket_status': '01'
      }
      this.bucketProp = bucket
      this.bucketShow = true
    }
  }
}
</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;
}

.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>
