<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 id="viewDealers-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="商户类型">
                  <dealerType id="viewDealers-dealerType" changeOnSelect v-model="dealerType" @change="getDealerType" allowClear></dealertype>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="商户级别">
                  <v-select code="DEALER_LEVEL" id="viewDealers-dealerLevel" v-model="queryParam.dealer.dealerLevel" allowClear placeholder="请选择商户级别"></v-select>
                </a-form-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-item label="地区">
                  <AreaList id="viewDealers-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                </a-form-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" id="viewDealers-binding" class="button-error" @click="openAddDealer=true"><a-icon type="plus" />立即绑定经销商</a-button>
          </a-empty>
        </div>
        <div class="tableCon" v-else>
          <div style="margin-bottom:10px;"><a-button type="primary" id="viewDealers-binding-btn" class="button-error" @click="openAddDealer=true">绑定经销商</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"
                :id="'viewDealers-del-btn'+record.id"
                @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 { Empty } from 'ant-design-vue'
// 组件
import { STable, VSelect } from '@/components'
import chooseDealer from '@/views/common/chooseDealer.vue'
import AreaList from '@/views/common/areaList.js'
import dealerType from '@/views/common/dealerType.js'
// 接口
import { queryPageAreaDealer, batchBindDealer, bindDealer, deleteBindDealer } from '@/api/subarea'
export default {
  mixins: [commonMixin],
  components: { STable, VSelect, chooseDealer, AreaList, dealerType },
  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 {
      spinning: false,
      disabled: false, // 查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE, // 数据为空显示图片
      visible: this.showModal, // 是否显示弹窗
      openAddDealer: false, // 打开绑定经销商弹窗
      flag: true, // 是否显示绑定经销商按钮
      dealerType: [], // 商户类型
      //  查询条件
      queryParam: {
        dealer: {
          nameLike: '', // 经销商名称/别名
          dealerType1: undefined, //  商户类型
          dealerType2: undefined, //  商户类型
          dealerLevel: null, // 商户级别
          auditState: undefined, // 审核状态
          provinceSn: undefined, // 省
          citySn: undefined, // 市
          districtSn: undefined// 区
        }
      },
      columns: [
        { title: '经销商名称', dataIndex: 'dealer.dealerName', width: '25%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户别名', dataIndex: 'dealer.dealerAlias', width: '25%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户类型', dataIndex: 'dealerTypeName', width: '20%', 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.list.length; i++) {
              data.list[i].no = no + i + 1
              if (data.list[i].dealer.dealerTypeName1) {
                data.list[i].dealerTypeName = data.list[i].dealer.dealerTypeName1 + '>' + data.list[i].dealer.dealerTypeName2
              }
            }
          }
          this.disabled = false
          this.spinning = false
          this.setTableH()
          return data
        })
      }
    }
  },
  methods: {
    // 商户类型 change
    getDealerType (v, o) {
      this.queryParam.dealer.dealerType1 = v[0]
      this.queryParam.dealer.dealerType2 = v[1]
    },
    // 绑定
    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.dealerType = []
      this.queryParam = {
        dealer: {
          nameLike: '',
          dealerType1: undefined, //  商户类型
          dealerType2: undefined, //  商户类型
          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)
      }
    },
    // 地区 change
    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>
