<template>
  <div class="permissionSetting-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" @back="handleBack" class="permissionSetting-cont">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="permissionSetting-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin-left: 20px;color: #666;">经销商：{{ $route.params.name }}</span>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="permissionSetting-main">
        <!-- 搜索条件 -->
        <div ref="tableSearch" class="table-page-search-wrapper">
          <a-form-model
            id="permissionSetting-form"
            ref="ruleForm"
            class="form-model-con"
            layout="inline"
            :model="queryParam">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="品牌" prop="productBrandSn">
                  <ProductBrand id="chooseProducts-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品分类" prop="productType">
                  <productTypeAll placeholder="请选择产品分类" @change="changeProductType" v-model="productType" id="chooseProducts-productType"></productTypeAll>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="价格级别" prop="priceLevel">
                  <v-select code="PRICE_LEVEL" id="productLevelEdit-priceLevel" v-model="queryParam.priceLevel" allowClear placeholder="请选择价格级别"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="getData" :disabled="disabled" id="permissionSetting-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="permissionSetting-reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <!-- 操作按钮 -->
        <div class="table-operator">
          <a-button type="primary" class="button-info" @click="chooseTModal">选择品类</a-button>
          <span v-if="!showEmpty && $route.params.dealerLevel != 'special'">
            <a-button type="primary" class="button-success" @click="handleEdit()">批量编辑</a-button>
            <a-button type="primary" class="button-error" @click="handleDel()">批量删除</a-button>
          </span>
        </div>
        <!-- 列表 -->
        <div :style="{height:tableHeight+'px'}">
          <ve-table
            border-y
            v-show="!showEmpty"
            :scroll-width="0"
            :max-height="(tableHeight)"
            :show-header="showTableHead"
            :row-style-option="{clickHighlight: true}"
            :cellSelectionOption="{enable: false}"
            :virtual-scroll-option="{enable: true}"
            :columns="columns"
            :table-data="dataSource"
            row-key-field-name="dealerScopeSn"
            :checkbox-option="checkboxOption"
          />
          <div v-show="showEmpty" class="empty-data"><a-empty description="暂无产品" :image="simpleImage"/></div>
        </div>
      </a-card>
    </a-spin>
    <!-- 选择产品分类 -->
    <chooseTypeModal ref="chooseType" :openModal="openTypeModal" @close="openTypeModal=false" @ok="resetSearchForm" />
    <!-- 修改价格等级 -->
    <editPriceLevelModal :priceLevelVal="itemPriceLevel" :openModal="openPriceLevelModal" @close="closePriceLevelModal" @ok="handlePriceLevelOk" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import ChooseTypeModal from './chooseTypeModal.vue'
