<template>
  <div>
    <el-page-header
      :content="detailsId?'编辑':'新增'"
      style=" padding: 20px 20px 0 20px;"
      @back="handleBack"
    />
    <sales-header ref="header" @setStokType="setStokType" />
    <sales-table
      :data-list="dataList"
      :column="column"
      :is-operation="detailsId ? false : true"
      is-selection
      @handleSelection="handleSelection"
    >
      <template #bts>
        <div v-if="!detailsId">
          <el-button v-if="dis" type="primary" size="mini" @click="handleAdd">添加 </el-button>
          <el-button v-if="dis" type="danger" size="mini" @click="delChange">删除 </el-button>
        </div>
      </template>
      <template #events>
        <div v-if="!detailsId">
          <el-button type="primary" :disabled="!dis" size="mini" @click="handelSubmit(1)">提交</el-button>
          <el-button v-if="dis" size="mini" @click="onReset">重置 </el-button>
          <el-button v-if="stokType == 1 || details.stockType ==1" size="mini" :disabled="dis" @click="handleInform(2)">通知发货</el-button>
        </div>
        <div v-else>
          <el-button type="primary" size="mini" @click="handelSubmit(2)">保存</el-button>
          <el-button v-if="!detailsId" size="mini" @click="onReset">重置</el-button>
        </div>
      </template>

      <template v-slot:operation="{ item: { row, $index } }">
        <el-popconfirm v-if="dis" style="margin-left: 10px" title="删除？" @onConfirm="handleDel(row, $index)">
          <el-button slot="reference" type="text" size="mini">删除</el-button>
        </el-popconfirm>
      </template>
    </sales-table>
    <sales-dialog
      ref="dia"
      :dialog-visible="dialogVisible"
      :customer-number="customerNumber"
      :data-list="dataList"
      :func="getDialogList"
      @confirm="confirm"
    />
  </div>
</template>

<script>
import SalesDialog from '@/components/SalesDialog/SalesDialog'
import SalesHeader from '@/components/SalesHeader/SalesHeader'
import SalesTable from '@/components/SalesTable/SalesTable'
import { addFrontOrder, getFrontOrderDetail, sbumitFrontOrder, updateFrontOrder } from '@/api/sales'
import { getcustomerFrontList, getFrontListCustomer } from '@/api/stock'

