<template>
  <div class="purchaseOrderEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="purchaseOrderEdit-cont">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="purchaseOrderEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <p class="billno">单号：{{ detail&&detail.purchaseBillNo }}</p>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_purchasePrint')">
          <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="purchaseOrderEdit-preview-btn" :disabled="localDataSource.length==0" @click="handlePrint('preview')">打印预览</a-button>
          <a-button key="1" type="primary" id="purchaseOrderEdit-print-btn" :disabled="localDataSource.length==0" @click="handlePrint('print')">快捷打印</a-button>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="purchaseOrderEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              基础信息
              <a-button
                type="primary"
                shape="circle"
                size="small"
                icon="edit"
                class="edit-circle-btn"
                id="purchaseOrderEdit-edit-circle-btn"
                @click.stop="handleEditInfo" />
            </template>
            <a-descriptions :column="2">
              <a-descriptions-item label="供应商">{{ detail&&detail.purchaseTargetName }}</a-descriptions-item>
              <a-descriptions-item label="支付方式">{{ detail&&detail.settleStyleEntity.name }}</a-descriptions-item>
              <a-descriptions-item label="收货人">{{ detail&&detail.consigneeName }}（{{ detail&&detail.consigneeTel }}）</a-descriptions-item>
              <a-descriptions-item label="收货地址">
                {{ detail&&detail.shippingAddressProvinceName }} -
                {{ detail&&detail.shippingAddressCityName }} -
                {{ detail&&detail.shippingAddressCountyName }} -
                {{ detail&&detail.shippingAddress }}
              </a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <!-- 选择产品 -->
      <a-card size="small" :bordered="false" class="purchaseOrderEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              选择产品<span class="sub-title">①输入查询条件--->②查找到需要采购的产品--->③录入采购数量--->④点击“添加”</span>
              <p class="tag-txt">注意：仅限采购【箭冠】产品。自建产品的采购入库请使用“散件入库”功能</p>
            </template>
            <!-- 选择产品 -->
            <div>
              <!-- 搜索条件 -->
              <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="关键词">
                        <a-input id="purchaseOrderEdit-bundleName" v-model.trim="queryParam.queryWord" allowClear placeholder="产品名称/产品编码/原厂编码/适用车型"/>
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-item label="产品品牌">
                        <ProductBrand id="purchaseOrderEdit-productBrand" v-model="queryParam.productBrandSn"></ProductBrand>
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-item label="产品分类">
                        <ProductType id="purchaseOrderEdit-productType" @change="changeProductType" v-model="productType"></ProductType>
                      </a-form-item>
                    </a-col>
                    <!-- <template v-if="advanced">
                      <a-col :md="6" :sm="24">
                        <a-form-item label="适用车型">
                          <a-cascader
                            :options="typeData"
                            expand-trigger="hover"
                            id="purchaseOrderEdit-state"
                            placeholder="请选择适用车型"
                            allowClear
                            v-model="queryParam.brand" />
                        </a-form-item>
                      </a-col>
                    </template> -->
                    <a-col :md="6" :sm="24">
                      <a-button style="margin-bottom: 18px;" type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="purchaseOrderEdit-refresh">查询</a-button>
                      <a-button style="margin: 0 0 18px 8px" @click="resetSearchForm" :disabled="disabled" id="purchaseOrderEdit-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.id"
                :columns="columns"
                :data="loadData"
                :scroll="{ x: 1190, y:300 }"
                :defaultLoadData="false"
                bordered>
                <!-- 采购数量 -->
                <template slot="storageQuantity" slot-scope="text, record">
                  <a-input-number
                    v-model="record.qty"
                    :precision="0"
                    :min="0"
                    :max="999999"
                    placeholder="请输入数量" />
                </template>
                <!-- 操作 -->
                <template slot="action" slot-scope="text, record">
                  <a-button
                    size="small"
                    type="primary"
                    class="button-info"
                    :loading="addLoading"
                    @click="handleAdd(record,0)"
                    :disabled="record.purchasePrice<=0"
                    id="purchaseOrderEdit-add-btn">添加</a-button>
                </template>
              </s-table>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <!-- 已选产品 -->
      <a-card size="small" :bordered="false" class="purchaseOrderEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              已选产品
              <!-- <a-button size="small" class="import-btn" id="purchaseOrderEdit-import-btn" @click.stop="handleImport">导入明细</a-button> -->
            </template>
            <!-- 已选产品 -->
            <div>
              <!-- 总计 -->
              <a-alert type="info" showIcon style="margin-bottom:15px">
                <div slot="message">产品款数 <strong>{{ detail ? ((detail.totalCategory || detail.totalCategory==0) ? detail.totalCategory : '--') : '--' }}</strong> ，
                  采购数量合计 <strong>{{ detail ? ((detail.totalQty || detail.totalQty==0) ? detail.totalQty : '--') : '--' }}</strong> ，
                  采购金额合计￥<strong>{{ detail ? ((detail.discountedAmount || detail.discountedAmount==0) ? detail.discountedAmount : '--') : '--' }}</strong></div>
              </a-alert>
              <!-- 列表 -->
              <s-table
                class="sTable"
                ref="purchaseTable"
                size="small"
                :rowKey="(record) => record.id"
                :columns="chooseColumns"
                :data="chooseLoadData"
                :scroll="{ x: 1070, y: 300 }"
                bordered>
                <!-- 采购数量 -->
                <template slot="storageQuantity" slot-scope="text, record">
                  <a-input-number
                    id="purchaseOrderEdit-qty"
                    v-model="record.qty"
                    :precision="0"
                    :min="1"
                    :max="999999"
                    @blur="e => qtyBlur(e.target.value, record)"
                    placeholder="请输入" />
                </template>
                <!-- 操作 -->
                <template slot="action" slot-scope="text, record">
                  <a-button
                    size="small"
                    type="primary"
                    class="button-error"
                    :loading="delLoading"
                    @click="handleDel(record)"
                    id="purchaseOrderEdit-del-btn">删除</a-button>
                </template>
              </s-table>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-affix :offset-bottom="0" v-if="detail">
        <div style="text-align: center;width: 100%;background-color: #fff;padding: 12px 0;box-shadow: 0 0 20px #dcdee2;">
          <a-button
            type="primary"
            id="purchaseOrderEdit-submit-btn"
            size="large"
            class="button-primary"
            :loading="subLoading"
            @click="handleSubmit"
            style="padding: 0 60px;">提交</a-button>
        </div>
      </a-affix>
    </a-spin>
    <!-- 选择基本信息弹框 -->
    <basic-info-modal ref="baseInfo" :openModal="openModal" @ok="handleOk" @cancel="openModal=false" />
    <!-- 打印 -->
    <div id="print"></div>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import basicInfoModal from './basicInfoModal.vue'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import { purchaseDetailBySn, purchaseWriteSubmit, purchaseDetailPrint } from '@/api/purchase'
