<template>
  <el-dialog
    title="出库单编辑"
    append-to-body
    fullscreen
    :before-close="crud.cancelCU"
    :visible.sync="crud.status.cu > 0 || crud.status.view > 0"
    @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-input v-show="false" v-model="form.stor_code" placeholder="仓库编码" />
      <el-input v-show="false" v-model="form.stor_name" placeholder="仓库名称" />
      <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"
          @change="storChange"
        >
          <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"
        >
          <el-option
            v-for="item in billtypelist"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </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>

    <div class="crud-opts2">
      <span class="role-span">出库明细</span>
      <span v-if="crud.status.cu > 0" class="crud-opts-right2">

        <!--左侧插槽-->
        <slot name="left" />
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="queryDtl()"
        >
          添加物料
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="insertdtl()"
        >
          新增一行
        </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="50" align="center" />
      <el-table-column show-overflow-tooltip prop="material_code" label="物料编码" width="190" align="center">
        <template scope="scope">
          <el-input v-show="!scope.row.edit" v-model="scope.row.material_code" disabled class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="queryMater(scope.$index, scope.row)" />
          </el-input>
          <span v-show="scope.row.edit">{{ scope.row.material_code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="material_name" label="物料名称" align="center" min-width="150px" show-overflow-tooltip />
      <el-table-column show-overflow-tooltip prop="pcsn" label="子卷号" align="center">
        <template scope="scope">
          <el-input v-show="!scope.row.edit" v-model="scope.row.pcsn" size="mini" />
          <span v-show="scope.row.edit">{{ scope.row.pcsn }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="plan_qty" label="出库重量" width="150" align="center">
        <template scope="scope">
          <el-input-number v-show="!scope.row.edit" v-model="scope.row.plan_qty" :precision="3" :controls="false" :min="1" style="width: 120px" />
          <span v-show="scope.row.edit">{{ scope.row.plan_qty }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="qty_unit_name" label="单位" align="center" />
      <!-- <el-table-column prop="quality_scode" label="品质类型" align="center" width="110px">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.quality_scode"
            class="filter-item"
            :disabled="scope.row.edit"
          >
            <el-option
              v-for="item in dict.ST_QUALITY_SCODE"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

        </template>
      </el-table-column>
      <el-table-column prop="ivt_level" label="库存等级" align="center" width="100px">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.ivt_level"
            class="filter-item"
            :disabled="scope.row.edit"
          >
            <el-option
              v-for="item in dict.ST_IVT_LEVEL"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="is_active" label="是否可用" align="center" width="110px">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.is_active"
            class="filter-item"
            :disabled="scope.row.edit"
          >
            <el-option
              v-for="item in dict.is_used"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>-->

      <el-table-column prop="source_bill_type" label="源单类型" align="center" width="130px" :formatter="invtypeFormat" show-overflow-tooltip />
      <el-table-column prop="source_bill_code" label="源单号" align="center" width="130px" show-overflow-tooltip />
      <el-table-column show-overflow-tooltip prop="remark" label="明细备注" align="center">
        <template scope="scope">
          <el-input v-model="scope.row.remark" size="mini" />
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="crud.status.cu > 0" align="center" label="操作" width="160" 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="materType" @tableChanged="tableChanged" />
    <MaterDialog :dialog-show.sync="materShow" :mater-opt-code.sync="materType" @setMaterValue="setMaterValue" />
  </el-dialog>
</template>

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

const defaultForm = {
  bill_code: '',
  stor_id: '',
  stor_code: '',
  stor_name: '',
  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, MaterDialog },
  mixins: [crud(), form(defaultForm)],
  props: {
    dialogShow: {
      type: Boolean,
      default: false
    }
  },
  dicts: ['io_bill_status', 'ST_QUALITY_SCODE', 'ST_IVT_LEVEL', 'is_used', 'QC_INV_TYPE'],
  data() {
    return {
      dialogVisible: false,
      dtlShow: false,
      materType: '',
      materShow: false,
      flagnow: false,
      nowrow: {},
      nowindex: '',
      storlist: [],
      billtypelist: [
        { 'name': '发货出库', 'code': '111111' }
      ],
      invtypelist: [],
      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) {
        this.dialogVisible = newValue
      }
    }
  },
  methods: {
    open() {
      // 查询原材料库的仓库
      crudStorattr.getStor({ 'is_productstore': '1' }).then(res => {
        this.storlist = res.content
      })
      /*     crudRawAssist.getType({ 'io_code': '0101', 'io_flag': '01' }).then(res => {
        this.billtypelist = res
      })
      checkoutbill.getInvTypes().then(res => {
        this.invtypelist = res
      })*/
    },
    close() {
      this.$emit('AddChanged')
    },
    [CRUD.HOOK.beforeSubmit]() {
      if (this.form.tableData.length === 0) {
        this.crud.notify('请至少选择一条明细', CRUD.NOTIFICATION_TYPE.INFO)
        return false
      }
    },
    [CRUD.HOOK.afterToEdit]() {
      checkoutbill.getOutBillDtl({ 'iostorinv_id': this.form.iostorinv_id }).then(res => {
        this.form.tableData = res
        // 将明细变成不可编辑
        for (let i = 0; i < this.form.tableData.length; i++) {
          const row = this.form.tableData[i]
          row.edit = true
          this.form.tableData.splice(i, 1, row)
        }
      })
    },
    [CRUD.HOOK.afterToView]() {
      checkoutbill.getOutBillDtl({ 'iostorinv_id': this.form.iostorinv_id }).then(res => {
        this.form.tableData = res
        // 将明细变成不可编辑
        for (let i = 0; i < this.form.tableData.length; i++) {
          const row = this.form.tableData[i]
          row.edit = true
          this.form.tableData.splice(i, 1, row)
        }
      })
    },
    invtypeFormat(row, column) {
      for (const item of this.invtypelist) {
        if (item.code === row.source_bill_type) {
          return item.name
        }
      }
    },
    storChange(row) {
      this.storlist.forEach((item) => {
        if (item.stor_id === row) {
          this.form.stor_code = item.stor_code
          this.form.stor_name = item.stor_name
        }
      })
    },
    async queryMater(index, row) {
      if (this.form.bill_type === '') {
        this.crud.notify('请选择业务类型！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      this.materShow = true
      /*     checkoutbill.paramByCodeType({ 'bill_type': this.form.bill_type }).then(res => {
             this.materType = res.materType
             this.nowindex = index
             this.nowrow = row
           })*/
    },
    async queryDtl(index, row) {
      if (this.form.bill_type === '') {
        this.crud.notify('请选择业务类型！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      this.dtlShow = true
      /*    checkoutbill.paramByCodeType({ 'bill_type': this.form.bill_type }).then(res => {
            this.materType = res.materType
          })*/
    },
    tableChanged(rows) {
      const tablemap = new Map()
      rows.forEach((item) => {
        if (this.form.tableData.length !== 0) {
          this.flagnow = false
          for (let i = 0; i < this.form.tableData.length; i++) {
            if (this.form.tableData[i].material_id === item.material_id) {
              this.flagnow = true
            }
          }
          if (!this.flagnow) {
            item.edit = true
            item.quality_scode = '00'
            tablemap.set(item.material_id, item)
          }
        } else {
          item.edit = true
          item.quality_scode = '00'
          tablemap.set(item.material_id, item)
        }
      })
      for (const value of tablemap.values()) {
        this.form.tableData.push(value)
      }
      this.form.detail_count = this.form.tableData.length
    },
    setMaterValue(row) {
      for (let i = 0; i < this.form.tableData.length; i++) {
        if (this.form.tableData[i].material_id === row.material_id) {
          this.crud.notify('不允许添加相同物料！')
          return false
        }
      }
      this.nowrow.material_id = row.material_id
      this.nowrow.material_code = row.material_code
      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.nowrow.plan_qty = '1'
      this.nowrow.edit = false
      this.form.tableData.splice(this.nowindex, 1, this.nowrow) // 通过splice 替换数据 触发视图更新
    },
    async insertdtl() {
      if (this.form.bill_type === '') {
        this.crud.notify('请选择业务类型！', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      this.form.tableData.push({ material_id: '', material_code: '', material_name: '', pcsn: '', quality_scode: '00', plan_qty: '1', qty_unit_name: '', qty_unit_id: '', remark: '', edit: false })
      this.form.detail_count = this.form.tableData.length
    },
    deleteRow(index, rows) {
      this.form.total_qty = parseFloat(this.form.total_qty) - parseFloat(rows[index].plan_qty)
      rows.splice(index, 1)
      this.nowindex = ''
      this.nowrow = {}
      this.form.detail_count = this.form.tableData.length
    }
  }
}
</script>

<style>
.crud-opts2 {
  padding: 0 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}
.crud-opts2 .crud-opts-right2 {
  margin-left: auto;
  padding: 4px 4px;
}
.input-with-select  {
  background-color: #fff;
}
</style>
