<template>
  <div class="purchaseOrderWarehousing-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" @back="handleBack" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="purchaseOrderWarehousing-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span class="billno">单号：{{ (detail&&detail[0]&&detail[0].purchaseBillNo) ? detail[0].purchaseBillNo : '--' }}</span>
        </template>
      </a-page-header>
      <!-- 内容 -->
      <a-card size="small" v-for="(item,bindex) in detail" :key="item.id" :bordered="false" class="purchaseOrderWarehousing-cont">
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom:10px">
          <div slot="message" >
            <div>产品款数 <strong>{{ item.totalPutCategory }}</strong> ，本次发货数量合计 <strong>{{ item.totalPutQty }}</strong> ，本次发货金额合计￥<strong>{{ item.totalPutAmount }}</strong></div>
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable"
          :ref="'table-'+bindex"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :tableId="item.receivingBillSn"
          :index="bindex"
          :scroll="{ x: 1280 }"
          bordered>
          <!-- 采购数量 -->
          <template slot="origqty" slot-scope="text, record, index">
            <div>{{ text }}</div>
            <div v-if="record.origqty">原采购数量：{{ record.origqty }}</div>
          </template>
          <!-- 仓库仓位 -->
          <template slot="warehousePosition" slot-scope="text, record, index">
            <a-cascader
              size="small"
              @change="e => changeWarehouseCascade(e, record, index, bindex)"
              v-model="record.warehouseCascade"
              :disabled="!(item.auditState=='WAIT_PUT_WAREHOUSE' || item.auditState == 'PUT_WAREHOUSE_AUDIT_REJECT')"
              expand-trigger="hover"
              :options="warehouseCascadeData"
              :fieldNames="{ label: 'name', value: 'sn', children: 'warehouseLocationList' }"
              id="purchaseOrderWarehousing-warehouseCascade"
              placeholder="请选择仓库仓位"
              :allowClear="false"
              style="width: 100%;" />
          </template>
        </s-table>
        <div style="text-align: center;">
          <a-button
            type="primary"
            class="button-warning"
            :id="'purchaseOrderWarehousing-warehousing-'+bindex"
            @click="handleWarehousing(item,bindex)"
            v-if="item.auditState=='WAIT_PUT_WAREHOUSE' || item.auditState == 'PUT_WAREHOUSE_AUDIT_REJECT'"
          >确认入库</a-button>
        </div>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import { purchaseWriteStockIn, receivingQuery, receivingDetail } from '@/api/purchase'
