<template>
  <div class="warehouseAllocationEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="warehouseAllocationEdit-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="warehouseAllocationEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;">调出仓库：{{ (basicInfoData&&basicInfoData.outWarehouseName) || '--' }}</span>
          <span style="margin: 0 15px;color: #666;">调入仓库：{{ (basicInfoData&&basicInfoData.putWarehouseName) || '--' }}</span>
        </template>
      </a-page-header>
      <!-- 选择产品 -->
      <a-card size="small" :bordered="false" class="warehouseAllocationEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="选择产品">
            <!-- 筛选条件 -->
            <div class="table-page-search-wrapper">
              <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
                <a-row :gutter="15">
                  <a-col :md="6" :sm="24">
                    <a-form-item label="产品编码" prop="productCode">
                      <a-input id="warehouseAllocationEdit-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-item label="产品名称" prop="productName">
                      <a-input id="warehouseAllocationEdit-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-item label="原厂编码" prop="productOrigCode">
                      <a-input id="warehouseAllocationEdit-productOrigCode" v-model.trim="queryParam.productOrigCode" placeholder="请输入原厂编码" allowClear />
                    </a-form-item>
                  </a-col>
                  <template v-if="advanced">
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="产品品牌">
                        <ProductBrand id="warehouseAllocationEdit-brandSn" placeholder="请选择产品品牌" v-model="queryParam.brandSn"></ProductBrand>
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="产品分类">
                        <ProductType id="warehouseAllocationEdit-productType" placeholder="请选择产品分类" :isDealer="true" @change="changeProductType" v-model="productType"></ProductType>
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-item label="调出仓位" prop="warehouseLocationSn">
                        <a-select id="warehouseAllocationEdit-warehouseLocationSn" placeholder="请选择" allowClear v-model="queryParam.warehouseLocationSn" style="width: 100%;">
                          <a-select-option v-for="item in warehouseOutLocData" :key="item.warehouseLocationSn" :value="item.warehouseLocationSn">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                  </template>
                  <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                    <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="warehouseAllocationList-refresh">查询</a-button>
                    <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="warehouseAllocationList-reset">重置</a-button>
                    <a @click="advanced=!advanced" style="margin-left: 5px">
                      {{ advanced ? '收起' : '展开' }}
                      <a-icon :type="advanced ? 'up' : 'down'"/>
                    </a>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <!-- 列表 -->
            <s-table
              class="sTable"
              ref="table"
              size="small"
              :rowKey="(record) => record.stockSn+record.productSn+record.warehouseSn+record.warehouseLocationSn"
              :columns="columns"
              :customRow="handleClickRow"
              :data="loadData"
              :defaultLoadData="false"
              :scroll="{ y: 300 }"
              bordered>
              <!-- 产品分类 -->
              <template slot="productType" slot-scope="text, record">
                <span v-if="record.dealerProduct.productTypeName2 || record.dealerProduct.productTypeName3">{{ record.dealerProduct.productTypeName2 }} {{ record.dealerProduct.productTypeName3 ? '>' : '' }} {{ record.dealerProduct.productTypeName3 }}</span>
                <span v-else>--</span>
              </template>
              <!-- 调入仓位 -->
              <template slot="putWarehouseLocationSn" slot-scope="text, record">
                <div @dblclick.stop>
                  <a-select size="small" id="warehouseAllocationEdit-putWarehouseLocationSn" placeholder="请选择" v-model="record.putWarehouseLocationSn" style="width: 100%;">
                    <a-select-option v-for="item in warehousePutLocData" :key="item.warehouseLocationSn" :disabled="item.warehouseLocationSn==record.warehouseLocationSn" :value="item.warehouseLocationSn">{{ item.name }}</a-select-option>
                  </a-select>
                </div>
              </template>
              <!-- 调出数量 -->
              <template slot="outQty" slot-scope="text, record">
                <div @dblclick.stop>
                  <a-input-number
                    size="small"
                    id="warehouseAllocationEdit-outQty"
                    v-model="record.outQty"
                    :precision="0"
                    :min="1"
                    :max="record.currentQty"
                    placeholder="请输入"
                    style="width: 100%;" />
                </div>
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="link" class="button-primary" @click="handleAdd(record)" id="warehouseAllocationEdit-add-btn">添加</a-button>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <!-- 已选产品 -->
      <a-card size="small" :bordered="false" class="warehouseAllocationEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="已选产品">
            <!-- 总计 -->
            <a-alert type="info" style="margin-bottom:10px">
              <div slot="message">
                总款数 <strong>{{ (productTotal&&(productTotal.productTotalCategory || productTotal.productTotalCategory==0)) ? productTotal.productTotalCategory : '--' }}</strong> ，
                总数量 <strong>{{ (productTotal&&(productTotal.productTotalQty || productTotal.productTotalQty==0)) ? productTotal.productTotalQty : '--' }}</strong>
                <div style="display: inline-block;" v-if="$hasPermissions('M_ShowAllCost')">，总成本 <strong>{{ (productTotal&&(productTotal.productTotalCost || productTotal.productTotalCost==0)) ? toThousands(productTotal.productTotalCost,2) : '--' }}</strong></div>
              </div>
            </a-alert>
            <!-- 筛选条件 -->
            <a-row :gutter="15" justify="space-between">
              <a-col :span="18">
                <div class="table-page-search-wrapper">
                  <a-form layout="inline" @keyup.enter.native="$refs.chooseTable.refresh(true)">
                    <a-row :gutter="15">
                      <a-col :md="9" :sm="24">
                        <a-form-item label="产品编码" prop="productCode">
                          <a-input id="warehouseAllocationEdit-productCode" v-model.trim="chooseQueryParam.productCode" placeholder="请输入产品编码" allowClear />
                        </a-form-item>
                      </a-col>
                      <a-col :md="9" :sm="24">
                        <a-form-item label="产品名称" prop="productName">
                          <a-input id="warehouseAllocationEdit-productName" v-model.trim="chooseQueryParam.productName" placeholder="请输入产品名称" allowClear />
                        </a-form-item>
                      </a-col>
                      <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                        <a-button type="primary" @click="$refs.chooseTable.refresh(true)" :disabled="chooseDisabled" id="warehouseAllocationList-refresh">查询</a-button>
                        <a-button style="margin-left: 8px" @click="chooseResetSearchForm" :disabled="chooseDisabled" id="warehouseAllocationList-reset">重置</a-button>
                      </a-col>
                    </a-row>
                  </a-form>
                </div>
              </a-col>
              <a-col :span="6">
                <div style="margin-top: 4px;text-align: right;">
                  <!-- <a-button size="small" style="margin-left: 8px" id="chainTransferOutEdit-import-btn">导入明细</a-button> -->
                  <a-button size="small" type="danger" style="margin-left: 8px" @click.stop="handleDel('', 'all')" id="warehouseAllocationEdit-del-all-btn">整单删除</a-button>
                </div>
              </a-col>
            </a-row>
            <!-- 列表 -->
            <s-table
              class="sTable"
              ref="chooseTable"
              size="small"
              :rowKey="(record) => record.id"
              :columns="chooseColumns"
              :data="chooseLoadData"
              :defaultLoadData="false"
              :scroll="{ y: 300 }"
              bordered>
              <!-- 产品分类 -->
              <template slot="productType" slot-scope="text, record">
                <span v-if="record.productTypeName2 || record.productTypeName3">{{ record.productTypeName2 }} {{ record.productTypeName3 ? '>' : '' }} {{ record.productTypeName3 }}</span>
                <span v-else>--</span>
              </template>
              <!-- 调入仓位 -->
              <template slot="putWarehouseLocationSn" slot-scope="text, record">
                <a-select
                  size="small"
                  id="warehouseAllocationEdit-putWarehouseLocationSn"
                  @change="chooseWarehouseLocChange(record)"
                  placeholder="请选择"
                  v-model="record.putWarehouseLocationSn"
                  style="width: 100%;">
                  <a-select-option v-for="item in warehousePutLocData" :key="item.warehouseLocationSn" :disabled="item.warehouseLocationSn==record.outWarehouseLocationSn" :value="item.warehouseLocationSn">{{ item.name }}</a-select-option>
                </a-select>
              </template>
              <!-- 调出数量 -->
              <template slot="outQty" slot-scope="text, record">
                <a-input-number
                  size="small"
                  id="warehouseAllocationEdit-outQty"
                  v-model="record.outQty"
                  :precision="0"
                  :min="1"
                  :max="999999"
                  placeholder="请输入"
                  @blur="e => outQtyBlur(e.target.value, record)"
                  style="width: 100%;" />
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="link" class="button-error" @click="handleDel(record)" id="warehouseAllocationEdit-del-btn">删除</a-button>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="warehouseAllocationEdit-submit"
        size="large"
        :disabled="spinning"
        class="button-primary"
        @click="handleSubmit"
        style="padding: 0 60px;">提交</a-button>
    </div>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { allocWarehouseDetailList, allocWarehouseDetail, updatePutWhLocation, productQuery, allocWarehouseDetailCount, allocWarehouseDetailSave, allocWarehouseDetailDel, allocWarehouseSubmit } from '@/api/allocWarehouse'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import { warehouseLocAllList } from '@/api/warehouse'
