<template>
  <div class="chainTransferInEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="chainTransferInEdit-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="chainTransferInEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_allocLinkagePutPrint')">
          <Print :disabled="localDataSource.length==0" :showExport="false" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="chainTransferInEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="基础信息">
            <a-descriptions :column="3">
              <a-descriptions-item label="调入单号">{{ (basicInfoData&&basicInfoData.allocationLinkagePutNo) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="调出对象">{{ (basicInfoData&&basicInfoData.outTenantName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务状态">{{ (basicInfoData&&basicInfoData.stateDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="财务状态">{{ (basicInfoData&&basicInfoData.settleStateDictValue) || '--' }}</a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card size="small" :bordered="false" class="chainTransferInEdit-cont">
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom: 10px">
          <div slot="message">
            总款数 <strong>{{ (basicInfoData&&(basicInfoData.productTotalCategory || basicInfoData.productTotalCategory==0)) ? basicInfoData.productTotalCategory : '--' }}</strong> ，
            总数量 <strong>{{ (basicInfoData&&(basicInfoData.productTotalQty || basicInfoData.productTotalQty==0)) ? basicInfoData.productTotalQty : '--' }}</strong> ，
            总成本 <strong>{{ (basicInfoData&&(basicInfoData.productTotalCost || basicInfoData.productTotalCost==0)) ? '￥'+basicInfoData.productTotalCost : '--' }}</strong>
          </div>
        </a-alert>
        <!-- 筛选条件 -->
        <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="chainTransferInEdit-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="chainTransferInEdit-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品分类">
                  <a-cascader
                    @change="changeProductType"
                    change-on-select
                    v-model="productType"
                    expand-trigger="hover"
                    :options="productTypeList"
                    :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
                    id="chainTransferInEdit-productType"
                    placeholder="请选择产品分类"
                    allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="chainTransferInEdit-refresh">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="chainTransferInEdit-reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          bordered>
          <!-- 仓库仓位 -->
          <template slot="warehouse" slot-scope="text, record, index">
            <a-cascader
              size="small"
              @change="e => changeWarehouseCascade(e, record, index)"
              v-model="record.warehouseCascade"
              expand-trigger="hover"
              :allowClear="false"
              :options="warehouseCascadeData"
              :fieldNames="{ label: 'name', value: 'sn', children: 'warehouseLocationList' }"
              id="chainTransferInEdit-warehouseCascade"
              placeholder="请选择仓库仓位"
              style="width: 100%;" />
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="chainTransferInEdit-submit"
        size="large"
        class="button-primary"
        :disabled="spinning"
        @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 { dealerProductTypeList } from '@/api/dealerProductType'
import { warehouseCascadeList } from '@/api/warehouse'
import { allocLinkagePutDetailSn, allocLinkagePutDetailList, allocLinkagePutDetailCount, allocLinkagePutDetailUpdate, allocLinkagePutSubmit, allocLinkagePutDetailPrint } from '@/api/allocLinkagePut'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
export default {
  name: 'AllocLinkagePutEdit',
  components: { STable, VSelect, Print },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      queryParam: {
        productCode: '', //  产品编码
        productName: '', //  产品名称
        productTypeSn1: '', //  产品分类1
        productTypeSn2: '', //  产品分类2
        productTypeSn3: '' //  产品分类3
      },
      disabled: false, //  查询、重置按钮是否可操作
      productTypeList: [], //  产品分类  下拉数据
      productType: [],
      warehouseCascadeData: [], //  仓库仓位
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '18%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本价', dataIndex: 'putCost', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调入数量', dataIndex: 'putQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本小计', dataIndex: 'costSubtotal', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库仓位', scopedSlots: { customRender: 'warehouse' }, width: '16%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam, { allocationLinkagePutSn: this.$route.params.sn })
        return allocLinkagePutDetailList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.getDetailCount(params)
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              const warehouseSn = data.list[i].warehouseSn || undefined
              const warehouseLocationSn = data.list[i].warehouseLocationSn || undefined
              data.list[i].warehouseSnBackups = warehouseSn
              data.list[i].warehouseLocationSnBackups = warehouseLocationSn
              if (warehouseSn || warehouseLocationSn) {
                data.list[i].warehouseCascade = [warehouseSn, warehouseLocationSn]
              } else {
                data.list[i].warehouseCascade = undefined
              }
              // 成本小计  由于数据库内小数位数为4位，页面则需显示2位。因此会做小数运算精度处理
              data.list[i].costSubtotal = getOperationalPrecision(data.list[i].putCost, data.list[i].putQty)
            }
            this.localDataSource = data.list || []
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      localDataSource: [],
      basicInfoData: null, //  基本信息
      productTotal: null, //  合计
      printerType: 'NEEDLE' //  打印机类型
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.productType = []
      this.$refs.table.refresh(true)
    },
    // 基本信息
    getDetail () {
      allocLinkagePutDetailSn({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
          this.getProductType()
        } else {
          this.basicInfoData = null
        }
      })
    },
    //  提交
    handleSubmit () {
      this.spinning = true
      allocLinkagePutSubmit({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.handleBack()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 合计
    getDetailCount (params) {
      allocLinkagePutDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/allocationManagement/chainTransferIn/list' })
    },
    //  产品分类  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] : ''
    },
    changeWarehouseCascade (val, opt, ind) {
      if (val.length < 2) {
        this.$message.warning('当前仓库无仓位，请选择其他仓库')
        const warehouseSnBackups = this.localDataSource[ind].warehouseSnBackups || undefined
        const warehouseLocationSnBackups = this.localDataSource[ind].warehouseLocationSnBackups || undefined
        this.localDataSource[ind].warehouseSn = warehouseSnBackups
        this.localDataSource[ind].warehouseLocationSn = warehouseLocationSnBackups
        if (warehouseSnBackups || warehouseLocationSnBackups) {
          this.localDataSource[ind].warehouseCascade = [warehouseSnBackups, warehouseLocationSnBackups]
        } else {
          this.localDataSource[ind].warehouseCascade = undefined
        }
      } else {
        this.localDataSource[ind].warehouseSn = val[0] ? val[0] : ''
        this.localDataSource[ind].warehouseLocationSn = val[1] ? val[1] : ''
        this.handleAdd(this.localDataSource[ind])
      }
    },
    //  添加/编辑
    handleAdd (row) {
      // 清空成本价或数量时,值应保持未清空前的值，因成本价和数量都不可为空
      if (!row.warehouseSn) {
        row.warehouseSn = row.warehouseSnBackups
        return
      }
      if (!row.warehouseLocationSn) {
        row.warehouseLocationSn = row.warehouseLocationSnBackups
        return
      }
      const params = {
        id: row.id,
        warehouseLocationSn: row.warehouseLocationSn,
        warehouseSn: row.warehouseSn
      }
      this.spinning = true
      allocLinkagePutDetailUpdate(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    //  产品分类  列表
    getProductType () {
      dealerProductTypeList({ sysFlag: this.basicInfoData.allocationType == 'JIANGUAN' ? '1' : '0' }).then(res => {
        if (res.status == 200) {
          this.productTypeList = res.data
        } else {
          this.productTypeList = []
        }
      })
    },
    getWarehouseCascade () {
      warehouseCascadeList({}).then(res => {
        if (res.status == 200) {
          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 = []
        }
      })
    },
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      const url = allocLinkagePutDetailPrint
      const params = { sn: this.$route.params.sn, type: printerType }
      // 打印或导出
      hdPrint(printerType, type, url, params, '', function () {
        _this.spinning = false
      })
    },
    pageInit () {
      this.getDetail()
      this.getWarehouseCascade()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

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