<template>
  <el-dialog
    :title="crud.status.title"
    append-to-body
    fullscreen
    :before-close="crud.cancelCU"
    :visible.sync="crud.status.cu > 0 || crud.status.view > 0"
    width="1200px"
    @open="open"
    @close="close"
  >
    <el-row v-show="crud.status.cu > 0" :gutter="20">
      <el-col :span="20" style="border: 1px solid white">
        <span />
      </el-col>
      <el-col :span="4">
        <span>
          <el-button icon="el-icon-check" size="mini" :loading="crud.cu === 2" type="primary" @click="crud.submitCU">保存</el-button>
          <el-button icon="el-icon-close" size="mini" type="info" @click="crud.cancelCU">关闭</el-button>
        </span>
      </el-col>
    </el-row>

    <el-form ref="form" style="border: 1px solid #cfe0df;margin-top: 10px;padding-top: 10px;" :inline="true" :model="form" :rules="rules" size="mini" label-width="85px" label-suffix=":">
      <el-form-item label="单据号" prop="bill_code">
        <label slot="label">单&nbsp;&nbsp;据&nbsp;号:</label>
        <el-input v-model="form.bill_code" disabled placeholder="系统生成" clearable style="width: 210px" />
      </el-form-item>
      <el-form-item label="仓库" prop="stor_id">
        <label slot="label">仓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库:</label>
        <el-select
          v-model="form.stor_id"
          clearable
          placeholder="仓库"
          class="filter-item"
          style="width: 210px"
          :disabled="crud.status.view > 0"
        >
          <el-option
            v-for="item in storlist"
            :key="item.stor_id"
            :label="item.stor_name"
            :value="item.stor_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="bill_type">
        <el-select
          v-model="form.bill_type"
          clearable
          placeholder="业务类型"
          style="width: 210px"
          class="filter-item"
          :disabled="crud.status.view > 0"
          @change="billTypeChange"
        >
          <el-option
            v-for="item in dict.ST_INV_IN_TYPE"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="bill_status">
        <el-select
          v-model="form.bill_status"
          clearable
          style="width: 210px"
          placeholder="单据状态"
          class="filter-item"
          disabled
        >
          <el-option
            v-for="item in dict.io_bill_status"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="明细数" prop="detail_count">
        <label slot="label">明&nbsp;&nbsp;细&nbsp;数:</label>
        <el-input v-model="form.detail_count" size="mini" disabled style="width: 210px" />
      </el-form-item>
      <el-form-item label="总重量" prop="total_qty">
        <label slot="label">总&nbsp;&nbsp;重&nbsp;量:</label>
        <el-input-number
          v-model="form.total_qty"
          :controls="false"
          :precision="3"
          :min="0"
          disabled
          style="width: 210px"
        />
      </el-form-item>
      <el-form-item label="业务日期" prop="biz_date">
        <el-date-picker v-model="form.biz_date" type="date" placeholder="选择日期" style="width: 210px" value-format="yyyy-MM-dd" :disabled="crud.status.view > 0" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <label slot="label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注:</label>
        <el-input v-model="form.remark" style="width: 380px;" rows="2" type="textarea" :disabled="crud.status.view > 0" />
      </el-form-item>
    </el-form>

    <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
    <div class="crud-opts2" style="margin-bottom: 5px;">
      <span class="crud-opts-right2">
        <!--左侧插槽-->
        <slot name="left" />
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="insertEvent()"
        >
          添加箱号物料
        </el-button>
      </span>

    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      :data="form.tableData"
      style="width: 100%;"
      border
      :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
    >
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column show-overflow-tooltip prop="sale_order_name" label="订单号" />
      <el-table-column show-overflow-tooltip width="205" prop="customer_name" label="客户编号" />
      <el-table-column prop="customer_name" label="客户名称" />
      <el-table-column show-overflow-tooltip prop="package_box_sn" width="250" label="箱号" />
      <el-table-column show-overflow-tooltip width="100" prop="quanlity_in_box" label="箱内子卷数" />
      <el-table-column show-overflow-tooltip width="150" prop="container_name" label="子卷号" />
      <el-table-column show-overflow-tooltip width="150" prop="product_name" label="物料编码" />
      <el-table-column show-overflow-tooltip width="150" prop="product_description" label="物料描述" />
      <el-table-column show-overflow-tooltip prop="width" label="幅宽" />
      <el-table-column show-overflow-tooltip prop="thickness" label="产品厚度" />
      <el-table-column v-if="crud.status.cu > 0" align="center" label="操作" width="170" fixed="right">
        <template scope="scope">
          <el-button
            type="danger"
            class="filter-item"
            size="mini"
            icon="el-icon-delete"
            @click.native.prevent="deleteRow(scope.$index, form.tableData)"
          />
        </template>
      </el-table-column>
    </el-table>

    <AddDtl :dialog-show.sync="dtlShow" :open-param="opendtlParam" @tableChanged="tableChanged" />
    <MaterDtl
      :dialog-show.sync="materShow"
      :is-single="true"
      :mater-opt-code="materType"
      @tableChanged2="tableChanged2"
    />

  </el-dialog>
</template>

<script>
import crudOperation from '@crud/CRUD.operation'
import CRUD, { crud, form } from '@crud/crud'
import AddDtl from '@/views/wms/st/inbill/AddDtl'
import crudStorattr from '@/views/wms/basedata/st/stor/storattr'
import crudRawAssist from '@/views/wms/st/inbill/rawassist'
import MaterDtl from '@/views/wms/pub/MaterDialog'
import checkoutbill from '@/views/wms/st/outbill/checkoutbill'
import crudUserStor from '@/views/wms/basedata/st/userStor/userStor'

