<template>
  <div>
    <a-card size="small" :bordered="false" class="shoppingProductsList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="shoppingProductsList-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="产品编码/原厂编码">
                <a-input id="shoppingProductsList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码/原厂编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品名称">
                <a-input id="shoppingProductsList-name" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="品牌">
                <productBrand id="shoppingProductsList-productBrandSn" v-model="queryParam.productBrandSn"></productBrand>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品分类">
                <productType id="shoppingProductsList-productType" placeholder="请选择产品分类" @change="changeProductType" v-model="productType"></productType>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-if="!itemCategorySn">
              <a-form-item label="商城类目">
                <a-cascader
                  id="shoppingProductsList-category"
                  expandTrigger="hover"
                  :changeOnSelect="true"
                  :fieldNames="fieldNames"
                  :options="categoryOptions"
                  placeholder="请选择商城类目"
                  @change="changeProductsCategory"
                  allowClear
                  v-model="category"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="热销产品">
                <v-select code="FLAG" id="shoppingProductsList-hotFlag" v-model="queryParam.hotFlag" allowClear placeholder="请选择是否是热销产品"></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品商城状态">
                <v-select code="SHOP_PRODUCT_STATUS" id="shoppingProductsList-status" v-model="queryParam.status" allowClear placeholder="请选择产品商城状态"></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="shoppingProductsList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="shoppingProductsList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button type="primary" id="shoppingProductsList-addProduct-btn" v-if="$hasPermissions('B_category_chooseProduct')&&itemCategorySn" @click="handleChooseProduct">选择产品</a-button>
        <a-button type="primary" v-if="$hasPermissions('B_shoppingProducts_import')&&!itemCategorySn" id="shoppingProductsList-import-btn" @click="handleAddProduct">产品导入</a-button>
        <span v-if="productNum&&productNum*1>0">
          <a-button type="primary" v-if="$hasPermissions('B_groundingProducts_btn')" id="shoppingProductsList-grounding-btn" class="button-info" @click="changeStatus('1')">批量上架</a-button>
          <a-button v-if="$hasPermissions('B_offProducts_btn')" @click="changeStatus('0')" id="shoppingProductsList-off-btn">批量下架</a-button>
          <a-button
            v-if="$hasPermissions('B_delProducts_btn')"
            type="primary"
            class="button-error"
            id="shoppingProductsList-delProduct-btn"
            ghost
            @click="handleDel()">批量删除</a-button>
          <span v-if="rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length>0">已选{{ rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length }}项</span>
        </span>
      </div>
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height:itemCategorySn?(tableHeight-10+'px'):(tableHeight+70+'px')}"
          size="small"
          :rowKey="(record) => record.shopProductSn"
          rowKeyName="shopProductSn"
          :columns="columns"
          :data="loadData"
          :pageSize="20"
          :row-selection="{ columnWidth: 40}"
          @rowSelection="rowSelectionFun"
          :scroll="{ y: itemCategorySn?tableHeight-100:tableHeight-20 }"
          :defaultLoadData="false"
          bordered>
          <!-- 产品编码 -->
          <template slot="productCode" slot-scope="text, record">
            <span style="padding-right: 6px;">{{ record.productCode }}</span>
            <a-badge v-if="record.hotFlag=='1'" count="热" :number-style="{ zoom:'80%' }"></a-badge>
          </template>
          <!-- 产品分类 -->
          <template slot="productType" slot-scope="text, record">
            <span v-if="record.productTypeName2 || record.productTypeName3">{{ record.productTypeName2 }} {{ record.productTypeName3 ? '>' : '' }} {{ record.productTypeName3 }}</span>
            <span v-else>--</span>
          </template>
          <!-- 商城类目 -->
          <template slot="categoryName" slot-scope="text, record">
            <span v-if="record.categoryName1 || record.categoryName2">{{ record.categoryName1 }} {{ (record.categoryName1&&record.categoryName2) ? '>' : '' }} {{ record.categoryName2 }}</span>
            <span v-else>--</span>
          </template>
          <!-- 售价类型 -->
          <template slot="priceType" slot-scope="text, record">
            <span v-if="record.priceType">{{ record.priceType=='TERMINAL_PRICE'?'终端价':'自定义' }}</span>
            <span v-else>--</span>
          </template>
          <!-- 是否是热销产品 -->
          <template slot="hotFlag" slot-scope="text, record">
            <span v-if="record.hotFlag">{{ record.hotFlag=='1'?'是':'否' }}</span>
            <span v-else>--</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_editProducts_btn')"
              @click="handleEdit(record)"
              class="button-info"
              :id="'chooseProductEdit-edit-btn'+record.id">编辑</a-button>
            <a-button
              size="small"
              type="link"
              @click="changeStatus('1',record)"
              class="button-info"
              v-if="$hasPermissions('B_groundingProducts_btn')&&record.status=='0'"
              :id="'chooseProductEdit-top-btn'+record.id">上架</a-button>
            <a-button
              size="small"
              type="link"
              @click="changeStatus('0',record)"
              class="button-info"
              v-if="$hasPermissions('B_offProducts_btn')&&record.status!='0'"
              :id="'chooseProductEdit-bottom-btn'+record.id">下架</a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              v-if="$hasPermissions('B_delProducts_btn')"
              @click="handleDel(record)"
              :id="'chooseProductEdit-del-btn'+record.id">删除</a-button>
          </template>
        </s-table>
      </a-spin>
    </a-card>
    <!-- 添加产品 -->
    <chooseProduct
      ref="chooseProduct"
      :chooseData="chooseDataList"
      :openModal="showProModal"
      @ok="addProductSuccess"
      @close="closeProductModal"></chooseProduct>
    <!-- 导入产品 -->
    <importGuideModal :openModal="openGuideModal" @close="openGuideModal=false" @ok="hanldeOk" />
    <!-- 编辑 -->
    <editProductModal ref="editProduct" :itemSn="itemProductSn" :openModal="openEditModal" @close="openEditModal=false" @ok="hanldeEditOk" ></editProductModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import importGuideModal from './importGuideModal.vue'