import { purchaseUpdateWarehouse } from '@/api/purchaseDetail'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import { warehouseCascadeList } from '@/api/warehouse'
export default {
  components: { STable, VSelect, ProductType, ProductBrand },
  data () {
    return {
      spinning: false,
      detail: null, //  详情数据
      productType: [],
      queryParam: {
        productBrandSn: undefined,
        queryWord: '',
        brand: '',
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      },
      disabled: false, //  查询、重置按钮是否可操作
      warehouseCascadeData: [], //  仓库仓位
      defaultWarehouseCascade: [], //  默认仓库仓位
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 70, align: 'center' },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: 180, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'dealerProductEntity.origCode', width: 180, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购单价', dataIndex: 'discountedPrice', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购数量', dataIndex: 'qty', width: 80, align: 'center', scopedSlots: { customRender: 'origqty' } },
        { title: '本次发货数量', dataIndex: 'shippedQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '本次发货金额', dataIndex: 'discountedAmount', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') }, fixed: 'right' },
        { title: '本次入库数量', dataIndex: 'putQty', width: 100, align: 'center', customRender: function (text) { return text || '--' }, fixed: 'right' },
        { title: '仓库仓位', scopedSlots: { customRender: 'warehousePosition' }, width: 150, align: 'center', fixed: 'right' }
      ],
      chooseLoadData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.queryParam.receivingBillSn = parameter.tableId
        return receivingDetail(Object.assign(parameter, this.queryParam)).then(res => {
          const data = res.data
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
            data.list[i].shippedQty = data.list[i].putQty
            const warehouseSn = data.list[i].warehouseSn || undefined
            const warehouseLocationSn = data.list[i].warehouseLocationSn || undefined
            if (warehouseSn || warehouseLocationSn) {
              data.list[i].warehouseSnBackups = warehouseSn
              data.list[i].warehouseLocationSnBackups = warehouseLocationSn
              data.list[i].warehouseCascade = [warehouseSn, warehouseLocationSn]
            } else {
              //  设置默认仓库
              if (this.defaultWarehouseCascade.length > 0) {
                data.list[i].warehouseCascade = this.defaultWarehouseCascade
                data.list[i].warehouseSn = this.defaultWarehouseCascade[0]
                data.list[i].warehouseLocationSn = this.defaultWarehouseCascade[1]
              } else {
                data.list[i].warehouseCascade = undefined
              }
            }
          }
          this.disabled = false
          this.chooseLoadData[parameter.index] = data.list
          return data
        })
      }
    }
  },
  methods: {
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  重置产品库
    resetSearchForm () {
      this.queryParam = {
        productBrandSn: undefined,
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        queryWord: '',
        brand: ''
      }
      this.productType = []
      this.$refs.table.refresh(true)
    },
    // 判断是否选择了仓库
    hasChoseWarehousing (data) {
      return data.find(item => !item.warehouseCascade || item.warehouseCascade.length == 0)
    },
    //  确认入库
    handleWarehousing (row, index) {
      const list = this.chooseLoadData[index]
      if (this.hasChoseWarehousing(list)) {
        this.$message.warning('请选择仓库仓位！')
        return
      }
      this.spinning = true
      purchaseWriteStockIn({ id: row.id }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.getDetail()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/purchasingManagement/purchaseOrder/list', query: { closeLastOldTab: true } })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //  详情
    getDetail () {
      receivingQuery({ purchaseBillSn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detail = res.data
        } else {
          this.detail = null
        }
      })
    },
    //  仓库仓位  级联  列表
    getWarehouseCascade () {
      const _this = this
      warehouseCascadeList({}).then(res => {
        if (res.status == 200) {
          res.data.filter(item => {
            // 过滤默认仓库
            if (item.defaultFlag == 1 && item.wasteFlag == 0) { //  defaultFlag为1,且不是废品仓
              _this.defaultWarehouseCascade[0] = item.warehouseSn
              // 过滤默认仓位
              item.warehouseLocationList.filter(subItem => {
                if (subItem.defaultFlag == 1 && subItem.wasteFlag == 0) {
                  _this.defaultWarehouseCascade[1] = subItem.warehouseLocationSn
                  if (_this.detail && _this.detail.length > 0) {
                    _this.detail.map((k, i) => {
                      _this.$refs['table-' + i][0].refresh(true)
                    })
                  }
                }
              })
            }
          })
          res.data.map(item => {
            item.sn = item.warehouseSn
            if (item.warehouseLocationList) {
              item.warehouseLocationList.map(subItem => {
                subItem.sn = subItem.warehouseLocationSn
              })
            }
          })
          this.warehouseCascadeData = res.data
        } else {
          this.warehouseCascadeData = []
        }
      })
    },
    // 修改仓库仓位
    changeWarehouseCascade (val, opt, ind, bindex) {
      let loadData = this.chooseLoadData[bindex][ind]
      if (val.length == 1) {
        this.$message.warning('当前仓库无仓位，请选择其他仓库')
        const warehouseSnBackups = loadData.warehouseSnBackups || undefined
        const warehouseLocationSnBackups = loadData.warehouseLocationSnBackups || undefined
        loadData.warehouseSn = warehouseSnBackups
        loadData.warehouseLocationSn = warehouseLocationSnBackups
        if (warehouseSnBackups || warehouseLocationSnBackups) {
          loadData.warehouseCascade = [warehouseSnBackups, warehouseLocationSnBackups]
        } else {
          loadData.warehouseCascade = undefined
        }
      } else {
        loadData.warehouseSn = val[0] ? val[0] : ''
        loadData.warehouseLocationSn = val[1] ? val[1] : ''
        loadData.warehouseSnBackups = val[0] ? val[0] : ''
        loadData.warehouseLocationSnBackups = val[1] ? val[1] : ''
        loadData = this.chooseLoadData[bindex][ind]
        this.updateWarehouse(loadData, bindex)
      }
    },
    // 修改仓库
    updateWarehouse (row, bindex) {
      this.spinning = true
      purchaseUpdateWarehouse({
        id: row.id,
        warehouseSn: row.warehouseSn,
        warehouseLocationSn: row.warehouseLocationSn
      }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          console.log(bindex, this.$refs)
          this.$refs['table-' + bindex][0].refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    }
  },
  mounted () {
    this.getDetail()
    this.getWarehouseCascade()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (!vm.disabled) {
        vm.getDetail()
        vm.getWarehouseCascade()
      }
    })
  }
}
</script>

<style lang="less">
  .purchaseOrderWarehousing-wrap{
    position: relative;
    height: 100%;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
    .billno{
      font-size: 14px;
      font-weight: bold;
      margin: 0 15px;
    }
    .purchaseOrderWarehousing-cont{
      margin-top: 10px;
    }
  }
</style>
