<template>
  <div v-if="showPage" class="purchaseNewOrderEdit-wrap">
    <a-page-header :ghost="false" :backIcon="false" class="purchaseNewOrderEdit-cont">
      <!-- 自定义的二级文字标题 -->
      <template slot="subTitle">
        <a id="purchaseNewOrderEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        <p class="billno">单号：{{ detail&&detail.purchaseBillNo }}</p>
        <a-button type="danger" ghost @click="isShowBisiceInfo=!isShowBisiceInfo" style="margin-left:30px;vertical-align:middle;">
          基础信息
          <a-icon :type="isShowBisiceInfo ? 'up' : 'down'"/>
        </a-button>
      </template>
      <!-- 操作区，位于 title 行的行尾 -->
      <template slot="extra" v-if="$hasPermissions('B_purchasePrint')">
        <Print :disabled="localDataSource.length==0" @handlePrint="handlePrint"></Print>
      </template>
    </a-page-header>
    <!-- 产品列表 -->
    <div ref="tableSearch" class="choosedList-cont">
      <!-- 基础信息 -->
      <div style="padding:10px;" v-if="isShowBisiceInfo">
        <a-descriptions title="基础信息" size="small">
          <a-descriptions-item label="供应商">
            {{ detail&&detail.purchaseTargetName || '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="支付方式">
            {{ detail&&detail.settleStyleSnDictValue || '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="收货人">
            {{ detail&&detail.consigneeName || '--' }}（{{ detail&&detail.consigneeTel || '--' }}）
          </a-descriptions-item>
          <a-descriptions-item label="收货地址" span="3">
            <div v-if="detail&&(detail.shippingAddressProvinceName || detail.shippingAddressCityName || detail.shippingAddressCountyName || detail.shippingAddress)">
              {{ detail&&detail.shippingAddressProvinceName || '' }}
              {{ detail&&detail.shippingAddressCityName || '' }}
              {{ detail&&detail.shippingAddressCountyName || '' }}
              {{ detail&&detail.shippingAddress || '' }}
              <a-button type="link" @click="openAddrModal=true">更换地址 >></a-button>
            </div>
            <div v-else><a-button type="link" @click="openAddrModal=true">选择地址 >></a-button></div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
      <!-- 添加产品 -->
      <chooseProductModal
        ref="chooseProduct"
        :isDealerUp="isDealerUp"
        :purchaseBillSn="$route.params.sn"
        :showModal="openChooseProduct"
        @close="openChooseProduct=false"
        @add="handleAdd"
      ></chooseProductModal>
      <!-- 上次缺货 -->
      <outStockModal :openModal="openOutStockModal" :paramsData="paramsData" @close="openOutStockModal=false" @ok="hanldeOkOutStock" />
      <!-- 购物车 -->
      <shopingCatModal :showModal="openShopCatModal" :paramsData="paramsData" @close="openShopCatModal=false" @ok="getOrderDetail(false, true)"></shopingCatModal>
      <!-- 已选产品 -->
      <div>
        <div class="chooseBox-title">
          <div class="sub-title" style="display: flex;">
            已选产品
            <p class="tag-txt">注意：仅限采购【箭冠】产品。自建产品的采购入库请使用“散件入库”功能</p>
          </div>
          <div class="actions-button">
            <a-button v-if="detail&&detail.totalCategory" id="purchaseNewOrderEdit-add-btn" type="danger" @click="openChooseProduct=true"><a-icon type="plus-circle" />添加产品</a-button>
            <a-button id="purchaseNewOrderEdit-import-btn" type="danger" ghost @click="openGuideModal=true"><a-icon type="import" />产品导入</a-button>
            <a-button id="purchaseNewOrderEdit-outStock-btn" type="danger" ghost @click="handleOutStock"><a-icon type="funnel-plot" />上次缺货</a-button>
            <a-button id="purchaseNewOrderEdit-cart-btn" v-if="$hasPermissions('M_shoppingCart')" type="danger" ghost @click="hanldCart"><a-icon type="shopping" />购物车</a-button>
          </div>
        </div>
        <div class="choosed-table" v-if="detail&&detail.totalCategory">
          <!-- 搜索条件 -->
          <div class="table-page-search-wrapper">
            <a-row :gutter="15">
              <a-col :span="24">
                <a-form-model :model="productForm" layout="inline" @keyup.enter.native="$refs.purchaseTable.refresh(true)" >
                  <a-row :gutter="15">
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="产品编码">
                        <a-input v-model.trim="productForm.productCode" allowClear placeholder="输入产品编码" />
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-model-item label="产品名称">
                        <a-input v-model.trim="productForm.productName" allowClear placeholder="输入产品名称" />
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                      <a-form-model-item style="margin-bottom: 10px;">
                        <a-button type="primary" @click="$refs.purchaseTable.refresh(true)" :disabled="purchaseDisabled" id="purchaseNewOrderEdit-refresh">查询</a-button>
                        <a-button style="margin-left: 5px" @click="resetPurchaseForm" id="purchaseNewOrderEdit-reset">重置</a-button>
                      </a-form-model-item>
                    </a-col>
                  </a-row>
                </a-form-model>
              </a-col>
            </a-row>
          </div>
          <!-- 列表 -->
          <s-table
            class="sTable"
            ref="purchaseTable"
            :style="{ height: tableHeight +'px', overflow: 'auto' }"
            size="small"
            :rowKey="(record) => record.id"
            :columns="chooseColumns"
            :data="chooseLoadData"
            :defaultLoadData="false"
            :showPagination="false"
            :pageSize="5000"
            bordered>
            <!-- 采购数量 -->
            <template slot="storageQuantity" slot-scope="text, record">
              <a-input-number
                size="small"
                id="purchaseNewOrderEdit-qty"
                v-model="record.qty"
                :precision="0"
                :min="1"
                :max="999999"
                @blur="e => qtyBlur(e.target.value, record)"
                style="width: 100%;"
                placeholder="请输入" />
            </template>
            <!-- 操作 -->
            <template slot="action" slot-scope="text, record">
              <a-button
                size="small"
                type="link"
                class="button-error"
                :loading="delLoading"
                @click="handleDel(record)"
                id="purchaseNewOrderEdit-del-btn">删除</a-button>
            </template>
          </s-table>
        </div>
        <div v-else>
          <div v-if="!spinning&&localDataSource.length==0">
            <a-empty
              :image="simpleImage"
              :image-style="{
                height: '60px',
              }"
            >
              <span slot="description"> 暂无产品 </span>
              <a-button type="primary" class="button-error" @click="openChooseProduct=true"><a-icon type="plus-circle" />立即添加产品</a-button>
            </a-empty>
          </div>
          <div style="text-align: center;padding: 30px 50px;" v-if="spinning">
            <a-spin :spinning="spinning" tip="Loading..."></a-spin>
          </div>
        </div>
      </div>
      <!-- 底部栏 -->
      <div class="footer-cont">
        <!-- 总计 -->
        <div>
          <span style="color:#666;">
            共计 {{ detail && (detail.totalCategory || detail.totalCategory==0) ? detail.totalCategory : '--' }} 款
            {{ detail && (detail.totalQty || detail.totalQty==0) ? detail.totalQty : '--' }} 件产品 ，
          </span>
          <div style="display: inline-block;" v-if="$hasPermissions('M_ShowAllCost')">
            合计： <strong>{{ detail && (detail.discountedAmount || detail.discountedAmount==0) ?toThousands(detail.discountedAmount, 2) : '--' }}</strong>
          </div>
        </div>
        <div>
          <a-button
            type="primary"
            id="purchaseNewOrderEdit-submit-btn"
            size="large"
            class="button-primary"
            :loading="subLoading"
            @click="handleSubmit"
            style="padding: 0 60px;">提交</a-button>
        </div>
      </div>
    </div>
    <!-- 导入产品 -->
    <importGuideModal :openModal="openGuideModal" :params="{purchaseBillSn: $route.params.sn}" @close="openGuideModal=false" @ok="hanldeOks" />
    <!-- 选择地址 -->
    <choose-address-modal :openModal="openAddrModal" @ok="handleAddrOk" @close="openAddrModal=false" />
  </div>
</template>

<script>
import { Empty } from 'ant-design-vue'
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import ImportGuideModal from './importGuideModal.vue'
import outStockModal from './outStockModal.vue'
import chooseAddressModal from '@/views/common/receivingAddress/chooseAddressModal.vue'
import { purchaseDetailBySn, purchaseWriteSubmit, purchaseDetailPrint, purchaseDetailExport, purchaseDetailAddress } from '@/api/purchase'
import { purchaseDetailList, purchaseDetailSave, purchaseDetailDel, purchaseDetailCount, purchaseDetailCancelList } from '@/api/purchaseDetail'
// 选择产品
import chooseProductModal from './chooseProductModal.vue'
// 打印
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
const shopingCatModal = () => import(/* webpackChunkName: "shopingCatModal" */ '@/views/common/shopingCatModal.vue')
export default {
  name: 'PurchaseEdit',
  components: { STable, VSelect, ImportGuideModal, outStockModal, Print, chooseAddressModal, chooseProductModal, shopingCatModal },
  mixins: [commonMixin],
  data () {
    return {
      isShowBisiceInfo: false,
      showPage: false,
      spinning: false,
      detail: null, // 详细信息
      openChooseProduct: false,
      openShopCatModal: false,
      tableHeight: 0,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      // -------已选产品-------------
      subLoading: false,
      orderCountData: null,
      delLoading: false,
      productForm: {
        productName: '',
        productCode: '',
        orderBy: 'purchase_bill_detail.CREATE_DATE desc'
      },
      purchaseDisabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 查询总计
        const params = Object.assign({ pageNo: 1, pageSize: 5000 }, this.productForm, { purchaseBillSn: this.$route.params.sn })
        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
            data.list[i].qtyBackups = data.list[i].qty
          }
          this.localDataSource = data.list
          this.disabled = false
          this.spinning = false
          return data
        })
      },
      localDataSource: [],
      openGuideModal: false, //  导入产品引导
      openOutStockModal: false,
      paramsData: null,
      openAddrModal: false // 选择地址弹框是否显示
    }
  },
  computed: {
    isDealerUp () {
      return this.detail && this.detail.purchaseTargetType == 'DEALER_UP'
    },
    chooseColumns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: '20%', align: 'center' },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '35%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '采购数量', scopedSlots: { customRender: 'storageQuantity' }, width: '8%', align: 'center' },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(3, 0, { title: '采购单价', dataIndex: 'discountedPrice', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
        arr.splice(6, 0, { title: '采购金额', dataIndex: 'discountedAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 获取采购单基本信息
    getOrderDetail (noRefashTable, isReset, flag) {
      this.spinning = true
      purchaseDetailBySn({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detail = res.data
          if (!noRefashTable) {
            if (this.detail.totalCategory) {
              if (isReset) {
                this.resetPurchaseForm()
              } else {
                this.$refs.purchaseTable.refresh(!!flag)
              }
            } else {
              this.localDataSource = []
              this.spinning = false
            }
          } else {
            this.spinning = false
          }
        } else {
          this.spinning = false
        }
      })
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          purchaseDetailDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.getOrderDetail(false, false, true)
              _this.$message.success(res.message)
              _this.delLoading = false
            } else {
              _this.delLoading = false
            }
          })
        }
      })
    },
    // 修改数量后
    qtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.qtyBackups) {
        this.handleAdd(record, 1)
      }
    },
    // 重置已选产品列表
    resetPurchaseForm () {
      this.productForm.productName = ''
      this.productForm.productCode = ''
      this.$nextTick(() => {
        this.$refs.purchaseTable.refresh(true)
      })
    },
    //  添加或修改
    handleAdd (row, type) {
      let params = {}
      if (type == 0 && !row.qty) {
        this.$message.warning('请输入数量后再添加！')
        this.$refs.chooseProduct.spinning = false
        return
      }
      // 添加
      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 { //  编辑
        // 清空成本价或数量时,值应保持未清空前的值，因成本价和数量都不可为空
        if (!row.qty) {
          row.qty = row.qtyBackups
          return
        }
        params = row
      }
      this.addLoading = true
      purchaseDetailSave(params).then(res => {
        if (res.status == 200) {
          this.getOrderDetail(false, true, true)
          this.$message.success(res.message)
          if(type == 0){
            row.qtyBackups = row.qty
          }
        } else {
          row.qty = row.qtyBackups
        }
        this.addLoading = false
        this.$refs.chooseProduct.spinning = false
      })
    },
    //  提交
    handleSubmit () {
      const _this = this
      if (_this.detail && !_this.detail.totalCategory) {
        this.$message.info('请添加产品')
        return false
      }
      this.subLoading = true
      purchaseWriteSubmit({ id: this.detail.id }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          setTimeout(() => {
            _this.handleBack()
          }, 1000)
        }
        _this.subLoading = false
      })
    },
    // 导入产品
    hanldeOks () {
      this.getOrderDetail(false, true, true)
    },
    // 打开购物车
    hanldCart () {
      this.paramsData = {
        purchaseBillSn: this.$route.params.sn,
        purchaseBillNo: this.detail && this.detail.purchaseBillNo ? this.detail.purchaseBillNo : undefined
      }
      this.openShopCatModal = true
    },
    // 上次缺货
    handleOutStock () {
      // 校验是否存在历史采购单，且上次采购存在缺货产品
      purchaseDetailCancelList({ pageNo: 1, pageSize: 5 }).then(res => {
        if (res.status == 200) {
          const purchaseBillNo = res.data && res.data.list && res.data.list[0].purchaseBillNo || '--'
          this.paramsData = {
            purchaseBillSn: this.$route.params.sn,
            purchaseBillNo: purchaseBillNo
          }
          this.openOutStockModal = true
        }
      })
    },
    //  地址保存
    handleAddrOk (data) {
      const params = {
        purchaseBillSn: this.$route.params.sn,
        shippingAddressProvinceName: data.provinceName,
        shippingAddressCityName: data.cityName,
        shippingAddressCountyName: data.countyName,
        shippingAddress: data.addr,
        consigneeName: data.consigneeName,
        consigneeTel: data.consigneeTel
      }
      purchaseDetailAddress(params).then(res => {
        if (res.status == 200) {
          this.openAddrModal = false
          this.getOrderDetail(true)
        }
      })
    },
    // 上次缺货 导入成功
    hanldeOkOutStock () {
      this.getOrderDetail(false, true, true)
      this.paramsData = null
      this.openOutStockModal = false
    },
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      if (type == 'preview') {
        _this.openChooseProduct = false
        _this.openOutStockModal = false
      }
      _this.$store.state.app.printLoading = true
      let url = purchaseDetailPrint
      let params = { sn: this.$route.params.sn, type: printerType }
      if (type == 'export') { //  导出
        url = purchaseDetailExport
        params = { sn: this.$route.params.sn }
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '采购单', function () {
        _this.$store.state.app.printLoading = false
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ name: 'purchaseOrderNewList' })
    },
    setTableH () {
      this.tableHeight = window.innerHeight - (this.isShowBisiceInfo ? 440 : 310)
    },
    pageInit () {
      this.$nextTick(() => {
        this.setTableH()
        this.getOrderDetail(false, true)
      })
    }
  },
  watch: {
    isShowBisiceInfo (newValue, oldValue) {
      this.setTableH()
    }
  },
  mounted () {
    this.showPage = true
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    this.showPage = true
    // 如果是新页签打开或者进入新的子页（例：存在列表第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">
  .purchaseNewOrderEdit-wrap{
    position: relative;
    height: 100%;
    box-sizing: border-box;
    .billno{
      margin: 0 0 0 30px;
      font-size: 18px;
      font-weight: 600;
      display: inline-block;
      vertical-align: middle;
      color: #666;
    }
    .choosedList-cont{
      position: relative;
      background-color: #fff;
      height: calc(100% - 60px);
      .chooseBox-title{
        display:flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
        padding: 8px 0;
        .actions-button{
          button{
            margin-left: 10px;
            margin-right: 10px;
          }
        }
        .import-btn{
          margin-left: 15px;
        }
        .sub-title{
          font-size: 14px;
          color: #333;
          margin-left: 10px;
          font-weight:bold;
        }
        .tag-txt{
          font-size: 12px;
          color: #ed1c24;
          margin: 0 15px;
        }
      }
      .choosed-table{
        padding:10px;
      }
      .footer-cont{
        position:absolute;
        width:100%;
        bottom:0;
        display:flex;
        justify-content: flex-end;
        align-items: center;
        padding: 8px;
        border-top: 1px solid #eee;
        > div{
          &:first-child{
            padding: 0 15px;
            strong{
              color: #ff8d00;
              font-size: 18px;
            }
          }
        }
      }
      .ant-input-number-sm input{
        text-align: center;
      }
    }
    .purchaseNewOrderEdit-cont{
      margin-bottom: 8px;
      .sub-title{
        font-size: 12px;
        color: #808695;
        margin-left: 10px;
      }
    }
  }
</style>
