<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
              :loading="allDivBtn"
              class="filter-item"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="allDivStruct()"
            >
              全部分配
            </el-button>
          </slot>
          <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="sap_pcsn" label="SAP批次" align="center" />
        <el-table-column
          show-overflow-tooltip
          prop="plan_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="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
          :loading="divBtn"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="divStruct()"
        >
          分配货位
        </el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="unDivStruct()"
        >
          取消分配
        </el-button>
        <el-button
          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="sap_pcsn" label="SAP批次" 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"
      :stor-id="storId"
      :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, { allDivStruct } 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,
      divBtn: false,
      allDivBtn: false,
      bucketShow: false,
      sects: [],
      sect_val: null,
      form: {
        dtl_row: null,
        storage_qty: '',
        point_code: null,
        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
      })
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    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 = []
      })
    },
    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)
        })
      })
    },
    allDivStruct() {
      if (!this.sect_id) {
        this.crud.notify('请先选择虚拟库区区域！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      this.allDivBtn = true
      const data = {}
      data.sect_id = this.sect_id
      data.iostorinv_id = this.openParam[0].iostorinv_id
      crudRawAssist.allDivStruct(data).then(res => {
        crudRawAssist.getIODtl({ 'bill_code': this.openParam[0].bill_code, 'open_flag': '1' }).then(res => {
          this.openParam = res
        })
      }).finally(() => {
        this.allDivBtn = false
      })
    },
    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.divBtn = true
        this.form.sect_id = this.sect_id
        this.form.stor_id = this.stor_id
        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.divBtn = false
            this.crud.notify('分配货位成功！', CRUD.NOTIFICATION_TYPE.SUCCESS)
          })
        }).finally(() => {
          this.divBtn = false
        })
      } 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
      }
      // 如果勾选了，直接跳后台
      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)
        })
      })
    }
  }
}
</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>
