<template>
  <div class="subPage">
    <div class="system-table-search">
      <div class="flex-h">
        <div class="flex-item flex-h">
          <el-button size="mini" type="success" @click="addCard">新增课程体验卡</el-button>
        </div>
        <ul>
          <li>
            <!-- <span>选择案场：</span> -->
            <el-select v-model="CaseId" placeholder="请选择案场">
              <el-option
                v-for="item in cases"
                :key="item.CaseId"
                :label="item.CaseName"
                :value="item.CaseId">
              </el-option>
            </el-select>
          </li>
        </ul>
        <el-button
          size="mini"
          type="primary" @click="search">搜索</el-button>
      </div>
      <div class="moreFilter"></div>
    </div>
    <div class="system-table-box">
      <el-table
        :data="cardList.list"
        stripe
        style="width: 100%">
        <el-table-column
          prop="CardName"
          label="卡名称">
        </el-table-column>
        <!-- <el-table-column
          prop="xxx"
          label="卡类型">
        </el-table-column> -->
        <el-table-column
          prop="Price"
          label="卡价格">
        </el-table-column>
        <el-table-column
          prop="StartDate"
          label="有效期"
          width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.StartDate !== '0001-01-01T00:00:00Z'" style="width:100%;display:block;text-align:center;white-space: nowrap;">{{toolClass.dateFormat(scope.row.StartDate, 'yyyy-MM-dd')}}</span>
            <span style="width:100%;display:block;text-align:center;white-space: nowrap;">至</span>
            <span v-if="scope.row.EndDate !== '0001-01-01T00:00:00Z'" style="width:100%;display:block;text-align:center;white-space: nowrap;">{{toolClass.dateFormat(scope.row.EndDate, 'yyyy-MM-dd')}}</span>
            <span v-if="scope.row.StartDate === '0001-01-01T00:00:00Z' && scope.row.EndDate === '0001-01-01T00:00:00Z'">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="SendType"
          label="发放类型">
          <template slot-scope="scope">
            <span>{{SendType(scope.row.SendType)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="TotalCount"
          label="总数量">
        </el-table-column>
        <!-- <el-table-column
          prop="SentCount"
          label="已发">
        </el-table-column>
        <el-table-column
          prop="UsedCount"
          label="实际使用">
        </el-table-column> -->
        <el-table-column
          prop="Status"
          label="状态">
          <template slot-scope="scope">
            {{scope.row.Status == 1 ? '正常' : '已过期'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed='right' width="350">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="sendCard(scope.$index, scope.row)">赠送客户</el-button>
            <el-button
              size="mini"
              type="success"
              v-if="scope.row.SendType === 'channel'"
              v-clipboard:copy="clientUrl + '/wechat/user.html#/receiveChannelShared/' + scope.row.CardId + '/card/receive'"
              v-clipboard:success="onCopy"
              v-clipboard:error="onError"
              >点击复制链接</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page.sync="postData.page"
      :page-size="postData.pagesize"
      layout="prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog
      title="选择赠送客户"
      :visible.sync="centerDialogVisible"
      width="800px"
      @close="dialogPostData.page = 1"
      center>
      <div>
        <ul class="dialogSearchList flex-h" style="margin-bottom:10px;">
          <li class="flex-item">
            <el-input
              placeholder="请输入用户名"
              v-model="dialogPostData.username"
              clearable>
            </el-input>
          </li>
          <li class="flex-item">
            <el-input
              placeholder="请输入手机号"
              v-model="dialogPostData.phone"
              clearable>
            </el-input>
          </li>
          <li class="flex-item">
            <el-input
              placeholder="请输入推荐人"
              v-model="dialogPostData.recommendname"
              clearable>
            </el-input>
          </li>
          <li>
            <el-button type="primary" @click="dialogSearch">搜索</el-button>
          </li>
        </ul>
        <ul class="dialogSearchList flex-h">
          <li class="flex-item">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="dialogPostData.begindate"
              type="date"
              placeholder="选择起始日期">
            </el-date-picker>
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="dialogPostData.enddate"
              type="date"
              placeholder="选择截止日期">
            </el-date-picker>
          </li>
        </ul>
      </div>
      <div>
        <el-table
          ref="multipleTable"
          :data="customers.list"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection">
          </el-table-column>
          <el-table-column
            prop="Name"
            label="姓名">
          </el-table-column>
          <el-table-column
            prop="CustomerName"
            label="微信昵称">
          </el-table-column>
          <el-table-column
            prop="Phone"
            label="手机号">
          </el-table-column>
          <el-table-column
            prop="CreatDate"
            label="创建时间">
            <template slot-scope="scope">
              <span v-if="scope.row.CreateDate !== '0001-01-01T00:00:00Z'">{{toolClass.dateFormat(scope.row.CreateDate, 'yyyy-MM-dd')}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="RecommendName"
            label="推荐人">
          </el-table-column>
        </el-table>
      </div>
      <div>
        <el-pagination
          @current-change="handleCurrentChangeDialog"
          :current-page.sync="dialogPostData.page"
          :page-size="dialogPostData.pagesize"
          layout="prev, pager, next, jumper"
          :total="dialogTotal">
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="toSendCard">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="手动复制"
      :visible.sync="copyDialogVisible"
      width="300px"
      center>
      <div>
        <el-input
          placeholder="请输入内容"
          v-model="currentCopyUrl"
          clearable>
        </el-input>
        <!-- <a :data-clipboard-text="currentCopyUrl" ref="copy" @click="toCopy">复制链接</a> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="copyDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapState: mapCardState, mapActions: mapCardActions } = createNamespacedHelpers('card')
const { mapState: mapCustomerState, mapActions: mapCustomerActions } = createNamespacedHelpers('customer')

export default {
  name: '',
  data () {
    return {
      currentCopyUrl: '',
      copyDialogVisible: false,
      selectCustomer: [],
      dialogTotal: 0,
      dialogPostData: {
        username: '',
        phone: '',
        recommendname: '',
        begindate: '',
        enddate: '',
        page: 1, // 当前页码
        pagesize: 6, // 请求数据量
      },
      customerList: [],
      centerDialogVisible: false,
      total: 0,
      postData: { // 表格搜索条件
        caseid: '', // 案场id
        page: 1, // 当前页码
        pagesize: 10, // 请求数据量
      },
    }
  },
  mounted () {
    this.$nextTick(function () {
      this.getList()
    })
  },
  computed: {
    ...mapCardState({
      cardList: x => x.cardList,
    }),
    ...mapState({
      clientUrl: x => x.app.clientUrl,
      cases: x => x.app.cases.list,
      defaultCaseId: x => x.app.cases.default
    }),
    ...mapCustomerState({
      customers: x => x.customers,
    }),
    CaseId: {
      get () {
        return this.postData.caseid || this.defaultCaseId
      },
      set (val) {
        this.postData.caseid = val
      }
    }
  },
  methods: {
    ...mapCardActions([
      'GetCardList',
      'giveCard',
    ]),
    ...mapCustomerActions([
      'GetCustomerList',
      'SetCustomerListNull',
    ]),
    SendType (type) {
      if (type === 'channel') {
        return '渠道'
      }
      if (type === 'case') {
        return '案场'
      }
      if (type === 'system') {
        return '系统'
      }
    },
    toSendHistory () { // 查看赠送记录
      this.$router.push({ name: 'givingRecords' })
    },
    dialogSearch () { // 赠送客户搜索
      this.GetCustomerList(this.dialogPostData).then((res) => {
        this.dialogTotal = res.pagenum
      })
    },
    handleCurrentChangeDialog (val) {
      this.dialogPostData.page = val
      this.GetCustomerList(this.dialogPostData).then((res) => {
        this.dialogTotal = res.pagenum
      })
    },
    handleSelectionChange (val) {
      // console.log(val)
      this.selectCustomer = val
    },
    toSendCard () { // 赠送卡
      if (this.selectCustomer.length) {
        this.selectCustomer = this.selectCustomer.map(x => x.CustomerId).join(',')
        this.giveCard({
          id: this.currentCardId,
          users: this.selectCustomer,
        }).then(res => {
          this.$message({
            type: 'success',
            message: '赠送成功！'
          })
          this.centerDialogVisible = false
          this.selectCustomer = []
          if (this.customers.list.length) {
            this.customers.list = []
          }
          this.dialogPostData = {
            username: '',
            phone: '',
            recommendname: '',
            begindate: '',
            enddate: '',
            page: 1, // 当前页码
            pagesize: 6, // 请求数据量
          }
          this.getList()
        })
      } else {
        this.$message({
          type: 'error',
          message: '请先选择需要赠送的客户!'
        })
      }
    },
    closeDialog () { // 关闭弹窗
      this.centerDialogVisible = false
      if (this.customers.list.length) {
        this.customers.list = []
      }
    },
    sendCard (index, row) { // 赠送卡弹窗
      this.currentCardId = row.CardId
      this.centerDialogVisible = true
    },
    search () { // 搜索
      this.postData.page = 1
      this.currentList = []
      this.getList()
    },
    getList () { // 获取列表
      this.GetCardList({
        ...this.postData,
        caseid: this.CaseId || this.defaultCaseId
      }).then((res) => {
        this.total = res.pagenum
        // console.log(JSON.stringify(res))
      })
    },
    handleCurrentChange (val) { // 跳转到分页
      this.getList()
    },
    handleEdit (index, row) { // 编辑
      this.$router.push({ name: 'editCard', query: { id: row.CardId } })
    },
    // handleCopy (url) { // 复制弹窗
    //   this.currentCopyUrl = url
    //   this.copyDialogVisible = true
    // },
    toCopy (index, row) { // 复制
      // console.log(1)
      var clipboard = new Clipboard(this.$refs['copy' + index])
      clipboard.on('success', e => {
        // console.log('复制成功')
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // console.log('该浏览器不支持自动复制')
        clipboard.destroy()
      })
    },
    addCard () {
      this.$router.push({ name: 'addCard', query: {} })
    },
    onCopy () {
      this.$message({
        type: 'success',
        message: '复制成功！'
      })
    },
    onError () {
      this.$message({
        type: 'error',
        message: '复制失败！'
      })
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import "page.scss";
.dialogSearchList {
  align-items: center;
  > li {
    font-size: 0;
    margin-left: 10px;
    &:first-child {
      margin-left: 0;
    }
    > *:nth-child(2) {
      margin-left: 10px;
    }
  }
}
.copyBtn {
  line-height: 29px;
  border-radius: 3px;
  color: #fff;
  background: #67c23a;
  display: inline-block;
  padding: 0 15px;
  margin-left: 10px;
}
</style>
