<template>
  <p-spin :spinning="spinning">
    <p-card>
      <div slot="title" style="display: inline-block; cursor: pointer" @click="back">
        <a-icon class="mr-10" style="color: #1990ff" type="arrow-left"/>
        出库订单信息
      </div>
      <div slot="extra">
        <p-button type="primary" @click="onSubmit">保存</p-button>
      </div>
      <p-grid-form ref="formTarget" :span="6" :labelCol="{ span: 6 }" :items="items"/>
    </p-card>
    <p-card title="出库订单明细列表">
      <div slot="extra">
        <p-button type="primary" @click="onAdd">新增</p-button>
      </div>
      <div class="table">
        <p-table-edit-pro
            ref="table"
            bordered
            dragle
            :columns="columns"
            :dataSource.sync="tableData"
            row-key="lineid"
            :rowSelectType="false"
            :scroll="{ x: true }"
        >
          <span slot="action" slot-scope="text, record">
            <div>
              <a @click="grid_deleteClick(record)">删除</a>
            </div>
          </span>
        </p-table-edit-pro>
      </div>
    </p-card>
  </p-spin>
</template>

<script>
import {editForm, columns} from './js/config'
import {saveDoBillH, queryDoBillDList} from './api'
import {getDefaultCargoOwner} from "@/views/kzyWMS/utils/setCargoOwner";

export default {
  props: {
    type: '',
    editData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      spinning: false,
      items: editForm(this),
      columns: columns(this),
      tableData: [],
      selectedRowKeys: [],
      dataSource: [],
    }
  },
  mounted() {
    if (this.type === 'add') {
      this.setDefaultData()
      return
    }
    if (this.type === 'edit') {
      // 修改
      this.queryDetails(this.editData)
      this.editData.isEmergency = String(this.editData.isEmergency)
      this.$nextTick(() => {
        this.$refs.formTarget.form.setFieldsValue({
          ...this.editData,
          warehouseId: this.editData.branchid,
          warehouseCode: this.editData.branchcode,
          warehouseName: this.editData.branchname,
          cargoOwnerId: this.editData.consignorid,
          cargoOwnerName: this.editData.consignorname,
          customerName: this.editData.shippername,
          customerId: this.editData.shipperid,
          attainDate: this.editData.attainDate,
          billDate: this.editData.billDate,
        })
      })
    }
  },
  methods: {
    // 设置默认数据
    async setDefaultData() {
      // 设置仓库
      const {warehouseId, warehouseCode, warehouseName} = this.$store.getters.warehouse || {}
      this.$refs.formTarget.form.setFieldsValue({
        branchid: warehouseId,
        branchcode: warehouseCode,
        branchname: warehouseName
      })
      // 设置货主
      const cargoOwner = await getDefaultCargoOwner()
      if (!!cargoOwner) {
        const {companyCode, companyId, companyName} = cargoOwner
        console.log(cargoOwner)
        this.$refs.formTarget.form.setFieldsValue({
          consignorid: companyId,
          consignorcode: companyCode,
          consignorname: companyName
        })
      }
    },
    back() {
      this.$emit('back')
    },
    onSubmit() {
      this.$refs.formTarget.form.validateFields((error, values) => {
        if (error) {
          this.$message.warn('必填项未填写完成，请完成必填项')
          return
        }
        let a = true
        this.$refs.table.validateFields((error, values, selectData) => {
          if (error) {
            this.$message.warn('必填项未填写完成，请完成必填项')
            return
          }
          values.forEach((t) => {
            if (t.itemPcs == 0 && t.itemOdd == 0) {
              a = false
              return
            }
          })
        })
        if (!a) {
          this.$message.warn('件数或零散数需要大于0')
          return
        }
        console.log(values, 'values')
        if (!error) {
          let detailed = JSON.parse(JSON.stringify(this.tableData))
          detailed.forEach((item) => {
            if (item.lineid.includes('add')) {
              delete item.lineid
            }
            return item
          })
          values.shippercode = values.customerCode
          values.shipperid = values.customerId
          values.shippername = values.customerName
          values.omsDoBillDDOList = this.tableData
          values.attainDate = this.moment(values.attainDate).format('YYYY-MM-DD')
          values.billDate = this.moment(values.billDate).format('YYYY-MM-DD')
          let params = {}
          if (this.type == 'edit') {
            // 编辑
            values.status = this.editData.status
            values.receiveAddress = this.editData.receiveAddress
            values.billtype = this.editData.billtype
            values.billid = this.editData.billid
            values.billno = this.editData.billno
            params = {
              updateItems: [values],
            }
          } else {
            // 新增
            params = {
              insertItems: [values],
            }
          }
          // let params = Object.assign({}, this.formData, { detailed })
          this.spinning = true
          saveDoBillH(params).then((res) => {
            this.spinning = false
            if (res.success) {
              this.$message.success(res.message)
              this.$emit('back')
            } else {
              this.$message.warn(res.message)
            }
          }).catch(() => {
            this.spinning = false
          })
        }
      })
    },
    // 查询明细
    queryDetails(data) {
      this.spinning = true
      console.log(data, 'this.formData')
      queryDoBillDList({billId: data.billid, billno: data.billno, pageSize: 10, pageNum: 1}).then((res) => {
        this.spinning = false
        this.tableData = res.data.list
        if (res.data.list.length > 0) {
          res.data.list.map((res, index) => {
            this.tableData[index].itemName = res.itemname
            this.tableData[index].itemId = res.itemid
            this.tableData[index].itemCode = res.itemcode
          })
        }
      }).catch(() => {
        this.spinning = false
      })
    },
    // 新增明细
    onAdd() {
      let formData = this.$refs.formTarget.form.getFieldsValue()
      if (!formData.branchid) {
        this.$message.warn('请选择仓库名称')
        return false
      }
      if (!formData.consignorid) {
        this.$message.warn('请选择货主名称')
        return false
      }
      if (!formData.customerId) {
        this.$message.warn('请选择客户名称')
        return false
      }
      if (!formData.billtype) {
        this.$message.warn('请选择单据类型')
        return false
      }
      const {consignorname} = formData
      // const id = 'local' + Math.floor(Math.random() * 1000000)
      this.$refs.table.createRow(0, {consignorname})
    },
    // 删除明细
    grid_deleteClick(record) {
      let index = this.tableData.findIndex((item) => item.lineid === record.lineid)
      this.tableData.splice(index, 1)
      this.$message.success('明细删除成功')
      return
    },
  },
}
</script>

<style lang="less" scoped>
.searchModal {
  cursor: pointer;
}
/deep/ .p-search-modal .modal-cap-search{
  z-index: 1;
}
/deep/ .date-range {
  .ant-calendar-picker {
    width: 100% !important;
  }
}
</style>
