<template>
  <a-drawer
    :zIndex="zIndex"
    :title="title"
    placement="right"
    :visible="visible"
    :width="width"
    :get-container="false"
    :wrap-style="{ position: 'absolute' }"
    @close="onClose"
    wrapClassName="chooseProduct-drawer jg-drawer-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="chooseProduct-drawer-box">
        <!-- 搜索条件 -->
        <div ref="searchBox" class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchForm">
            <a-row type="flex" :gutter="12" justify="start">
              <a-col flex="auto">
                <a-form-model-item label="产品编码">
                  <a-input id="purchaseOrderEdit-code" ref="searchProductCode" v-model.trim="queryParam.code" allowClear placeholder="请输入产品编码"/>
                </a-form-model-item>
              </a-col>
              <a-col flex="auto">
                <a-form-model-item label="产品名称">
                  <a-input id="purchaseOrderEdit-name" v-model.trim="queryParam.name" allowClear placeholder="请输入产品名称"/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :flex="2">
                <a-form-model-item label="原厂编码">
                  <a-input id="purchaseOrderEdit-origCode" v-model.trim="queryParam.origCode" allowClear placeholder="请输入原厂编码"/>
                </a-form-model-item>
              </a-col> -->
              <a-col flex="250px">
                <a-form-item label="产品分类">
                  <ProductType id="purchaseOrderEdit-productType" :isDealer="true" :tenantId="$route.params.dealerSn" @change="changeProductType" v-model="productType"></ProductType>
                </a-form-item>
              </a-col>
              <a-col flex="250px">
                <a-form-item label="产品品牌">
                  <ProductBrand id="purchaseOrderEdit-productBrand" :tenantId="$route.params.dealerSn" v-model="queryParam.productBrandSn"></ProductBrand>
                </a-form-item>
              </a-col>
              <a-col flex="auto">
                <a-button type="primary" @click="searchForm" id="purchaseOrderEdit-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm" id="purchaseOrderEdit-reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 列表 -->
        <s-table
          v-if="hasVaild&&showTable"
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ x: tableWidth , y:tableHeight }"
          @dblclick="handleAdd"
          :pageSize="30"
          bordered>
          <!-- 产品图片 -->
          <template slot="imageUrl" slot-scope="text, record">
            <img
              :src="record.productMainPic && record.productMainPic.imageUrl?(record.productMainPic.imageUrl+'?x-oss-process=image/resize,h_30,m_lfit'):defImg"
              width="30"
              height="30"
              :id="'purchaseOrderEdit-imgview-'+record.id"
              style="cursor: pointer;"
              @click="handlePicDetail(record)" />
          </template>
          <!-- 包装数 -->
          <template slot="baozh" slot-scope="text, record">
            {{ record.packQty||'--' }}{{ record.packQty ? record.unit : '' }}/{{ record.packQtyUnit||'--' }}
          </template>
          <!-- 产品编码 -->
          <template slot="code" slot-scope="text, record">
            <a-tooltip placement="top" v-if="record.stockState=='NOT_ENOUGH'">
              <template slot="title">
                该产品暂时缺货！
              </template>
              <span class="noStock">{{ record.code || '--' }}</span>
            </a-tooltip>
            <span v-else>{{ record.code || '--' }}</span>
          </template>
          <!-- 采购数量 -->
          <template slot="storageQuantity" slot-scope="text, record">
            <div @dblclick.stop>
              <a-input-number
                size="small"
                :id="'purchaseOrderEdit-cQty-'+record.id"
                v-model="record.qty"
                :precision="0"
                :min="0"
                :max="999999"
                style="width: 100%;"
                placeholder="请输入数量" />
            </div>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              :id="'purchaseOrderEdit-cadd-'+record.id"
              class="button-primary"
              :loading="addLoading"
              @click="handleAdd(record)"
            >添加</a-button>
          </template>
        </s-table>
        <div v-else>
          <a-empty
            :image="simpleImage"
            :image-style="{
              height: '60px',
            }"
          >
            <span style="color:red" slot="description">请输入查询条件</span>
          </a-empty>
        </div>
      </div>
    </a-spin>
  </a-drawer>
</template>

