<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"
            :rules="rules"
            @keyup.enter.native="handleSearch">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="类型" prop="goodsType">
                  <v-select code="DEALER_GOODS_TYPE" id="permissionSetting-goodsType" v-model="queryParam.goodsType" allowClear placeholder="请选择类型"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="类型名称" prop="goodsName">
                  <a-input id="permissionSetting-goodsName" v-model.trim="queryParam.goodsName" allowClear placeholder="请输入类型名称"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品编码" prop="goodsCode">
                  <a-input id="permissionSetting-goodsCode" v-model.trim="queryParam.goodsCode" allowClear placeholder="请输入产品编码"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="handleSearch" :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 id="permissionSetting-brand" type="primary" class="button-error" @click="choosePModal('BRAND')">选择产品品牌</a-button>
          <a-button id="permissionSetting-type" type="primary" class="button-info" @click="choosePModal('CATEGORY')">选择产品分类</a-button>
          <a-button id="permissionSetting-product" type="primary" class="button-success" @click="choosePModal('PRODUCT')">选择产品</a-button>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button size="small" type="link" class="button-error" @click="handleDel(record)">删除</a-button>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 选择产品品牌 -->
    <chooseBrandModal :openModal="openBrandModal" :chooseData="chooseBrand" @close="openBrandModal=false" @ok="handleBrandOk" />
    <!-- 选择产品分类 -->
    <chooseTypeModal :openModal="openTypeModal" :chooseData="chooseType" @close="openTypeModal=false" @ok="handleTypeOk" />
    <!-- 选择产品 -->
    <chooseProductsModal
      type="dealership"
      :dealerSn="$route.params.sn"
      :openModal="openProductsModal"
      :chooseData="chooseProducts"
      @close="openProductsModal=false"
      @ok="handleProductsOk" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import ChooseProductsModal from '@/views/common/chooseProductsModal.vue'
import ChooseBrandModal from '@/views/common/chooseBrandModal.vue'
import ChooseTypeModal from '@/views/common/chooseTypeModal.vue'
import { dealerScopeList, dealerScopeSave, dealerScopeDel, dealerScopeQueryList } from '@/api/dealerScope'
export default {
  name: 'MerchantInfoManagementSet',
  mixins: [commonMixin],
  components: { STable, VSelect, ChooseProductsModal, ChooseBrandModal, ChooseTypeModal },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        goodsType: undefined,
        goodsName: '',
        goodsCode: ''
      },
      rules: {
        // goodsType: [ { required: true, message: '请选择类型', trigger: 'change' } ]
      },
      disabled: false, //  查询、重置按钮是否可操作
      loading: false, //  表格加载中
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '添加时间', dataIndex: 'createDate', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '类型', dataIndex: 'type', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '类型名称', dataIndex: 'goodsName', align: 'center', width: '20%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品名称', dataIndex: 'product.name', align: 'center', width: '30%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品编码', dataIndex: 'product.code', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return dealerScopeList(Object.assign(parameter, this.queryParam, { dealerSn: this.$route.params.sn })).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
              const goodsType = data.list[i].goodsType
              data.list[i].type = goodsType == 'PRODUCT' ? '产品' : goodsType == 'BRAND' ? '品牌' : goodsType == 'CATEGORY' ? '分类' : '--'
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      openBrandModal: false, //  选择产品品牌
      openTypeModal: false, //  选择产品分类
      openProductsModal: false, //  选择产品
      chooseBrand: [], //  所选品牌
      chooseProducts: [], //  所选产品
      chooseType: [] //  所选分类
    }
  },
  methods: {
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          return false
        }
      })
    },
    // 选择产品
    choosePModal (type) {
      const productList = []
      const brandList = []
      const typeList = []
      dealerScopeQueryList({ dealerSn: this.$route.params.sn, goodsType: type }).then(res => {
        if (res.status == 200) {
          const data = res.data
          data.map(item => {
            if (item.goodsType == 'PRODUCT') {
              productList.push(item)
            } else if (item.goodsType == 'BRAND') {
              brandList.push(item)
            } else if (item.goodsType == 'CATEGORY') {
              typeList.push(item)
            }
          })
          if (type == 'PRODUCT') { //  选择产品
            // this.chooseProducts = productList  //  包含先前所选产品
            this.chooseProducts = [] //  不包含先前所选产品
            this.openProductsModal = true
          } else if (type == 'BRAND') { //  选择品牌
            this.chooseBrand = brandList
            this.openBrandModal = true
          } else if (type == 'CATEGORY') { //  选择分类
            this.chooseType = typeList
            this.openTypeModal = true
          }
        }
      })
    },
    // 品牌
    handleBrandOk (obj) {
      this.chooseBrand = obj
      this.changeData('BRAND')
    },
    // 产品
    handleProductsOk (obj) {
      this.chooseProducts = obj
      this.changeData('PRODUCT')
    },
    // 分类
    handleTypeOk (obj) {
      this.chooseType = obj
      this.changeData('CATEGORY')
    },
    changeData (type) {
      const _this = this
      if (type == 'PRODUCT') { //  选择产品
        if (_this.chooseProducts.length > 0) {
          const snList = []
          _this.chooseProducts.map(item => {
            const productSn = item.productSn ? item.productSn : item.product.productSn ? item.product.productSn : ''
            snList.push(productSn)
          })
          this.setData(snList, type)
        }
      } else if (type == 'BRAND') { //  选择品牌
        if (_this.chooseBrand.length > 0) {
          const snList = []
          _this.chooseBrand.map(item => {
            snList.push(item.brandSn)
          })
          this.setData(snList, type)
        }
      } else if (type == 'CATEGORY') { //  选择分类
        if (_this.chooseType.length > 0) {
          const snList = []
          _this.chooseType.map(item => {
            snList.push(item.productTypeSn)
          })
          this.setData(snList, type)
        }
      }
    },
    // 添加经销权
    setData (snList, type) {
      const _this = this
      const params = {
        dealerSn: _this.$route.params.sn,
        goodsType: type,
        goodsSnList: snList
      }
      _this.spinning = true
      dealerScopeSave(params).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh(true)
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          dealerScopeDel({ sn: row.dealerScopeSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 重置表单
    resetSearchForm () {
      this.queryParam.goodsType = undefined
      this.queryParam.goodsName = ''
      this.queryParam.goodsCode = ''
      this.$refs.table.refresh(true)
    },
    // 返回
    handleBack () {
      this.$router.push({ path: '/dealerManagement/merchantInfoManagement/list', query: { closeLastOldTab: true } })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 292
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.$refs.table.refresh(true)
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.$refs.table.refresh(true)
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less" scoped>
  .permissionSetting-wrap{
    .permissionSetting-cont{
      margin-bottom: 10px;
    }
  }
</style>
