<template>
  <el-main class="bg_white">
    <div class="m-t-10 table_90 border-r-10 text-black f-12">
      <el-row>
        <el-col :span="8">
          <el-button type="primary" size="mini" @click="getList(1)">搜索</el-button>
          <el-button type="primary" size="mini" @click="reset()">重置</el-button>
        </el-col>
        <el-col :span="16" class="text-r">
          <el-button type="primary" size="mini" @click="batchExport">导出</el-button>
        </el-col>
      </el-row>
    </div>
    <!--表格-->
    <div class="m-t-10 table_90 p-b-20 border-r-10 text-black f-12">
      <vxe-table
        border
        resizable
        show-overflow
        ref="xTable"
        height="700"
        :scroll-x="{ enabled: false }"
        :scroll-y="{ enabled: false }"
        :header-cell-style="header_style"
        :data="tableData"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
      >
        <vxe-colgroup title="SKU" header-align="center">
          <vxe-column field="model">
            <template #header>
              <el-input size="mini" v-model="form_requst.model" @keydown.enter.native="getList"></el-input>
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="产品名" header-align="center">
          <vxe-column field="name" header-align="center">
            <template #header>
              <el-input size="mini" v-model="form_requst.name" @keydown.enter.native="getList"></el-input>
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="变更人" header-align="center">
          <vxe-column field="user" header-align="center">
            <template #header>
              <el-input size="mini" v-model="form_requst.user" @keydown.enter.native="getList"></el-input>
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="变更时间" header-align="center">
          <vxe-column field="edit_time" header-align="center" align="right">
            <template #header>
              <el-date-picker
                v-model="form_requst.edit_time"
                type="date"
                placeholder="请选择发货日期"
                :disabledDate="pickerOptions"
                value-format="YYYY-MM-DD"
                size="mini"
                style="width: 100%"
                @change="getList"
              ></el-date-picker>
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="变更对象" header-align="center">
          <vxe-column field="type" header-align="center">
            <template #header>
              <el-select v-model="form_requst.type" placeholder clearable filterable size="mini" @clear="clear('type')">
                <el-option v-for="(item, index) in typeList" :key="index" :label="item.name" :value="item.value" @click="getList"></el-option>
              </el-select>
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-column field="cost_old" title="变更前" header-align="center" align="right"></vxe-column>
        <vxe-column field="cost_now" title="变更后" header-align="center" align="right"></vxe-column>
        <vxe-column field="cost_change" title="前后差异" header-align="center" align="right">
          <template #default="{ row }">
            <span v-if="row.cost_change > 0" class="text-red">{{ row.cost_change }}</span>
            <span v-else class="text-green">{{ row.cost_change }}</span>
          </template>
        </vxe-column>
        <vxe-column field="range" title="变更幅度" header-align="center" align="right">
          <template #default="{ row }">
            <span v-if="row.range > 0" class="text-red">{{ row.range }} %</span>
            <span v-else class="text-green">{{ row.range }} %</span>
          </template>
        </vxe-column>
        <vxe-column field="content" title="变更内容" header-align="center" v-if="userInfo.isall == 1"></vxe-column>
      </vxe-table>
      <el-pagination
        :current-page="form_requst.page"
        :page-sizes="[20, 40, 60]"
        :page-size="form_requst.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
        class="m-t-10 m-b-20 table_90"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </el-main>
</template>

<script>
import { mapState } from 'vuex'
import { mapActions } from 'vuex'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'

export default {
  data() {
    return {
      loading: null,
      header_style: {
        'background-color': '#F5F7FA',
        color: '#606266',
        fontSize: '10px',
        fontWeight: '600',
        textAlign: 'center'
      },
      form_requst: {
        page: 1,
        size: 20,
        model: '',
        name: '',
        user: '',
        edit_time: '',
        type: '',
        is_new: 1
      },
      tableData: [],
      typeList: [],
      count: '',
      pickerOptions(time) {
        return time.getTime() > Date.now() //选当前时间以后的时间
      }
    }
  },
  //清除缓存
  beforeRouteUpdate(to, from, next) {
    this.form_requst.is_new = to.query.is_new
    if (to.fullPath != from.fullPath) {
      this.getList(1)
      next()
    }
  },
  computed: {
    ...mapState({
      // 取出页面标签
      userInfo: state => state.user.userInfo
    })
  },

  activated() {
    this.form_requst.is_new = this.$route.query.is_new
    this.getList()
  },
  methods: {
    ...mapActions({
      // 关闭标签及页面
      handleCloseTag: 'topNavTag/removeNavTag'
    }),
    //成本列表
    getList(type) {
      if (type == 1) {
        this.form_requst.page = 1
      }
      this.listLoading = true
      this.$http
        .get('cost/getlog', this.form_requst)
        .then(res => {
          if (res.errno == 200) {
            this.tableData = res.data.list
            this.count = res.data.count
            this.typeList = res.data.type
          } else {
            ElMessage({
              type: 'error',
              message: res.errmsg
            })
          }
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    //分页
    handleSizeChange(new_size) {
      this.form_requst.size = new_size
      this.getList()
    },
    handleCurrentChange(new_page) {
      this.form_requst.page = new_page
      this.getList()
    },

    //批量导出
    batchExport() {
      console.log(this.userInfo.isall)
      this.loading = ElLoading.service({
        lock: true,
        text: '此操作需要一段时间请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      /* this.batchExportShow = true*/
      const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
      axios
        .get(
          process.env.VUE_APP_API_BASEURL +
            apiVersion +
            '/' +
            '/cost/exportlog?isall=' +
            this.userInfo.isall +
            '&is_new=' +
            this.$route.query.is_new,
          {
            responseType: 'blob',
            headers: {
              /*'X-Token': getToken(),*/
              'Content-Type': 'application/json;charset=utf-8'
            }
          }
        )
        .then(res => {
          if (!res) {
            this.$message.error('下载模板文件失败')
            return false
          }
          const stream = res.data // 后端用stream返回Excel文件
          const blob = new Blob([stream])
          // 前端获取业务码，成功执行正常业务
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          const timeStamp = new Date().toString()
          const nameStr = decodeURI(escape(JSON.parse(res.headers['content-disposition'].split(';')[1].split('=')[1])))
          downloadElement.download = nameStr // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
          this.loading.close()
        })
    },
    //重置
    reset() {
      this.form_requst = {
        page: 1,
        size: 20,
        model: '',
        name: '',
        user: '',
        edit_time: '',
        type: ''
      }
    },
    //clear select
    clear(item) {
      if (item == 'type') {
        this.form_requst.type = ''
      }
      this.getList()
    },
    cancel() {
      // let routeData = this.$router.push({
      //   path: '/mold/index',
      // });
      // window.opener = null;
      // // //新页面中,才能使用如下关闭
      // window.close()

      this.handleCloseTag()
    }
  }
}
</script>
<style scoped>
/*新样式*/
.vxe-table--render-default {
  font-size: 12px;
}
::v-deep(.vxe-header--column, .vxe-table--render-default) {
  padding: 5px 0 !important;
}
::v-deep(.vxe-body--column) {
  height: 32px !important;
}
::v-deep(.vxe-table--render-default .vxe-cell) {
  padding-left: 2px;
  padding-right: 2px;
}
::v-deep(.el-input__inner) {
  width: 100% !important;
}
</style>
