<template>
  <div>
    <a-card size="small" :bordered="false" class="costCollectionList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="costCollectionList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam">
          <a-row :gutter="15">
            <a-col :md="5" :sm="24">
              <a-form-model-item label="客户名称">
                <custList dataAuthFlag="0" ref="dealerSubareaScopeList" id="costCollectionList-dealerName" placeholder="请输入客户名称" @change="custChange"></custList>
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="区域">
                <subarea id="costCollectionList-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="地区">
                <AreaList id="costCollectionList-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="状态">
                <v-select
                  v-model="queryParam.subsidyQueryStatus"
                  id="costCollectionList-subsidyQueryStatus"
                  code="SUBSIDY_QUERY_STATUS"
                  placeholder="请选择状态"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-button
                type="primary"
                @click="$refs.table.refresh(true)"
                :disabled="disabled"
                id="costCollectionList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="costCollectionList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <a-button id="costCollectionList-add-btn" type="primary" @click="handleAdd">新增</a-button>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :style="{ height: tableHeight+70+'px' }"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight}"
          :defaultLoadData="false"
          bordered>
          <!-- 客户名称 -->
          <template slot="customName" slot-scope="text, record">
            {{ record.dealerEntity&&record.dealerEntity.dealerName?record.dealerEntity.dealerName:record.defaultFlag==1?'默认':'--' }}
          </template>
          <!-- 结束时间 -->
          <template slot="endDate" slot-scope="text, record">
            {{ record.status==='END'? record.ruleEndDate:'--' }}
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="handleEdit(record)"
              v-if="$hasPermissions('B_tireSubsidySetting_edit')&&record.status=='WAIT'"
              :id="'costCollectionList-edit-btn'+record.id"
            >
              编辑
            </a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              :id="'costCollectionList-end-btn'+record.id"
              v-if="$hasPermissions('B_tireSubsidySetting_end')&&record.status=='IN_USE'&&record.defaultFlag==0"
              @click="handleEndOrDel(record,'end')"
            >
              结束
            </a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              @click="handleEndOrDel(record,'del')"
              v-if="$hasPermissions('B_tireSubsidySetting_del')&&record.status=='WAIT'"
              :id="'costCollectionList-del-btn'+record.id"
            >
              删除
            </a-button>
            <span v-if="record.status=='IN_USE'&&record.defaultFlag==1">--</span>
          </template>
        </s-table>
      </a-spin>
    </a-card>
    <!-- 新增 -->
    <cost-add-modal v-drag :openModal="openCostAddModal" :pageType="pageType" @ok="$refs.table.refresh(true)" @close="openCostAddModal = false" />
    <!-- 编辑 -->
    <edit-modal
      v-drag
      :openModal="openCostEditModal"
      ref="costEditModal"
      :pageType="pageType"
      @ok="$refs.table.refresh(true)"
      @close="openCostEditModal = false" ></edit-modal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import AreaList from '@/views/common/areaList.js'
