<template>
  <div>
    <a-card size="small" :bordered="false" class="addSubsidyList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="addSubsidyList-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="客户名称">
                <dealerSubareaScopeList ref="dealerSubareaScopeList" id="addSubsidyList-dealerName" @change="custChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="区域">
                <subarea id="addSubsidyList-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="地区">
                <AreaList id="addSubsidyList-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="addSubsidyList-subsidyQueryStatus"
                  code="INCREMENT_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="addSubsidyList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="addSubsidyList-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="addSubsidyList-add" 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="record.status=='IN_USE' && record.isSomeTimeFlag"
              :id="'addSubsidyList-edit-btn'+record.id"
            >
              编辑
            </a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              :id="'costCollectionList-end-btn'+record.id"
              v-if="record.status=='IN_USE'&&record.defaultFlag==0&&!record.isSomeTimeFlag"
              @click="handleEndOrDel(record,'end')"
            >
              结束
            </a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              @click="handleEndOrDel(record)"
              v-if="record.status=='IN_USE'&&record.defaultFlag==0&&record.isSomeTimeFlag"
              :id="'addSubsidyList-del-btn'+record.id"
            >
              删除
            </a-button>
            <span v-if="record.status=='END'">--</span>
          </template>
        </s-table>
      </a-spin>
    </a-card>
    <!-- 新增 -->
    <add-subsidy-modal v-drag :openModal="openAddSubsidyModal" :pageType="pageType" @ok="$refs.table.refresh(true)" @close="openAddSubsidyModal = false" />
    <!-- 编辑 -->
    <edit-modal
      v-drag
      :openModal="openEditSubsidyModal"
      ref="editSubsidyModal"
      :pageType="pageType"
      @ok="$refs.table.refresh(true)"
      @close="openEditSubsidyModal = 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 addSubsidyModal from './addSubsidyModal.vue'
