<template>
  <div>
    <a-card size="small" :bordered="false" class="productChangeRecordList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="productChangeRecordList-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="变更时间">
                <rangeDate ref="rangeDate" id="productChangeRecordList-time" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品编码">
                <a-input id="productChangeRecordList-code" v-model.trim="queryParam.code" allowClear placeholder="请输入产品编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品名称">
                <a-input id="productChangeRecordList-name" v-model.trim="queryParam.name" allowClear placeholder="请输入产品名称"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="变更状态">
                  <v-select code="ENABLE_FLAG" id="productChangeRecordList-productStatus" v-model="queryParam.enabledFlag" allowClear placeholder="请选择变更状态"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="品牌">
                  <ProductBrand id="productChangeRecordList-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品分类">
                  <ProductType id="productChangeRecordList-productType" placeholder="请选择产品分类" @change="changeProductType" v-model="productType"></ProductType>
                </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="productChangeRecordList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="productChangeRecordList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                v-if="$hasPermissions('B_priceChangeRecord_export')"
                class="button-warning"
                @click="handleExport"
                :loading="exportLoading"
                id="productChangeRecordList-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" class="productChangeRecordList-wrap" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+95+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 产品分类 -->
          <template slot="productType" slot-scope="text, record">
            <span v-if="record.productEntity.productTypeName2 || record.productEntity.productTypeName3">{{ record.productEntity.productTypeName2 }} {{ record.productEntity.productTypeName3 ? '>' : '' }} {{ record.productEntity.productTypeName3 }}</span>
            <span v-else>--</span>
          </template>
          <!-- 变更状态 -->
          <span slot="productStatus" slot-scope="text, record">
            <a-switch checkedChildren="启用" :id="'productChangeRecordList-enabledFlag'+record.id" unCheckedChildren="禁用" v-model="record.enabledFlag" @change="changeFlagHandle(text, record)"/>
          </span>
          <!-- 省级价变更后 -->
          <template slot="afterProvincePrice" slot-scope="text, record">
            <span v-if="record.afterProvincePrice || record.afterProvincePrice==0" :class="record.beforeProvincePrice != record.afterProvincePrice ? 'red' : ''">{{ toThousands(record.afterProvincePrice) }}</span>
            <span v-else>--</span>
          </template>
          <!-- 市级价变更后 -->
          <template slot="afterCityPrice" slot-scope="text, record">
            <span v-if="record.afterCityPrice || record.afterCityPrice==0" :class="record.beforeCityPrice != record.afterCityPrice ? 'red' : ''">{{ toThousands(record.afterCityPrice) }}</span>
            <span v-else>--</span>
          </template>
          <!-- 特约价变更后 -->
          <template slot="afterSpecialPrice" slot-scope="text, record">
            <span v-if="record.afterSpecialPrice || record.afterSpecialPrice==0" :class="record.beforeSpecialPrice != record.afterSpecialPrice ? 'red' : ''">{{ toThousands(record.afterSpecialPrice) }}</span>
            <span v-else>--</span>
          </template>
          <!-- 终端价变更后 -->
          <template slot="afterTerminalPrice" slot-scope="text, record">
            <span v-if="record.afterTerminalPrice || record.afterTerminalPrice==0" :class="record.beforeTerminalPrice != record.afterTerminalPrice ? 'red' : ''">{{ toThousands(record.afterTerminalPrice) }}</span>
            <span v-else>--</span>
          </template>
          <!-- 车主价变更后 -->
          <template slot="afterCarOwnersPrice" slot-scope="text, record">
            <span v-if="record.afterCarOwnersPrice || record.afterCarOwnersPrice==0" :class="record.beforeCarOwnersPrice != record.afterCarOwnersPrice ? 'red' : ''">{{ toThousands(record.afterCarOwnersPrice) }}</span>
            <span v-else>--</span>
          </template>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
