<template>
  <div class="relatedDealersList-wrap">
    <div ref="headerBar">
      <a-page-header :ghost="false" :backIcon="false" class="header-bar">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="salesEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span class="subTitle-word text-overflow" style="max-width:300px;margin-left:15px;">省仓名称：{{ $route.params.name ||'--' }}</span>
        </template>
      </a-page-header>
    </div>
    <a-card size="small" :bordered="false" class="relatedDealersList-cont">
      <a-tabs v-model="activeKeyVal">
        <a-tab-pane key="1" tab="关联经销商">
          <a-spin :spinning="spinning" tip="Loading...">
            <!-- 筛选条件 -->
            <div class="table-page-search-wrapper">
              <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
                <a-row :gutter="15">
                  <a-col :md="4" :sm="24">
                    <a-form-model-item label="地区">
                      <AreaList id="actualSalesReportList-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="4" :sm="24">
                    <a-form-model-item label="区域/分区">
                      <subarea ref="subarea" id="relatedDealersList-subarea" @change="subareaChange"></subarea>
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="4" :sm="24">
                    <a-form-item label="经销商名称">
                      <a-input id="relatedDealersList-purchaseBillNo" v-model.trim="queryParam.nameLike" allowClear placeholder="请输入经销商名称"/>
                    </a-form-item>
                  </a-col>
                  <a-col :md="4" :sm="24">
                    <a-form-item label="商户类型">
                      <dealerType id="relatedDealersList-dealerType" changeOnSelect v-model="dealerType" @change="getDealerType" allowClear></dealertype>
                    </a-form-item>
                  </a-col>
                  <a-col :md="4" :sm="24">
                    <a-form-model-item label="商户级别" prop="dealerLevel">
                      <v-select code="DEALER_LEVEL" id="relatedDealersList-dealerLevel" v-model="queryParam.dealerLevel" allowClear placeholder="请选择商户级别"></v-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="4" :sm="24" style="margin-bottom: 10px;">
                    <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryCheckMakeInventoryList-refresh">查询</a-button>
                    <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="inventoryCheckMakeInventoryList-reset">重置</a-button>
                    <a-button
                      style="margin-left: 10px"
                      type="primary"
                      class="button-warning"
                      @click="handleExport"
                      :disabled="disabled"
                      :loading="exportLoading"
                      v-if="$hasPermissions('B_serviceCenter_export')"
                    >导出</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <div class="relatedDealersList-btn" style="margin-bottom:10px;">
              <a-button type="primary" @click="openDealersModal">新增经销商</a-button>
            </div>
            <!-- 列表 -->
            <s-table
              class="sTable"
              ref="table"
              size="small"
              :rowKey="(record) => record.dealerSn"
              rowKeyName="dealerSn"
              :columns="columns"
              :data="loadData"
              :defaultLoadData="false"
              :style="{ height: tableHeight+70+'px' }"
              :scroll="{ y: tableHeight }"
              :rowClassName="(record, index) => record.checkProfitLossQty < 0 ? 'redBg-row':''"
              bordered>
              <!-- 地区 -->
              <template slot="address" slot-scope="text, record">
                {{ record.provinceName }}/{{ record.cityName }}/{{ record.districtName }}
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button
                  size="small"
                  type="link"
                  v-if="$hasPermissions('B_serviceCenter_unbinding')"
                  class="button-info"
                  @click="handleDelete(record)"
                  id="provincialWarehouse-edit-btn">解绑</a-button>
                <span v-else>--</span>
              </template>
            </s-table>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <!-- 关联经销商 -->
    <a-drawer
      title="选择经销商"
      placement="right"
      closable
      :visible="openDealerModal"
      class="lookUpCustomers-modal"
      @close="closeDealerModal"
      width="72%"
    >
      <div class="dealerModalCon">
        <chooseDealer ref="dealerChoose" :itemSn="$route.params.sn" @plAdd="handleAddDealer"></chooseDealer>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import chooseDealer from './chooseDealer.vue'
