<template>
  <div class="storeTransferOutEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="storeTransferOutEdit-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="storeTransferOutEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;">调往对象名称：{{ (basicInfoData&&basicInfoData.putPersonName) || '--' }}</span>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_storeCallOutPrint')">
          <a-checkbox key="4" v-model="printCostChecked">打印成本</a-checkbox>
          <Print :disabled="chooseLoadDataSource.length==0" :showExport="false" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <!-- 选择产品 -->
      <a-card size="small" :bordered="false" class="storeTransferOutEdit-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="storeTransferOutEdit-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="storeTransferOutEdit-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-form-item label="仓库">
                      <a-select id="storeTransferOutEdit-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 v-if="advanced">
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="产品品牌">
                        <ProductBrand id="storeTransferOutEdit-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="storeTransferOutEdit-productType" placeholder="请选择产品分类" :isDealer="true" @change="changeProductType" v-model="productType"></ProductType>
                      </a-form-model-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="storeTransferOutList-refresh">查询</a-button>
                    <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="storeTransferOutList-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"
              :scroll="{ y: 300 }"
              :defaultLoadData="false"
              bordered>
              <div slot="costTitle">
                <a-tooltip placement="top">
                  <template slot="title">
                    参考成本价
                  </template>
                  <span style="margin-right: 5px;">参考成本价</span> <a-icon type="question-circle" />
                </a-tooltip>
              </div>
              <!-- 调出数量 -->
              <template slot="outQty" slot-scope="text, record">
                <div @dblclick.stop>
                  <a-input-number
                    size="small"
                    v-if="record.currentQty"
                    v-model="record.outQty"
                    :precision="0"
                    :min="1"
                    :max="record.currentQty"
                    placeholder="请输入"
                    style="width: 100%;" />
                  <span v-else>--</span>
                </div>
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button
                  size="small"
                  v-if="record.currentQty"
                  type="link"
                  class="button-primary"
                  @click.stop="handleAdd(record)"
                  id="storeTransferOutEdit-add-btn">添加</a-button>
                <span v-else>--</span>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <!-- 已选产品 -->
      <a-card size="small" :bordered="false" class="storeTransferOutEdit-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)) ? '￥'+productTotal.productTotalCost : '--' }}</strong>
                </div>
              </div>
            </a-alert>
            <!-- 筛选条件 -->
            <a-row :gutter="15">
              <a-col :span="20">
                <div class="table-page-search-wrapper">
                  <a-form layout="inline" @keyup.enter.native="$refs.chooseTable.refresh(true)">
                    <a-row :gutter="15">
                      <a-col :md="8" :sm="24">
                        <a-form-item label="产品编码" prop="productCode">
                          <a-input id="storeTransferOutEdit-productCode" v-model.trim="chooseQueryParam.productCode" placeholder="请输入产品编码" allowClear />
                        </a-form-item>
                      </a-col>
                      <a-col :md="8" :sm="24">
                        <a-form-item label="产品名称" prop="productName">
                          <a-input id="storeTransferOutEdit-productName" v-model.trim="chooseQueryParam.productName" placeholder="请输入产品名称" allowClear />
                        </a-form-item>
                      </a-col>
                      <a-col :md="8" :sm="24" style="margin-bottom: 10px;">
                        <a-button type="primary" @click="$refs.chooseTable.refresh(true)" :disabled="chooseDisabled" id="storeTransferOutList-refresh">查询</a-button>
                        <a-button style="margin-left: 8px" @click="chooseResetSearchForm" :disabled="chooseDisabled" id="storeTransferOutList-reset">重置</a-button>
                      </a-col>
                    </a-row>
                  </a-form>
                </div>
              </a-col>
              <a-col :span="4" style="text-align: right;">
                <!-- <a-button size="small" id="storeTransferOutEdit-import-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>
              <div slot="costTitle">
                <a-tooltip placement="top">
                  <template slot="title">
                    系统中不同批次的产品，成本价可能不同，此值是按照实际出库批次的成本计算得到。
                  </template>
                  <span style="margin-right: 5px;">实际总成本</span> <a-icon type="question-circle" />
                </a-tooltip>
              </div>
              <!-- 调出数量 -->
              <template slot="outQty" slot-scope="text, record">
                <a-input-number
                  size="small"
                  id="storeTransferOutEdit-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-info" @click="handleViewDetail(record)">出库明细</a-button>
                <a-button size="small" type="link" class="button-error" @click="handleDel(record)">删除</a-button>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
        <!-- 出入库明细 -->
        <outInDetialModal ref="outInDetialModal" :openModal="showOutInModal" @close="showOutInModal=false"></outInDetialModal>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="storeTransferOutEdit-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 { getOperationalPrecision } from '@/libs/tools.js'
