<template>
    <div>
        <!-- 积分管理 -->

      <Card>
        <div class="info-item">
          <div class="platform-handle-btn">
            <Button type="primary" style="margin-right:10px" @click="handleShowTrans">转 账</Button>
            <Button type="primary" style="margin-right:10px"  @click="handleShowPrice">设置价格</Button>
            <Button type="default" style="margin-right:10px" @click="handleAddIntegral">增 发</Button>
            <Button type="default" @click="handleRecover">回 收</Button>
          </div>
        <div class="platform-modular">
          <p class="base-info">
            <span class="left-label">{{platformIntegralData.name}}</span>
            <span class="left-info">{{platformIntegralData.label}}</span>
          </p>
          <p class="base-info">
            <span class="left-label">积分账户</span>
            <span class="left-info">{{platformIntegralData.account}}</span>
          </p>
          <p class="base-info">
            <span class="left-label">积分余额</span>
            <span class="left-info">{{platformIntegralData.balanceNum}}</span>
          </p>
          <p class="base-info">
            <span class="left-label">积分价格</span>
            <span class="left-info">{{platformIntegralData.price}}￥</span>
          </p>
        </div>
        </div>
        <div class="info-item">
            <h3>系统积分列表</h3>
            <Divider />
              <div class="search-con">
                <Input placeholder="请输入积分标记" class="search-input" v-model="searchContent.label" style="width: 200px"/>
                <Input placeholder="请输入商户名称" class="search-input" v-model="searchContent.merchantName" style="width: 200px"/>
                <Select class="search-input"  v-model="searchContent.status" placeholder="请选择积分状态" style="width: 200px">
                  <Option value="">全部</Option>
                  <Option v-for="(item, index) in integralType"
                    :value="item.type"
                    :key="'series-option-' + index"
                  >
                    {{item.label}}
                  </Option>
                </Select>
                <ButtonGroup class="search-btngroup">
                  <Button type="primary" style="margin-left: 20px" @click="handleSearch">查 找</Button>
                  <Button type="primary" @click="handleRefresh">
                    <Icon type="md-refresh" />
                  </Button>
                </ButtonGroup>
              </div>
              <tables
                ref="tables"
                editable
                pagable
                v-model="tableData"
                :columns="columns"
                :currentPage="searchContent.pageNum"
                :pageSize="searchContent.pageSize"
                :totalSize="totalSize"
                :loading="loading"
                @on-change="handleCurrentChange"
              />
        </div>
      </Card>
      <Modal
        v-model="exchangeModal"
        width="350"
        @on-cancel="handleCancelExchange"
      >
      <div class="modal-content">

        <div class="item-modal">
          <label for="">{{ratioDTO.label}}</label>
          <Input  type='number' v-model="ratioDTO.merchantRatio" style="width:70px"></Input>
        </div>
        <div class="item-modal">
          <Icon type="md-swap" size="26" />
        </div>
        <div class="item-modal">
          <label for="">BASE</label>
          <Input v-model="ratioDTO.baseRatio" type='number' style="width:70px"></Input>
        </div>
        </div>
      <div slot="footer">
        <Button
          @click="handleExchange"
          type="primary"
          >确 定</Button
        >
      </div>
    </Modal>
    <Modal
      title="设置价格"
      v-model="setPriceModal"
      width="300"
      @on-cancel="handleCancelPrice"
      >
      <div class="model-item">
          <Input v-model="dto.price" type='number' style="width:150px"><span slot="append">元</span></Input>
          </div>
      <div slot="footer">
        <Button
          @click="handleSetPrice"
          type="primary"
          >确 定</Button
        >
      </div>
    </Modal>
    <Modal
        title="积分转账"
        v-model="transModal"
        @on-cancel="handleCancelTrans"
        width="350"
      > <div class="model-item">
          <label class="label">转账对象：</label>
          <RadioGroup v-model="trans.type" style="width:100%">
            <Radio :label="1">
              <span>商户</span>
            </Radio>
            <Radio :label="2">
              <span>用户</span>
            </Radio>
          </RadioGroup>
        </div>
        <Tabs type="card" v-model="currentTab" @on-click="shopTab">
        <TabPane label="单个" name="single">

        <div class="model-item">
          <label class="label">转账手机号：</label>
          <Input
            v-model="trans.phone"
            placeholder="请输入转账手机号"
          />
        </div>
        <div class="model-item">
          <label class="label">转账数量：</label>
          <Input
            v-model="trans.amount"
            placeholder="请输入转账数量"
          />
        </div>
        </TabPane>
        <TabPane label="批量" name="batch" style="padding-left:10px">
          <p>
            <h5>上传批量转账文件</h5>
            <file-upload
              :width="45"
              style="margin-top: 5px"
              :maxNum="1"
              :maxSize="30"
              iconType="md-cloud-upload"
              v-model="trans.path"
              :defaultList="trans.defaultpath"
            />
          </p>
          <span class="downLoad" type="text" @click="downloadFile">下载批量转账文件</span>
        </TabPane>
    </Tabs>

        <div slot="footer">
          <Button
            type="primary"
            @click="handleTrans"
          >
            确定
          </Button>
        </div>
      </Modal>
      <Modal
      title="积分审核"
      v-model="checkModal"
      @on-cancel="handleCancelCheck"
      width="400"
      >
      <div class="model-item">
        <label class="label">结果：</label>
      <Select
        placeholder="请选择状态"
        class="search-input"
        v-model="checkDTO.status"
      >
        <Option
          v-for="(item, index) of checkSelect"
          :value="item.series_id"
          :key="'series-option-' + index"
        >{{ item.series_name }}</Option
        >
      </Select>
      </div>
      <div class="model-item">
        <label class="label">备注：</label>
        <Input
          placeholder="请输入备注"
          class="search-input"
          v-model="checkDTO.failReason"
        />
      </div>
      <div slot="footer">
        <Button
          type="primary"
          @click="handleSureCheck"
        >
          确定
          </Button>
      </div>
    </Modal>
    <Modal
      :title="optTitle"
      v-model="optModal"
      width="300"
      @on-cancel="handleCancelOpt"
      >
      <div class="model-item">
          <Input v-model="opt.amount" type='number' style="width:150px"><span slot="append">数量</span></Input>
          </div>
      <div slot="footer">
        <Button
          @click="handleOpt"
          type="primary"
          >确 定</Button
        >
      </div>
    </Modal>

    </div>
