<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">
    <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"
              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"
                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"
              class="button-primary"
              :loading="addLoading"
              @click="handleAdd(record)"
              v-if="record.purchasePrice>0"
              id="purchaseOrderEdit-add-btn">添加</a-button>
            <span v-else>--</span>
          </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: '70%'
    },
    zIndex: {
      type: Number,
      default: 1050
    },
    isDealerUp: {
      type: Boolean
    },
    purchaseBillSn: {
      type: String
    }
  },
  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,
      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
          return data
        })
      },
      defImg
    }
  },
  computed: {
    hasVaild () {
      return this.queryParam.code || this.queryParam.name || this.queryParam.productBrandSn || this.queryParam.productTypeSn1
    },
    tableWidth () {
      let w = 1100
      if (this.isDealerUp) {
        w = 1200
      }
      if (this.$hasPermissions('M_ShowAllCost')) {
        w = this.isDealerUp ? 1200 : 1100
      }
      return w
    },
    columns () {
      const _this = this
      const arr = [
        { title: '产品编码', scopedSlots: { customRender: 'code' }, width: '150px', align: 'center', fixed: 'left' },
        { title: '产品名称', dataIndex: 'name', width: '250px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        // { title: '原厂编码', dataIndex: 'origCode', width: '14%', align: 'center', customRender: function (text) { return text && text != ' ' ? 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(2, 0, { title: '产品来源', dataIndex: 'sysFlagDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' } })
      }
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(this.isDealerUp ? 3 : 2, 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
        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 - 285
      })
    }
  }
}
</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>