import subarea from '@/views/common/subarea.js'
import AreaList from '@/views/common/areaList.js'
import { hdExportExcel } from '@/libs/exportExcel'
import dealerType from '@/views/common/dealerType.js'
import { queryServiceCenterDealerPage, serviceCenterBinding, serviceCenterUnbinding, serviceCenterExport } from '@/api/serviceCenter'
export default {
  name: 'LookUpCustomers',
  mixins: [commonMixin],
  components: { STable, VSelect, chooseDealer, subarea, AreaList, dealerType },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      disabled: false,
      exportLoading: false,
      dealerType: [],
      queryParam: {
        subareaSn: undefined,
        subareaAreaSn: undefined,
        provinceSn: undefined,
        citySn: undefined,
        districtSn: undefined,
        nameLike: '',
        relationType: 'purchase',
        dealerType1: undefined, //  商户类型
        dealerType2: undefined, //  商户类型
        dealerLevel: undefined
      },
      tableHeight: 0,
      activeKeyVal: '1',
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return queryServiceCenterDealerPage(Object.assign(parameter, this.queryParam)).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
              data.list[i].loginFlag = Number(data.list[i].loginFlag)
              if (data.list[i].dealerTypeName1) {
                data.list[i].dealerTypeName = data.list[i].dealerTypeName1 + '>' + data.list[i].dealerTypeName2
              }
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '8%', align: 'center' },
        { title: '经销商名称', dataIndex: 'dealerName', width: '20%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '地区', scopedSlots: { customRender: 'address' }, width: '20%', align: 'center', ellipsis: true },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户类型', dataIndex: 'dealerTypeName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户级别', dataIndex: 'dealerLevelDictValue', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '添加时间', dataIndex: 'createDate', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '12%', align: 'center' }
      ],
      openDealerModal: false
    }
  },
  methods: {
    // 打开经销商弹窗
    openDealersModal () {
      this.openDealerModal = true
      this.$nextTick(() => {
        this.$refs.dealerChoose.pageInit()
      })
    },
    // 关闭关联经销商弹窗
    closeDealerModal () {
      this.openDealerModal = false
      this.$refs.dealerChoose.clearSelect()
    },
    getDealerType (v, o) {
      this.queryParam.dealerType1 = v[0]
      this.queryParam.dealerType2 = v[1]
    },
    // 关联经销商
    handleAddDealer (list) {
      const newList = list.map(item => {
        return {
          dealerSn: item.dealerSn,
          dealerName: item.dealerName,
          dealerLevel: item.dealerLevel
        }
      })
      this.spinning = true
      const params = {
        serviceCenterSn: this.$route.params.sn,
        dealerList: newList
      }
      serviceCenterBinding(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
        }
        this.spinning = false
        this.closeDealerModal()
        this.$refs.table.refresh()
      })
    },
    areaChange (val) {
      this.queryParam.provinceSn = val[0] ? val[0] : ''
      this.queryParam.citySn = val[1] ? val[1] : ''
      this.queryParam.districtSn = val[2] ? val[2] : ''
    },
    subareaChange (val) {
      this.queryParam.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 解绑
    handleDelete (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '解绑后，该经销商无法向省仓采购，确定解绑吗？',
        centered: true,
        onOk () {
          const ajaxData = {
            serviceCenterSn: _this.$route.params.sn,
            dealerSn: row.dealerSn
          }
          _this.submitDel(ajaxData)
        }
      })
    },
    submitDel (params) {
      this.spinning = true
      serviceCenterUnbinding(params).then(res => {
        if (res.status == 200) {
          this.$message.success('解绑成功')
          this.$refs.table.refresh(true)
        }
        this.spinning = false
      })
    },
    //  重置
    resetSearchForm () {
      this.dealerType = []
      this.queryParam = {
        subareaSn: undefined,
        subareaAreaSn: undefined,
        provinceSn: undefined,
        citySn: undefined,
        districtSn: undefined,
        nameLike: '',
        serviceCenterSn: this.$route.params.sn,
        relationType: 'purchase',
        dealerType1: undefined, //  商户类型
        dealerType2: undefined, //  商户类型
        dealerLevel: undefined
      }
      this.$refs.areaList.clearData()
      this.$refs.subarea.clearData()
      this.$refs.table.refresh()
    },
    //  导出
    handleExport () {
      const _this = this
      _this.exportLoading = true
      _this.spinning = true
      _this.queryParam.serviceCenterName = this.$route.params.name
      hdExportExcel(serviceCenterExport, _this.queryParam, '省仓客户列表导出', function () {
        _this.exportLoading = false
        _this.spinning = false
      })
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'provincialWarehouseList' })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      _this.resetSearchForm()
    },
    setTableH () {
      const headHeight = this.$refs.headerBar.offsetHeight
      this.tableHeight = window.innerHeight - headHeight - 340
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less" scoped>
  .relatedDealersList-wrap{
    .table-operator{
    text-align:right;
    }
  }
</style>