import editModal from './editModal.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
// 接口
import { tireSubsidyRuleList, endSubsidyRule, delSubsidyRule } from '@/api/subsidyRule'
export default {
  name: 'AddSubsidyList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, AreaList, dealerSubareaScopeList, addSubsidyModal, editModal },
  props: {
    pageType: { //  弹框显示状态
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      //  查询条件
      queryParam: {
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: '' // 分区
        },
        dealerSn: undefined, // 客户sn
        dealerName: undefined, // 客户名称
        provinceSn: undefined, // 省
        citySn: undefined, // 市
        districtSn: undefined, // 区
        ruleType: undefined, // 页面类型
        subsidyQueryStatus: 'NOT_FINISH'// 状态
      },
      openAddSubsidyModal: false, // 新增弹窗
      openEditSubsidyModal: false, // 编辑弹窗
      // 加载数据方法 必须为 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
              if (data.list[i].ruleStartDate) {
                data.list[i].ruleStartDate = this.pageType === 'SUBSIDY_QUARTER_FEE' ? this.getYearAndQuarter(data.list[i].ruleStartDate).showWords : this.getYear(data.list[i].ruleStartDate)
              }
              if (data.list[i].ruleEndDate) {
                data.list[i].ruleEndDate = this.pageType === 'SUBSIDY_QUARTER_FEE' ? this.getYearAndQuarter(data.list[i].ruleEndDate).showWords : this.getYear(data.list[i].ruleEndDate)
              }
              if (data.list[i].ruleStartDate) {
                data.list[i].isSomeTimeFlag = this.pageType === 'SUBSIDY_QUARTER_FEE' ? this.isSameQuarter(data.list[i].ruleStartDate) : this.isSameYear(data.list[i].ruleStartDate)
              }
            }
          }
          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: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerEntity.dealerName', width: '14%', align: 'center', scopedSlots: { customRender: 'customName' }, ellipsis: true },
        { title: '开始' + (_this.pageType === 'SUBSIDY_QUARTER_FEE' ? '季度' : '年份'), dataIndex: 'ruleStartDate', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '结束' + (_this.pageType === 'SUBSIDY_QUARTER_FEE' ? '季度' : '年份'), dataIndex: 'ruleEndDate', width: '14%', align: 'center', scopedSlots: { customRender: 'endDate' } },
        { title: '增量补贴（' + (_this.pageType === 'SUBSIDY_QUARTER_FEE' ? '季度）' : '年度）'),
          children: [
            { title: '1阶目标（条）', dataIndex: 'ruleTarget1', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
            { title: '1阶补贴（元）', dataIndex: 'ruleValue1', width: '13%', align: 'right', customRender: text => { return (text || text == 0) ? _this.toThousands(text) : '--' } },
            { title: '2阶目标（条）', dataIndex: 'ruleTarget2', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
            { title: '2阶补贴（元）', dataIndex: 'ruleValue2', width: '13%', align: 'right', customRender: text => { return (text || text == 0) ? _this.toThousands(text) : '--' } },
            { title: '3阶目标（条）', dataIndex: 'ruleTarget3', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
            { title: '3阶补贴（元）', dataIndex: 'ruleValue3', width: '13%', align: 'right', customRender: text => { return (text || text == 0) ? _this.toThousands(text) : '--' } }
          ] },
        { title: '状态', dataIndex: 'statusDictValue', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '11%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    // 计算是第几季度
    getYearAndQuarter (dateString) {
      // 解析日期字符串
      const date = new Date(dateString)
      // 获取年份
      const year = date.getFullYear()
      // 获取月份
      const month = date.getMonth() + 1 // getMonth() 返回的是0-11，所以要加1
      // 确定季度
      let quarter
      if (month >= 1 && month <= 3) {
        quarter = 1
      } else if (month >= 4 && month <= 6) {
        quarter = 2
      } else if (month >= 7 && month <= 9) {
        quarter = 3
      } else {
        quarter = 4
      }
      return { showWords: year + '年' + quarter + '季度', quarter }
    },
    // 获取年份
    getYear (dateString) {
      const year = new Date(dateString).getFullYear()
      return year
    },
    // 当前时间与创建时间是否属于同一年
    isSameYear (fixedDate) {
      // 获取当前时间
      const currentDate = new Date()
      const currentYear = currentDate.getFullYear()

      // 比较年份
      return currentYear === fixedDate
    },
    // 当前时间与创建时间是否属于同一季度
    isSameQuarter (inputVal) {
      const currentDate = new Date()
      const quarterNum = this.getYearAndQuarter(currentDate).quarter
      const yearNum = currentDate.getFullYear()
      const fullWord = yearNum + '年' + quarterNum + '季度'
      return fullWord === inputVal
    },
    // 新增
    handleAdd () {
      this.openAddSubsidyModal = 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,
        defaultFlag: row.defaultFlag,
        ruleSn: row.ruleSn,
        ruleTarget1: row.ruleTarget1 || undefined,
        ruleValue1: row.ruleValue1 || undefined,
        ruleTarget2: row.ruleTarget2 || undefined,
        ruleValue2: row.ruleValue2 || undefined,
        ruleTarget3: row.ruleTarget3 || undefined,
        ruleValue3: row.ruleValue3 || undefined
      }
      this.$refs.editSubsidyModal.getFormData(sendData)
      this.openEditSubsidyModal = true
    },
    // 结束  删除
    handleEndOrDel (row, type) {
      const ajaxName = type === 'end' ? endSubsidyRule : delSubsidyRule
      let tipWord = null
      if (this.pageType === 'SUBSIDY_QUARTER_FEE') {
        tipWord = '确定' + (type === 'end' ? '结束' : '删除') + '季度补贴吗？' + (type === 'end' ? '结束' : '删除') + '后以默认季度补贴计算'
      } else {
        tipWord = '确定' + (type === 'end' ? '结束' : '删除') + '年度增量补贴吗？' + (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) {
              if (res.data && res.data === 'FALSE') {
                _this.$info({
                  title: '提示',
                  content: '当前规则不可操作，请刷新后重试',
                  centered: true,
                  onOk () {
                    console.log('知道了')
                  }
                })
              } else {
                _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
    }
  }
}
</script>
