<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="loadData.length==0" @click="handlePrint('preview')">打印预览</a-button>
          <a-button key="1" type="primary" id="chainTransferInEdit-print-btn" :disabled="loadData.length==0" @click="handlePrint('print')">快捷打印</a-button>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="chainTransferInDetail-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-alert type="info" showIcon style="margin-bottom:15px">
        <div slot="message">总款数 <strong>{{ (basicInfoData&&basicInfoData.productTotalCategory) || 0 }}</strong> ，总数量 <strong>{{ (basicInfoData&&basicInfoData.productTotalQty) || 0 }}</strong> ，总成本￥<strong>{{ (basicInfoData&&basicInfoData.productTotalCost) || 0 }}</strong></div>
      </a-alert>
      <a-card size="small" :bordered="false" class="chainTransferInEdit-cont">
        <!-- 筛选条件 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="getProductList(1)">
            <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: 24px;">
                <a-button type="primary" @click="getProductList(1)" :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>
        <!-- 列表 -->
        <a-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :dataSource="loadData"
          :scroll="{ x: 1415 }"
          bordered>
          <!-- 仓库仓位 -->
          <template slot="warehouse" slot-scope="text, record, index">
            <a-cascader
              @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>
        </a-table>
      </a-card>
      <a-affix :offset-bottom="0">
        <div style="text-align: center;width: 100%;background-color: #fff;padding: 12px 0;box-shadow: 0 0 20px #dcdee2;">
          <a-button
            type="primary"
            id="chainTransferInEdit-submit"
            size="large"
            class="button-primary"
            @click="handleSubmit"
            style="padding: 0 60px;">提交入库</a-button>
        </div>
      </a-affix>
    </a-spin>
    <!-- 打印 -->
    <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: 80, align: 'center', fixed: 'left' },
        { title: '产品编码', dataIndex: 'productCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本价(￥)', dataIndex: 'putCost', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调入数量', dataIndex: 'putQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本小计(￥)', dataIndex: 'costSubtotal', width: 115, align: 'center' },
        { title: '仓库仓位', scopedSlots: { customRender: 'warehouse' }, width: 280, align: 'center' }
      ],
      loadData: [],
      pageNo: 1, //  分页页码
      pageSize: 10, //  分页 每页多少条
      paginationProps: {
        showSizeChanger: true, //  是否可以改变 pageSize
        total: 0, //  分页总条数
        current: 1,
        onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize),
        onChange: (current) => this.changePage(current)
      },
      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.getProductList(1)
    },
    // 基本信息
    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
        }
      })
    },
    // 产品列表数据
    getProductList (pageNo) {
      this.disabled = true
      this.pageNo = pageNo || this.pageNo
      const params = Object.assign({ pageNo: this.pageNo, pageSize: this.pageSize }, this.queryParam, { allocationLinkagePutSn: this.$route.params.sn })
      allocLinkagePutDetailList(params).then(res => {
        if (res.status == 200) {
          this.getDetailCount(params)
          const data = res.data
          this.paginationProps.total = Number(res.data.count) || 0
          this.paginationProps.current = data.pageNo
          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.loadData = data.list
          this.disabled = false
        } else {
          this.paginationProps.total = 0
          this.paginationProps.current = 1
          this.loadData = []
        }
      })
    },
    // 合计
    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.loadData[ind].warehouseSnBackups || undefined
        const warehouseLocationSnBackups = this.loadData[ind].warehouseLocationSnBackups || undefined
        this.loadData[ind].warehouseSn = warehouseSnBackups
        this.loadData[ind].warehouseLocationSn = warehouseLocationSnBackups
        if (warehouseSnBackups || warehouseLocationSnBackups) {
          this.loadData[ind].warehouseCascade = [warehouseSnBackups, warehouseLocationSnBackups]
        } else {
          this.loadData[ind].warehouseCascade = undefined
        }
      } else {
        this.loadData[ind].warehouseSn = val[0] ? val[0] : ''
        this.loadData[ind].warehouseLocationSn = val[1] ? val[1] : ''
        this.handleAdd(this.loadData[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.getProductList()
          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="printf" name="printf" src="' + url + '" hidden></iframe>'
      if (type == 'preview') { //  预览
        window.open(url)
      } else if (type == 'print') { //  打印
        window.frames['printf'].focus()
        window.frames['printf'].print()
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getDetail()
      vm.getProductList(1)
      vm.getWarehouseCascade()
    })
  }
}
</script>

<style lang="less">
  .chainTransferInEdit-wrap{
    .chainTransferInEdit-back{
      margin-bottom: 15px;
    }
    .chainTransferInEdit-cont{
      margin-bottom: 15px;
    }
  }
</style>
