<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')">
          <a-radio-group key="3" v-model="printerType">
            <a-radio value="NEEDLE">针式</a-radio>
            <a-radio value="INK">喷墨</a-radio>
          </a-radio-group>
          <a-button key="2" id="chainTransferInEdit-preview-btn" :disabled="localDataSource.length==0" @click="handlePrint('preview')">打印预览</a-button>
          <a-button key="1" type="primary" id="chainTransferInEdit-print-btn" :disabled="localDataSource.length==0" @click="handlePrint('print')">快捷打印</a-button>
        </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="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="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"
          :scroll="{ x: 1110 }"
          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 id="print"></div>
  </div>
</template>

<script>
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'
export default {
  components: { STable, VSelect },
  data () {
    return {
      spinning: false,
      queryParam: {
        productCode: '', //  产品编码
        productName: '', //  产品名称
        productTypeSn1: '', //  产品分类1
        productTypeSn2: '', //  产品分类2
        productTypeSn3: '' //  产品分类3
      },
      disabled: false, //  查询、重置按钮是否可操作
      productTypeList: [], //  产品分类  下拉数据
      productType: [],
      warehouseCascadeData: [], //  仓库仓位
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 70, align: 'center', fixed: 'left' },
        { title: '产品编码', dataIndex: 'productCode', width: 180, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: 180, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本价', dataIndex: 'putCost', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调入数量', dataIndex: 'putQty', width: 80, 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: 'costSubtotal', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库仓位', scopedSlots: { customRender: 'warehouse' }, width: 200, 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 => {
          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
            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', query: { closeLastOldTab: true } })
    },
    //  产品分类  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) {
      const _this = this
      _this.spinning = true
      allocLinkagePutDetailPrint({ sn: this.$route.params.sn, type: this.printerType }).then(res => {
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          this.print(res, type)
        }
      })
    },
    print (data, type) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }))
      document.getElementById('print').innerHTML = '<iframe id="printfcie" name="printfcie" src="' + url + '" hidden></iframe>'
      if (type == 'preview') { //  预览
        window.open(url)
      } else if (type == 'print') { //  打印
        window.frames['printfcie'].focus()
        window.frames['printfcie'].print()
      }
    }
  },
  mounted () {
    this.getDetail()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getWarehouseCascade()
      if (!vm.disabled) {
        vm.getDetail()
        vm.resetSearchForm()
      }
    })
  }
}
</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>
