<template>
  <div class="bg-in-stock">
    <el-form ref="goodsLendAddForm" :model="goodsLendAddForm" :rules="goodsLendAddFormRule" label-width="120px" class="change-form" inline style="">
      <h3>库位管理</h3>
      <!-- <el-form-item label="仓库编号" prop="code">
        <el-input v-model="goodsLendAddForm.code"  placeholder="请输入仓库编号"></el-input>
      </el-form-item> -->
      <el-form-item label="仓库名称" prop="name" style="width:340px">
        <el-input v-model="goodsLendAddForm.name" placeholder="请输入仓库名称"></el-input>
      </el-form-item>
      <el-form-item label="库位号" prop="code" style="width:340px">
        <el-input v-model="goodsLendAddForm.code" placeholder="请输入库位号"></el-input>
      </el-form-item>
      <el-form-item label="仓库类型" prop="type">
        <el-select v-model="goodsLendAddForm.type" clearable>
              <el-option key="d" label="大型" value="大型" />
              <el-option key="z" label="中型" value="中型" />
              <el-option key="s" label="小型" value="小型" />
            </el-select>
      </el-form-item>
      <el-form-item label="库位说明" prop="intro">
        <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入内容"
                v-model="goodsLendAddForm.intro">
              </el-input>
      </el-form-item>
      <div class="mx">
        <h3>商品明细</h3>
        <el-button class="button" size="mini" type="primary" @click="handleSelectWarehouseEntryBatch"
          v-if="type !== 'return' && type !== 'detail'">选择</el-button>
      </div>
      <div style="display:block">
        <el-form-item>
          <el-table :data="goodsLendAddForm.product_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.warehouse_entry_sn }}
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="批次编号">
              <template slot-scope="scope">
                {{ scope.row.sn }}
              </template>
            </el-table-column> -->
            <el-table-column label="商品编号">
              <template slot-scope="scope">
                {{ scope.row.product_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template slot-scope="scope">
                {{ scope.row.product_name }}
              </template>
            </el-table-column>
            <el-table-column label="sku">
              <template slot-scope="scope">
                {{ scope.row.sku }}
              </template>
            </el-table-column>
            <el-table-column label="序列号">
              <template slot-scope="scope">
                {{ scope.row.sn_code }}
              </template>
            </el-table-column>
            <el-table-column label="规格型号">
              <template slot-scope="scope">
                {{ scope.row.product_specification }}
              </template>
            </el-table-column>
            <el-table-column label="单位">
              <template slot-scope="scope">
                {{ scope.row.product_unit }}
              </template>
            </el-table-column>
            <el-table-column label="库存数量">
              <template slot-scope="scope">
                {{ scope.row.remain_num }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="借出数量">
              <template slot-scope="scope">
                <el-input :disabled="type === 'return' || type === 'detail'" v-model="scope.row.lend_num"
                  oninput="value = value.replace(/[^\d]/g,'')" :maxlength="20"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="归还数量" v-if="type === 'return' || type === 'detail'">
              <template slot-scope="scope">
                <el-input oninput="value = value.replace(/[^\d]/g,'')" v-model="scope.row.return_num" clearable type="number" :maxlength="20"
                  :disabled="type === 'detail'"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="type !== 'return' && type !== 'detail'">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                  @click="goodsLendAddForm.product_list.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <!-- <el-button type="primary" @click="returngoodsLendAddForm" v-if="type === 'return' && type !== 'detail'">保存
      </el-button> -->
      <el-button type="primary" @click="submitGoodsLendAddForm" v-if="type !== 'return' && type !== 'detail'">保存
      </el-button>
      <el-button @click="$router.back()">返回
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as API_GoodsLend from '@/api/goodsLend'
import { Foundation } from '~/ui-utils'
import * as API_Setting from '@/api/setting'
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_Auth from '@/api/auth'
export default {
  name: 'goodsLendAdd',
  data() {
    return {
      adminList: [],
      warehouseList: [],
      deptList: [],
      deptListAll: [],
      id: '',
      type: '',
      /** 出库单表单*/
      goodsLendAddForm: {
        // product_list: []
      },
      goodsLendAddFormRule: {
        lend_person_id: { required: true, message: '请选择出借人', trigger: 'change' },
        // warehouse_id: { required: true, message: '请选择报仓库', trigger: 'change' },
        dept_id: { required: true, message: '请选择所属部门', trigger: 'change' },
        lend_register_id: { required: true, message: '请选择经手人', trigger: 'change' },
        lend_desc: this.MixinRequired('请填写借出说明')
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        this.GET_AdministratorList()
        if (this.$route.name === 'goodsLendEdit') {
          this.type = 'edit'
        } else if (this.$route.name === 'goodsLendReturn') {
          this.type = 'return'
        } else if (this.$route.name === 'goodsLendAdd') {
          this.goodsLendAddForm = {
            // product_list: []
          }
          // this.goodsLendAddForm.lend_register_id = this.user.uid
          // this.goodsLendAddForm.lend_person_id = this.user.uid
          // this.goodsLendAddForm.dept_id = this.user.dept_id
          this.GET_WarehouseList({ dept_id: this.user.dept_id })
          // this.$set(this.goodsLendAddForm, 'lend_time', new Date().getTime())
        } else if (this.$route.name === 'goodsLendDetail') {
          this.type = 'detail'
        }
        if (this.$route.params.id) {
          this.id = this.$route.params.id
          this.GET_info(this.id)
          // this.GET_goodsLendAddDetail()
        }
      }
    }
  },
  mounted() {
    this.GET_DeptList()
  },
  methods: {
    forceUpdate(e) {
      this.$forceUpdate()
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    /** 清除已选商品明细 */
    cleanGoodsList() {
      // 切换部门或仓库需要清除已选对应仓库下的商品数据
      this.$set(this.goodsLendAddForm, 'product_list', [])
    },
    changewarehouseList(e) {
      this.$set(this.goodsLendAddForm, 'warehouse_id', '')
      this.GET_WarehouseList({ dept_id: e })
      this.cleanGoodsList()
    },
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll(e).then(response => {
        this.warehouseList = response
      })
    },
    /** 提交 */
    submitGoodsLendAddForm() {
      this.$refs['goodsLendAddForm'].validate(valid => {
        if (valid) {
          const { id } = this.goodsLendAddForm
          const params = this.MixinClone(this.goodsLendAddForm)
          /* if (params.dept_id) {
            params.dept_name = this.deptListAll.find(dept => dept.id === params.dept_id).name
          }
          if (params.warehouse_id) {
            params.warehouse_name = this.warehouseList.find(ware => ware.id === params.warehouse_id).name
          }
          if (params.lend_person_id) {
            params.lend_person = this.adminList.find(admin => admin.id === params.lend_person_id).real_name
          }
          if (params.lend_register_id) {
            params.lend_register = this.adminList.find(admin => admin.id === params.lend_register_id).real_name
          }
          if (params.return_person_id) {
            params.return_person = this.adminList.find(admin => admin.id === params.return_person_id).real_name
          }
          if (params.return_register_id) {
            params.return_register = this.adminList.find(admin => admin.id === params.return_register_id).real_name
          }
          let errMsg = ''
          params.lend_time = Math.floor(params.lend_time / 1000)
          params.product_list = params.product_list.map(item => {
            if (!item.lend_num) {
              errMsg = '请填写借出数量！'
            } else if (item.lend_num > item.remain_num) {
              errMsg = '借出数量不可大于库存数量！'
            }
            item.product_sn = item.product_sn
            item.product_name = item.product_name
            item.specification = item.product_specification
            item.product_id = item.product_id
            item.unit = item.product_unit
            item.lend_num = item.lend_num
            item.stock_sn = item.warehouse_entry_sn
            item.stock_num = item.remain_num
            item.stock_batch_sn = item.sn
            return item
          })
          if (errMsg) {
            this.$message.error(errMsg)
            return
          }*/
          if (id) {
            API_GoodsLend.update(id, params).then(response => {
              this.$message.update('修改成功！')
              const { callback } = this.$route.params
              if (typeof callback === 'function') callback()
              this.$store.dispatch('delCurrentViews', {
                view: this.$route,
                $router: this.$router
              })
              this.$router.push({ name: 'goodsLend' })
            })
          } else {
            API_GoodsLend.create(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: 'goodsLend' })
            })
          }
        }
      })
    },
    /** 归还登记 */
    returngoodsLendAddForm() {
      const { id } = this.goodsLendAddForm
      const params = this.MixinClone(this.goodsLendAddForm)
      if (params.return_person_id) {
        params.return_person = this.adminList.find(admin => admin.id === params.return_person_id).real_name
      }
      if (params.return_register_id) {
        params.return_register = this.adminList.find(admin => admin.id === params.return_register_id).real_name
      }
      params.dept_name = this.deptListAll.find(dept => dept.id === params.dept_id).name
      params.warehouse_name = this.warehouseList.find(ware => ware.id === params.warehouse_id).name
      params.lend_time = Math.floor(params.lend_time / 1000)
      params.product_list = params.product_list.map(item => {
        item.product_sn = item.product_sn
        item.product_name = item.product_name
        item.specification = item.product_specification
        item.product_id = item.product_id
        item.unit = item.product_unit
        item.stock_sn = item.warehouse_entry_sn
        item.stock_num = item.remain_num
        item.stock_batch_sn = item.sn
        return item
      })
      API_GoodsLend.returnGoodsLend(id, 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: 'goodsLend' })
      })
    },
    // 选择出库单
    async handleSelectWarehouseEntryBatch() {
      if (!this.goodsLendAddForm.warehouse_id) {
        this.$message.error('请先选择仓库！')
        return
      }
      const goodsData = await this.$EnwarehouseEntryBatch({
        goodsApi: 'admin/erp/warehouseEntryBatch',
        selectedIds: this.id ? this.goodsLendAddForm.product_list && this.goodsLendAddForm.product_list.map(item => item.id) : this.goodsLendAddForm.product_list.map(item => item.id),
        warehouseList: this.warehouseList,
        purchasePlanApiParams: { warehouse_id: this.goodsLendAddForm.warehouse_id }
      })
      this.$set(this.goodsLendAddForm, 'product_list', goodsData.purchasePlans)
      this.$set(this.goodsLendAddForm, 'warehouse_id', goodsData.warehouse_id)
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
        this.deptListAll = response
      })
    },
    /** 获取采购计划详情页面数据 */
    GET_goodsLendAddDetail() {
      API_GoodsLend.getgoodsLendAddInfo(this.id).then(response => {
        this.goodsLendAddForm = response
        this.GET_WarehouseList({ dept_id: response.dept_id })
        // 归还人
        this.goodsLendAddForm.return_person_id = response.return_person_id || response.lend_person_id
        this.goodsLendAddForm.return_person = response.return_person || response.lend_person
        // 归还登记人
        this.goodsLendAddForm.return_register_id = response.return_register_id || this.user.uid
        this.goodsLendAddForm.lend_time = Math.floor(this.goodsLendAddForm.lend_time * 1000)
        this.goodsLendAddForm.product_list = this.goodsLendAddForm.product_list.map(item => {
          item.product_sn = item.product_sn
          item.product_name = item.product_name
          item.product_specification = item.specification
          item.product_id = item.product_id
          item.product_unit = item.unit
          item.lend_num = item.lend_num
          item.sn = item.stock_batch_sn
          item.remain_num = item.stock_num
          item.warehouse_entry_sn = item.stock_sn
          return item
        })
      })
    },
    GET_info(val){
      API_GoodsLend.getInfo({id:val}).then(res=>{
        this.goodsLendAddForm=res
      })
    },
  }
}
</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;
    }
  }
}
</style>
