<template>
  <a-spin :spinning="spinning" tip="Loading...">
    <!-- 搜索条件 -->
    <div ref="tableSearch" class="table-page-search-wrapper newTableSearchName">
      <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
        <a-row :gutter="15">
          <a-col :md="8" :sm="24">
            <a-form-item label="经销商名称/别名">
              <a-input id="chooseDealer-nameLike" v-model.trim="queryParam.nameLike" allowClear placeholder="请输入经销商名称/别名"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="商户类型">
              <dealerType id="chooseDealer-dealerType" v-model="dealerType" changeOnSelect @change="getDealerType" allowClear></dealerType>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="商户级别" prop="dealerLevel">
              <v-select code="DEALER_LEVEL" id="ucModal-dealerLevel" v-model="queryParam.dealerLevel" allowClear placeholder="请选择商户级别"></v-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24" v-if="pageType!='viewDealers'">
            <a-form-item label="所在区域/分区">
              <subarea id="chooseDealer-subarea" ref="subarea" @change="subareaChange"></subarea>
            </a-form-item>
          </a-col>
          <div v-else>
            <a-col :md="8" :sm="24">
              <a-form-item label="审核状态">
                <v-select code="AUDIT_STATE" id="viewDealers-auditState" v-model="queryParam.auditState" allowClear placeholder="请选择审核状态"></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-model-item label="地区">
                <AreaList id="viewDealers-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
              </a-form-model-item>
            </a-col>
          </div>
          <a-col :md="pageType!='viewDealers'?8:6" :sm="24" style="margin-bottom: 10px;">
            <a-button type="primary" @click="searchForm(true)" :disabled="disabled" id="chooseDealer-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="chooseDealer-reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
      <!-- 列表 -->
      <div style="margin-bottom: 10px">
        <a-button type="primary" ghost :loading="loading" @click="handleBatchAudit">批量添加</a-button>
        <span style="margin-left: 5px">
          <template v-if="selectCount"> {{ `已选 ${selectCount} 项` }} </template>
        </span>
      </div>
    </div>
    <s-table
      class="sTable"
      ref="table"
      size="small"
      :rowKey="(record) => record.dealerSn"
      rowKeyName="dealerSn"
      :row-selection="{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: pageType=='viewDealers'?!!record.subareaAreaSn: !!record.chooseId} }) }"
      @rowSelection="rowSelectionFun"
      :columns="columns"
      :data="loadData"
      :style="{ height:pageType=='viewDealers'? tableHeight+84.5+'px':tableHeight-15+'px' }"
      :scroll="{ y: pageType=='viewDealers'?tableHeight:tableHeight+80 }"
      :defaultLoadData="false"
      bordered>
      <template slot="areas" slot-scope="text, record">
        <span v-if="record.subareaArea">{{ record.subareaArea.subareaName }}>{{ record.subareaArea.subareaAreaName }}</span>
        <span v-else>--</span>
      </template>
      <template slot="action" slot-scope="text, record">
        <a-button
          size="small"
          type="link"
          class="button-error"
          @click="handleAdd(record)"
          v-if="record.subareaAreaSn != parentData.subareaAreaSn"
          id="marketingDivisionSetNew-del-btn">添加</a-button>
        <span style="color:#666" v-else>已添加</span>
      </template>
    </s-table>
  </a-spin>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import AreaList from '@/views/common/areaList.js'
import { queryDealerPageList } from '@/api/dealer'
import subarea from '@/views/common/subarea.js'
import dealerType from '@/views/common/dealerType.js'
export default {
  name: 'ChooseDealer',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, AreaList, dealerType },
  props: {
    pageType: {
      type: String,
      default: ''
    },
    parentData: {
      type: Object,
      default: function () {
        return null
      }
    }
  },
  data () {
    return {
      spinning: false,
      dealerType: [],
      queryParam: { //  查询条件
        nameLike: '',
        dealerType1: undefined, //  商户类型
        dealerType2: undefined, //  商户类型
        dealerLevel: null,
        auditState: undefined,
        provinceSn: undefined,
        citySn: undefined,
        districtSn: undefined,
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        }
      },
      tableHeight: 0,
      disabled: false, //  查询、重置按钮是否可操作
      loading: false, // 批量添加loading
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        return queryDealerPageList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          const _this = this
          if (res.status == 200) {
            data = res.data
            const no = 0
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              if (data.list[i].dealerTypeName1) {
                data.list[i].dealerTypeName = data.list[i].dealerTypeName1 + '>' + data.list[i].dealerTypeName2
              }
            }
          }
          this.spinning = false
          return data
        })
      },
      rowSelectionInfo: null
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '经销商名称', dataIndex: 'dealerName', width: '30%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '商户别名', dataIndex: 'dealerAlias', align: 'left', width: '30%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '商户类型', dataIndex: 'dealerTypeName', width: '25%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户级别', dataIndex: 'dealerLevelDictValue', width: '15%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (_this.pageType == 'viewDealers') {
        arr.splice(4, 0, { title: '审核状态', dataIndex: 'auditStateDictValue', width: '20%', align: 'center', customRender: function (text) { return text || '--' } })
        arr.splice(5, 0, { title: '当前所属区域', scopedSlots: { customRender: 'areas' }, width: '20%', align: 'center' })
        arr.splice(6, 0, { title: '操作', scopedSlots: { customRender: 'action' }, width: '20%', align: 'center' })
      } else {
        arr.splice(4, 0, { title: '所在区域', dataIndex: 'subareaArea.subareaName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } })
        arr.splice(5, 0, { title: '所在分区', dataIndex: 'subareaArea.subareaAreaName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      return arr
    },
    selectCount () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    getDealerType (v, o) {
      this.queryParam.dealerType1 = v[0]
      this.queryParam.dealerType2 = v[1]
    },
    areaChange (val) {
      this.queryParam.provinceSn = val[0] ? val[0] : ''
      this.queryParam.citySn = val[1] ? val[1] : ''
      this.queryParam.districtSn = val[2] ? val[2] : ''
    },
    searchForm (flag) {
      this.$refs.table.refresh(flag)
      this.$refs.table.clearSelected()
      this.spinning = false
    },
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.dealerType = []
      this.queryParam = {
        nameLike: '',
        dealerType1: undefined, //  商户类型
        dealerType2: undefined, //  商户类型
        dealerLevel: null,
        auditState: undefined,
        provinceSn: undefined,
        citySn: undefined,
        districtSn: undefined,
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        }
      }
      if (this.pageType != 'viewDealers') {
        this.$refs.subarea.clearData()
      } else {
        this.$refs.areaList.clearData()
      }
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    clearTable () {
      this.rowSelectionInfo = null
      this.$refs.table.clearTable()
    },
    // 批量添加
    handleBatchAudit () {
      const _this = this
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        _this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      const dealerSnList = _this.rowSelectionInfo.selectedRowKeys
      this.spinning = false
      this.$emit('plAdd', dealerSnList)
    },
    handleAdd (row) {
      if (row.subareaArea) {
        const _this = this
        this.$confirm({
          title: '提示',
          content: '当前经销商已被其他区域分区绑定，确定要更新绑定关系吗?',
          centered: true,
          onOk () {
            _this.spinning = true
            _this.$emit('add', row)
          }
        })
      } else {
        this.spinning = true
        this.$emit('add', row)
      }
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.resetSearchForm()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 285
    }
  },
  mounted () {
    this.pageInit()
  },
  activated () {
    this.pageInit()
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  }
}
</script>