// 组件
import { STable, VSelect } from '@/components'
import getDate from '@/libs/getDate.js'
import rangeDate from '@/views/common/rangeDate.vue'
import ProductBrand from '@/views/common/productBrand.js'
import ProductType from '@/views/common/productType.js'
// 接口
import { productPriceChangeList, productPriceChangeExport, priceChangeEnabled } from '@/api/product'
export default {
  name: 'PriceChangeRecordList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, ProductBrand, ProductType },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出loading
      //  查询条件
      queryParam: {
        beginDate: getDate.getThreeMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        name: '', //  产品名称
        code: '', //  产品编码
        productBrandSn: undefined, //  品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        enabledFlag: undefined// 变更状态
      },
      productType: [], // 产品分类
      //  变更时间
      time: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ],
      total: 0, // 数据总条数
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 获取表格数据 有分页
        return productPriceChangeList(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].enabledFlag = data.list[i].enabledFlag + '' === '1'
            }
            this.total = data.count || 0
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: 50, align: 'center' },
        { title: '变更时间', dataIndex: 'updateDate', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', align: 'left', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'productEntity.code', width: 140, align: 'left', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'productEntity.productBrandName', width: 120, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, width: 120, align: 'left' },
        { title: '单位', dataIndex: 'productEntity.unit', width: 50, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '变更原因', dataIndex: 'changeReason', width: 70, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '变更状态', scopedSlots: { customRender: 'productStatus' }, width: 70, align: 'center' }
      ]
      arr.push({
        title: '省级价',
        dataIndex: 'sdtermindfaldsdPrice',
        align: 'center',
        children: [
          { title: '变更前', dataIndex: 'beforeProvincePrice', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
          { title: '变更后', scopedSlots: { customRender: 'afterProvincePrice' }, width: 70, align: 'right' }
        ]
      })
      arr.push({
        title: '市级价',
        dataIndex: 'sdterminaldsdPrice',
        align: 'center',
        children: [
          { title: '变更前', dataIndex: 'beforeCityPrice', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
          { title: '变更后', scopedSlots: { customRender: 'afterCityPrice' }, width: 70, align: 'right' }
        ]
      })
      arr.push({
        title: '特约价',
        dataIndex: 'gterminaldsdPrice',
        align: 'center',
        children: [
          { title: '变更前', dataIndex: 'beforeSpecialPrice', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
          { title: '变更后', scopedSlots: { customRender: 'afterSpecialPrice' }, width: 70, align: 'right' }
        ]
      })
      arr.push({
        title: '终端价',
        dataIndex: 'hterminaldsdPrice',
        align: 'center',
        children: [
          { title: '变更前', dataIndex: 'beforeTerminalPrice', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
          { title: '变更后', scopedSlots: { customRender: 'afterTerminalPrice' }, width: 70, align: 'right' }
        ]
      })
      arr.push({
        title: '车主价',
        dataIndex: 'sterminaldsdPrice',
        align: 'center',
        children: [
          { title: '变更前', dataIndex: 'beforeCarOwnersPrice', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
          { title: '变更后', scopedSlots: { customRender: 'afterCarOwnersPrice' }, width: 70, align: 'right' }
        ]
      })
      return arr
    }
  },
  methods: {
    //  变更时间 change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.code = ''
      this.queryParam.name = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.enabledFlag = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    // 审核
    handleAudit (row) {
      this.itemId = row.id
      this.openAuditModal = true
    },
    //  编辑
    handleEdit (row) {
      this.itemId = row.id
      this.openModal = true
    },
    //  关闭弹框
    closeModal () {
      this.itemId = ''
      this.openModal = false
    },
    //  关闭审核弹框
    closeAuditModal () {
      this.itemId = ''
      this.openAuditModal = false
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      this.exportLoading = true
      _this.spinning = true
      productPriceChangeExport(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 - 225
    },
    // 修改状态
    changeFlagHandle (text, record) {
      const _data = {
        id: record.id,
        enabledFlag: record.enabledFlag ? '1' : '0'
      }
      this.spinning = true
      priceChangeEnabled(_data).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.$refs.table.refresh()
          this.spinning = false
        }
      })
    }
  },
  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.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .productChangeRecordList-wrap{
    .red{
      color: #ed1c24;
    }
  }
</style>
