<template>
  <div>
    <a-card size="small" :bordered="false" class="merchantInfoManagementList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="区域">
                <subarea id="merchantInfoManagementList-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="经销商名称/商户别名">
                <a-input id="merchantInfoManagementList-nameLike" v-model.trim="queryParam.nameLike" allowClear placeholder="请输入商户名称/别名"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商户类型">
                <dealerType id="merchantInfoManagementList-dealerType" changeOnSelect v-model="dealerType" @change="getDealerType" allowClear></dealertype>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商户级别">
                <v-select code="DEALER_LEVEL" id="merchantInfoManagementList-dealerLevel" v-model="queryParam.dealerLevel" allowClear placeholder="请选择商户级别"></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="审核状态">
                  <v-select code="AUDIT_STATE" id="merchantInfoManagementList-auditState" v-model="queryParam.auditState" allowClear placeholder="请选择审核状态"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="合作状态">
                  <v-select code="DEALER_COOPERATE_FLAG" id="merchantInfoManagementList-cooperateFlag" v-model="queryParam.cooperateFlag" allowClear placeholder="请选择合作状态"></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="merchantInfoManagementList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="merchantInfoManagementList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                v-if="$hasPermissions('B_merchantInfo_export')"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                id="merchantInfoManagementList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px" id="merchantInfoManagementList-advanced">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <a-button id="merchantInfoManagementList-add" type="primary" v-if="$hasPermissions('B_merchantInfo_add')" @click="handleAdd">新增</a-button>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 经销商 -->
          <template slot="dealerName" slot-scope="text, record">
            <span v-if="$hasPermissions('B_merchantInfo_detail')" :id="'merchantInfoManagementList-dealerName'+record.id" :title="record.dealerName" class="link-bule" @click="handleDetail(record)">{{ record.dealerName }}</span>
            <span v-else :title="record.dealerName">{{ record.dealerName }}</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              :id="'merchantInfoManagementList-audit-btn'+record.id"
              type="link"
              class="button-warning"
              v-if="record.auditState == 'WAIT' && $hasPermissions('B_merchantInfo_audit')"
              @click="handleAudit(record)" >审核</a-button>
            <a-button
              size="small"
              :id="'merchantInfoManagementList-cooperation-btn'+record.id"
              type="link"
              class="button-info"
              v-if="$hasPermissions('B_merchantInfo_cooperation')"
              @click="handleCooperation(record)" >合作设置</a-button>
            <a-button
              size="small"
              :id="'merchantInfoManagementList-level-btn'+record.id"
              type="link"
              class="button-primary"
              v-if="$hasPermissions('B_merchantInfo_level')"
              @click="handleLevel(record)">级别设置</a-button>
            <a-button
              size="small"
              :id="'merchantInfoManagementList-edit-btn'+record.id"
              type="link"
              class="button-info"
              v-if="$hasPermissions('B_merchantInfo_edit')"
              @click="handleEdit(record)">编辑</a-button>
            <br>
            <a-button
              size="small"
              :id="'merchantInfoManagementList-price-btn'+record.id"
              type="link"
              class="button-error"
              v-if="record.auditState != 'WAIT'&&record.dealerLevel && $hasPermissions('B_merchantInfo_priceSpread')"
              @click="handlePriceSpread(record)">差价</a-button>
            <a-button
              size="small"
              :id="'merchantInfoManagementList-power-btn'+record.id"
              type="link"
              class="button-error"
              v-if="record.auditState != 'WAIT'&&record.dealerLevel && $hasPermissions('B_merchantInfo_distribution')"
              @click="handleDistribution(record)">经销权</a-button>
            <span v-if="!(record.auditState == 'WAIT' && $hasPermissions('B_merchantInfo_audit')) && !$hasPermissions('B_merchantInfo_cooperation') && !(record.auditState != 'WAIT' && $hasPermissions('B_merchantInfo_distribution')) && !$hasPermissions('B_merchantInfo_level') && !$hasPermissions('B_merchantInfo_edit')">--</span>
          </template>
        </s-table>
      </a-spin>
      <!-- 产品详情 -->
      <merchant-info-management-detail-modal
        v-drag
        :openModal="openModal"
        :isAudit="isAudit"
        :itemId="itemId"
        @ok="resetForm"
        @close="closeModal" />
      <!-- 合作设置 -->
      <UpdateCooperate ref="updateCooperate" v-drag :openUcModal="openUcModal" @ok="resetForm" @close="openUcModal=false"></UpdateCooperate>
      <!-- 级别设置 -->
      <UpdateDealerLeve ref="updateDealerLevel" v-drag :openUdModal="openUdModal" @ok="resetForm" @close="openUdModal=false"></UpdateDealerLeve>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