export default {
  name: 'AllocWarehouseEdit',
  components: { STable, VSelect, ProductType, ProductBrand },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      chooseLoading: false,
      queryParam: {
        productCode: '',
        productName: '',
        productOrigCode: '', // 原厂编码
        brandSn: undefined,
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined,
        warehouseLocationSn: undefined // 调出仓位
      },
      chooseQueryParam: {
        productCode: '',
        productName: ''
      },
      disabled: false, //  查询、重置按钮是否可操作
      chooseDisabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      productType: [],
      warehousePutLocData: [], //  调入仓位  下拉数据
      warehouseOutLocData: [], //  调出仓位  下拉数据
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '17%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'brandName', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分类', scopedSlots: { customRender: 'productType' }, width: '9%', align: 'center' },
        { title: '调出仓位', dataIndex: 'warehouseLocationName', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调入仓位', scopedSlots: { customRender: 'putWarehouseLocationSn' }, width: '8%', align: 'center' },
        { title: '调出数量', scopedSlots: { customRender: 'outQty' }, width: '7%', align: 'center' },
        { title: '可用库存数', dataIndex: 'currentQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '冻结库存数', dataIndex: 'freezeQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'unit', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        params.enabledFlag = 1
        params.warehouseSn = this.basicInfoData ? this.basicInfoData.outWarehouseSn : ''
        return productQuery(params).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
          }
          this.disabled = false
          return data
        })
      },
      // 表头
      chooseColumns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'brandName', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分类', scopedSlots: { customRender: 'productType' }, width: '9%', align: 'center' },
        { title: '调出仓位', dataIndex: 'outWarehouseLocationName', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调入仓位', scopedSlots: { customRender: 'putWarehouseLocationSn' }, width: '8%', align: 'center' },
        { title: '调出数量', scopedSlots: { customRender: 'outQty' }, width: '8%', align: 'center' },
        { title: '单位', dataIndex: 'productUnit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        this.chooseDisabled = true
        const params = Object.assign(parameter, this.chooseQueryParam, { allocationWarehouseSn: this.$route.params.sn })
        return allocWarehouseDetailList(params).then(res => {
          this.getDetailCount(Object.assign(params, this.chooseQueryParam))
          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].outQty = data.list[i].allocationQty
            data.list[i].outQtyBackups = data.list[i].allocationQty
          }
          this.chooseDisabled = false
          return data
        })
      },
      basicInfoData: null, //  基本信息
      productTotal: null //  合计
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productOrigCode = ''
      this.queryParam.brandSn = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.queryParam.warehouseLocationSn = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    // 双击快速添加
    handleClickRow (record) {
      return {
        on: {
          dblclick: (event) => {
            event.stopPropagation()
            this.handleAdd(record)
          }
        }
      }
    },
    // 已选产品  重置
    chooseResetSearchForm () {
      this.chooseQueryParam.productCode = ''
      this.chooseQueryParam.productName = ''
      this.$refs.chooseTable.refresh(true)
    },
    // 基本信息
    getDetail () {
      this.disabled = true
      allocWarehouseDetail({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
          this.resetSearchForm()
          this.getWarehouseLoc(res.data.putWarehouseSn, 'put')
          this.getWarehouseLoc(res.data.outWarehouseSn, 'out')
        } else {
          this.basicInfoData = null
        }
        this.disabled = false
      })
    },
    //  添加/编辑
    handleAdd (row, isEdit) {
      if (!isEdit && !row.putWarehouseLocationSn) {
        this.$message.warning('请选择调入仓位后再添加！')
        return
      }
      if (!isEdit && !row.outQty) {
        this.$message.warning('请输入调出数量后再添加！')
        return
      }
      const params = {
        id: isEdit ? row.id : undefined,
        allocationWarehouseSn: this.$route.params.sn,
        allocationCost: isEdit ? row.allocationCost : row.putCost,
        allocationQty: row.outQty,
        brandSn: row.brandSn,
        outWarehouseLocationSn: isEdit ? row.outWarehouseLocationSn : row.warehouseLocationSn,
        productCode: row.productCode,
        productOrigCode: row.productOrigCode || undefined,
        productSn: row.productSn,
        productTypeSn1: row.productTypeSn1,
        productTypeSn2: row.productTypeSn2,
        productTypeSn3: row.productTypeSn3,
        putWarehouseLocationSn: row.putWarehouseLocationSn
      }
      if (isEdit) { // 编辑
        // 清空数量时,值应保持未清空前的值，因数量不可为空
        if (!row.outQty) {
          row.outQty = row.outQtyBackups
          return
        }
      }
      this.spinning = true
      allocWarehouseDetailSave(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          if (isEdit) {
            this.$refs.table.refresh()
          }
          this.$refs.chooseTable.refresh()
          this.spinning = false
        } else {
          this.spinning = false
          row.outQty = row.outQtyBackups
        }
      })
    },
    //  删除
    handleDel (row, isAll) {
      const _this = this
      const content = isAll ? '删除后不可恢复，确定要进行整单删除吗？' : '删除后不可恢复，确定要进行删除吗？'
      this.$confirm({
        title: '提示',
        content: content,
        centered: true,
        onOk () {
          let params
          if (isAll) { //  整单删除
            params = { allocationWarehouseSn: _this.$route.params.sn }
          } else { //  单个删除
            params = {
              allocationWarehouseSn: _this.$route.params.sn,
              productSn: row.productSn,
              outWarehouseLocationSn: row.outWarehouseLocationSn,
              putWarehouseLocationSn: row.putWarehouseLocationSn
            }
          }
          _this.spinning = true
          allocWarehouseDetailDel(params).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.$refs.chooseTable.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  提交
    handleSubmit () {
      const _this = this
      _this.spinning = true
      allocWarehouseSubmit({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          setTimeout(() => {
            _this.handleBack()
            _this.spinning = false
          }, 1000)
        } else {
          _this.spinning = false
        }
      })
    },
    // 合计
    getDetailCount (params) {
      allocWarehouseDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/allocationManagement/warehouseAllocation/list' })
    },
    // 已选产品 调出数量  blur
    outQtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.outQtyBackups) {
        this.handleAdd(record, 'edit')
      }
    },
    // 已选产品 仓位  change
    chooseWarehouseLocChange (row) {
      const params = {
        allocationWarehouseSn: this.$route.params.sn,
        productSn: row.productSn,
        outWarehouseLocationSn: row.outWarehouseLocationSn,
        putWarehouseLocationSn: row.putWarehouseLocationSn
      }
      this.spinning = true
      updatePutWhLocation(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.$refs.chooseTable.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    //  产品分类  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] : ''
    },
    // 获取仓库仓位
    getWarehouseLoc (sn, type) {
      warehouseLocAllList({ warehouseSn: sn }).then(res => {
        if (type == 'put') {
          this.warehousePutLocData = res.data || []
        } else if (type == 'out') {
          this.warehouseOutLocData = res.data || []
        }
      })
    },
    pageInit () {
      this.chooseResetSearchForm()
      this.getDetail()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .warehouseAllocationEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    .warehouseAllocationEdit-back, .warehouseAllocationEdit-cont{
      margin-bottom: 10px;
    }
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
  }
</style>