</template>
<script>
import FileUpload from '_c/file-upload'
import Tables from '_c/tables'
import { IntegralStatus, IntegralStateObj } from '@/enums'
import store from '@/store'
import config from '@/config'
import axios from 'axios'
const baseUrl =
  process.env.NODE_ENV === 'development'
    ? config.baseUrl.dev.mall
    : config.baseUrl.pro.mall
export default{
  inject: ['reload'],
  components: {
    FileUpload,
    Tables
  },
  data () {
    return {
      currentTab: 'single',
      exchangeModal: false,
      setPriceModal: false,
      transModal: false,
      checkModal: false,
      optModal: false,
      optTitle: '',
      optType: '',
      opt: {
        amount: '',
        label: ''
      },
      ratioDTO: {
        label: '',
        merchantRatio: '',
        baseRatio: ''
      },
      dto: {
        label: '',
        price: ''
      },
      trans: {
        phone: '',
        amount: '',
        type: 1,
        path: [],
        defaultpath: []
      },
      checkDTO: {
        label: '',
        status: '',
        failReason: ''
      },
      searchContent: {
        pageNum: 1,
        pageSize: 10,
        label: '',
        merchantName: '',
        status: ''
      },

      checkSelect: [
        {
          series_id: 5,
          series_name: '通过'
        },
        {
          series_id: 4,
          series_name: '拒绝'
        }
      ],
      integralType: [
        {
          label: '待审核',
          type: 3
        },
        {
          label: '可用',
          type: 5
        },
        {
          label: '禁用',
          type: 6
        }
      ],
      modal9: false,
      platformIntegralData: {},
      columns: [
        { title: '编号', type: 'index', align: 'center', width: 100 },
        { title: '标识', key: 'label', align: 'center', width: 120 },
        { title: '名称', key: 'name', align: 'center', width: 120 },
        { title: '描述', key: 'description', align: 'center', width: 150 },
        { title: '发行量', key: 'issueNum', align: 'center', width: 150 },
        { title: '发行账户', key: 'issueAddr', align: 'left', minWidth: 150 },
        { title: '兑换比例',
          key: 'baseRatio',
          align: 'center',
          width: 150,
          render: (h, params) => {
            let searchIdCard = h('Icon', {
              props: {
                size: 20,
                type: 'ios-create-outline',
                color: '#000'
              },
              style: {
                marginLeft: '5px',
                cursor: 'pointer'
              },
              on: {
                click: this.handleShowExchange(params.row)
              }
            })
            let contentDiv = h(
              'div',
              {
                style: {
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  height: '30px'
                }
              },
              [`${params.row.merchantRatio}:${params.row.baseRatio}`, searchIdCard]
            )
            return [contentDiv]
          }
        },
        { title: '申请人', key: 'applyName', align: 'center', width: 120 },
        { title: '状态',
          key: 'status',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h('span', IntegralStateObj[params.row.status])
          }
        },
        { title: '操作',
          key: 'account',
          align: 'center',
          fixed: 'right',
          minWidth: 150,
          render: (h, params) => {
            let status = params.row.status
            let offShelfBtn = h(
              'Button',
              {
                props: {
                  type: status == IntegralStatus.DISABLE ? 'primary' : 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleOffShelf(params.row)
                },
                style: {
                  marginRight: '5px',
                  display: status == 5 || status == 6 ? 'inline-block' : 'none'
                }
              },
              status == 6 ? '启 用' : '禁 用'
            )
            let checkBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleCheck(params.row)
                },
                style: {
                  marginRight: '5px',
                  display: status == 3 ? 'inline-block' : 'none'
                }
              },
              '审 核'
            )
            return h('div', [offShelfBtn, checkBtn])
          }
        }
      ],
      loading: false,
      tableData: [],
      totalSize: 0
    }
  },
  methods: {
    // 下载批量转账文件
    downloadFile () {
      axios({
        headers: {
          adminId: store.state.admin.uid,
          token: store.state.admin.token
        },
        method: 'GET',
        url: `${baseUrl}/integralManage/downloadexcel`,
        responseType: 'blob'
      }).then((res) => {
        let content = res.data
        let blob = new Blob([content])
        let fileName = '批量转账文件.xlsx'
        if ('download' in document.createElement('a')) {
          let link = document.createElement('a')
          link.download = fileName
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href)
          document.body.removeChild(link)
        } else {
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleAddIntegral () {
      this.optType = 1
      this.optTitle = '增发'
      this.optModal = true
      this.opt.label = this.platformIntegralData.label
    },
    handleRecover () {
      this.optType = 2
      this.optTitle = '回收'
      this.optModal = true
      this.opt.label = this.platformIntegralData.label
    },
    handleCancelOpt () {
      this.optModal = false
      this.opt.amount = ''
    },
    handleOpt () {
      let apiName = this.optType == 1 ? 'addPlatFormIntegral' : 'recoverPlatFormIntegral'
      if (!this.opt.amount) {
        return this.$Message.warning(`请填写${this.optTitle}数量！`)
      }
      if (this.opt.amount <= 0) {
        return this.$Message.warning(`${this.optTitle}数量输入有误！`)
      }
      if (this.optType == 2) {
        if (this.opt.amount > this.platformIntegralData.balanceNum) {
          return this.$Message.warning(`${this.optTitle}数量不能大于积分余额！`)
        }
      }
      this.api({
        apiName: apiName,
        postdata: this.opt,
        success: (res) => {
          this.handleCancelOpt()
          this.getPlatformBaseIntegralDetail()
          this.$Notice.success({ title: `提交${this.optTitle}完成！` })
        }
      })
    },
    handleCancelCheck () {
      this.checkModal = false
      this.checkDTO.status = ''
      console.log(this.status)
      this.checkDTO.failReason = ''
    },
    handleSureCheck () {
      let { failReason, status, label } = this.checkDTO
      if (!status) {
        return this.$Message.warning('请选择审核状态！')
      }
      this.api({
        apiName: 'integralManageCheck',
        postdata: { label, failReason, status },
        complete: () => {
          this.handleCancelCheck()
        },
        success: () => {
          this.requestData()
          this.$Notice.success({ title: `操作成功！` })
        }
      })
    },
    handleOffShelf (row) {
      return () => {
        let label = row.label
        let status = row.status == IntegralStatus.DISABLE ? IntegralStatus.AVAIABLE : IntegralStatus.DISABLE
        let title = row.status == IntegralStatus.DISABLE ? '启用' : '禁用'
        this.$Modal.confirm({
          title,
          content: `确认要${title}名称为 ${row.name} 的积分 ？`,
          onOk: () => {
            this.api({
              apiName: 'integralManageDisable',
              postdata: { label, status },
              success: () => {
                this.requestData()
                this.$Notice.success({ title: `操作成功！` })
              }
            })
          }
        })
      }
    },
    handleCheck (row) {
      return () => {
        this.checkDTO.label = row.label
        this.checkModal = true
      }
    },
    requestData () {
      this.loading = true
      this.api({
        apiName: 'getIntegralManageList',
        postdata: this.searchContent,
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          this.tableData = res.data.records
          this.totalSize = res.data.total
        }
      })
    },
    getPlatformBaseIntegralDetail () {
      this.api({
        apiName: 'platformBaseIntegralDetail',
        success: (res) => {
          this.platformIntegralData = res.data
        }
      })
    },
    handleCancelExchange () {
      this.exchangeModal = false
      this.ratioDTO.merchantRatio = ''
      this.ratioDTO.baseRatio = ''
    },
    handleExchange () {
      let { merchantRatio, baseRatio } = this.ratioDTO
      if (!merchantRatio || !baseRatio) {
        return this.$Message.warning('请输入兑换值！')
      }
      if (merchantRatio <= 0 || baseRatio <= 0) {
        return this.$Message.warning('兑换比例输入格式有误！')
      }
      this.api({
        apiName: 'setIntegralRatio',
        postdata: this.ratioDTO,
        success: (res) => {
          this.handleCancelExchange()
          this.requestData()
          this.$Notice.success({ title: '兑换成功' })
        }
      })
    },
    handleShowExchange (row) {
      return () => {
        this.ratioDTO.label = row.label
        this.exchangeModal = true
      }
    },
    shopTab (name) {
      this.currentTab = name
    },
    handleShowTrans () {
      this.transModal = true
    },
    handleCancelTrans () {
      this.currentTab = 'single'
      this.trans.type = 1
      this.trans.amount = ''
      this.trans.phone = ''
      this.trans.path = []
      this.transModal = false
    },
    handleTrans () {
      if (this.currentTab == 'single') {
        if (!this.trans.phone) {
          return this.$Message.warning(`请输入转账手机号码`)
        }
        if (!/^1[3|4|5|7|8][0-9]{9}$/.test(this.trans.phone)) {
          return this.$Message.warning(`手机号码格式输入有误`)
        }
        if (!this.trans.amount) {
          return this.$Message.warning(`请输入转账数量`)
        }
        if ((this.trans.amount <= 0 || this.trans.amount > this.platformIntegralData.balanceNum)) {
          return this.$Message.warning(`转账数量需大于0且不超过积分余额`)
        }
        this.trans.amount = parseFloat(this.trans.amount)
        if (!/^[0-9]+(.[0-9]{1,2})?$/.test(this.trans.amount)) {
          return this.$Message.warning(`转账数量格式最多至小数点后两位！`)
        }
      } else {
        if (!this.trans.path.length) {
          return this.$Message.warning(`请上传批量转账文件！`)
        }
        this.trans.path = this.trans.path[0]
      }
      let apiName = this.currentTab == 'single' ? 'transSinglePlatform' : 'integralPlatformTransBatch'
      let title = this.currentTab == 'single' ? '单个转账中！' : '批量转账中！'
      this.api({
        apiName,
        postdata: this.trans,
        success: (res) => {
          this.handleCancelTrans()
          this.$Notice.success({ title })
        }
      })
    },
    handleCancelPrice () {
      this.setPriceModal = false
      this.dto.price = ''
    },
    handleShowPrice () {
      this.setPriceModal = true
    },
    handleSetPrice () {
      if (!this.dto.price) {
        return this.$Message.warning(`请输入价格`)
      }
      if ((this.dto.price <= 0 || this.dto.price > 999999)) {
        return this.$Message.warning(`价格格式输入有误！`)
      }
      this.dto.price = parseFloat(this.dto.price)
      if (!/^[0-9]+(.[0-9]{1,2})?$/.test(this.dto.price)) {
        return this.$Message.warning(`金额格式最多至小数点后两位！`)
      }
      this.dto.label = this.platformIntegralData.label
      this.api({
        apiName: 'setPlatformIntegralPrice',
        postdata: this.dto,
        success: (res) => {
          this.handleCancelPrice()
          // this.getPlatformBaseIntegralDetail()
          this.$Notice.success({ title: '设置中' })
        }
      })
    },
    handleCurrentChange (pageNum) {
      this.searchContent.pageNum = pageNum
      this.requestData()
    },
    handleRefresh () {
      this.reload()
    },
    handleSearch () {
      this.requestData()
    }
  },
  created () {
    this.requestData()
    this.getPlatformBaseIntegralDetail()
  }
}
</script>
<style lang="less" scoped>
.info-item {
  padding: 20px 36px;
  border: 1px solid #dcdee2;
  border-radius: 5px;
  margin-bottom: 15px;
}
.platform-handle-btn{
  // margin-left: 70%;
  margin-bottom: 20px;
  text-align: right;

}
.platform-modular {
  margin-top: 20px;
  display: flex;
      // justify-content: space-between;
  // flex: 1;
  flex-wrap: wrap;
  .base-info{
    border: 1px solid #F8F8F8;
        width: 50%;
        // display: flex;
        // flex: 1;
        // flex-wrap: wrap;
        .left-label{
          display: inline-block;
          width: 35%;
          height: 40px;
          padding-right:10px;
          line-height: 40px;
          text-align: right;
          background: #F8F8F8;
        }
        .left-info{
          display: inline-block;
          width: 60%;
          padding-left:10px;
          line-height: 40px;
          // background: #F8F8F8;
        }
  }
}
 .search-con {
  display: flex;
  padding: 10px 0;
  .search-input {
    width: 200px;
    margin-right: 10px;
  }
}
 .model-item {
    display: flex;
    margin-bottom: 10px;
    align-items: center;
    justify-content: center;
    .label {
      display: inline-block;
      width: 100px;
      text-align: right;
    }
  }
  .modal-content {
    display: flex;
    justify-content: space-around;
    .item-modal {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
  }
  .downLoad{
  cursor:pointer;
}
.downLoad:hover{
        color: #2d8cf0;
      }
</style>