// 组件
import { STable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import merchantInfoManagementDetailModal from './detailModal.vue'
import UpdateCooperate from './updateCooperate.vue'
import UpdateDealerLeve from './updateDealerLevel.vue'
import dealerType from '@/views/common/dealerType.js'
// 接口
import { dealerQueryList, dealerExport } from '@/api/dealer'
export default {
  name: 'MerchantInfoManagementList',
  mixins: [commonMixin],
  components: { STable, VSelect, merchantInfoManagementDetailModal, subarea, UpdateCooperate, UpdateDealerLeve, dealerType },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      dealerType: [], // 所选商户类型 列表
      queryParam: { //  查询条件
        nameLike: '', //  商户名称、别名
        dealerType1: undefined, //  商户类型
        dealerType2: undefined, //  商户类型
        dealerLevel: undefined, // 商户级别
        subareaArea: {
          subareaSn: undefined, //  区域
          subareaAreaSn: undefined // 分区
        },
        auditState: undefined, // 审核状态
        cooperateFlag: undefined //  合作状态
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出loading
      dateFormat: 'YYYY-MM-DD', // 日期显示格式
      total: 0, // 总计
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '经销商名称', scopedSlots: { customRender: 'dealerName' }, width: '12%', align: 'left' },
        { title: '商户别名', dataIndex: 'dealerAlias', width: '12%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '商户类型', dataIndex: 'dealerTypeName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户级别', dataIndex: 'dealerLevelDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '联系人', dataIndex: 'contact', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '联系电话', dataIndex: 'dealerTelephone', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '绑定手机号码', dataIndex: 'managerMobile', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核状态', dataIndex: 'auditStateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '合作状态', dataIndex: 'cooperateFlagDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '生效时间', dataIndex: 'cooperateEffectiveTime', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '12%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return dealerQueryList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 计算表格序号
            const no = (data.pageNo - 1) * data.pageSize
            this.total = data.count || 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.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      openModal: false, //  查看详情  弹框
      openUcModal: false, // 合作设置 弹框
      openUdModal: false, // 级别设置 弹框
      itemId: '', //  当前商户sn
      isAudit: false// 是否显示审核按钮
    }
  },
  methods: {
    // 区域  change
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 商户类型 change
    getDealerType (v, o) {
      this.queryParam.dealerType1 = v[0]
      this.queryParam.dealerType2 = v[1]
    },
    //  重置列表
    resetSearchForm () {
      this.dealerType = []
      this.queryParam = {
        nameLike: '', //  商户名称、别名
        dealerType1: undefined, //  商户类型
        dealerType2: undefined, //  商户类型
        dealerLevel: undefined, // 商户级别
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        },
        auditState: undefined, // 审核状态
        cooperateFlag: undefined //  合作状态
      }
      this.$refs.subarea.clearData()
      this.$refs.table.refresh(true)
    },
    // 刷新当前列表
    resetForm () {
      this.$refs.table.refresh()
      this.openModal = false
      this.isAudit = false
      this.openUcModal = false
      this.openUdModal = false
    },
    // 新增
    handleAdd () {
      this.$router.push({ name: `merchantInfoManagementAdd` })
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: `merchantInfoManagementEdit`, params: { id: row.dealerSn } })
    },
    // 合作设置
    handleCooperation (row) {
      this.$refs.updateCooperate.setData(row)
      this.openUcModal = true
    },
    // 价格级别
    handleLevel (row) {
      this.$refs.updateDealerLevel.setData(row)
      this.openUdModal = true
    },
    // 经销权
    handleDistribution (row) {
      this.$router.push({ name: `merchantInfoManagementSet`, params: { sn: row.dealerSn, name: row.dealerName, dealerLevel: row.dealerLevel } })
    },
    // 差价
    handlePriceSpread (row) {
      this.$router.push({ name: `rebateBinding`, params: { sn: row.dealerSn, name: row.dealerName } })
    },
    // 审核
    handleAudit (row) {
      this.itemId = row.dealerSn
      this.openModal = true
      this.isAudit = true
    },
    //  详情
    handleDetail (row) {
      this.itemId = row.dealerSn
      this.openModal = true
      this.isAudit = false
    },
    //  关闭弹框
    closeModal () {
      this.itemId = ''
      this.openModal = false
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      this.exportLoading = true
      _this.spinning = true
      dealerExport(params).then(res => {
        this.exportLoading = false
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          this.download(res)
        }
      })
    },
    // 导出成功
    download (data) {
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const a = moment().format('YYYYMMDDHHmmss')
      const fname = '经销商资料' + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 235
    }
  },
  watch: {
    // 展开关闭  监听表格高度变化
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.$refs.table.refresh()
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .merchantInfoManagementList-wrap{
    .productPic{
      cursor: pointer;
    }
  }
</style>
