<template>
  <div class="work-order__wrapper">
    <template v-if="isSalesWarehouselist">
      <el-form ref="formRef" :model="list">
        <el-table size="mini" border :data="list">
          <el-table-column prop="orderCode" label="销售订单" width="160px" show-overflow-tooltip />
          <el-table-column prop="outCode" label="发货单" width="160px" show-overflow-toolti />
          <el-table-column prop="outChildCode" label="发货工单" width="160px" show-overflow-tooltip />
          <el-table-column label="发货仓库所在供应商名称" prop="supplierName" width="170px" show-overflow-tooltip />
          <el-table-column label="发货仓库所在供应商编码" prop="supplierNo" width="170px" show-overflow-tooltip />
          <el-table-column prop="wsm_name" label="发货仓库名称" width="160px" show-overflow-tooltip />
          <el-table-column prop="wsm_code" label="发货仓库编码" width="170px" show-overflow-tooltip />
          <el-table-column prop="contactor_name" label="发货仓库负责人" width="110px" show-overflow-tooltip />
          <el-table-column prop="num" label="发货数量" show-overflow-tooltip />
          <el-form>
            <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="''"
                    @reschange="onNumberChange($event, scope.$index)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column 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
                    :is-detail="false"
                    :size="'mini'"
                    :value="list[scope.$index].return_wsm_code"
                    :placeholder="'仓库名称'"
                    :is-relation="true"
                    :wsmtype="'5'"
                    :company-no="currentCompany"
                    :disbaled="!currentCompany"
                    :names="''"
                    @searchChange="onStockChange($event, scope.$index)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-form>
          <el-table-column label="退货仓库所在供应商名称" prop="returnSupplierName" width="160px" show-overflow-tooltip />
          <el-table-column label="退货仓库所在供应商编码" prop="returnSupplierNo" width="160px" show-overflow-tooltip />
          <el-table-column label="退货仓库负责人" width="110px" prop="returnSupplierNameContactor" show-overflow-tooltip />
        </el-table>
      </el-form>
    </template>

    <template v-else>
      <el-form ref="formRef" :model="formData" :rules="rules">
        <el-form-item prop="return_wsm_code" label="销售仓" style="display:flex">
          <search-stock
            style="width:300px"
            :is-detail="false"
            :size="'mini'"
            :value="wsmCode"
            :placeholder="'销售仓'"
            :is-relation="true"
            :wsmtype="'5'"
            :company-no="currentCompany"
            :disbaled="!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">保存</el-button>
  </div>
</template>

<script>
import asyncRequest from '@/apis/service/sellOut/sellAfterApply'
import companyHelper from '@/mixins/companyHelper'
import resToken from '@/mixins/resToken'
export default {
  name: 'WorkOrder',
  mixins: [resToken, companyHelper],
  props: ['sitem'],
  data: () => ({
    list: [],
    loading: false,
    subLoading: false,
    companyNo: '',
    formData: {
      return_wsm_code: '',
      return_num: '0'
    }
  }),
  computed: {
    state() {
      const { order_type, send_type } = this.sitem || {}

      return ({
        isHasWorkOrder: this.list && this.list.length !== 0, // true:有发货工单 false：无发货工单
        isStock: String(order_type) === '1', // true:库存品 false：非库存品/采返商品/报备商品
        isHasAddr: String(send_type) === '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'
        }],
        return_num: [{
          required: false
        }]
      })
    }
  },
  watch: {
    sitem: {
      handler() {
        if (!this.sitem) return
        this.onRequestSendList()
      },
      immediate: true
    }
  },
  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({ orderCode: this.sitem.orderCode })
      switch (code) {
        case 0:
          this.list = data.list.map(item => ({ ...item, return_num: 0, return_wsm_code: '' }))
          break
        default:
          this.$message.warning(message)
          break
      }
    },
    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

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

        const salesWarehouseParams = {
          list,
          type: '1',
          returnCode: this.sitem.returnCode
        }

        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,
          type: '1'
        }

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