import costAddModal from './costAddModal.vue'
import editModal from './editModal.vue'
import custList from '@/views/common/custList.vue'
// 接口
import { tireSubsidyRuleList, delSubsidyRule, endSubsidyRule } from '@/api/subsidyRule'
export default {
  name: 'CostCollectionList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, AreaList, custList, costAddModal, editModal },
  props: {
    pageType: { //  弹框显示状态
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      openCostAddModal: false, // 新增弹窗
      openCostEditModal: false, // 编辑弹窗
      exportLoading: false, // 导出按钮加载状态
      showExport: false, // 导出弹窗
      timeInfo: [], // 日期
      //  查询条件
      queryParam: {
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: '' // 分区
        },
        dealerSn: undefined, // 客户sn
        dealerName: undefined, // 客户名称
        provinceSn: undefined, // 省
        citySn: undefined, // 市
        districtSn: undefined, // 区
        ruleType: undefined, // 页面类型
        subsidyQueryStatus: 'NOT_FINISH'// 状态默认值
      },
      totalData: null, // 合计
      rules: {
        'queryDate': [{ required: true, message: '请选择查询季度', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 获取列表数据  有分页
        this.queryParam.ruleType = this.pageType
        const params = Object.assign(parameter, this.queryParam)
        return tireSubsidyRuleList(params).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
            }
          }
          this.disabled = false
          this.spinning = false
          return data
        })
      }
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerEntity.dealerName', width: '20%', align: 'left', scopedSlots: { customRender: 'customName' }, ellipsis: true },
        { title: '开始时间', dataIndex: 'ruleStartDate', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '结束时间', dataIndex: 'ruleEndDate', width: '12%', align: 'center', scopedSlots: { customRender: 'endDate' } },
        { title: '状态', dataIndex: 'statusDictValue', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.pageType === 'SERVICE_FEE') {
        arr.splice(7, 0, { title: '服务费比例（%）', dataIndex: 'ruleValue1', width: '12%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text * 100) + '%' : '--') } })
      } else {
        arr.splice(7, 0, { title: '运费补贴（元）', dataIndex: 'ruleValue1', width: '12%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 新增
    handleAdd () {
      this.openCostAddModal = true
    },
    // 客户名称 change
    custChange (val) {
      this.queryParam.dealerName = val.name
      this.queryParam.dealerSn = val.key
    },
    // 地区
    areaChange (val) {
      this.queryParam.provinceSn = val[0] ? val[0] : undefined
      this.queryParam.citySn = val[1] ? val[1] : undefined
      this.queryParam.districtSn = val[2] ? val[2] : undefined
    },
    // 区域分区  change
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : ''
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : ''
    },
    //  重置
    resetSearchForm () {
      this.queryParam.provinceSn = undefined
      this.queryParam.citySn = undefined
      this.queryParam.districtSn = undefined
      this.queryParam.dealerName = undefined
      this.queryParam.dealerSn = undefined
      this.queryParam.ruleType = undefined
      this.queryParam.subareaArea.subareaSn = ''
      this.queryParam.subareaArea.subareaAreaSn = ''
      this.queryParam.subsidyQueryStatus = 'NOT_FINISH'
      this.$refs.subarea.clearData()
      this.$refs.dealerSubareaScopeList.resetForm()
      this.$refs.areaList.clearData()
      this.$refs.table.refresh(true)
    },
    // 编辑
    handleEdit (row) {
      const sendData = {
        dealerName: row.dealerEntity && row.dealerEntity.dealerName ? row.dealerEntity.dealerName : undefined,
        ruleStartDate: row.ruleStartDate,
        ruleValue1: this.pageType === 'SERVICE_FEE' ? (row.ruleValue1 * 100) : row.ruleValue1,
        defaultFlag: row.defaultFlag,
        ruleSn: row.ruleSn
      }
      this.$refs.costEditModal.getFormData(sendData)
      this.openCostEditModal = true
    },
    // 结束  删除
    handleEndOrDel (row, type) {
      const ajaxName = type === 'end' ? endSubsidyRule : delSubsidyRule
      let tipWord = null
      if (this.pageType === 'SERVICE_FEE') {
        tipWord = type === 'end' ? '确定结束服务费比例吗？结束后以默认服务费比例计算' : '确定删除服务费比例吗？'
      } else {
        tipWord = type === 'end' ? '确定结束运费补贴吗？结束后以默认运费补贴计算' : '确定删除运费补贴吗？'
      }
      const _this = this
      _this.$confirm({
        title: '提示',
        content: tipWord,
        centered: true,
        onOk () {
          ajaxName({ ruleSn: row.ruleSn, ruleType: _this.pageType }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh(true)
            }
          })
        }
      })
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        this.setTableH()
      })
      this.resetSearchForm()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 300
    }
  },
  mounted () {
    this.pageInit()
  }
}
</script>
