<template>
  <div v-if="showPage" class="jg-page-wrap purchaseNewOrderEdit-wrap">
    <a-page-header :ghost="false" :backIcon="false" class="header-bar">
      <!-- 自定义的二级文字标题 -->
      <template slot="subTitle">
        <p class="billno">单号：{{ detail&&detail.purchaseBillNo }}</p>
        <a-button type="link" class="button-default" @click="isShowBisiceInfo=!isShowBisiceInfo" style="margin-left:10px;vertical-align:middle;">
          <a-icon :type="isShowBisiceInfo ? 'eye-invisible' : 'eye'"/>
          {{ isShowBisiceInfo?'隐藏':'查看' }}信息
        </a-button>
        <a-button id="purchaseNewOrderEdit-back-btn" type="link" @click="handleBack" class="button-default"> <a-icon type="rollback" /> 返回列表</a-button>
      </template>
      <!-- 操作区，位于 title 行的行尾 -->
      <template slot="extra">
        <div style="margin-top: 5px;">
          <PrintPanel ref="printBox" v-if="$hasPermissions('B_purchasePrint')" :disabled="localDataSource.length==0" @handlePrint="handlePrint"></PrintPanel>
          <a-divider type="vertical" v-if="detail&&detail.totalCategory" />
          <a-button type="link" v-if="detail&&detail.totalCategory" @click="showSearch=!showSearch" :class="showSearch?'button-error':'button-default'"> <a-icon type="search" /> 筛选</a-button>
          <a-divider type="vertical" v-if="detail&&detail.totalCategory" />
          <a-button v-if="detail&&detail.totalCategory" id="purchaseNewOrderEdit-add-btn" type="link" @click="openChooseProduct=true"><a-icon type="plus" />添加产品</a-button>
          <a-divider type="vertical" />
          <a-dropdown>
            <a-menu slot="overlay" @click="handleActions">
              <a-menu-item key="3" v-if="$hasPermissions('M_shoppingCart')">
                <a-icon type="shopping" /> 购物车
              </a-menu-item>
              <a-menu-item key="2" v-if="!isDealerUp">
                <a-icon type="funnel-plot" />上次缺货
              </a-menu-item>
              <a-menu-item key="1">
                <a-icon type="import" />导入产品
              </a-menu-item>
            </a-menu>
            <a-button type="link" class="button-default"> <a-icon type="unordered-list" />  更多</a-button>
          </a-dropdown>
        </div>
      </template>
    </a-page-header>

    <!-- 产品列表 -->
    <div ref="tableSearch" class="choosedList-cont">
      <!-- 基础信息 -->
      <div class="baseInfo-bar" v-if="isShowBisiceInfo">
        <a-descriptions size="small">
          <div slot="title">基础信息</div>
          <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>
      <!-- 已选产品 -->
      <div class="purchaseTable">
        <div class="choosed-table" v-if="detail&&detail.totalCategory">
          <!-- 搜索条件 -->
          <div class="table-page-search-wrapper" v-if="showSearch">
            <a-row :gutter="15">
              <a-col :span="24">
                <a-form-model :model="productForm" layout="inline" @keyup.enter.native="getTableData()" >
                  <a-row :gutter="15">
                    <a-col :md="5" :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="5" :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">
                      <div style="margin-bottom: 10px;">
                        <a-button type="primary" @click="getTableData()" :disabled="purchaseDisabled" id="purchaseNewOrderEdit-refresh">查询</a-button>
                        <a-button style="margin-left: 5px" @click="resetPurchaseForm" id="purchaseNewOrderEdit-reset">重置</a-button>
                      </div>
                    </a-col>
                  </a-row>
                </a-form-model>
              </a-col>
            </a-row>
          </div>
          <!-- 列表 -->
          <a-spin :spinning="spinning" tip="Loading...">
            <ve-table
              border-y
              :border-around="false"
              :max-height="tableHeight"
              :row-style-option="{clickHighlight: true}"
              :cellSelectionOption="{enable: false}"
              :virtual-scroll-option="{enable: true}"
              :columns="chooseColumns"
              :table-data="localDataSource"
              row-key-field-name="id"
            />
          </a-spin>
        </div>
        <div class="choosed-table" 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" />立即添加产品</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-bar" v-if="detail&&detail.totalCategory">
        <!-- 总计 -->
        <div>
          <div style="display: inline-block;">
            产品总款数：<span style="color:#666">{{ detail && (detail.totalCategory || detail.totalCategory==0) ? detail.totalCategory : '--' }}</span>，
            采购总数量：<span style="color:#666">{{ detail && (detail.totalQty || detail.totalQty==0) ? detail.totalQty : '--' }}</span>，
          </div>
          <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" />
    <!-- 添加产品 -->
    <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>
</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 PrintPanel from '@/views/common/printPanel.vue'
import { hdPrint } from '@/libs/JGPrint'
const shopingCatModal = () => import(/* webpackChunkName: "shopingCatModal" */ '@/views/common/shopingCatModal.vue')
const qtyComp = {
  name: 'qtyComp',
  template: `
        <a-input-number
              size="small"
              v-model="row.qty"
              :precision="0"
              :min="1"
              :max="999999"
              @blur="e => that.qtyBlur(e.target.value, row)"
              style="width: 100%;"
              placeholder="请输入" />
    `,
  props: {
    row: Object,
    column: Object,
    rowIndex: Number,
    that: Object
  }
}
const actionComp = {
  name: 'actionComp',
  template: `
        <a-button
          size="small"
          type="link"
          class="button-error"
          :loading="row.delLoading"
          @click="that.handleDel(row)"
          >删除</a-button>
    `,
  props: {
    row: Object,
    column: Object,
    rowIndex: Number,
    that: Object
  }
}

