<template>
  <div class="chainTransferOutEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="chainTransferOutEdit-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="chainTransferOutEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <a class="head-order-number">单号：{{ basicInfoData&&basicInfoData.allocationLinkageOutNo || '--' }}</a>
          <span style="margin: 0 15px;color: #666;">调往对象：{{ (basicInfoData&&basicInfoData.putTenantName) || '--' }}</span>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_allocLinkageOutPrint')">
          <Print :disabled="localDataSource.length==0" :showExport="false" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <!-- 选择产品 -->
      <div class="chainTransferOutEdit-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="chainTransferOutEdit-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="chainTransferOutEdit-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="chainTransferOutEdit-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="chainTransferOutEdit-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="chainTransferOutEdit-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="仓库">
                        <a-select id="chainTransferOutEdit-warehouseSn" allowClear placeholder="请选择仓库" v-model="queryParam.warehouseSn" >
                          <a-select-option v-for="item in warehouseList" :key="item.warehouseSn" :value="item.warehouseSn">{{ 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="chainTransferOutEdit-refresh">查询</a-button>
                    <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="chainTransferOutEdit-reset">重置</a-button>
                    <a @click="advanced=!advanced" style="margin-left: 8px">
                      {{ 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.stockDetailSn"
              rowKeyName="stockDetailSn"
              :columns="columns"
              @dblclick="handleClickRow"
              :data="loadData"
              :defaultLoadData="false"
              :scroll="{ y: 200 }"
              bordered>
              <!-- 调出数量 -->
              <template slot="outQty" slot-scope="text, record">
                <div @dblclick.stop>
                  <a-input-number
                    size="small"
                    id="chainTransferOutEdit-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="chainTransferOutEdit-add-btn">添加</a-button>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </div>
      <!-- 已选产品 -->
      <div class="chainTransferOutEdit-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="17">
                <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="chainTransferOutEdit-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="chainTransferOutEdit-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="chainTransferOutList-refresh">查询</a-button>
                        <a-button style="margin-left: 8px" @click="chooseResetSearchForm" :disabled="chooseDisabled" id="chainTransferOutList-reset">重置</a-button>
                      </a-col>
                    </a-row>
                  </a-form>
                </div>
              </a-col>
              <a-col :span="7" style="text-align: right;">
                <a-button
                  type="danger"
                  ghost
                  size="small"
                  @click="openGuideModal=true"
                  style="margin-right: 5px"
                  id="chainTransferOutEdit-import-btn">导入产品</a-button>
                <a-button
                  size="small"
                  type="primary"
                  ghost
                  style="margin-left: 8px"
                  :disabled="localDataSource.length==0"
                  @click.stop="handleDel('', 'all')"
                  id="chainTransferOutEdit-del-all-btn">清空列表</a-button>
              </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="action" slot-scope="text, record">
                <a-button size="small" type="link" class="button-error" @click="handleDel(record)" id="chainTransferOutEdit-del-btn">删除</a-button>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="chainTransferOutEdit-submit"
        size="large"
        :disabled="spinning"
        class="button-primary"
        @click="handleSubmit"
        style="padding: 0 60px;">提交</a-button>
    </div>
    <!-- 导入产品 -->
    <importGuideModal :openModal="openGuideModal" :params="{allocationLinkageOutSn: $route.params.sn}" @close="openGuideModal=false" @ok="pageInit" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { getOperationalPrecision } from '@/libs/tools.js'
import { allocLinkageOutDetailSn, allocLinkageOutDetailList, allocLinkageOutDetailSave, allocLinkageOutDetailDel, allocLinkageOutDetailCount, allocLinkageOutSubmit, allocLinkageOutDetailDelAll, allocLinkageOutDetailPrint, importProductInsertBatch } from '@/api/allocLinkageOut'
import { productQuery } from '@/api/allocWarehouse'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import { warehouseAllList } from '@/api/warehouse'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
import importGuideModal from './importGuideModal.vue'
export default {
  name: 'AllocLinkageOutEdit',
  components: { STable, VSelect, Print, ProductType, ProductBrand, importGuideModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      queryParam: {
        productCode: '',
        productName: '',
        productOrigCode: '',
        warehouseSn: undefined,
        brandSn: undefined,
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined
      },
      productType: [],
      warehouseList: [], //  仓库  下拉数据
      disabled: false, //  查询、重置按钮是否可操作
      chooseDisabled: false,
      openGuideModal: false,
      advanced: false, // 高级搜索 展开/关闭
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 箭冠品牌 sysFlag传1,非箭冠品牌传0。与新增时所选调出产品类型有关
        this.queryParam.sysFlag = this.basicInfoData.allocationType == 'JIANGUAN' ? '1' : '0'
        const params = Object.assign(parameter, this.queryParam, { wasteFlag: 0 })
        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
        })
      },
      chooseQueryParam: {
        productCode: '',
        productName: ''
      },
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        this.chooseDisabled = true
        const params = Object.assign(parameter, this.chooseQueryParam, { allocationLinkageOutSn: this.$route.params.sn })
        return allocLinkageOutDetailList(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
            // 成本小计  由于数据库内小数位数为4位，页面则需显示2位。因此会做小数运算精度处理
            data.list[i].costSubtotal = getOperationalPrecision(data.list[i].outCost, data.list[i].outQty)
          }
          this.chooseDisabled = false
          this.getDetailCount(params)
          this.localDataSource = data.list
          return data
        })
      },
      basicInfoData: null, //  基本信息
      productTotal: null, //  合计
      localDataSource: []
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'brandName', width: '9%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓库', dataIndex: 'warehouseName', width: '9%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '9%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        // { title: '成本价', dataIndex: 'putCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '库存数量', dataIndex: 'currentQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'unit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调出数量', scopedSlots: { customRender: 'outQty' }, width: '8%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(7, 0, { title: '成本价', dataIndex: 'putCost', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
      }
      return arr
    },
    chooseColumns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'dealerProductEntity.origCode', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'dealerProductEntity.productBrandName', width: '9%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓库', dataIndex: 'warehouseName', width: '9%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '9%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '成本价', dataIndex: 'outCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调出数量', dataIndex: 'outQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '成本小计', dataIndex: 'costSubtotal', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(8, 0, { title: '成本价', dataIndex: 'outCost', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
        arr.splice(10, 0, { title: '成本小计', dataIndex: 'costSubtotal', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    resetData () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productOrigCode = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.brandSn = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.productType = []
    },
    // 已选产品  重置
    chooseResetSearchForm () {
      this.chooseQueryParam.productCode = ''
      this.chooseQueryParam.productName = ''
      this.$refs.chooseTable.refresh(true)
    },
    // 双击快速添加
    handleClickRow (record) {
      this.handleAdd(record)
    },
    // 基本信息
    getDetail () {
      allocLinkageOutDetailSn({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
          this.$refs.table.refresh(true)
        } else {
          this.basicInfoData = null
        }
      })
    },
    //  添加/编辑
    handleAdd (row, isEdit) {
      if (!isEdit && !row.outQty) {
        this.$message.warning('请输入调出数量后再添加！')
        return
      }
      const params = {
        id: isEdit ? row.id : undefined,
        allocationLinkageOutSn: this.$route.params.sn,
        outCost: isEdit ? row.outCost : row.putCost,
        outQty: row.outQty,
        productSn: row.productSn,
        productProduceDate: row.productProduceDate,
        productExpiryDate: row.productExpiryDate,
        warehouseSn: row.warehouseSn,
        warehouseLocationSn: row.warehouseLocationSn
      }
      this.spinning = true
      allocLinkageOutDetailSave(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
        }
      })
    },
    //  删除
    handleDel (row, isAll) {
      const _this = this
      const content = isAll ? '删除后不可恢复，确定要清空列表吗？' : '删除后不可恢复，确定要进行删除吗？'
      this.$confirm({
        title: '提示',
        content: content,
        centered: true,
        onOk () {
          if (isAll) { //  清空列表
            _this.spinning = true
            allocLinkageOutDetailDelAll({ sn: _this.$route.params.sn }).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
              }
            })
          } else { //  单个删除
            _this.spinning = true
            allocLinkageOutDetailDel({ id: row.id }).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
      allocLinkageOutSubmit({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          setTimeout(() => {
            _this.handleBack()
            _this.spinning = false
          }, 1000)
        } else {
          _this.spinning = false
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/allocationManagement/chainTransferOut/list' })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 合计
    getDetailCount (params) {
      allocLinkageOutDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  产品分类  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] : ''
    },
    // 仓库下拉数据
    getWarehouseList (type) {
      warehouseAllList({ wasteFlag: 0 }).then(res => {
        if (res.status == 200) {
          this.warehouseList = res.data
        } else {
          this.warehouseList = []
        }
      })
    },
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      const url = allocLinkageOutDetailPrint
      const params = { sn: this.$route.params.sn, type: printerType, showFlag: this.$hasPermissions('M_ShowAllCost') ? 1 : 0 }
      // 打印或导出
      hdPrint(printerType, type, url, params, '连锁调出单', function () {
        _this.spinning = false
      })
    },
    pageInit () {
      this.resetData()
      this.chooseResetSearchForm()
      this.getDetail()
      this.getWarehouseList()
    }
  },
  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">
  .chainTransferOutEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    .chainTransferOutEdit-back, .chainTransferOutEdit-cont{
      margin-bottom: 10px;
    }
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
  }
</style>
