<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input
        v-model="listQuery.keyword"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="请输入关键字"
        clearable
      /> -->
      <el-select v-model="listQuery.settlementStatus" clearable class="filter-item" style="width:200px;margin-right:10px" placeholder="请选择结算状态">
        <el-option v-for="item of settlementStatusOptions" :key="item.value" v-bind="item" />
      </el-select>
      <el-select v-model="listQuery.dealStatus" clearable class="filter-item" style="width:200px;margin-right:10px" placeholder="请选择已处理状态">
        <el-option v-for="item of dealStatusOptions" :key="item.value" v-bind="item" />
      </el-select>
      <el-date-picker
        v-model="listQuery.dateArr"
        type="datetimerange"
        class="filter-item"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="timestamp"
        align="right"
        clearable
      />
      <el-button
        type="primary"
        style="margin-left:10px"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        :loading="exportLoading"
        icon="el-icon-download"
        type="primary"
        style="margin-left:10px"
        @click="handleExport"
      >导出</el-button>
    </div>
    <el-table :data="list" border style="width: 100%">
      <el-table-column label="用户名" prop="residentInformation.name" />
      <el-table-column label="店名" prop="residentInformation.speciallyBusinessInfo.name" />
      <el-table-column label="结算积分数" prop="num" />

      <el-table-column label="提交时间">
        <template slot-scope="scope">
          <span>{{
            scope.row.createDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结算状态">
        <template slot-scope="scope">
          <span>{{
            scope.row.settlementStatus | optionsFilter(settlementStatusOptions)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已处理状态">
        <template slot-scope="scope">
          <span>{{
            scope.row.dealStatus | optionsFilter(dealStatusOptions)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理备注" prop="remark" />
      <el-table-column label="发票状态">
        <template slot-scope="scope">
          <span>{{
            scope.row.invoiceStatus | optionsFilter(invoiceStatusOptions)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300px" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.invoiceStatus == '1' && scope.row.dealStatus != '0'"
            type="primary"
            size="mini"
            style="font-size:12px;padding:10px 20px"
            @click="handleEdit(scope.row)"
          >处理</el-button>
          <el-button
            v-if="scope.row.invoiceStatus != '1'"
            type="success"
            size="mini"
            style="font-size:12px;padding:10px 20px;border-radius:21px"
            @click="handleDelivery(scope.row)"
          >收到发票</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="listQuery.lastPageIndex"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog
      class="dialog"
      title="积分结算"
      append-to-body
      center
      width="364px"
      :visible.sync="diaVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :close="closeDia"
    >
      <div class="preview-container">
        <el-form
          ref="form"
          label-position="left"
          label-width="100px"
          :rules="rules"
          :model="form"
        >
          <el-form-item label="结算状态" prop="dealStatus">
            <el-radio v-model="form.dealStatus" :label="0">兑换</el-radio>
            <el-radio v-model="form.dealStatus" :label="1">不兑换</el-radio>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="closeDia">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { settlementList, settlementDeal } from '@/api/fingertipIntegral'
export default {
  components: { Pagination },
  filters: {
    optionsFilter(value, options = []) {
      const findItem = options.find((option) => option.value === value)
      if (findItem) {
        return findItem.label
      }
      return ''
    }
  },
  data() {
    return {
      total: 0,
      listQuery: {
        lastPageIndex: 1,
        size: 10,
        category: undefined,
        dealStatus: undefined,
        endDate: undefined,
        id: undefined,
        innerCategory: undefined,
        keyword: undefined,
        settlementStatus: undefined,
        startDate: undefined,
        status: undefined,
        dateArr: []
      },
      list: undefined,

      exportLoading: false,

      settlementStatusOptions: [
        {
          label: '待处理',
          value: '0'
        },
        {
          label: '已处理',
          value: '1'
        }
      ],
      dealStatusOptions: [
        {
          label: '兑换',
          value: '0'
        },
        {
          label: '不兑换',
          value: '1'
        }
      ],
      invoiceStatusOptions: [
        {
          label: '未收',
          value: '0'
        },
        {
          label: '已收',
          value: '1'
        }
      ],

      diaVisible: false,
      form: {
        dealStatus: 0,
        remark: undefined
      },
      rules: {
        dealStatus: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  watch: {
    'listQuery.lastPageIndex': {
      handler(val) {
        this.getList()
      },
      deep: true // true 深度监听
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      const listQuery = JSON.parse(JSON.stringify(this.listQuery))
      const { dateArr } = listQuery
      if (dateArr) {
        listQuery.startDate = dateArr[0]
        listQuery.endDate = dateArr[1]
      }
      settlementList(listQuery).then(res => {
        this.list = res.d.records
        this.total = res.d.total
        // this.pageSize = res.d.pageSize
      })
    },
    handleEdit(item) {
      this.form = {
        id: item.id,
        dealStatus: 0,
        remark: undefined,
        invoiceStatus: item.invoiceStatus
      }
      this.$nextTick(() => {
        const formEl = this.$refs['form']
        if (formEl) formEl.clearValidate()
        this.diaVisible = true
      })
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          settlementDeal(this.form).then(() => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.closeDia()
            this.getList()
          })
        }
      })
    },
    closeDia() {
      this.diaVisible = false
    },
    handleExport() {
      const that = this
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['用户名', '店名', '结算积分数', '提交时间', '结算状态', '已处理状态', '处理备注', '发票状态']
        const filterVal = ['residentInformation.name', 'residentInformation.speciallyBusinessInfo.name', 'num', 'createDate', 'settlementStatus', 'dealStatus', 'remark', 'invoiceStatus']
        this.exportLoading = true
        const listQuery = JSON.parse(JSON.stringify(this.listQuery))
        const { dateArr } = listQuery
        if (dateArr) {
          listQuery.startDate = dateArr[0]
          listQuery.endDate = dateArr[1]
        }
        listQuery.size = 999999
        settlementList(listQuery).then(res => {
          setTimeout(() => {
            this.exportLoading = false
          }, 3000)

          const data = that.formatJson(filterVal, res.d.records)
          excel.export_json_to_excel({
            header: tHeader,
            data: data,
            filename: '结算记录'
          })
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          let value
          if (j === 'invoiceStatus' || j === 'dealStatus' || j === 'settlementStatus') {
            value = this.$options.filters['optionsFilter'](v[j], this[`${j}Options`])
          } else if (j === 'createDate') {
            value = this.$options.filters['parseTime'](v[j])
          } else if (j === 'residentInformation.name') {
            value = v['residentInformation']['name']
          } else if (j === 'residentInformation.speciallyBusinessInfo.name') {
            value = v['residentInformation']['speciallyBusinessInfo']['name']
          } else {
            value = v[j]
          }
          // if (!value && value !== 0) value = "N/A";
          return value
        })
      )
    },
    handleDelivery(item) {
      this.$confirm('是否收到发票?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        settlementDeal({
          id: item.id,
          dealStatus: item.dealStatus,
          invoiceStatus: 1
        }).then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getList()
        })
      })
    },
    handleSearch() {
      const { listQuery } = this
      this.listQuery.lastPageIndex = 1
      Object.keys(listQuery).forEach(key => {
        if (listQuery[key] === '') listQuery[key] = undefined
      })
      this.getList()
    }
  }
}
</script>

<style></style>
