<template>
  <div class="work-order__wrapper">
    <template v-if="isSalesWarehouselist">
      <el-form ref="formRef" :model="list">
        <div>
          <show-data-table
            style="margin: 0px; padding: 0"
            :sitem="{...sitem,...outItem,...{currentWorkOrder}}"
            :columns="setWorkOrderColumns"
          />
          <el-table size="mini" border :data="list">
            <el-table-column prop="outChildCode" label="发货工单编号" width="160px" show-overflow-tooltip />
            <el-table-column label="发货仓库名称" prop="wsm_name" width="180px" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-popover placement="top" width="380" trigger="hover">
                  <h2>发货仓库</h2>
                  <ul>
                    <li>编码 : {{ scope.row.wsm_code }}</li>
                    <li>负责人 : {{ scope.row.contactor_name }}</li>
                    <li>所在供应商名称 : {{ scope.row.supplierName }}</li>
                    <li>所在供应商编码 : {{ scope.row.supplierNo }}</li>
                  </ul>
                  <i slot="reference" class="el-icon-warning-outline" />
                </el-popover>
                <span>{{ scope.row.wsm_name }}</span>
              </template>
            </el-table-column>

            <el-table-column width="110px" show-overflow-tooltip>
              <template slot="header">
                <span style="color:red;margin-right:2px">*</span>退货数量
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="`${scope.$index}.return_num`" :rules="paramsRules.return_num">
                  <digital-input
                    :values="list[scope.$index].return_num"
                    :placeholder="'退货数量'"
                    :disabled="false"
                    :max="100000000000"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    :new-time="newTime"
                    @reschange="onNumberChange($event, scope.$index)"
                  />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column v-if="!state.isStock" min-width="160px" show-overflow-tooltip>
              <template slot="header">
                <span style="color:red;margin-right:2px">*</span>退货仓库
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="`${scope.$index}.return_wsm_code`" :rules="paramsRules.return_wsm_code">
                  <search-stock
                    :size="'mini'"
                    :value="list[scope.$index].return_wsm_code"
                    :placeholder="'仓库名称'"
                    :is-relation="true"
                    :wsmtype="'5'"
                    :company-no="currentCompany"
                    :names="''"
                    @searchChange="onStockChange($event, scope.$index)"
                  />

                </el-form-item></template>
            </el-table-column>

            <el-table-column label="退货仓库" align="center">
              <!-- <el-table-column label="所在供应商名称" prop="returnSupplierName" min-width="160px" show-overflow-tooltip />
              <el-table-column label="所在供应商编码" prop="returnSupplierNo" min-width="160px" show-overflow-tooltip />
              <el-table-column label="负责人" width="110px" prop="returnSupplierNameContactor" show-overflow-tooltip /> -->

              <tempalte v-if="state.isStock">
                <el-table-column label="负责人" min-width="110px" prop="contactor_name" show-overflow-tooltip />
                <el-table-column label="仓库名称" prop="wsm_name" min-width="160px" show-overflow-tooltip />
                <el-table-column label="所在供应商名称" prop="supplierName" min-width="160px" show-overflow-tooltip />
                <el-table-column label="所在供应商编码" prop="supplierNo" min-width="160px" show-overflow-tooltip />
              </tempalte>

              <template v-else>
                <el-table-column label="所在供应商名称" prop="returnSupplierName" min-width="160px" show-overflow-tooltip />
                <el-table-column label="所在供应商编码" prop="returnSupplierNo" min-width="160px" show-overflow-tooltip />
                <el-table-column label="负责人" min-width="110px" prop="returnSupplierNameContactor" show-overflow-tooltip />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </template>

    <template v-else>
      <el-form ref="formRef" :model="formData" :rules="paramsRules">
        <el-form-item prop="return_wsm_code" label="销售仓">
          <search-stock
            style="width:300px"
            :size="'mini'"
            :value="wsmCode"
            :placeholder="'销售仓'"
            :is-relation="true"
            :wsmtype="'5'"
            :company-no="currentCompany"
            :names="''"
            @searchChange="onStockChange1($event)"
          />
        </el-form-item>
      </el-form>
    </template>

    <el-button class="fr" style="margin:10px 0px" size="mini" type="primary" :loading="subLoading" @click="onSetOrderReturnChild">{{ confirmText }}</el-button>
  </div>
</template>