import editProductModal from './editProductModal.vue'
import productType from '@/views/common/productType.js'
import productBrand from '@/views/common/productBrand.js'
import chooseProduct from '@/views/easyPassManagement/shoppingManagement/chooseProductsModal'
// 接口
import { shopProductList, saveBatchProductExcel, shopProductDel, shopProductUpdateStatus, queryProductSnList, saveBatchProduct, queryExtList } from '@/api/shopProduct'
export default {
  name: 'ShoppingProductsList',
  mixins: [commonMixin],
  props: {
    itemCategorySn: {// 当前行类目sn
      type: String,
      default: ''
    }
  },
  components: { STable, VSelect, importGuideModal, editProductModal, productType, productBrand, chooseProduct },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      // form表单label布局
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      showProModal: false, // 打开添加产品弹窗
      productType: [], // 产品分类
      chooseDataList: [], // 已选产品sn集合
      // 查询条件
      queryParam: {
        productName: '', // 产品名称
        productCode: '', // 产品编码/原厂编码
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        hotFlag: undefined, // 是否是热销产品
        status: undefined, // 状态
        categorySn1: undefined, // 商城一级类目
        categorySn2: undefined// 商城二级类目
      },
      productNum: null, // 列表数据总条数
      categoryOptions: [], // 产品类目列表
      fieldNames: { label: 'categoryName', value: 'categorySn', children: 'shopCategoryList' },
      category: [], // 类目val
      rowSelectionInfo: null, // 已选数据
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        if (this.itemCategorySn) {
          this.queryParam.categorySn = this.itemCategorySn
        }
        return shopProductList(Object.assign(parameter, this.queryParam)).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
            }
            this.disabled = false
            this.productNum = data.count
          }
          this.spinning = false
          return data
        })
      },
      openGuideModal: false, // 打开导入弹窗
      openEditModal: false, // 打开编辑弹窗
      itemProductSn: null// 当前行商城产品sn
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', align: 'center', width: '50px' },
        { title: '产品编码', dataIndex: 'productCode', width: '12%', align: 'center', scopedSlots: { customRender: 'productCode' } },
        { title: '产品名称', dataIndex: 'productName', width: '22%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', align: 'center', width: '10%', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'productBrandName', align: 'center', width: '10%', customRender: function (text) { return text || '--' } },
        { title: '产品分类', align: 'center', width: '15%', scopedSlots: { customRender: 'productType' } },
        // { title: '售价', dataIndex: 'price', width: '7%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } },
        { title: '售价类型', dataIndex: 'priceType', scopedSlots: { customRender: 'priceType' }, align: 'center', width: '10%' },
        // { title: '终端价', dataIndex: 'terminalPrice', width: '7%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } },
        // { title: '车主价', dataIndex: 'carOwnersPrice', width: '7%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } },
        { title: '热销产品', dataIndex: 'hotFlag', scopedSlots: { customRender: 'hotFlag' }, align: 'center', width: '8%' },
        { title: '易码通优先级', dataIndex: 'hotSort', align: 'center', width: '7%', customRender: function (text) { return (text || text == 0) ? text : '--' } },
        { title: '添加时间', dataIndex: 'createDate', align: 'center', width: '10%', customRender: function (text) { return text || '--' } },
        { title: '产品商城状态', dataIndex: 'statusDictValue', align: 'center', width: '6%', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '14%', align: 'center' }
      ]
      // 售价
      if (_this.$hasPermissions('M_shoppingProductsList_salesPrice')) {
        arr.splice(6, 0, { title: '售价', dataIndex: 'price', width: '7%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } })
      }
      // 终端价
      const pos = _this.$hasPermissions('M_shoppingProductsList_salesPrice') ? 8 : 7
      if (_this.$hasPermissions('M_shoppingProductsList_terminalPrice')) {
        arr.splice(pos, 0, { title: '终端价', dataIndex: 'terminalPrice', width: '7%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } })
      }
      // 车主价
      if (_this.$hasPermissions('M_shoppingProductsList_carOwnersPrice')) {
        arr.splice((pos * 1 + 1), 0, { title: '车主价', dataIndex: 'carOwnersPrice', width: '7%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } })
      }
      if (!_this.itemCategorySn) {
        arr.splice(6, 0, { title: '商城类目', scopedSlots: { customRender: 'categoryName' }, width: '15%', align: 'center' })
      }
      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 选择产品
    async handleChooseProduct () {
      // 回显已选择产品并禁用
      const res = await queryProductSnList({})
      if (res.status == 200) {
        this.chooseDataList = res.data || []
      }
      this.showProModal = true
    },
    // 选择产品 成功
    addProductSuccess (list) {
      const _this = this
      _this.spinning = true
      const newList = list.map(item => {
        return {
          categorySn: _this.$route.params.sn,
          productSn: item.productSn,
          productCode: item.code,
          priceType: 'TERMINAL_PRICE',
          price: item.terminalPrice
        }
      })
      _this.hanldeOk(newList, 'chooseProduct')
    },
    // 获取产品类目列表
    getCategoryList () {
      const _this = this
      _this.spinning = true
      queryExtList({}).then(res => {
        if (res.status == 200) {
          this.categoryOptions = res.data || []
        }
        _this.spinning = false
      })
    },
    // 关闭选择弹窗
    closeProductModal () {
      this.showProModal = false
      this.chooseDataList = []
    },
    // 导入产品
    handleAddProduct () {
      this.openGuideModal = true
    },
    // 导入产品成功
    hanldeOk (list, typeVal) {
      const _this = this
      _this.spinning = true
      const ajaxName = (typeVal && typeVal === 'chooseProduct') ? saveBatchProduct : saveBatchProductExcel
      ajaxName(list).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$nextTick(() => {
            _this.showProModal = false
            _this.$refs.table.refresh(true)
          })
        }
        _this.spinning = false
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.productName = ''
      this.queryParam.productCode = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.hotFlag = undefined
      this.queryParam.status = undefined
      this.queryParam.categorySn1 = undefined
      this.queryParam.categorySn2 = undefined
      this.productType = []
      this.category = []
      this.$refs.table.refresh(true)
    },
    // 编辑
    handleEdit (row) {
      this.itemProductSn = row.shopProductSn
      this.openEditModal = true
      const _this = this
      this.$nextTick(() => {
        _this.$refs.editProduct.getDetail()
      })
    },
    // 编辑成功
    hanldeEditOk () {
      this.itemProductSn = null
      this.$refs.table.refresh()
    },
    //  产品分类  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] : ''
    },
    // 商城类目
    changeProductsCategory (val) {
      this.queryParam.categorySn1 = val[0] ? val[0] : undefined
      this.queryParam.categorySn2 = val[1] ? val[1] : undefined
    },
    // 删除
    handleDel (row) {
      const _this = this
      let shopProductSnList = []
      if (row && Object.keys(row).length > 0) {
        shopProductSnList.push(row.shopProductSn)
      } else {
        shopProductSnList = _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys ? _this.rowSelectionInfo.selectedRowKeys : []
      }
      if (shopProductSnList && shopProductSnList.length == 0) {
        this.$message.warning('请在列表中勾选产品！')
        return
      }
      this.confirmDel(shopProductSnList)
    },
    // 确认删除
    confirmDel (shopProductSnList) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认删除产品吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          shopProductDel({ shopProductSnList }).then(res => {
            if (res.status == 200) {
              if (res.data && res.data.length > 0) {
                _this.$confirm({
                  title: '提示',
                  content: res.data.join('、') + '产品正在参与促销活动，无法删除',
                  centered: true,
                  okText: '知道了',
                  cancelText: '取消', // 将cancelText设置为空字符串或去掉该属性可以隐藏取消按钮
                  cancelButtonProps: {
                    style: {
                      display: 'none' // 通过设置样式隐藏取消按钮
                    }
                  },
                  onOk () {
                    _this.$refs.table.clearSelected()
                    _this.$refs.table.refresh()
                  }
                })
              } else {
                _this.$message.success(res.message)
                _this.$refs.table.clearSelected()
                _this.$refs.table.refresh()
              }
            }
            _this.spinning = false
          })
        }
      })
    },
    // 批量上、下架
    changeStatus (type, row) {
      let newRow = []
      if (!row) {
        newRow = this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys
        if (!this.rowSelectionInfo || (newRow.length < 1)) {
          this.$message.warning('请在列表中进行勾选！')
          return false
        }
      } else {
        newRow.push(row.shopProductSn)
      }
      this.handleChangeStatus(type, newRow)
    },
    // 确定上、下架
    handleChangeStatus (typeVal, ajaxData) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认' + (typeVal === '0' ? '下架' : '上架') + '产品吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          shopProductUpdateStatus({ shopProductSnList: ajaxData, status: typeVal }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.clearSelected()
              _this.$refs.table.refresh()
            }
            _this.spinning = false
          })
        }
      })
    },
    // 初始化
    pageInit () {
      const _this = this
      if (!_this.itemCategorySn) {
        _this.getCategoryList()
      }
      _this.closeProductModal()
      _this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh(true)
    }
  }
}
</script>