import { storeCallOutDetailList, storeCallOutDetail, storeCallOutDetailCount, storeCallOutDetailSave, storeCallOutDetailDel, storeCallOutSubmit, storeCallOutDetailPrint } from '@/api/storeCallOut'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import { warehouseAllList } from '@/api/warehouse'
import { productQuery } from '@/api/allocWarehouse'
import Print from '@/views/common/print.vue'
import outInDetialModal from './outInDetialModal.vue'
import { hdPrint } from '@/libs/JGPrint'
export default {
  name: 'StoreCallOutEdit',
  components: { STable, VSelect, Print, ProductType, ProductBrand, outInDetialModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      showOutInModal: false,
      queryParam: {
        productCode: '',
        productName: '',
        warehouseSn: undefined,
        brandSn: undefined,
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined
      },
      chooseQueryParam: {
        productCode: '',
        productName: ''
      },
      disabled: false, //  查询、重置按钮是否可操作
      loading: false, //  表格加载中
      chooseDisabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      productBrandList: [], //  产品品牌  下拉数据
      productTypeList: [], //  产品分类  下拉数据
      productType: [],
      warehouseList: [], //  仓库  下拉数据
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return productQuery(Object.assign(parameter, this.queryParam, { 'currentQtyFlag': 0 })).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].outQty = 1
          }
          this.disabled = false
          return data
        })
      },
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        this.chooseDisabled = true
        const params = Object.assign(this.chooseQueryParam, { storeCallOutSn: this.$route.params.sn })
        return storeCallOutDetailList(Object.assign(parameter, params)).then(res => {
          this.getDetailCount(params)
          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].outQtyBackups = data.list[i].outQty
            // 成本小计  由于数据库内小数位数为4位，页面则需显示2位。因此会做小数运算精度处理
            data.list[i].costSubtotal = getOperationalPrecision(data.list[i].outCost, data.list[i].outQty)
          }
          this.chooseLoadDataSource = data.list || []
          this.chooseDisabled = false
          return data
        })
      },
      chooseLoadDataSource: [],
      basicInfoData: null, //  基本信息
      productTotal: null, //  合计
      printCostChecked: true //  打印成本
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '18%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '18%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'unit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '仓库', dataIndex: 'warehouseName', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '库存数量', dataIndex: 'currentQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { slots: { title: 'costTitle' }, dataIndex: 'putCost', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? 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, { slots: { title: 'costTitle' }, dataIndex: 'putCost', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    },
    chooseColumns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '16%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '18%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'productUnit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '成本价(￥)', dataIndex: 'outCost', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库', dataIndex: 'warehouseName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '调出数量', scopedSlots: { customRender: 'outQty' }, width: '8%', align: 'center' },
        // { slots: { title: 'costTitle' }, dataIndex: 'costSubtotal', width: '8%', 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(4, 0, { title: '成本价(￥)', dataIndex: 'outCost', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(8, 0, { slots: { title: 'costTitle' }, dataIndex: 'costSubtotal', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.brandSn = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      const url = storeCallOutDetailPrint
      const params = { sn: this.$route.params.sn, type: printerType, costFlag: this.printCostChecked ? '1' : '0' }
      // 打印或导出
      hdPrint(printerType, type, url, params, '', function () {
        _this.spinning = false
      })
    },
    // 双击快速添加
    handleClickRow (record) {
      return {
        on: {
          dblclick: (event) => {
            event.stopPropagation()
            this.handleAdd(record)
          }
        }
      }
    },
    // 已选产品  重置
    chooseResetSearchForm () {
      this.chooseQueryParam.productCode = ''
      this.chooseQueryParam.productName = ''
      this.$refs.chooseTable.refresh(true)
    },
    // 基本信息
    getDetail () {
      storeCallOutDetail({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
        } else {
          this.basicInfoData = null
        }
      })
    },
    //  添加/编辑
    handleAdd (row, isEdit) {
      const params = {
        id: isEdit ? row.id : undefined,
        storeCallOutSn: this.$route.params.sn,
        outCost: isEdit ? row.outCost : row.putCost,
        outQty: row.outQty, //  添加时调出数量默认为1
        productSn: row.productSn,
        productCode: row.productCode,
        productOrigCode: row.productOrigCode || undefined,
        productTypeSn1: row.productTypeSn1,
        productTypeSn2: row.productTypeSn2,
        productTypeSn3: row.productTypeSn3,
        brandSn: row.brandSn,
        warehouseSn: row.warehouseSn,
        warehouseLocationSn: row.warehouseLocationSn
      }
      if (isEdit) { // 编辑
        // 清空数量时,值应保持未清空前的值，因数量不可为空
        if (!row.outQty || row.outQty == row.outQtyBackups) {
          row.outQty = row.outQtyBackups
          return
        }
      }
      this.spinning = true
      storeCallOutDetailSave(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
        }
      })
    },
    // 出入库明细
    handleViewDetail (row) {
      this.showOutInModal = true
      this.$refs.outInDetialModal.getData(row)
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          storeCallOutDetailDel({ 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
      storeCallOutSubmit({ 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) {
      storeCallOutDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/allocationManagement/storeTransferOut/list' })
    },
    // 已选产品 调出数量  blur
    outQtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.outQtyBackups) {
        this.handleAdd(record, 'edit')
      }
    },
    //  产品分类  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({}).then(res => {
        if (res.status == 200) {
          this.warehouseList = res.data
        } else {
          this.warehouseList = []
        }
      })
    },
    pageInit () {
      this.printCostChecked = true
      this.getDetail()
      this.getWarehouseList()
      this.resetSearchForm()
      this.chooseResetSearchForm()
    }
  },
  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">
  .storeTransferOutEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    .storeTransferOutEdit-back, .storeTransferOutEdit-cont{
      margin-bottom: 10px;
    }
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
  }
</style>