<script>
import { Empty } from 'ant-design-vue'
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import defImg from '@/assets/def_img@2x.png'
import { productListPurchase } from '@/api/product'
export default {
  mixins: [commonMixin],
  components: {
    STable, VSelect, ProductType, ProductBrand
  },
  props: {
    showModal: { // 显示隐藏弹框
      type: Boolean,
      default: false
    },
    width: { // 弹框宽度
      type: [String, Number],
      default: '80%'
    },
    zIndex: { // 弹框层级
      type: Number,
      default: 100
    },
    isDealerUp: { // 是否上级经销商
      type: Boolean,
      default: false
    },
    purchaseBillSn: { // 采购单sn
      type: String,
      default: ''
    }
  },
  watch: {
    showModal (newValue, oldValue) {
      this.visible = newValue
      if (newValue) {
        // 初始化页面
        this.resetSearchForm()
        this.$refs.searchProductCode.focus()
        this.setTableH()
      }
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  data () {
    return {
      visible: this.showModal, // 显示弹框
      title: '添加产品', // 标题
      tableHeight: 0, // 表格高度
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE, // 默认图片
      // 选择产品
      addLoading: false, // 添加按钮loading
      spinning: false,
      productType: [], // 产品分类默认值
      queryParam: {
        productBrandSn: undefined, // 产品品牌
        code: '', //  产品编码
        name: '', //  产品名称
        origCode: '', //  原厂编码
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      },
      advanced: false, //  高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      showTable: false, // 是否显示表格
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return productListPurchase(Object.assign(parameter, this.queryParam, { purchaseBillSn: this.purchaseBillSn })).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
            data.list[i].qtyBackups = data.list[i].qty
          }
          this.disabled = false
          this.setTableH()
          return data
        })
      },
      defImg // 默认图片
    }
  },
  computed: {
    // 是否有筛选条件，至少一个
    hasVaild () {
      return this.queryParam.code || this.queryParam.name || this.queryParam.productBrandSn || this.queryParam.productTypeSn1
    },
    // 动态计算表格宽度
    tableWidth () {
      let w = 1410
      if (this.isDealerUp) {
        w = 1510
      }
      if (this.$hasPermissions('M_ShowAllCost')) {
        w = this.isDealerUp ? 1510 : 1410
      }
      return w
    },
    // 列定义
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '50px', align: 'center' },
        { title: '产品名称', dataIndex: 'name', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'origCode', width: '150px', align: 'center', customRender: function (text) { return text && text != ' ' ? text : '--' } },
        { title: '在途数', dataIndex: 'transitQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '可用库存', dataIndex: 'currentStockQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '产品图片', scopedSlots: { customRender: 'imageUrl' }, width: '80px', align: 'center' },
        { title: '单位', dataIndex: 'unit', width: '60px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '包装数', scopedSlots: { customRender: 'baozh' }, width: '60px', align: 'center' },
        { title: '终端会员价', dataIndex: 'terminalPrice', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '车主零售价', dataIndex: 'carOwnersPrice', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '采购数量', dataIndex: 'qty', scopedSlots: { customRender: 'storageQuantity' }, width: '100px', align: 'center', fixed: 'right' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '100px', align: 'center', fixed: 'right' }
      ]
      // 产品来源，如果时上级
      if (this.isDealerUp) {
        arr.splice(0, 0, { title: '产品编码', scopedSlots: { customRender: 'code' }, width: '150px', align: 'center', fixed: 'left' })
        arr.splice(2, 0, { title: '产品来源', dataIndex: 'sysFlagDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' } })
      } else {
        arr.splice(0, 0, { title: '产品编码', dataIndex: 'code', width: '150px', align: 'center', customRender: function (text) { return text || '--' }, fixed: 'left', sorter: true })
      }
      // 成本价权限
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(this.isDealerUp ? 4 : 3, 0, { title: '成本价', dataIndex: 'purchasePrice', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 查看产品
    handlePicDetail (row) {
      this.$router.push({ name: 'viewProduct', params: { sn: row.productSn } })
    },
    //  产品分类  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] : ''
    },
    // 查询列表
    searchForm () {
      if (this.hasVaild) {
        this.showTable = true
        if (this.$refs.table) {
          this.$refs.table.refresh(true)
        }
      } else {
        this.$message.info('请输入查询条件')
      }
    },
    // 重置产品库
    resetSearchForm () {
      this.queryParam = {
        productBrandSn: undefined,
        code: '', //  产品编码
        name: '', //  产品名称
        origCode: '', //  原厂编码
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      }
      this.productType = []
      this.showTable = false
    },
    // 关闭弹框
    onClose () {
      this.$emit('close')
    },
    // 添加产品
    handleAdd (record) {
      this.spinning = true
      this.$emit('add', record, 0)
    },
    // 计算表格高度
    setTableH () {
      this.$nextTick(() => {
        const searchBoxH = this.$refs.searchBox.offsetHeight
        this.tableHeight = window.innerHeight - searchBoxH - 225
      })
    }
  }
}
</script>

<style lang="less">
.chooseProduct-drawer {
  .ant-drawer-header{
    padding: 13px 20px;
  }
  .ant-drawer-body {
    padding: 15px 20px;
    height: calc(100% - 50px);
    display: flex;
    flex-direction: column;
    overflow: auto;
    > div {
      height: 100%;
    }
    .noStock{
      text-decoration: line-through;
      color: red;
    }
    .ant-input-number-sm input{
      text-align: center;
    }
  }
}
</style>