export default {
  name: 'WarehouseForm',
  components: {
    SalesHeader,
    SalesTable,
    SalesDialog
  },
  props: ['detailsId', 'pageType'],
  data() {
    return {
      dialogVisible: false,
      customerNumber: '',
      dataList: [],
      selection: [],
      disabled: false,
      flag: 1,
      dis: true,
      column: [
        {
          prop: 'materialName',
          label: '产品名称',
          width: '180'
        },
        {
          prop: 'materialCode',
          label: '物料编码',
          width: '180'
        },
        {
          prop: 'specification',
          label: '规格型号',
          width: '300'
        },
        {
          prop: 'frontStockNum',
          label: ' 前置仓结存数量',
          width: '180'
        },
        {
          prop: 'customerStockNum',
          label: '自有仓结存数量',
          width: '180'
        },
        {
          prop: 'qty',
          label: '数量',
          width: '180',
          isInput: true
        },
        {
          prop: 'notes',
          label: '备注',
          width: '180',
          isInput: true,
          type: 'text'
        }
      ],
      isFront: JSON.parse(localStorage.getItem('supply_user')).isFront,
      salesId: '',
      stokType: null,
      details: {}
    }
  },
  created() {
    if (this.detailsId) {
      getFrontOrderDetail({ id: this.detailsId }).then(res => {
        this.details = res.data
        this.dataList = res.data.orders
        // this.dataList  = res.data.orders.map(k => {
        //   k.disabledId = k.customerStockId
        //   return k
        // })
        this.customerNumber = res.data.customerNumber
        this.$refs.header.screenForm = res.data
        this.$refs.header.screenForm.disabled = this.disabled = true
        this.$refs.header.screenForm.provinceId = res.data.province
        this.$refs.header.screenForm.cityId = res.data.city
        this.$refs.header.screenForm.areaId = res.data.area
        this.$refs.header.screenForm.streetId = res.data.street
        this.$refs.header.screenForm.stockType = Number(res.data.stockType)
      })
    } else {
      Object.assign(this.$data, this.$options.data())
      this.column = [
        {
          prop: 'materialName',
          label: '产品名称',
          width: '180'
        },
        {
          prop: 'materialCode',
          label: '物料编码',
          width: '180'
        },
        {
          prop: 'specification',
          label: '规格型号',
          width: '300'
        },
        {
          prop: 'frontStockNum',
          label: ' 前置仓结存数量',
          width: '180'
        },
        {
          prop: 'customerStockNum',
          label: '自有仓结存数量',
          width: '180'
        },
        {
          prop: 'qty',
          label: '数量',
          width: '180',
          isInput: true
        },
        {
          prop: 'notes',
          label: '备注',
          width: '180',
          isInput: true,
          type: 'text'
        }
      ]
    }
  },
  methods: {
    getDialogList(p) {
      let func = getcustomerFrontList
      if (this.isFront === true) {
        func = getcustomerFrontList
      }
      if (this.isFront === false) {
        func = getFrontListCustomer
      }
      return func(...p)
    },
    confirm(selected) {
      this.dataList = [...this.dataList, ...selected]
      for (let i = 0; i < this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData.length; i++) {
        for (let j = 0; j < this.dataList.length; j++) {
          if (
            this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i].id == this.dataList[j].id ||
            this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i].disabled === false
          ) {
            this.$set(this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i], 'disabled', false)
          } else {
            this.$set(this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i], 'disabled', true)
          }
        }
      }
      console.log(this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData)
      if (!this.detailsId) {
        this.$refs.header.screenForm.customerName = this.dataList[0].customerName
        this.$refs.header.screenForm.customerNumber = this.dataList[0].customerNumber
        // this.$refs.header.screenForm.stockType = this.dataList[0].stockType
      }

      this.customerNumber = this.dataList[0].customerNumber
      this.dialogVisible = false
      this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.$refs.tableView.clearSelection()
    },
    handleDel(item, index) {
      this.dataList.splice(index, 1)
      this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData.find(k => {
        if (k.id == item.id) {
          this.$set(k, 'disabled', true)
          return
        }
      })
      // this.$refs.multipleTable.clearSelection()

      // console.log(this.$refs.dia)
      // if (!this.dataList.length) {
      //   this.$nextTick(() => {
      //     Object.assign(this.$refs.header.$data, this.$refs.header.$options.data())
      //     this.customerNumber = ''
      //   })
      // }
    },
    // 去掉相同数据
    resArr(arr1, arr2) {
      return arr1.filter(v => arr2.every(val => val.id != v.id))
    },
    setStokType(e) {
      this.stokType = e
    },
    delChange() {
      if (this.dataList.length) {
        for (let i = 0; i < this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData.length; i++) {
          for (let j = 0; j < this.selection.length; j++) {
            if (
              this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i].id == this.selection[j].id ||
              this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i].disabled === true
            ) {
              // k.disabled = true
              this.$set(this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i], 'disabled', true)
            }
          }
        }
        this.dataList = this.resArr(this.dataList, this.selection)

        if (!this.dataList.length) {
          this.customerNumber = ''
        }
      }
    },
    handleSelection(data) {
      this.selection = data
    },
    handleInform(status = 2) {
      sbumitFrontOrder({ id: this.salesId, status }).then(res => {
        this.$successMsg('通知发货')
        this.handleBack()
      })
    },
    handleAdd() {
      // if (!this.stokType) {
      //   this.$errorMsg('请先选择发货仓库')
      //   return
      // }
      this.dialogVisible = true
    },
    handelSubmit(type, status = 1) {
      if (!this.dataList.length) {
        this.$errorMsg('请添加产品')
        return
      }
      for (let i = 0; i < this.dataList.length; i++) {
        this.dataList[i].id = ''
        this.dataList[i].directFlag = this.dataList[i].flag
        if (Number(this.dataList[i].qty) < 0 || !this.dataList[i].qty) {
          this.$errorMsg(`第${i + 1}产品数量有误`)
          return
        }
      }

      const params = {
        ...this.$refs.header.screenForm,
        orders: this.dataList,
        status: status
      }
      this.$refs.header.$refs.form.validate(valid => {
        if (valid) {
          if (type == 1) {
            params.id = ''
            addFrontOrder(params).then(res => {
              this.$successMsg('新增成功')
              this.dis = false
              this.disabled = true
              this.$set(this.$refs.header.screenForm, 'disabled', true)
              this.column = [
                {
                  prop: 'materialName',
                  label: '产品名称',
                  width: '180'
                },
                {
                  prop: 'materialCode',
                  label: '物料编码',
                  width: '180'
                },
                {
                  prop: 'specification',
                  label: '规格型号',
                  width: '300'
                },
                {
                  prop: 'stockQty',
                  label: '库存数量',
                  width: '180'
                },
                {
                  prop: 'qty',
                  label: '数量',
                  width: '180'
                },
                {
                  prop: 'notes',
                  label: '备注',
                  width: '180',

                  type: 'text'
                }
              ]
              if (this.stokType === 2) {
                this.handleBack()
              }
              this.salesId = res.data
              this.$set(this.$refs.header.screenForm, 'id', res.data)
              this.$forceUpdate()
            })
          } else {
            updateFrontOrder(params).then(res => {
              this.$successMsg('编辑成功')
              this.handleBack()
              this.$forceUpdate()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    onReset() {
      Object.assign(this.$data, this.$options.data())
      Object.assign(this.$refs.header.$data, this.$refs.header.$options.data())
    },
    handleBack() {
      this.$emit('close')
    }

  }
}
</script>

<style scoped></style>
