<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="5" :sm="24">
              <a-form-item label="商户类型">
                <v-select code="DEALER_TYPE" id="merchantInfoManagementList-dealerType" v-model="queryParam.dealerType" allowClear placeholder="请选择商户类型"></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="7" :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="7" :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">
                {{ 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')" style="color: #ed1c24;cursor: pointer;" @click="handleDetail(record)">{{ record.dealerName }}</span>
            <span v-else>{{ record.dealerName }}</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button size="small" type="link" class="button-warning" v-if="record.auditState == 'WAIT' && $hasPermissions('B_merchantInfo_audit')" @click="handleAudit(record)" >审核</a-button>
            <a-button size="small" type="link" class="button-info" v-if="$hasPermissions('B_merchantInfo_cooperation')" @click="handleCooperation(record)" >合作设置</a-button>
            <a-button size="small" type="link" class="button-error" v-if="record.auditState != 'WAIT' && $hasPermissions('B_merchantInfo_distribution')" @click="handleDistribution(record)">经销权</a-button>
            <a-button size="small" type="link" class="button-primary" v-if="$hasPermissions('B_merchantInfo_level')" @click="handleLevel(record)">级别设置</a-button>
            <a-button size="small" type="link" class="button-info" v-if="$hasPermissions('B_merchantInfo_edit')" @click="handleEdit(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 { dealerQueryList, dealerExport } from '@/api/dealer'
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'
export default {
  name: 'MerchantInfoManagementList',
  mixins: [commonMixin],
  components: { STable, VSelect, merchantInfoManagementDetailModal, subarea, UpdateCooperate, UpdateDealerLeve },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        nameLike: '', //  商户名称、别名
        dealerType: 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: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户名称', scopedSlots: { customRender: 'dealerName' }, width: '10%', align: 'left', ellipsis: true },
        { title: '商户别名', dataIndex: 'dealerAlias', width: '10%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '商户类型', dataIndex: 'dealerTypeDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户级别', dataIndex: 'dealerLevelDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '联系人', dataIndex: 'contact', width: '7%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '联系电话', dataIndex: 'dealerTelephone', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '绑定手机号码', dataIndex: 'managerMobile', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核状态', dataIndex: 'auditStateDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '合作状态', dataIndex: 'cooperateFlagDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '生效时间', dataIndex: 'cooperateEffectiveTime', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '12%', align: 'center' }
      ],
      loading: false,
      // 加载数据方法 必须为 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
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      openModal: false, //  查看详情  弹框
      openUcModal: false, // 合作设置 弹框
      openUdModal: false, // 级别设置 弹框
      itemId: '', //  当前商户sn
      isAudit: false
    }
  },
  methods: {
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置列表
    resetSearchForm () {
      this.queryParam = {
        nameLike: '', //  商户名称、别名
        dealerType: 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 } })
    },
    // 审核
    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>
