<template>
  <a-card size="small" :bordered="false" class="shoppingCar-wrap">
    <!-- 搜索条件 -->
    <div ref="tableSearch" 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-item label="产品编码">
              <a-input id="shoppingCar-code" v-model.trim="queryParam.code" allowClear placeholder="请输入产品编码"/>
            </a-form-item>
          </a-col>
          <a-col flex="auto">
            <a-form-item label="产品名称">
              <a-input id="shoppingCar-name" v-model.trim="queryParam.name" allowClear placeholder="请输入产品名称"/>
            </a-form-item>
          </a-col>
          <a-col flex="250px">
            <a-form-item label="产品分类">
              <ProductType id="shoppingCar-productType" placeholder="请选择产品分类" :isDealer="true" @change="changeProductType" v-model="productType"></ProductType>
            </a-form-item>
          </a-col>
          <a-col flex="250px">
            <a-form-item label="产品品牌">
              <ProductBrand id="shoppingCar-productBrandSn" placeholder="请选择产品品牌" v-model="queryParam.productBrandSn"></ProductBrand>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col flex="250px" v-if="modes=='pages'">
            <a-form-item label="产品状态">
              <v-select
                code="ONLINE_FLAG2"
                id="productPricingList-onlineFalg"
                v-model="queryParam.onlineFalg"
                allowClear
                placeholder="请选择产品状态"
              ></v-select>
            </a-form-item>
          </a-col>
          <a-col flex="auto" style="margin-bottom:10px;">
            <a-button type="primary" @click="searchForm" :disabled="disabled" id="shoppingCar-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="shoppingCar-reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-row :gutter="16">
          <a-col class="gutter-row" :span="24">
            <a-button type="primary" :loading="loading" ghost v-if="modes=='pages'" @click="deleteMore">
              批量删除
            </a-button>
            <a-button type="primary" :loading="loading" ghost v-if="modes=='modals'" @click="addMore">
              批量添加
            </a-button>
            <span style="font-weight: bold;margin-left:15px;" v-if="rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length">已选 {{ rowSelectionInfo.selectedRowKeys.length }} 项</span>
          </a-col>
        </a-row>
      </div>
    </div>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      :style="modes=='pages'?{ height: tableHeight+84.5+'px' }:{}"
      size="small"
      :row-selection="modes=='pages'?{ columnWidth: 40 }:{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: !record.productEntity.purchasePrice || !(record.productEntity.onlineFalg == 1&& record.dealerScopeFlag == 1) } }) }"
      @rowSelection="rowSelectionFun"
      rowKeyName="productSn"
      :rowKey="(record) => record.productSn"
      :columns="columns"
      :data="loadData"
      :scroll="modes=='pages'?{ y: tableHeight }:{ x:tableWidth, y: tableHeight }"
      :defaultLoadData="false"
      :pageSize="30"
      bordered>
      <!-- 采购数量 -->
      <template slot="purchaseQty" slot-scope="text, record">
        <a-input-number
          size="small"
          v-model="record.qty"
          :precision="0"
          :min="1"
          :max="999999"
          @blur="updateQty(record)"
          style="width: 100%;"
          placeholder="请输入采购数量" />
      </template>
      <!-- 包装数 -->
      <template slot="baozh" slot-scope="text, record">
        {{ record.productEntity.packQty||'--' }}{{ record.productEntity.packQty ? record.productEntity.unit : '' }}/{{ record.productEntity.packQtyUnit||'--' }}
      </template>
      <!-- 产品编码 -->
      <template slot="productCode" slot-scope="text, record">
        <div v-if="modes=='pages'">
          <span style="padding-right: 15px;">{{ text }}</span>
          <a-tag v-if="record.productEntity.onlineFalg == 0">下架</a-tag>
        </div>
        <div v-else>
          <span style="padding-right: 15px;">{{ text }}</span>
          <a-tag v-if="record.productEntity.onlineFalg == 0">下架</a-tag>
          <a-tag color="red" v-else-if="record.productEntity.onlineFalg == 1&& record.dealerScopeFlag == 0">无权限</a-tag>
        </div>
      </template>
    </s-table>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { mapActions } from 'vuex'
