<template>
  <div>
    <el-page-header
      :content="detailsId ? '编辑' : '新增'"
      style="padding: 20px 20px 0 20px"
      @back="handleBack"
    />
    <return-sales-header ref="header" :details="details" />
    <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="dialogVisible = true">添加</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="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:custom="{ item: { row, $index } }">
        <div>{{ diffQty(row) }}</div>
      </template>
      <!-- <template v-slot:custom="{ item: { row, $index } }">
        <el-radio v-model="row.flag" label="1">增加</el-radio>
        <el-radio v-model="row.flag" label="-1">减少</el-radio>
      </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"
      :data-list="dataList"
      :dialog-visible="dialogVisible"
      :return-id="returnId"
      :item-id="itemId"
      :func="getDialogList"
      @confirm="confirm"
    />
  </div>
</template>

<script>
import SalesDialog from '@/components/SalesDialog/SalesDialog'
import ReturnSalesHeader from '@/components/ReturnSalesHeader/ReturnSalesHeader'
import SalesTable from '@/components/SalesTable/SalesTable'
import {
  addFrontOrder,
  detailRefund,
  getFrontOrderDetail,
  addRefund,
  getFrontOrderList,
  sbumitFrontOrder,
  sendRefund,
  updateRefund,
  listOrder
} from '@/api/sales'
import { getcustomerFrontList, getFrontListCustomer } from '@/api/stock'

export default {
  name: 'WarehouseForm',
  components: {
    ReturnSalesHeader,
    SalesTable,
    SalesDialog
  },
  props: ['detailsId', 'pageType'],
  data() {
    return {
      dialogVisible: false,
      returnId: '',
      itemId: '',
      dataList: [],
      selection: [],
      flag: 1,
      dis: true,
      details: {},
      column: [
        {
          prop: 'materialName',
          label: '产品名称',
          width: '180'
        },
        {
          prop: 'materialCode',
          label: '物料编码',
          width: '180'
        },
        {
          prop: 'specification',
          label: '规格型号',
          width: '300'
        },

        {
          prop: 'qty',
          align: 'left',
          label: '退货数量',
          width: '180',
          isInput: true
        },

        {
          prop: '',
          label: '已退数量',
          width: '180',
          isCustom: true
        },
        // {
        //   prop: 'totalVolume',
        //   label: '总体积',
        //   width: '180'
        // },
        {
          prop: 'notes',
          label: '备注',
          isInput: true,
          type: 'text'
        }
      ],
      isFront: JSON.parse(localStorage.getItem('supply_user')).isFront,
      salesId: ''
    }
  },
  computed: {
    diffQty() {
      return row => {
        return Number(row.qty) - Number(row.refundQty)
      }
    }
  },
  created() {
    if (this.detailsId) {
      detailRefund({ id: this.detailsId }).then(res => {
        this.dataList = res.data.orders
        this.details = res.data
        this.dataList.forEach(k => {
          this.$set(k, 'refundQty', k.qty)
          k.diffQty = Number(k.qty) - Number(k.refundQty || 0)
        })
        this.details.customerOrderNo = res.data.customerOrderNo
        this.details.detailsId = res.data.id

        this.returnId = res.data.id + this.dataList[0].materialCode
      })
    } else {
      Object.assign(this.$data, this.$options.data())
    }
  },

  methods: {
    getDialogList(p) {
      // let func = getcustomerFrontList
      // if (this.isFront===true){
      //   func = getcustomerFrontList
      // }
      // if (this.isFront===false){
      //   func = getFrontListCustomer
      // }
      return listOrder(...p)
    },
    confirm(selected) {
      for (let i = 0; i < selected.length; i++) {
        if (selected[0].id != selected[i].id) {
          this.$errorMsg('不能选择不一样的销售单')
          return
        }
      }

      // console.log(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
          ) {
            if (
              this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i].itemId == this.dataList[j].itemId ||
              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)
            }
          } 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)
      selected.forEach(k => {
        k.diffQty = Number(k.qty) - Number(k.refundQty)
        k.qty = k.refundQty
      })
      const obj = {
        id: Object.freeze(this.dataList[0].id)
      }
      if (!this.detailsId) {
        this.details = this.dataList[0]
        this.details.customerOrderNo = obj.id
      }
      this.detailsId = this.detailsId

      this.returnId = obj.id
      this.itemId = this.dataList[0].itemId
      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) {
          if (k.itemId == item.itemId) {
            this.$set(k, 'disabled', true)
          } else {
            this.$set(k, 'disabled', false)
          }
          return
        }
      })
      if (!this.dataList.length) {
        this.returnId = ''
      }
      // if (!this.dataList.length){
      //   this.$nextTick(()=>{
      //     this.details = {}
      //     this.returnId = ''
      //   })
      // }
    },
    // 去掉相同数据
    resArr(arr1, arr2) {
      return arr1.filter(v => arr2.every(val => val.id != v.id))
    },
    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 === false
            ) {
              if (
                this.$refs.dia.$refs.pageRef.$refs.zjpage.$refs.tableEl.tableData[i].itemId ==
                  this.selection[j].itemId ||
                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)
              }
            } else {
              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.returnId = ''
        }
      }
    },
    handleSelection(data) {
      this.selection = data
    },

    handelSubmit(type, status = 1) {
      const list = JSON.parse(JSON.stringify(this.dataList))

      if (!list.length) {
        this.$errorMsg('请添加产品')
        return
      }
      for (let i = 0; i < list.length; i++) {
        list[i].directFlag = list[i].flag
        if (Number(list[i].qty) < 0 || !list[i].qty) {
          this.$errorMsg(`第${i + 1}产品退货数量有误`)
          return
        }
        list[i].id = ''
      }

      const params = {
        ...this.$refs.header.details,
        orders: list,
        customerOrderNo: this.details.customerOrderNo,
        status
      }
      if (type === 1) {
        params.id = ''
        addRefund(params).then(res => {
          this.$successMsg('新增成功')
          this.salesId = res.data
          this.column = [
            {
              prop: 'materialName',
              label: '产品名称',
              width: '180'
            },
            {
              prop: 'materialCode',
              label: '物料编码',
              width: '180'
            },
            {
              prop: 'specification',
              label: '规格型号',
              width: '300'
            },

            {
              prop: 'qty',
              align: 'left',
              label: '退货数量',
              width: '180'
            },

            {
              prop: 'notes',
              label: '备注',
              width: '180',

              type: 'text'
            }
          ]
          if (this.details.stockType === 2) {
            this.handleBack()
          }

          this.dis = false
          this.$forceUpdate()
        })
      } else {
        updateRefund(params).then(res => {
          this.$successMsg('编辑成功')
          this.handleBack()
          this.$forceUpdate()
        })
      }
    },
    handleInform(status = 2) {
      sendRefund({ id: this.salesId, status }).then(res => {
        this.$successMsg('退货通知')
        this.handleBack()
      })
    },

    handleBack() {
      this.$emit('close')
    },
    onReset() {
      Object.assign(this.$data, this.$options.data())
    }
  }
}
</script>

<style scoped></style>
