<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="记录类型" prop="moneyType">
        <el-select v-model="queryParams.moneyType" placeholder="请选择金额类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.change_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户编码" prop="loginName">
        <el-input
          v-model="queryParams.loginName"
          placeholder="请输入用户编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卡片编号" prop="cardNumber">
        <el-input
          v-model="queryParams.cardNumber"
          placeholder="请输入卡片编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卡片名称" prop="cardName">
        <el-input
          v-model="queryParams.cardName"
          placeholder="请输入卡片名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pns:integral:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pns:integral:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pns:integral:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['pns:integral:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['pns:integral:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="integralList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="交易时间" align="center" prop="rechargeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rechargeTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属机构" align="center" prop="organizationCode">
        <template slot-scope="scope">
          {{ orgFormatter(scope.row.organizationCode) }}
        </template>
      </el-table-column>
      <el-table-column label="操作账户" align="center" prop="rechargeNickName"/>
      <el-table-column label="用户编码" align="center" prop="loginName"/>
      <el-table-column label="用户名称" align="center" prop="nickName"/>
      <el-table-column label="积分类型" align="center" prop="moneyType">
        <template slot-scope="scope">
          <span v-if="scope.row.moneyType === 1 && scope.row.rechargeIntegral < 0" style="color: red"><dict-tag
            :options="dict.type.change_type" :value="scope.row.moneyType"/></span>
          <dict-tag v-else :options="dict.type.change_type" :value="scope.row.moneyType"/>
        </template>
      </el-table-column>
      <el-table-column label="卡片编号" align="center" prop="cardNumber"/>
      <el-table-column label="卡片名称" align="center" prop="cardName"/>
      <el-table-column label="交易积分" align="center" prop="rechargeIntegral"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pns:integral:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pns:integral:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改积分管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="金额类型" prop="moneyType">
          <el-select v-model="form.moneyType" placeholder="请选择金额类型" @change="changeType">
            <el-option
              v-for="dict in dict.type.change_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              :disabled="dict.value==4 || dict.value==5"
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="充值设备编码" prop="rechargeEquipmentCode">-->
        <!--          <el-input v-model="form.rechargeEquipmentCode" placeholder="请输入充值设备编码" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="充值设备名称" prop="rechargeEquipmentName">-->
        <!--          <el-input v-model="form.rechargeEquipmentName" placeholder="请输入充值设备名称" />-->
        <!--        </el-form-item>-->
        <el-form-item label="手机号" prop="phonenumber">
          <el-input
            v-model="form.phonenumber"
            @change="queryNickName"
            placeholder="请输入内容"
            :trigger-on-focus="false"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户名称" disabled/>
        </el-form-item>
        <el-form-item label="卡片编号" prop="cardNumber">
          <el-input v-model="form.cardNumber" placeholder="请输入卡片编号"/>
        </el-form-item>
        <!--        <el-form-item label="卡片名称" prop="cardName">-->
        <!--          <el-input v-model="form.cardName" placeholder="请输入卡片名称" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="充值时间" prop="rechargeTime">-->
        <!--          <el-date-picker clearable size="small"-->
        <!--            v-model="form.rechargeTime"-->
        <!--            type="date"-->
        <!--            value-format="yyyy-MM-dd"-->
        <!--            placeholder="选择充值时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <el-form-item label="充值积分" prop="rechargeIntegral">
          <el-input v-model="form.rechargeIntegral" placeholder="请输入充值积分"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelTemplate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listIntegral,
  getIntegral,
  delIntegral,
  addIntegral,
  updateIntegral,
  exportIntegral,
  doReturnPoints,
  importTemplate
} from '@/api/integral/integral'
import { queryUserInfoByPhonenumber } from '@/api/system/user'
import { getToken } from '@/utils/auth'
import user from '@/store/modules/user'

export default {
  name: 'Integral',
  dicts: ['change_type', 'yes_or_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      isDeletes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 积分管理表格数据
      integralList: [],
      userList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/pns/integral/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        moneyType: null,
        rechargeEquipmentCode: null,
        rechargeEquipmentName: null,
        loginName: null,
        nickName: null,
        cardNumber: null,
        cardName: null,
        organizationCode: null
      },
      // 表单参数
      form: {
        nickName: ''
      },
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        moneyType: [
          { required: true, message: '金额类型不能为空', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '用户编码不能为空', trigger: 'blur' }
        ],
        rechargeIntegral: [
          { required: true, message: '充值积分不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询积分管理列表 */
    getList() {
      this.queryParams.organizationCode = user.state.organ
      this.loading = true
      listIntegral(this.queryParams).then(response => {
        this.integralList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        moneyType: null,
        rechargeEquipmentCode: null,
        rechargeEquipmentName: null,
        loginName: null,
        nickName: null,
        cardNumber: null,
        cardName: null,
        rechargeTime: null,
        rechargeIntegral: null,
        isDelete: null,
        organizationCode: null,
        rechargeId: null,
        updateTime: null,
        phonenumber: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.isDeletes = selection.map(item => item.isDelete)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.moneyType = '3'
      this.open = true
      this.title = '添加积分管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getIntegral(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改积分管理'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateIntegral(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addIntegral(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除积分管理编号为"' + ids + '"的数据项？').then(function() {
        return delIntegral(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal.confirm('是否确认导出所有积分管理数据项？').then(() => {
        this.exportLoading = true
        return exportIntegral(queryParams)
      }).then(response => {
        this.$download.name(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },

    queryNickName() {
      if (this.form.phonenumber) {
        queryUserInfoByPhonenumber({ phonenumber: this.form.phonenumber }).then((response) => {
          if (response.code === 200) {
            this.userList = response.data
            if (this.userList != undefined) {
              this.form.loginName = this.userList.userName
              this.form.nickName = this.userList.nickName
            } else {
              this.form.nickName = ''
              this.form.loginName = ''
            }
          }
        }).catch((e) => {
          this.form.nickName = ''
          this.form.loginName = ''
        })
      }
    },

    handleImport() {
      this.upload.title = '集体充值'
      this.upload.open = true
    },

    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.cancel()
      this.getList()
    },

    importTemplate() {
      importTemplate().then(response => {
        this.$download.name(response.msg)
      })
    },

    submitFileForm() {
      this.$refs.upload.submit()
    },

    orgFormatter(val) {
      let name = ''
      user.state.organDicts.forEach(item => {
        if (item.deptCode == val) {
          name = item.deptName
        }
      })
      return name
    },

    changeType(v) {
      if (v == 2) {
        this.handleImport()
      }
    },

    cancelTemplate() {
      this.upload.open = false
      this.form.moneyType = '3'
    }

    // handleSelect(item) {
    //   this.form.loginName = item.userName;
    //   this.form.nickName = item.nickName;
    // }

  }
}
</script>
