<template>
  <div class="bg-in-stock">
    <el-form ref="purchaseWarehousingForm" :model="purchaseWarehousingForm" label-width="120px" inline
      style="width:1100px">
      <h3>采购入库单</h3>
      <el-form-item label="入库时间" prop="entry_time">
        <el-date-picker v-model="purchaseWarehousingForm.entry_time" value-format="timestamp" type="datetime"
          :disabled="type === 'detail' || type === 'audit'" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商" prop="supplier_id">
        <el-select v-model="purchaseWarehousingForm.supplier_id" :disabled="type === 'detail' || type === 'audit'">
          <el-option v-for="item in supplierList" :key="item.id" :label="item.custom_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="dept_id">
        <el-cascader v-model="purchaseWarehousingForm.dept_id" :options="deptList" :disabled="type === 'detail'" :props="{
          label: 'name',
          value: 'id',
          emitPath: false,
          checkStrictly: true
        }" clearable @change="changewarehouseList"></el-cascader>
      </el-form-item>
      <el-form-item label="仓库">
        <el-select v-model="purchaseWarehousingForm.warehouse_id" :disabled="type === 'detail' || type === 'audit'">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="相关合同">
        <el-button v-if="type !== 'detail'" class="button" size="mini" type="primary"
          :disabled="type === 'detail' || type === 'audit'" @click="handleSelectContract">选择</el-button>
        <span v-if="contract_sn">{{ contract_sn }}</span>
      </el-form-item>
      <el-form-item label="经手人" prop="handled_by_id">
        <el-select v-model="purchaseWarehousingForm.handled_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="purchaseWarehousingForm.handled_by" :minlength="2" :maxlength="20" clearable
          :disabled="type === 'detail'" placeholder="请输入经手人"></el-input> -->
      </el-form-item>
      <el-form-item label="车牌号" prop="plate_number">
        <el-input v-model="purchaseWarehousingForm.plate_number" :minlength="2" :maxlength="20" clearable
          :disabled="type === 'detail' || type === 'audit'" placeholder="请输入车牌号"></el-input>
      </el-form-item>
      <el-form-item label="送货单号" prop="delivery_number">
        <el-input v-model="purchaseWarehousingForm.delivery_number" :minlength="2" :maxlength="20" clearable
          :disabled="type === 'detail' || type === 'audit'" placeholder="请输入送货单号"></el-input>
      </el-form-item>
      <el-form-item label="关联计划">
        <el-button v-if="type !== 'detail'" class="button" size="mini" type="primary"
          :disabled="type === 'detail' || type === 'audit'" @click="handleSelectPlan">选择</el-button>
        <span v-if="plan_sn">{{ plan_sn }}</span>
      </el-form-item>
      <el-form-item label="附件" prop="contract_attachment" style="width: 500px;">
        <el-upload v-if="type !== 'detail'" multiple :action="MixinUploadApi" :file-list="fileList"
          :on-success="(res) => { purchaseWarehousingForm.contract_attachment = res.url }" :limit="1">
          <el-button size="mini" type="primary" :disabled="type === 'detail' || type === 'audit'">上传</el-button>
        </el-upload>
        <a v-if="purchaseWarehousingForm.contract_attachment && type !== 'add'"
          :href="purchaseWarehousingForm.contract_attachment"
          style="color:#409EFF;font-size:12px">下载附件</a>
      </el-form-item>
      <div class="mx">
        <h3>入库明细</h3>
        <el-button class="button" size="mini" type="primary" v-if="type !== 'detail'"
                   @click="handleSelectGoods">选择</el-button>
      </div>
      <div style="display:block">
        <el-form-item>
          <el-table :data="purchaseWarehousingForm.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.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.specification }}
              </template>
            </el-table-column>
            <el-table-column label="单位" width="150">
              <template slot-scope="scope">
                {{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column label="单价" width="150">
              <template slot-scope="scope">
                <el-input :maxlength="12" v-model="scope.row.price" @input="jisuan(scope.row)"
                          :disabled="type === 'detail'">
                  <template slot="prepend">¥</template>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column label="合同数量" width="130">
              <template slot-scope="scope">
                {{ scope.row.num }}
              </template>
            </el-table-column>
            <el-table-column label="已入库数量" width="130">
              <template slot-scope="scope">
                {{ scope.row.stock_num }}
              </template>
            </el-table-column>
            <el-table-column label="本次入库数量" width="130">
              <template slot-scope="scope">
                <el-input :maxlength="8" v-model="scope.row.rknum" @input="change(scope.row)"
                  :disabled="type === 'detail' || type === 'audit'" />
              </template>
            </el-table-column>
            <el-table-column label="税率(%)" width="80">
              <template slot-scope="scope">
                <el-input :maxlength="12" v-model="scope.row.tax_rate" :disabled="type === 'detail'" />
              </template>
            </el-table-column>
            <el-table-column label="合价" width="150">
              <template slot-scope="scope">
                {{ scope.row.total_price }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="130" v-if="type !== 'detail' && type !== 'audit'">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                  @click="purchaseWarehousingForm.product_list.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
      <div class="mx" v-if="type === 'detail'">
        <h3>退货单</h3>
      </div>
      <div v-if="type === 'detail'">
        <el-form-item>
          <en-table-layout :tableData="thtableData.data" style="width:1100px;padding:0px;" :toolbar="false" border>
            <template slot="table-columns">
              <el-table-column prop="sn" label="退货单编号">
                <template slot-scope="scope">
                  <router-link
                    v-if="checkPermission(['supplierReturns'])"
                    style="color: #409eff;"
                    :to="{ name: 'supplierReturnsDetail', params: { id: scope.row.id } }">
                    {{ scope.row.sn }}</router-link>
                    <span v-else>{{scope.row.sn}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="username" label="退货日期">
                <template slot-scope="scope">{{ scope.row.return_time | unixToDate }}</template>
              </el-table-column>
              <el-table-column prop="dept_name" label="所属部门" />
              <el-table-column prop="warehouse_name" label="仓库" />
              <el-table-column prop="supplier_name" label="供应商" />
              <el-table-column prop="warehouse_entry_sn" label="对应入库单编号" />
              <el-table-column prop="handle_by_name" label="经手人" />
              <el-table-column prop="status" label="状态">
                <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
              </el-table-column>
              <el-table-column prop="audit_by" label="审核人" />
            </template>
            <el-pagination v-if="thtableData" slot="pagination" @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange" :current-page="thtableData.page_no"
              :page-sizes="[10, 20, 50, 100]" :page-size="thtableData.page_size"
              layout="total, sizes, prev, pager, next, jumper" :total="thtableData.data_total">
            </el-pagination>
          </en-table-layout>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <el-button v-if="type === 'audit'" type="primary" @click="auditpurchaseWarehousingForm('AuditPass')">审核通过
      </el-button>
      <el-button v-if="type === 'audit'" type="danger" @click="auditpurchaseWarehousingForm('AuditReject')">审核驳回
      </el-button>
      <el-button v-if="type !== 'audit' && type !== 'detail'" type="primary" @click="submitpurchaseWarehousingForm">保存
      </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_BasicSetting from '@/api/basicSetting'
import * as API_Purchase from '@/api/purchase'
import { Foundation } from '~/ui-utils'
import * as API_Auth from '@/api/auth'
import * as API_Supplier from '@/api/supplier'
export default {
  name: 'purchaseWarehousingAdd',
  data() {
    return {
      thtableData: '',
      params: {
        page_no: 1,
        page_size: 10
      },
      type: '',
      adminList: [],
      fileList: [],
      supplierList: [],
      warehouseList: [],
      deptList: [],
      contract_sn: '',
      plan_sn: '',
      id: '',
      /** 出库单表单*/
      purchaseWarehousingForm: {
        handled_by_id: '',
        product_list: []
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (this.$route.name === 'purchaseWarehousingAudit') {
          this.type = 'audit'
        } else if (this.$route.name === 'purchaseWarehousingAdd') {
          this.type = 'add'
          this.purchaseWarehousingForm = {
            handled_by_id: '',
            product_list: []
          }
          this.purchaseWarehousingForm.handled_by_id = this.user.uid
          this.purchaseWarehousingForm.dept_id = this.user.dept_id
          this.GET_WarehouseList({ dept_id: this.user.dept_id })
          this.$set(this.purchaseWarehousingForm, 'entry_time', new Date().getTime())
        } else if (this.$route.name === 'purchaseWarehousingDetail') {
          this.type = 'detail'
        }
        if (this.$route.params.id) {
          this.id = this.$route.params.id
          this.GET_PurchaseWarehousingDetail()
        }
      }
    }
  },
  mounted() {
    this.GET_DeptList()
    this.GET_SupplierList()
    this.GET_AdministratorList()
  },
  methods: {
    /** 获取供应商退货列表 */
    GET_supplierReturnsList() {
      API_Supplier.getsupplierReturnsList(this.params).then(response => {
        this.thtableData = response
      })
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_supplierReturnsList()
    },
    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_supplierReturnsList()
    },
    statusFilter(val) {
      switch (val) {
        case 'NotSubmit':
          return '未提交'
        case 'Submit':
          return '已提交'
        case 'AuditPass':
          return '审核通过'
        case 'AuditReject ':
          return '审核驳回'
        default:
          return ''
      }
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    jisuan(row) {
      console.log(row)
      if (row.price && row.rknum) {
        row.total_price = row.price * row.rknum
      }
    },
    // 选择商品
    async handleSelectGoods() {
      const Goods = await this.$EnPickerGoods({
        goodsApi: '/admin/erp/product',
        selectedIds: this.id ? this.purchaseWarehousingForm.product_list && this.purchaseWarehousingForm.product_list.map(item => item.product_id) : this.purchaseWarehousingForm.product_list.map(item => item.product_id)
      })
      if (!Goods.length) return
      const product_list = Goods.map(item => {
        item.product_sn = item.sn
        item.product_name = item.name
        item.specification = item.specification
        item.product_id = item.id
        item.category_name = item.category_name
        item.category_id = item.category_id
        item.unit = item.unit
        return item
      })
      this.purchaseWarehousingForm.product_list = this.purchaseWarehousingForm.product_list && this.purchaseWarehousingForm.product_list.length ? this.purchaseWarehousingForm.product_list.concat(product_list) : this.purchaseWarehousingForm.product_list = product_list
    },
    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: 'purchaseWarehousing' })
    },
    auditpurchaseWarehousingForm(status) {
      this.$confirm('确定吗？', '提示', { type: 'warning' }).then(() => {
        API_Purchase.auditPurchaseWarehousing(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: 'purchaseWarehousing' })
        })
      }).catch(() => { })
    },
    submitpurchaseWarehousingForm() {
      const { id } = this.purchaseWarehousingForm
      const params = this.MixinClone(this.purchaseWarehousingForm)
      params.entry_time = Math.floor(params.entry_time / 1000)
      if (params.product_list && params.product_list.length) {
        params.product_list = params.product_list.map(item => {
          item.num = item.rknum
          item.product_id = item.product_id
          item.price = item.price
          item.tax_rate = item.tax_rate
          return item
        })
      }
      if (id) {
        API_Purchase.editPurchaseWarehousing(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: 'purchaseWarehousing' })
        })
      } else {
        API_Purchase.addPurchaseWarehousing(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: 'purchaseWarehousing' })
        })
      }
    },
    /** 获取采购入库详情页面数据 */
    GET_PurchaseWarehousingDetail() {
      API_Purchase.getPurchaseWarehousingInfo(this.id).then(response => {
        this.purchaseWarehousingForm = response
        this.GET_WarehouseList({ dept_id: response.dept_id })
        this.purchaseWarehousingForm.entry_time = Math.floor(response.entry_time * 1000)
        this.fileList = response.contract_attachment ? [{ name: '附件', url: response.contract_attachment }] : []
        this.contract_sn = response.contract_sn
        this.plan_sn = response.procurement_plan_sn
        if (response.product_list && response.product_list.length) {
          this.purchaseWarehousingForm.product_list = response.product_list.map(item => {
            item.product_sn = item.sn
            item.product_name = item.name
            item.rknum = item.num
            item.product_id = item.product_id
            item.num = item.contract_num
            item.stock_num = item.already_num
            item.price = item.contract_price
            return item
          })
        }
        this.params.warehouse_entry_id = this.id
        this.GET_supplierReturnsList()
      })
    },
    // 选择合同
    async handleSelectContract() {
      const Contract = await this.$EnPickerContract({
        goodsApi: '/admin/procurement/contract',
        purchasePlanApiParams: { contract_status: 'EXECUTING' },
        limit: 1,
        selectedIds: this.purchaseWarehousingForm.contract_id && [this.purchaseWarehousingForm.contract_id]
      })
      if (!Contract.length) return
      this.contract_sn = Contract[0].sn
      this.purchaseWarehousingForm.contract_id = Contract[0].id
      API_Purchase.getContractInfo(Contract[0].id).then(response => {
        this.purchaseWarehousingForm.product_list = this.purchaseWarehousingForm.product_list.concat(response.product_list)
      })
    },
    // 选择采购计划
    async handleSelectPlan() {
      const Plan = await this.$EnPickerPlan({
        goodsApi: '/admin/procurement/plan',
        limit: 1,
        selectedIds: this.purchaseWarehousingForm.purchase_plan_id && [this.purchaseWarehousingForm.purchase_plan_id]
      })
      if (!Plan.length) return
      this.plan_sn = Plan[0].sn
      this.purchaseWarehousingForm.purchase_plan_id = Plan[0].id
    },
    changewarehouseList(e) {
      this.$set(this.purchaseWarehousingForm, 'warehouse_id', '')
      this.GET_WarehouseList({ dept_id: e })
    },
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll(e).then(response => {
        this.warehouseList = response
      })
    },
    /** 获取供应商 */
    GET_SupplierList() {
      API_BasicSetting.getSupplierListAll().then(response => {
        this.supplierList = response
      })
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    change(row) {
      this.$forceUpdate()
      this.jisuan(row)
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
/deep/ .el-form-item {
  width: 350px;
}

/** 底部步骤 */
.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>