import { purchaseCartList, purchaseDeleteBatch, purchaseUpdateQty } from '@/api/purchaseCart'
import { purchaseDetailCancelSave } from '@/api/purchaseDetail'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import { STable, VSelect } from '@/components'
export default {
  name: 'ShoppingCarList',
  components: { STable, VSelect, ProductType, ProductBrand },
  mixins: [commonMixin],
  props: {
    modes: {
      type: String,
      default: 'pages'
    }
  },
  data () {
    return {
      loading: false,
      tableHeight: 0,
      tableWidth: 960,
      productType: [],
      queryParam: { //  查询条件
        code: '', //  产品编码
        name: '', //  产品名称
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        onlineFalg: undefined
      },
      paramsData: null,
      openEditPriceModal: false, // 自定义报价弹窗
      disabled: false, //  查询、重置按钮是否可操作
      columns: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return purchaseCartList(Object.assign(parameter, { productEntity: this.queryParam }, this.paramsData)).then(res => {
          let data
          if (res.status == 200) {
            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].qtyBack = data.list[i].qty
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      rowSelectionInfo: null
    }
  },
  methods: {
    ...mapActions(['getCartList']),
    // 查询
    searchForm () {
      // this.$refs.table.clearSelected() // 清空表格选中项
      this.$refs.table.refresh(true)
    },
    //  重置
    resetSearchForm () {
      this.queryParam.code = ''
      this.queryParam.name = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.onlineFalg = undefined
      this.productType = []
      this.$refs.table.refresh(true)
      this.rowSelectionInfo = null
      this.$refs.table.clearSelected()
    },
    // 设置表头
    getColumns () {
      const _this = this
      if (this.modes == 'pages') {
        this.columns = [
          { title: '产品编码', dataIndex: 'productEntity.code', scopedSlots: { customRender: 'productCode' }, width: '20%', align: 'center' },
          { title: '产品名称', dataIndex: 'productEntity.name', width: '30%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
          { title: '可用库存数量', dataIndex: 'currentStockQty', width: '14%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
          { title: '成本价', dataIndex: 'productEntity.purchasePrice', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
          { title: '单位', dataIndex: 'productEntity.unit', width: '8%', align: 'center', customRender: function (text) { return (!text || text == ' ') ? '--' : text } },
          { title: '包装数', scopedSlots: { customRender: 'baozh' }, dataIndex: 'productEntity.packQty', width: '8%', align: 'center' },
          { title: '采购数量', scopedSlots: { customRender: 'purchaseQty' }, width: '12%', align: 'center' }
        ]
      } else {
        this.columns = [
          { title: '产品编码', dataIndex: 'productEntity.code', scopedSlots: { customRender: 'productCode' }, width: '200px', align: 'center', fixed: 'left' },
          { title: '产品名称', dataIndex: 'productEntity.name', width: '250px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
          { title: '可用库存数量', dataIndex: 'currentStockQty', width: '140px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
          { title: '成本价', dataIndex: 'productEntity.purchasePrice', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
          { title: '单位', dataIndex: 'productEntity.unit', width: '80px', align: 'center', customRender: function (text) { return (!text || text == ' ') ? '--' : text } },
          { title: '包装数', scopedSlots: { customRender: 'baozh' }, dataIndex: 'productEntity.packQty', width: '80px', align: 'center' },
          { title: '采购数量', scopedSlots: { customRender: 'purchaseQty' }, width: '120px', align: 'center', fixed: 'right' }
        ]
      }
    },
    //  产品分类  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] : ''
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 修改数量
    updateQty (row) {
      if (row.qty != row.qtyBack && row.qty) {
        purchaseUpdateQty({ qty: row.qty, purchaseCartSn: row.purchaseCartSn }).then(res => {
          if (res.status == 200) {
            this.$message.info(res.message)
            row.qtyBack = row.qty
          } else {
            row.qty = row.qtyBack
          }
        })
      } else {
        row.qty = row.qtyBack
      }
    },
    // 批量删除
    deleteMore () {
      const rows = this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys || []
      if (!this.rowSelectionInfo || (rows.length <= 0)) {
        this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '您已经选择' + rows.length + '个产品，确认要将已选产品从购物车中移除吗？',
        centered: true,
        onOk: () => {
          this.loading = true
          purchaseDeleteBatch({
            productSnList: rows
          }).then(res => {
            if (res.status == 200) {
              this.$message.info(res.message)
              this.getCartList()
              this.searchForm()
            }
            this.loading = false
          })
        }
      })
    },
    // 保存
    addMore () {
      const _this = this
      const rows = this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys || []
      if (!this.rowSelectionInfo || (rows.length <= 0)) {
        this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      const rowsList = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
      const list = []
      rowsList.map(item => {
        list.push({
          cancelQty: item.qty,
          qty: item.qty,
          productSn: item.productSn,
          price: item.productEntity.purchasePrice
        })
      })
      const params = {
        confirm: false,
        purchaseBillSn: this.paramsData.purchaseBillSn,
        purchaseBillNo: this.paramsData.purchaseBillNo,
        purchaseBillDetailEntityList: list,
        purchaseCartFlag: true
      }
      purchaseDetailCancelSave(params).then(res => {
        if (res.status == 200 && res.data) {
          let content = ''
          if ((res.data.productSizeRepeat != res.data.productSize) && (res.data.productSizeRepeat != 0)) {
            content = `您已经选择 ${res.data.productSize} 个产品，其中 ${res.data.productSizeRepeat} 个产品已经存在于采购单中，本次只会加入不重复的产品。确认加入本次采购吗？`
            this.confirmFun(content, params)
          } else if (res.data.productSizeRepeat == res.data.productSize) {
            content = `抱歉，您选择的 ${res.data.productSize} 个产品，采购单中已经全部存在，无需加入！`
            this.$info({
              title: '提示',
              content: content,
              okText: '好的',
              centered: true,
              zIndex: 1100,
              onOk () {
                _this.$refs.table.clearSelected() // 清空表格选中项
              }
            })
          } else {
            content = `您已经选择 ${res.data.productSize} 个产品，确认要将已选产品加入本次采购吗？`
            this.confirmFun(content, params)
          }
        }
      })
    },
    confirmFun (content, params) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: content,
        okText: '确认加入',
        cancelText: '重新选择',
        centered: true,
        closable: true,
        zIndex: 1100,
        onOk () {
          _this.loading = true
          params.confirm = true
          purchaseDetailCancelSave(params).then(res => {
            if (res.status == 200) {
              _this.$emit('ok')
              _this.getCartList()
              _this.searchForm()
              _this.loading = false
            } else {
              _this.loading = false
            }
          })
        },
        onCancel () {
          _this.$refs.table.clearSelected() // 清空表格选中项
        }
      })
    },
    pageInit (paramsData) {
      this.paramsData = paramsData || {}
      this.getColumns()
      this.setTableH()
      this.resetSearchForm()
    },
    setTableH () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        const tableSearchH = this.$refs.tableSearch.offsetHeight
        this.tableHeight = window.innerHeight - tableSearchH - (this.modes == 'pages' ? 200 : 290)
      })
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less" scoped>
.setTableList{
  text-align: right;
  position: relative;
  span{
    margin-right: 10px;
    color:#56a2fb;
  }
  .setTableList-box{
    padding:10px 12px;
    border:1px solid #d5d5d5;
    border-radius: 5px;
    background:#fff;
    text-align: left;
    position: absolute;
    top:22px;
    right:0;
    z-index: 99999;
    div{
      margin-bottom: 10px;
      &:last-child{
        margin-bottom: 0px;
      }
    }
  }
}
</style>
