<template>
  <div class="work-order__wrapper">
    <el-form ref="formRef" :model="list">
      <el-table size="mini" border :data="list">
        <el-table-column label="发货工单" align="center">
          <el-table-column prop="outChildCode" label="编号" width="160px" show-overflow-tooltip />
          <el-table-column label="计划发货数量" width="100px" prop="num" />
          <el-table-column prop="outChildCode" label="提退货时的发货单状态" width="145px" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag size="mini">
                {{ (statusOptions.find(({value}) => value === String(scope.row.status)) || {}).label || '--' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="发货仓库名称" prop="wsm_name" min-width="180px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-popover placement="top" width="380" trigger="hover">
              <h3>发货仓库</h3>
              <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="list[scope.$index].num"
                :position="'right'"
                :precision="0"
                :size="'mini'"
                :controls="false"
                :append="''"
                @reschange="onNumberChange($event, scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!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
                :disabled="isStock"
                :size="'mini'"
                :value="list[scope.$index].return_wsm_code"
                :placeholder="'仓库名称'"
                :is-relation="true"
                :wsmtype="'5'"
                :company-no="currentCompany"
                @searchChange="onStockChange($event, scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="退货仓库" align="center">
          <tempalte v-if="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>
    </el-form>

    <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: () => ({
    names: [],
    list: [],
    loading: false,
    subLoading: false,
    companyNo: '',
    statusOptions: [
      { value: '1', label: '待发货' },
      { value: '2', label: '发货完成' },
      { value: '3', label: '已收货' },
      { value: '4', label: '已全部退货' }
    ]
  }),
  computed: {
    isStock() {
      const { order_type } = this.sitem || {}
      return order_type === '1'
    },
    paramsRules() {
      return ({
        return_wsm_code: [{
          required: true,
          message: '请选择退货仓库',
          trigger: 'change'
        }]
      })
    }
  },
  watch: {
    sitem: {
      async handler() {
        if (!this.sitem || !this.sitem.outCode) { return }
        const { outCode, order_type } = this.sitem
        const isStock = order_type === '1'
        const { data, code, message } = await asyncRequest.sendList({ outCode })
        switch (code) {
          case 0:
            this.list = data.map(item => {
              return {
                ...item,
                return_num: 0,
                names: isStock ? item.wsm_name : '',
                return_wsm_code: isStock ? [item.wsm_code] : ''
              }
            })
            break
          default:
            this.$message.warning(message)
            break
        }
      },
      immediate: true
    }
  },
  methods: {
    onStockChange({ code, supplierName, supplierNo, contactor_name } = {}, index) {
      this.$set(this.list, index, {
        ...this.list[index],
        returnSupplierNo: supplierNo,
        returnSupplierName: supplierName,
        return_wsm_code: code ? [code] : '',
        returnSupplierNameContactor: contactor_name
      })

      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 += Number(return_num)
          return {
            return_num,
            outChildCode,
            return_wsm_code: Array.isArray(return_wsm_code) ? return_wsm_code[0] : return_wsm_code
          }
        })

        if (Number(this.sitem.error_num) !== sum) {
          this.$message.warning('退货数量的和与异常数量不一致')
          return
        }

        const { code, message } = await asyncRequest.setOrderReturnChild({
          list,
          returnCode: this.sitem.returnCode
        })

        this.subLoading = false

        switch (code) {
          case 0:
            this.$emit('reload')
            break
          default:
            this.$message.warning(message)
            break
        }
      })
    }
  }
}
</script>
