<template>
  <div>
    <div class="my-title">{{ !id ? '新增' : display ? '详情' : '修改' }}</div>
    <!-- 表单 -->
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="auto">
      <el-row class="my-row">
        <el-col :span="8">
          <el-form-item label="项目号" prop="contractId">
            <contract-component v-model="dataForm.contractId" :contract-id="dataForm.contractId" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div class="title">发货时间</div>
        <el-table :data="dataForm.list" border style="width: 100%;">
          <el-table-column label="序号" type="index" width="50" align="center">
          </el-table-column>
          <el-table-column prop="productName" header-align="center" align="center" label="名称">
          </el-table-column>
          <el-table-column prop="productSpec" header-align="center" align="center" label="型号/规格">
          </el-table-column>
          <el-table-column prop="deliverCode" header-align="center" align="center" label="编号">
          </el-table-column>
          <el-table-column prop="batchNumber" header-align="center" align="center" label="批次号">
          </el-table-column>
          <el-table-column prop="deliverCnt" header-align="center" align="center" label="数量">
          </el-table-column>
          <el-table-column prop="price" header-align="center" align="center" label="单价">
          </el-table-column>
          <el-table-column prop="amount" header-align="center" align="center" label="总价">
          </el-table-column>
          <el-table-column prop="notes" header-align="center" align="center" label="备注">
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="80" label="操作">
            <template slot-scope="scope">
              <el-button style="color: red" type="text" size="small" @click="removeItem(scope.$index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="text-align: center; margin-top: 10px;">
          <el-button v-show="!display" type="primary" icon="el-icon-plus" @click="addDeliverList"></el-button>
        </el-row>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onChose">取消</el-button>
      <el-button v-if="!display" type="primary" @click="dataFormSubmit()" v-reClick>确定</el-button>
    </span>

    <el-dialog title="添加" width="70%" :close-on-click-modal="false" :visible.sync="addItemVisible">
      <div>
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()">
          <el-form-item label="名称/图号">
            <el-input v-model="dataForm.materialName" placeholder="名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button @click="search()">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table border :data="whMaterialRecords" @selection-change="itemSelectionChangeHandle">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center">
          </el-table-column>
          <el-table-column prop="orderName" header-align="center" align="center" min-width="100"
            :show-tooltip-when-overflow="true" label="名称">
          </el-table-column>
          <el-table-column prop="mapNumber" header-align="center" align="center" min-width="100"
            :show-tooltip-when-overflow="true" label="图号">
          </el-table-column>
          <el-table-column prop="specifications" header-align="center" align="center" min-width="100"
            :show-tooltip-when-overflow="true" label="规格">
          </el-table-column>
          <el-table-column prop="cnt" header-align="center" align="center" min-width="50"
            :show-tooltip-when-overflow="true" label="数量">
          </el-table-column>
          <el-table-column prop="cnt2" header-align="center" align="center" min-width="80"
            :show-tooltip-when-overflow="true" label="发货数量">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.cnt2" size="mini"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="notes" header-align="center" align="center" min-width="100"
            :show-tooltip-when-overflow="true" label="备注">
            <template slot-scope="scope">
              <el-input v-model="scope.row.notes"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer">
        <el-button @click="addItemVisible = false">取 消</el-button>
        <el-button type="primary" @click="addItemSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ContractComponent from '../common/contract-component'
export default {
  name: 'dispatch-add',
  components: { ContractComponent },
  computed: {},
  data() {
    return {
      productListVisible: false,
      drawListVisible: false,
      materialCompVisible: false,
      visible: false,
      display: false,
      addItemVisible: false,
      listingList: [],
      dataList: [],
      id: 0,
      whMaterialRecords: [],
      dataForm: {
        list: []
      },
      selectedItems: [],
      dataRule: {
        contractId: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
    }
  },
  methods: {
    onChose() {
      this.$emit('onChose')
    },
    async init(id, display) {

    },
    uploadSuccess(fileList) {
      this.fileList = fileList
    },
    // 添加组合物料
    addProduct() {
      this.productListVisible = true
      this.$nextTick(() => {
        this.$refs.productList.init()
      })
    },
    addProductItems(items) {
      // this.productDetails = []
      items.forEach((item) => {
        this.addProductItem(item)
      })
    },
    addProductItem(item) {
      let productId = item.productId
      if (!this.productDetails.some(item => item.productId === productId)) {
        this.productDetails.push({
          ...item
        })
      }
    },
    deleteProductHandle(productId) {
      this.productDetails.splice(this.productDetails.findIndex((item) => item.productId === productId), 1)
    },
    validateField(type) {
      this.$refs.dataForm.validateField(type)
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/biz-service/deliver/save`),
            method: 'post',
            data: this.$http.adornData(this.dataForm.list)
          }).then(({ data }) => {
            if (data && data.code === '200') {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.onChose()
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        } else {
          // this.$message.error('请检查输入参数')
        }
      })
    },
    // 添加发货清单
    addDeliverList() {
      this.addItemVisible = true
      this.search()
    },
    removeItem(index) {
      this.dataForm.list.splice(index, 1)
    },
    search() {
      this.$http({
        url: this.$http.adornUrl(`/biz-service/stock-mg-ctl/list`),
        method: 'get',
        params: this.$http.adornParams({
          'current': 1,
          'size': 10,
          'materialName': this.dataForm.materialName
        })
      }).then(({ data }) => {
        if (data && data.code === '200') {
          this.whMaterialRecords = data.data.records
          this.whMaterialRecords.forEach(item => {
            item.cnt2 = 0;
          });
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 选择数量变化时
    itemSelectionChangeHandle(val) {
      this.selectedItems = val
    },
    addItemSubmit() {
      // 判断是否有选择数据
      if (this.selectedItems.length === 0) {
        this.$message.error("请勾选数据")
        return
      }

      for (let index = 0; index < this.selectedItems.length; index++) {
        const element = this.selectedItems[index];
        if (element.cnt2 <= 0) {
          this.$message.error("第" + (index + 1) + "条发货数量不能小于等于0")
          return
        }
      }

      let data = this.selectedItems.map(item => {
        let temp = {
          productName: item.materialName,
          productNumber: '',
          productSpec: item.specifications,
          deleverCode: item.materialCode,
          batchNumber: (item.whBatchInfoList == null || item.whBatchInfoList.length === 0) ? '' : item.whBatchInfoList[0].batchNumber,
          deliverCnt: item.cnt2,
          price: (item.whBatchInfoList === null || item.whBatchInfoList.length === 0) ? '' : item.whBatchInfoList[0].price,
          notes: item.notes,
          mapNumber: item.mapNumber,
          materialId: item.materialId,
          unit: item.unitName
        }
        temp.amount = temp.deliverCnt * temp.price
        temp.contractId = this.dataForm.contractId
        return temp
      })

      this.dataForm.list = data

      this.addItemVisible = false
    }
  }
}
</script>

<style scoped lang="scss">
.my-row {
  margin-bottom: 0px;
}

.title {
  margin-bottom: 5px;
}

/deep/ .el-input-number--mini {
  width: 100px;
}
</style>