export default {
  name: 'PurchaseEdit',
  components: { STable, VSelect, ImportGuideModal, outStockModal, PrintPanel, 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,
      showSearch: false,
      productForm: {
        productName: '',
        productCode: '',
        orderBy: 'purchase_bill_detail.CREATE_DATE desc'
      },
      purchaseDisabled: false, //  查询、重置按钮是否可操作
      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: '序号', key: 'a', field: 'no', width: '5%', align: 'center', operationColumn: false },
        { title: '产品编码', key: 'b', field: 'productCode', width: '10%', align: 'center', operationColumn: false },
        { title: '产品名称', key: 'c', field: 'productName', width: '25%', align: 'center', operationColumn: false, ellipsis: { showTitle: true } },
        { title: '原厂编码', key: 'q', field: 'productOrgCode', width: '15%', align: 'center',operationColumn: false },
        { title: '可用库存', key: 'j', field: 'currentStockQty', width: '10%', align: 'center', operationColumn: false },
        { title: '采购数量',
          key: 'd',
          width: '10%',
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return <qtyComp row={row} column={column} rowIndex={rowIndex} that={_this} />
          } },
        { title: '单位', key: 'e', field: 'productUnit', width: '10%', align: 'center', operationColumn: false },
        { title: '操作',
          key: 'f',
          width: '10%',
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return <actionComp row={row} column={column} rowIndex={rowIndex} that={_this} />
          } }
      ]
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(4, 0, { title: '采购单价', key: 'h', field: 'discountedPriceText', width: '10%', align: 'right', operationColumn: false })
        arr.splice(6, 0, { title: '采购金额', key: 'i', field: 'discountedAmountText', width: '10%', align: 'right', operationColumn: false })
      }
      return arr
    }
  },
  methods: {
    handleActions (e) {
      if (e.key == 1) {
        this.openGuideModal = true
      }
      if (e.key == 2) {
        this.handleOutStock()
      }
      if (e.key == 3) {
        this.hanldCart()
      }
    },
    getTableData () {
      this.disabled = true
      this.spinning = true
      // 查询总计
      const params = Object.assign({ pageNo: 1, pageSize: 10000 }, this.productForm, { purchaseBillSn: this.$route.params.sn })
      purchaseDetailList(params).then(res => {
        const data = res.data
        const no = (data.pageNo - 1) * data.pageSize
        for (var i = 0; i < data.list.length; i++) {
          const row = data.list[i]
          row.no = no + i + 1
          row.qtyBackups = row.qty
          row.productCode = row.dealerProductEntity.code || '--'
          row.productName = row.dealerProductEntity.name || '--'
          row.productUnit = row.dealerProductEntity.unit || '--'
          row.discountedPriceText = (row.discountedPrice || row.discountedPrice == 0) ? this.toThousands(row.discountedPrice, 2) : '--'
          row.discountedAmountText = (row.discountedAmount || row.discountedAmount == 0) ? this.toThousands(row.discountedAmount, 2) : '--'
          row.currentStockQty = (row.currentStockQty || row.currentStockQty == 0) ? row.currentStockQty : '--'
          row.productOrgCode = row.dealerProductEntity.origCode || '--'
        }
        this.localDataSource = data.list
        this.disabled = false
        this.spinning = false
      })
    },
    // 获取采购单基本信息
    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.getTableData()
              }
            } 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 () {
          row.delLoading = true
          purchaseDetailDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.getOrderDetail(false, false, true)
              _this.$message.success(res.message)
              row.delLoading = false
            } else {
              row.delLoading = false
            }
          })
        }
      })
    },
    // 修改数量后
    qtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.qtyBackups) {
        this.handleAdd(record, 1)
      }
    },
    // 重置已选产品列表
    resetPurchaseForm () {
      this.productForm.productName = ''
      this.productForm.productCode = ''
      this.$nextTick(() => {
        this.getTableData()
      })
    },
    //  添加或修改
    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.spinning = 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.spinning = false
        _this.$refs.printBox.hovered = false
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ name: 'purchaseOrderNewList' })
    },
    setTableH () {
      this.tableHeight = window.innerHeight - (this.isShowBisiceInfo ? 127 : 0) - (this.showSearch ? 42 : 0) - 210
    },
    pageInit () {
      this.$nextTick(() => {
        this.setTableH()
        this.getOrderDetail(false, true)
      })
    }
  },
  watch: {
    isShowBisiceInfo (newValue, oldValue) {
      this.setTableH()
    },
    showSearch (newValue, oldValue) {
      if (this.isShowBisiceInfo) {
        this.isShowBisiceInfo = false
      } else {
        this.setTableH()
      }
    },
    '$store.state.app.winHeight' (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;

    .choosedList-cont{
      position: relative;
      background-color: #fff;
      height: calc(100% - 60px);
    }

  }
</style>