<script>
import asyncRequest from '@/apis/service/sellOut/sellAfterApply'
import companyHelper from '@/mixins/companyHelper'
import resToken from '@/mixins/resToken'
import { setWorkOrderColumns } from './ShowDataTableColumns'

export default {
  name: 'WorkOrder',
  mixins: [resToken, companyHelper],
  props: ['sitem', 'outItem', 'workOrderCount', 'currentWorkOrder'],
  data: () => ({
    list: [],
    companyNo: '',
    loading: false,
    subLoading: false,
    setWorkOrderColumns,
    newTime: null,
    formData: {
      return_wsm_code: '',
      return_num: '0'
    }
  }),
  computed: {
    confirmText() {
      if (!this.isSalesWarehouselist) return '保存'
      return Number(this.workOrderCount) !== Number(this.currentWorkOrder + 1) ? '保存当前设置,并切换至下一个' : '保存当前设置'
    },
    state() {
      const { order_type, is_addr } = this.sitem || {}
      return ({
        isHasWorkOrder: this.list && this.list.length !== 0, // true:有发货工单 false：无发货工单
        isStock: String(order_type) === '1', // true:库存品 false：非库存品/采返商品/报备商品
        isHasAddr: String(is_addr) === '1' // true:有地址 false：无地址
      })
    },
    isSalesWarehouselist() {
      const { isHasAddr, isHasWorkOrder, isStock } = this.state
      // 有发货工单 && 库存品
      if (isHasAddr && isHasWorkOrder & isStock) return true
      // 有地址 && 不是库存品
      if (isHasAddr && !isStock) return true
      return false
    },
    paramsRules() {
      return ({
        return_wsm_code: [{
          required: true,
          message: '请选择退货仓库',
          trigger: 'change'
        }]
      })
    }
  },
  watch: {
    outItem: {
      handler() {
        if (!this.outItem) return
        this.onRequestSendList()
      }
    }
  },
  methods: {
    onStockChange1({ code }) {
      this.formData.return_wsm_code = code ? [code] : ''
      this.$nextTick(() => this.$refs.formRef.validate())
    },
    async onRequestSendList() {
      const { data, code, message } = await asyncRequest.sendList({ outCode: this.outItem.outCode })

      switch (code) {
        case 0:
          this.list = data.map(item => ({
            ...item,
            return_num: this.outItem ? Number(this.outItem.return_num) : 0,
            return_wsm_code: this.sitem.order_type === '1' ? [item.wsm_code] : '' }
          ))
          break
        default:
          this.$message.warning(message)
          break
      }

      this.newTime = new Date().valueOf()
    },
    onStockChange({ code, supplierName, supplierNo, contactor } = {}, index) {
      this.$set(this.list, index, {
        ...this.list[index],
        return_wsm_code: code ? [code] : '',
        returnSupplierName: supplierName,
        returnSupplierNo: supplierNo,
        returnSupplierNameContactor: contactor
      })

      this.$nextTick(() => this.$refs.formRef.validate())
    },
    onNumberChange(return_num, index) {
      this.$set(this.list, index, {
        ...this.list[index],
        return_num
      })
    },
    async onSetOrderReturnChild() {
      this.$refs.formRef.validate(async isValid => {
        if (!isValid) return

        let sum = 0
        const list = this.list.map(({ outChildCode, return_num, return_wsm_code }) => {
          sum += return_num
          return {
            return_wsm_code: Array.isArray(return_wsm_code) ? return_wsm_code[0] : return_wsm_code,
            outChildCode,
            return_num
          }
        })

        const salesWarehouseParams = { list, returnCode: this.sitem.returnCode, outCode: this.outItem.outCode }
        const parms = {
          list: [{
            return_wsm_code: Array.isArray(this.formData.return_wsm_code)
              ? this.formData.return_wsm_code[0]
              : this.formData.return_wsm_code,
            return_num: this.sitem.num
          }],
          returnCode: this.sitem.returnCode,
          outCode: this.outItem.outCode
        }

        if (sum !== Number(this.outItem.return_num) && this.isSalesWarehouselist) {
          this.$message.warning('退货数量的和必须与发货单的退货数量一致')
          return
        }

        const { code, message } = await asyncRequest.reorderChildAdd(this.isSalesWarehouselist ? salesWarehouseParams : parms)
        this.subLoading = false
        switch (code) {
          case 0:
            this.$message.success('工单设置成功!')
            this.$emit('reload')
            break
          default:
            this.$message.warning(message)
            break
        }
      })
    }
  }
}
</script>