import { purchaseDetailList, purchaseDetailSave, purchaseDetailDel, purchaseDetailCount } from '@/api/purchaseDetail'
import { productListPurchase } from '@/api/product'
export default {
  components: { STable, VSelect, basicInfoModal, ProductType, ProductBrand },
  data () {
    return {
      spinning: false,
      openModal: false, // 选择基本信息弹框是否显示
      detail: null, // 详细信息
      subLoading: false,
      // 选择产品
      addLoading: false,
      productType: [],
      queryParam: {
        productBrandSn: undefined,
        queryWord: '',
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      },
      typeData: [], //    下拉数据
      advanced: false, //  高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'code', width: 220, align: 'center', sorter: true },
        { title: '产品名称', dataIndex: 'name', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'origCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '箱/单位', dataIndex: 'unit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购单价', dataIndex: 'purchasePrice', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) }, fixed: 'right' },
        { title: '采购数量', dataIndex: 'qty', scopedSlots: { customRender: 'storageQuantity' }, width: 150, align: 'center', fixed: 'right' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return productListPurchase(Object.assign(parameter, this.queryParam, { purchaseBillSn: this.$route.params.sn })).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].qty = 1
          }
          this.disabled = false
          return data
        })
      },
      // -------已选产品-------------
      orderCountData: null,
      delLoading: false,
      // 表头
      chooseColumns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: 220, align: 'center', sorter: true },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购单价', dataIndex: 'discountedPrice', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '采购数量', scopedSlots: { customRender: 'storageQuantity' }, width: 150, align: 'center' },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购金额', dataIndex: 'discountedAmount', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        this.disabled = true
        // 查询总计
        const params = Object.assign(parameter, { purchaseBillSn: this.$route.params.sn })
        // this.getCountQuery(params)
        return purchaseDetailList(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.localDataSource = data.list
          this.disabled = false
          return data
        })
      },
      localDataSource: [],
      printerType: 'NEEDLE' //  打印机类型
    }
  },
  methods: {
    // 获取采购单明细统计
    getCountQuery (params) {
      purchaseDetailCount(params).then(res => {
        this.orderCountData = res.data || null
      })
    },
    // 获取采购单基本信息
    getOrderDetail () {
      purchaseDetailBySn({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detail = res.data
        }
      })
    },
    //  基本信息编辑成功
    handleOk (data) {
      this.openModal = false
      this.getOrderDetail()
    },
    //  编辑基本信息
    handleEditInfo () {
      this.openModal = true
      this.$refs.baseInfo.setData(this.detail)
    },
    // ---已选产品-----
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          _this.spinning = true
          purchaseDetailDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.resetPurchaseDetail(true)
              _this.$message.success(res.message)
              _this.delLoading = false
              _this.spinning = false
            } else {
              _this.delLoading = false
              _this.spinning = false
            }
          })
        }
      })
    },
    // 重新查询已选产品
    resetPurchaseDetail (flag) {
      this.$refs.purchaseTable.refresh(!!flag)
      this.getOrderDetail()
    },
    // 修改数量后
    qtyBlur (val, record) {
      this.handleAdd(record, 1)
    },
    //  导入明细
    handleImport () {
      console.log(333)
    },
    // ---------产品库--------
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //  产品分类  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] : ''
    },
    //  重置产品库
    resetSearchForm () {
      this.queryParam = {
        productBrandSn: undefined,
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        queryWord: ''
      }
      this.productType = []
      this.$refs.table.refresh(true)
    },
    //  添加或修改
    handleAdd (row, type) {
      let params = {}
      // 添加
      if (type == 0) {
        params.productSn = row.productSn
        params.purchaseBillSn = this.detail.purchaseBillSn
        params.purchaseBillNo = this.detail.purchaseBillNo
        params.price = row.purchasePrice
        params.qty = row.qty
      } else {
        params = row
      }
      this.addLoading = true
      this.spinning = true
      purchaseDetailSave(params).then(res => {
        if (res.status == 200) {
          this.resetPurchaseDetail()
          this.$message.success(res.message)
          this.spinning = false
        } else {
          this.spinning = false
        }
        this.addLoading = false
      })
    },
    // ------------产品库 end --------
    //  提交
    handleSubmit () {
      const _this = this
      this.subLoading = true
      this.spinning = true
      purchaseWriteSubmit({ id: this.detail.id }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          setTimeout(() => {
            _this.handleBack()
            _this.spinning = false
          }, 1000)
        } else {
          _this.spinning = false
        }
        _this.subLoading = false
      })
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      const _this = this
      _this.spinning = true
      purchaseDetailPrint({ 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()
      }
    },
    //  返回列表
    handleBack () {
      this.$router.push({ name: 'purchaseOrderList' })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.openModal = false
      vm.getOrderDetail()
    })
  }
}
</script>

<style lang="less">
  .purchaseOrderEdit-wrap{
    .billno{
      margin: 0 0 0 30px;
      font-size: 18px;
      font-weight: 600;
      display: inline-block;
      vertical-align: top;
      color: #666;
    }
    .purchaseOrderEdit-cont{
      margin-bottom: 15px;
      .sub-title{
        font-size: 12px;
        color: #808695;
        margin-left: 10px;
      }
      .tag-txt{
        font-size: 12px;
        color: #ed1c24;
      }
      .edit-circle-btn{
        margin-left: 15px;
        i{
          vertical-align: text-bottom;
        }
      }
      .import-btn{
        margin-left: 15px;
      }
    }
  }
</style>