import editPriceLevelModal from './priceLevelModal.vue'
import productTypeAll from '@/views/common/productTypeAll.js'
import ProductBrand from '@/views/common/productBrand.js'
import { Empty } from 'ant-design-vue'
import { dealerScopeModifyPriceLevel, dealerScopeDelete, dealerScopeQueryList } from '@/api/dealerScope'
export default {
  name: 'MerchantInfoManagementSet',
  mixins: [commonMixin],
  components: { STable, VSelect, ChooseTypeModal, productTypeAll, ProductBrand, editPriceLevelModal },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        priceLevel: undefined
      },
      productType: [],
      disabled: false, //  查询、重置按钮是否可操作
      openTypeModal: false, //  选择产品分类
      openPriceLevelModal: false,
      itemPriceLevel: '',
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      dataSource: [],
      showEmpty: false,
      showTableHead: true, // 显示表头
      selectedRowKeys: []
    }
  },
  computed: {
    columns () {
      const _this = this
      // 操作按钮
      const actionFormat = function (record, data, h) {
        if (_this.$route.params.dealerLevel != 'special') {
          return (
            <div>
              <a-button size="small" type="link" class="button-info" onClick={() => _this.handleEdit(record)}>编辑</a-button>
              <a-button size="small" type="link" class="button-error" onClick={() => _this.handleDel(record)}>删除</a-button>
            </div>
          )
        } else {
          return (
            <div>
              <a-button
                size="small"
                type="link"
                class="button-info"
                onClick={() => _this.handleDel(record)}
              >删除</a-button>
            </div>
          )
        }
      }
      const arr = [
        { title: '', field: '', key: 'acheck', width: 60, type: 'checkbox', align: 'center' },
        { title: '品牌', field: 'productBrandName', key: 'a', align: 'center', width: 160, operationColumn: false, renderBodyCell: ({ row, column }) => { return row[column.field] || '--' } },
        { title: '一级分类', field: 'productTypeName1', key: 'b', width: 160, align: 'center', operationColumn: false, renderBodyCell: ({ row, column }) => { return row[column.field] || '--' } },
        { title: '二级分类', field: 'productTypeName2', key: 'c', width: 160, align: 'center', operationColumn: false, renderBodyCell: ({ row, column }) => { return row[column.field] || '--' } },
        { title: '三级分类', field: 'productTypeName3', key: 'd', width: 160, align: 'center', operationColumn: false, renderBodyCell: ({ row, column }) => { return row[column.field] || '--' } },
        { title: '操作', field: 'action', width: 100, key: 'e', align: 'center', fixed: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return actionFormat(row, row[column.field], h) } }
      ]
      return arr
    },
    checkboxOption () {
      const _this = this
      return {
        selectedRowKeys: _this.selectedRowKeys,
        // 行选择改变事件
        selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
          _this.selectedRowKeys = selectedRowKeys
        },
        // 全选改变事件
        selectedAllChange: ({ isSelected, selectedRowKeys }) => {
          _this.selectedRowKeys = selectedRowKeys
        }
      }
    }
  },
  methods: {
    getData () {
      const _this = this
      _this.disabled = true
      _this.spinning = true
      _this.queryParam.dealerSn = _this.$route.params.sn
      dealerScopeQueryList(_this.queryParam).then(res => {
        if (res.status == 200) {
          _this.dataSource = res.data
        }
        _this.showEmpty = _this.dataSource.length <= 0
        _this.disabled = false
        _this.spinning = false
      })
    },
    // 选择品类
    chooseTModal () {
      this.openTypeModal = true
      this.$nextTick(() => {
        this.$refs.chooseType.getDisabledList()
      })
    },
    // 打开编辑弹窗
    handleEdit (row) {
      if (row) {
        this.selectedRowKeys = []
        this.selectedRowKeys.push(row.dealerScopeSn)
        this.itemPriceLevel = row.priceLevel
      } else {
        this.itemPriceLevel = ''
        if (this.selectedRowKeys && this.selectedRowKeys.length === 0) {
          this.$message.warning('请选择一条数据')
          return
        }
      }
      this.$nextTick(() => {
        this.openPriceLevelModal = true
      })
    },
    // 编辑价格等级
    handlePriceLevelOk (val) {
      const _this = this
      dealerScopeModifyPriceLevel({
        snList: this.selectedRowKeys,
        priceLevel: val
      }).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.resetSearchForm()
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    closePriceLevelModal () {
      this.itemPriceLevel = ''
      this.openPriceLevelModal = false
    },
    //  选择分类  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] : ''
    },
    // 批量删除
    handleDel (row) {
      const _this = this
      if (!row && this.selectedRowKeys && this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择一条数据')
        return
      }
      const newSnList = row ? [row.dealerScopeSn] : _this.selectedRowKeys
      this.$confirm({
        title: '提示',
        content: '经销权删除后，该商户的差价设置将同步解除，确定删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          dealerScopeDelete({ snList: newSnList }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.resetSearchForm()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 重置表单
    resetSearchForm () {
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.priceLevel = undefined
      this.productType = []
      this.getData()
    },
    // 返回
    handleBack () {
      this.selectedRowKeys = []
      this.$router.push({ path: '/dealerManagement/merchantInfoManagement/list', query: { closeLastOldTab: true } })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 205
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less" scoped>
  .permissionSetting-wrap{
    .permissionSetting-cont{
      margin-bottom: 6px;
    }
    .empty-data{
      padding-top:100px;
    }
  }
  /deep/.ve-checkbox .ve-checkbox-checked .ve-checkbox-inner {
      background-color: #ed1c24 !important;
      border-color: #ed1c24 !important;
    }
  /deep/.ve-checkbox .ve-checkbox-indeterminate .ve-checkbox-inner::after{
    background-color: #ed1c24 !important;
  }
</style>
