<template>
  <div class="bg-in-stock">
    <el-form ref="supplierReturnsAddForm" :model="supplierReturnsAddForm" label-width="120px" inline style="width:1200px">
      <h3>退货单</h3>
      <el-form-item label="退货时间" prop="return_time">
        <el-date-picker v-model="supplierReturnsAddForm.return_time" value-format="timestamp" type="datetime"
          :disabled="type === 'detail' || type === 'audit'" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属部门">
        <el-cascader v-model="supplierReturnsAddForm.dept_id" :options="deptList"
          :disabled="type === 'detail' || type === 'audit'" :props="{
            label: 'name',
            value: 'id',
            emitPath: false,
            checkStrictly: true
          }" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="经手人" prop="handle_by_id">
        <el-select v-model="supplierReturnsAddForm.handle_by_id" :disabled="type === 'detail' || type === 'audit'">
          <el-option v-for="item in adminList" :key="item.id" :label="item.real_name" :value="item.id" />
        </el-select>
        <!-- <el-input v-model="supplierReturnsAddForm.handle_by" :minlength="2" :maxlength="20" clearable
          :disabled="type === 'detail' || type === 'audit'" placeholder="请输入经手人"></el-input> -->
      </el-form-item>
      <el-form-item label="对应入库单" style="white-space: nowrap;">
        <el-button v-if="supplierReturnsAddForm.warehouse_entry_sn" class="button" size="mini" type="text"
          @click="handleSelectWarehouseEntryBatch">{{
            supplierReturnsAddForm.warehouse_entry_sn }}</el-button>
        <el-button v-else-if="type !== 'detail'" class="button" size="mini" type="primary"
          @click="handleSelectWarehouseEntryBatch" :disabled="type === 'audit'">选择</el-button>
      </el-form-item>
      <el-form-item label="相关合同">
        <!-- <el-button v-if="type !== 'detail'" class="button" size="mini" type="primary" @click="handleSelectContract"
          :disabled="type === 'audit'">选择</el-button> -->
        <span v-if="supplierReturnsAddForm.contract_sn">{{ supplierReturnsAddForm.contract_sn }}</span>
      </el-form-item>
      <el-form-item label="附件" prop="attachment">
        <el-upload multiple :action="MixinUploadApi" :file-list="fileList"
          :on-success="(res) => { supplierReturnsAddForm.attachment = res.url }" :limit="1"
          :disabled="type === 'detail' || type === 'audit'">
          <el-button size="mini" type="primary" :disabled="type === 'detail' || type === 'audit'">上传</el-button>
        </el-upload>
        <a v-if="supplierReturnsAddForm.attachment" :href="supplierReturnsAddForm.attachment" target="_blank"
          style="color:#409EFF;font-size:12px">下载附件</a>
      </el-form-item>
      <div class="mx">
        <h3>退货明细</h3><span v-if="supplierReturnsAddForm.supplier_name"
          style="margin-left:10px;color:#409EFF;font-size:12px">供应商名称:{{ supplierReturnsAddForm.supplier_name
          }}</span>
      </div>
      <div style="display:block">
        <el-form-item>
          <el-table :data="supplierReturnsAddForm.item_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
            <el-table-column label="商品编号" width="150">
              <template slot-scope="scope">
                {{ scope.row.product_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称" width="150">
              <template slot-scope="scope">
                {{ scope.row.product_name }}
              </template>
            </el-table-column>
            <el-table-column label="规格型号" width="150">
              <template slot-scope="scope">
                {{ scope.row.product_specification }}
              </template>
            </el-table-column>
            <el-table-column label="单位" width="150">
              <template slot-scope="scope">
                {{ scope.row.product_unit }}
              </template>
            </el-table-column>
            <el-table-column label="采购价" width="150" v-if="checkPermission(['supplierReturns:caigouprice'])">
              <template slot-scope="scope">
                ¥{{ scope.row.entry_price ? scope.row.entry_price : scope.row.product_price }}
              </template>
            </el-table-column>
            <el-table-column label="入库数量" width="80">
              <template slot-scope="scope">
                {{ scope.row.entry_num }}
              </template>
            </el-table-column>
            <el-table-column label="退货数量" width="150">
              <template slot-scope="scope">
                <el-input maxlength="12" v-model="scope.row.return_num"
                  :disabled="type === 'detail' || type === 'audit'" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <el-button v-if="type === 'audit'" type="primary" @click="auditsupplierReturnsForm('AuditPass')">审核通过
      </el-button>
      <el-button v-if="type === 'audit'" type="danger" @click="auditsupplierReturnsForm('AuditReject')">审核驳回
      </el-button>
      <el-button v-if="type !== 'audit' && type !== 'detail'" type="primary" @click="submitsupplierReturnsAddForm">保存
      </el-button>
      <el-button @click="roBack()">返回
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as API_Setting from '@/api/setting'
import * as API_Supplier from '@/api/supplier'
import * as API_Purchase from '@/api/purchase'
import { Foundation } from '~/ui-utils'
import * as API_Auth from '@/api/auth'
export default {
  name: 'supplierReturnsAdd',
  data() {
    return {
      adminList: [],
      fileList: [],
      deptList: [],
      id: '',
      type: '',
      /** 商品列表 */
      goodsList: [],
      /** 供应商退货表单*/
      supplierReturnsAddForm: {
        contract_sn: '',
        warehouse_entry_sn: '',
        handle_by_id: '',
        item_list: []
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  mounted() {
    if (this.$route.name === 'supplierReturnsAudit') {
      this.type = 'audit'
    } else if (this.$route.name === 'supplierReturnsAdd') {
      this.supplierReturnsAddForm.handle_by_id = this.user.uid
      this.supplierReturnsAddForm.dept_id = this.user.dept_id
      this.$set(this.supplierReturnsAddForm, 'return_time', new Date().getTime())
    } else if (this.$route.name === 'supplierReturnsDetail') {
      this.type = 'detail'
    }
    if (this.$route.params.id) {
      this.id = this.$route.params.id
      this.supplierReturnsAddForm.id = this.$route.params.id
      this.GET_supplierReturnsDetail()
    }
    this.GET_DeptList()
    this.GET_AdministratorList()
  },
  methods: {
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    auditsupplierReturnsForm(status) {
      this.$confirm('确定吗？', '提示', { type: 'warning' }).then(() => {
        API_Supplier.auditsupplierReturns(this.id, { status: status }).then(response => {
          this.$message.success('审核完成')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'supplierReturns' })
        })
      }).catch(() => { })
    },
    // 选择合同
    async handleSelectContract() {
      const Contract = await this.$EnPickerContract({
        goodsApi: '/admin/procurement/contract',
        limit: 1,
        selectedIds: this.supplierReturnsAddForm.contract_id && [this.supplierReturnsAddForm.contract_id]
      })
      if (!Contract.length) return
      this.supplierReturnsAddForm.contract_sn = Contract[0].sn
      this.supplierReturnsAddForm.contract_id = Contract[0].id
    },
    // 选择出库单
    async handleSelectWarehouseEntryBatch() {
      const warehouseEntry = await this.$EnwarehouseEntry({
        goodsApi: 'admin/erp/warehouseEntry',
        purchasePlanApiParams: { status: 'AuditPass' },
        selectedIds: this.id ? this.supplierReturnsAddForm.item_list && this.supplierReturnsAddForm.item_list.map(item => item.id) : this.supplierReturnsAddForm.item_list.map(item => item.id),
        limit: 1
      })
      if (warehouseEntry || warehouseEntry.length) {
        this.supplierReturnsAddForm.warehouse_entry_id = warehouseEntry[0].id
        this.supplierReturnsAddForm.warehouse_entry_sn = warehouseEntry[0].sn
        this.supplierReturnsAddForm.contract_sn = warehouseEntry[0].contract_sn
        this.supplierReturnsAddForm.supplier_name = warehouseEntry[0].supplier_name
        API_Purchase.getPurchaseWarehousingInfo(warehouseEntry[0].id).then(response => {
          if (response.batch_list) {
            this.supplierReturnsAddForm.item_list = response.batch_list.map(item => {
              item.warehouse_entry_batch_id = item.id
              return item
            })
          }
        })
      }
    },
    roBack() {
      const { callback } = this.$route.params
      if (typeof callback === 'function') callback()
      this.$store.dispatch('delCurrentViews', {
        view: this.$route,
        $router: this.$router
      })
      this.$router.push({ name: 'supplierReturns' })
    },
    submitsupplierReturnsAddForm() {
      const { id } = this.supplierReturnsAddForm
      const params = this.MixinClone(this.supplierReturnsAddForm)
      params.return_time = Math.floor(params.return_time / 1000)
      if (id) {
        API_Supplier.editsupplierReturns(id, params).then(response => {
          this.$message.success('修改成功！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'supplierReturns' })
        })
      } else {
        API_Supplier.addsupplierReturns(params).then(() => {
          this.$message.success('添加成功！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'supplierReturns' })
        })
      }
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 获取采购计划详情页面数据 */
    GET_supplierReturnsDetail() {
      API_Supplier.getsupplierReturnsInfo(this.id).then(response => {
        this.supplierReturnsAddForm = response
        this.supplierReturnsAddForm.return_time = Math.floor(this.supplierReturnsAddForm.return_time * 1000)
        this.fileList = response.attachment ? [{ name: '附件', url: response.attachment }] : []
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;

  .button {
    margin-left: 10px;
  }
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.goods-info {
  display: flex;

  .goods-name-box {
    text-align: left;

    .goods-name {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 16px;
    }

    .specs {
      color: #999999;
    }
  }
}

/deep/ {
  .el-input--suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}

/deep/ .el-form-item {
  width: 500px;
}
</style>
