<template>
  <div>
    <a-drawer
      title="查看经销商"
      width="80%"
      :zIndex="100"
      :visible="visible"
      :get-container="false"
      class="viewsDealer"
      :wrap-style="{ position: 'absolute' }"
      @close="visible = false">
      <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="viewDealers-nameLike" v-model.trim="queryParam.dealer.nameLike" allowClear placeholder="请输入经销商名称/别名"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="商户类型">
                  <v-select code="DEALER_TYPE" id="viewDealers-dealerType" v-model="queryParam.dealer.dealerType" allowClear placeholder="请选择商户类型"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-model-item label="商户级别">
                  <v-select code="DEALER_LEVEL" id="viewDealers-dealerLevel" v-model="queryParam.dealer.dealerLevel" allowClear placeholder="请选择商户级别"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="审核状态">
                  <v-select code="AUDIT_STATE" id="viewDealers-auditState" v-model="queryParam.dealer.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>
              <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="searchForm" :disabled="disabled" id="viewDealers-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="viewDealers-reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div style="margin-top:200px;" v-if="flag">
          <a-empty
            :image="simpleImage"
            :image-style="{
              height: '60px',
            }"
          >
            <span slot="description"> 暂无数据 </span>
            <a-button type="primary" class="button-error" @click="openAddDealer=true"><a-icon type="plus" />立即绑定经销商</a-button>
          </a-empty>
        </div>
        <div class="tableCon" v-else>
          <div style="text-align:right;margin-bottom:10px;"><a-button type="primary" class="button-error" @click="openAddDealer=true"><a-icon type="plus" />绑定经销商</a-button></div>
          <s-table
            class="sTable"
            ref="table"
            size="small"
            :rowKey="(record) => record.id"
            :columns="columns"
            :data="loadData"
            :style="{ height: tableHeight+84.5+'px' }"
            :scroll="{ y: tableHeight }"
            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>
        </div>
      </a-spin>
    </a-drawer>

    <!-- 绑定经销商 -->
    <a-drawer
      title="绑定经销商"
      width="68%"
      :zIndex="200"
      :visible="openAddDealer"
      :get-container="false"
      :wrap-style="{ position: 'absolute' }"
      class="deraw-bindDealer"
      @close="openAddDealer = false">
      <div class="dealerModalCon">
        <chooseDealer ref="chooseDealer" v-if="openAddDealer" :parentData="parentData" pageType="viewDealers" @add="hanldAdd" @plAdd="hanldPlAdd"></chooseDealer>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import chooseDealer from '@/views/common/chooseDealer.vue'
import AreaList from '@/views/common/areaList.js'
import { Empty } from 'ant-design-vue'
import { queryPageAreaDealer, batchBindDealer, bindDealer, deleteBindDealer } from '@/api/subarea'
export default {
  mixins: [commonMixin],
  components: { STable, VSelect, chooseDealer, AreaList },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    parentData: {
      type: Object,
      default: function(){
        return null
      }
    }
  },
  watch: {
    showModal (newValue, oldValue) {
      this.visible = newValue
    },
    visible (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetData()
      }else{
        this.pageInit()
      }
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  data () {
    return {
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      spinning: false,
      visible: this.showModal,
      openAddDealer: false,
      flag: true,
      queryParam: { //  查询条件
        dealer:{
          nameLike: '',
          dealerType: null,
          dealerLevel: null,
          auditState: undefined,
          provinceSn: undefined,
          citySn: undefined,
          districtSn: undefined
        }
      },
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      disabled: false,
      tableHeight: 0,
      columns: [
        { title: '经销商名称', dataIndex: 'dealer.dealerName', width: '30%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户别名', dataIndex: 'dealer.dealerAlias', width: '30%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户类型', dataIndex: 'dealer.dealerTypeDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户级别', dataIndex: 'dealer.dealerLevelDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核状态', dataIndex: 'dealer.auditStateDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return queryPageAreaDealer(Object.assign(parameter, this.queryParam, {subareaSn: this.parentData.subareaSn, subareaAreaSn: this.parentData.subareaAreaSn})).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = 0
            for (var i = 0; i < data.length; i++) {
              data[i].no = no + i + 1
            }
          }
          this.disabled = false
          this.spinning = false
          this.setTableH()
          return data
        })
      },
    }
  },
  methods: {
    // 绑定
    hanldAdd(row){
      console.log(row)
      bindDealer({subareaAreaSn: this.parentData.subareaAreaSn,dealerSn:row.dealerSn}).then(res => {
        if(res.status == 200){
          this.resetSearchForm()
          this.$refs.chooseDealer.searchForm(false)
        }
        this.$refs.chooseDealer.searchForm
      })
    },
    // 批量绑定
    hanldPlAdd(rows){
      console.log(rows)
      batchBindDealer({subareaAreaSn: this.parentData.subareaAreaSn,dealerSnSet:rows}).then(res => {
        if(res.status == 200){
          this.resetSearchForm()
          this.$refs.chooseDealer.searchForm(false)
        }
        this.$refs.chooseDealer.spinning = false
      })
    },
    // 删除
    handleDel(row){
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定要删除当前经销商绑定关系吗?',
        centered: true,
        onOk () {
          _this.spinning = true
          deleteBindDealer({sn: row.subareaAreaDealerSn}).then(res => {
            if(res.status == 200){
              _this.resetSearchForm()
            }
            _this.spinning = false
          })
        }
      })
    },
    searchForm(){
      if(this.flag){
        this.hasData()
      }else{
        this.$refs.table.refresh(true)
      }
    },
    resetData(){
      this.queryParam = {
          dealer:{
            nameLike: '',
            dealerType: null,
            dealerLevel: null,
            auditState: undefined,
            provinceSn: undefined,
            citySn: undefined,
            districtSn: undefined
          }
        }
      this.$refs.areaList.clearData()
    },
    resetSearchForm () {
      if(this.flag){
        this.hasData()
      }else{
        this.resetData()
        this.$refs.table.refresh(true)
      }
    },
    areaChange(val){
      this.queryParam.dealer.provinceSn = val[0] ? val[0] : ''
      this.queryParam.dealer.citySn = val[1] ? val[1] : ''
      this.queryParam.dealer.districtSn = val[2] ? val[2] : ''
    },
   async hasData(){
      const ret = await queryPageAreaDealer({pageNo:1,pageSize:10,subareaSn: this.parentData.subareaSn, subareaAreaSn: this.parentData.subareaAreaSn}).then(res => res.data)
      this.flag = ret.count == 0
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.flag = true
      // 判断是已绑定数据
      this.hasData()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 290
    }
  },
}
</script>

<style lang="less">
.viewsDealer{
  .ant-drawer-body{
    padding:10px 20px 0;
  }
}
.deraw-bindDealer {
  .ant-drawer-body{
    padding:10px 20px 0;
  }
}
</style>