const defaultForm = {
  bill_code: '',
  stor_id: '',
  bill_status: '10',
  total_qty: '0',
  detail_count: '0',
  bill_type: '',
  remark: '',
  biz_date: new Date(),
  create_mode: '',
  tableData: []
}

export default {
  name: 'AddDialog',
  components: { AddDtl, MaterDtl },
  mixins: [crud(), form(defaultForm)],
  dicts: ['io_bill_status', 'ST_QUALITY_SCODE', 'ST_INV_IN_TYPE'],
  props: {
    dialogShow: {
      type: Boolean,
      default: false
    },
    bussConfig: {
      type: Object
    },
    openParam: {
      type: Object
    }
  },
  data() {
    return {
      dialogVisible: false,
      materShow: false,
      dtlShow: false,
      opendtlParam: null,
      bill_btn: false,
      mater_btn: false,
      materType: '',
      storlist: [],
      billtypelist: [],
      rules: {
        stor_id: [
          { required: true, message: '仓库不能为空', trigger: 'blur' }
        ],
        bill_type: [
          { required: true, message: '业务类型不能为空', trigger: 'blur' }
        ],
        biz_date: [
          { required: true, message: '业务日期不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dialogShow: {
      handler(newValue, oldValue) {
        this.dialogVisible = newValue
      }
    }
  },
  methods: {
    open() {
      crudUserStor.getUserStor().then(res => {
        this.storlist = res
      })
    },
    close() {
      this.$emit('AddChanged')
    },
    [CRUD.HOOK.afterToEdit]() {
      // 获取入库单明细
      crudRawAssist.getIODtl({ 'bill_code': this.form.bill_code }).then(res => {
        this.form.tableData = res
        // 将明细变成不可编辑
        for (let i = 0; i < this.form.tableData.length; i++) {
          const row = this.form.tableData[i]
          this.form.tableData.splice(i, 1, row)
        }
      })
    },
    [CRUD.HOOK.afterToAdd]() {
      this.bill_btn = false
      this.mater_btn = false
    },
    [CRUD.HOOK.afterToView]() {
      this.bill_btn = true
      this.mater_btn = true
      crudRawAssist.getIODtl({ 'bill_code': this.form.bill_code }).then(res => {
        this.form.tableData = res
        // 将明细变成不可编辑
        for (let i = 0; i < this.form.tableData.length; i++) {
          const row = this.form.tableData[i]
          this.form.tableData.splice(i, 1, row)
        }
      })
    },

    [CRUD.HOOK.beforeSubmit]() {
      // 提交前校验
      if (this.form.tableData.length === 0) {
        this.crud.notify('请至少选择一条明细', CRUD.NOTIFICATION_TYPE.INFO)
        return false
      }
    },
    billTypeChange(val) {
      if (val === '000101') {
        this.bill_btn = false
        this.mater_btn = true
      } else if (val === '000102') {
        this.bill_btn = true
        this.mater_btn = false
      } else {
        this.bill_btn = true
        this.mater_btn = true
      }
      this.form.tableData = []
      this.form.total_qty = 0
      this.form.detail_count = 0
    },
    tableChanged2(row) {
      // 新增一行物料时，给行进行赋值
      this.nowrow.material_code = row.material_code
      this.nowrow.material_id = row.material_id
      this.nowrow.material_name = row.material_name
      this.nowrow.qty_unit_id = row.base_unit_id
      this.nowrow.qty_unit_name = row.unit_name
      this.form.tableData.splice(this.nowindex, 1, this.nowrow) // 通过splice 替换数据 触发视图更新
    },
    fun(val) {
      return Number(val).toFixed(3)
    },
    async queryMater(index, row) {
      checkoutbill.paramByCodeType({ 'bill_type': this.form.bill_type, 'io_flag': '00' }).then(res => {
        this.materType = res.materType
        this.materShow = true
        this.nowindex = index
        this.nowrow = row
      })
    },
    async insertdtl() {
      if (this.form.bill_type == '') {
        this.crud.notify('请选择业务类型！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      this.form.tableData.push({ quality_scode: '01', is_active: '1', ivt_level: '01', plan_qty: '0' })
      this.form.detail_count = this.form.tableData.length
    },
    deleteRow(index, rows) {
      debugger
      const package_box_sn = rows[index].package_box_sn
      let len = rows.length
      while (len--) {
        const obj = rows[len]
        if (package_box_sn === obj.package_box_sn) {
          const index = rows.indexOf(obj)
          if (index > -1) { // 移除找到的指定元素
            this.form.total_qty = parseFloat(this.form.total_qty) - parseFloat(rows[index].plan_qty)
            rows.splice(index, 1)
            this.form.detail_count = this.form.tableData.length
          }
        }
      }
    },
    tableChanged(rows) {
      debugger
      // 对新增的行进行校验不能存在相同物料批次
      rows.forEach((item) => {
        let same_mater = true
        this.form.tableData.forEach((row) => {
          if (row.container_name === item.container_name) {
            same_mater = false
          }
        })
        if (same_mater) {
          item.quality_scode = '01'
          item.ivt_level = '01'
          item.is_active = '1'
          this.form.total_qty = parseFloat(this.form.total_qty) + parseFloat(item.plan_qty)
          this.form.tableData.splice(-1, 0, item)
        }
      })
      this.form.detail_count = this.form.tableData.length
    },
    async insertEvent(row) {
      if (this.form.bill_type == '') {
        this.crud.notify('请选择业务类型！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      this.opendtlParam = {
        optType: 'add'
      }
      this.dtlShow = true
    }
  }
}
</script>

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

.crud-opts2 .crud-opts-right2 {
  margin-left: auto;
}
</style>
