<template>
  <div class="menu">
    <div class="head clear-both">
      <el-button @click="add" plain type="success" style="float: right" v-if="!$store.state.readonly">新增来源码</el-button>
    </div>
    <el-table
      :data="sourceList"
      style="width: 100%">
      <el-table-column
        prop="title"
        label="名字">
      </el-table-column>
      <el-table-column
        prop="code"
        label="来源CODE">
        <template slot-scope="scope">
          <a href="javascript:void(0);" @click="goToOrder(scope.row.code)">{{scope.row.code}}</a>
        </template>
      </el-table-column>
      <el-table-column
        label="是否可提现">
        <template slot-scope="scope">
          {{scope.row.is_withdraw | isWithdraw}}
        </template>
      </el-table-column>
      <el-table-column
        prop="no_cash_user"
        label="不可提现用户">
        <template slot-scope="scope">
          <a href="javascript:void(0);" @click="getNoCashUser(scope.row.no_cash_user)">{{scope.row.no_cash_user}}</a>
        </template>
      </el-table-column>
      <el-table-column
        prop="desc"
        label="备注">
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="创建时间" sortable>
      </el-table-column>
      <el-table-column
        label="操作"
        width="250">
        <template slot-scope="scope">
          <el-button size="mini" plain type="primary" @click="edit(scope.row)" v-if="!$store.state.readonly">
            编辑
          </el-button>
          <el-button size="mini" type="danger" plain @click="del(scope.row)" v-if="!$store.state.readonly && $store.state.deletePermission">
            删除
          </el-button>
          <el-button size="mini" plain type="primary" @click="createInviteLink(scope.row.code)">
            复制链接
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <page :nowPage="nowPage" :total="total" :limit="limit" @pageChange="onPageChange" @sizeChange="onSizeChange"/>
    <el-dialog
      :title="dialog.title"
      center
      append-to-body
      :visible.sync="dialog.show"
      width="50%">
      <el-form ref="form" :rules="dialog.rules" :model="dialog.form" label-width="120px">
        <el-form-item label="名字" prop="title">
          <el-input v-model="dialog.form.title"></el-input>
        </el-form-item>
        <el-form-item label="来源CODE" prop="code">
          <el-input v-model="dialog.form.code"></el-input>
        </el-form-item>
        <el-form-item label="是否可提现">
          <el-switch
            v-model="dialog.form.is_withdraw"
            active-color="#13ce66"
            inactive-color="#eee">
          </el-switch>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="不可提现用户ID">
              <el-input v-model="dialog.form.no_cash_user"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="2">
            <el-button type="primary" @click="onSelectUser">选择用户</el-button>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="dialog.form.desc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
      <el-dialog :visible.sync="userDialog.show" append-to-body>
        <el-form label-width="90px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="ID">
                <el-input v-model="searchUserFrom.userId"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="昵称">
                <el-input v-model="searchUserFrom.nickName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电话">
                <el-input v-model="searchUserFrom.mobile"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" :offset="16">
              <el-form-item>
                <el-button style="float: right" type="primary" plain @click="getUser">搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          :data="userList"
          ref="multipleTable"
          @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            className="f-c"
            label="用户">
            <template slot-scope="scope">
              <img style="margin-right:5px;width: 50px;height: 50px;border-radius: 50px" :src="scope.row.avatar">{{scope.row.nickname}}(ID:{{scope.row.user_id}})
            </template>
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号">
          </el-table-column>
        </el-table>
        <user-page :total="userDialog.total" :limit="userDialog.limit" @pageChange="onUserPageChange" @sizeChange="onUserSizeChange"/>
        <span slot="footer" class="dialog-footer">
        <el-button @click="userDialog.show = false">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
      </el-dialog>
    </el-dialog>
    <el-dialog :visible.sync="noCashUserDialog.show" append-to-body>
      <el-table
        :data="noCashUserList"
        style="width: 100%">
        <el-table-column
          className="f-c"
          label="用户">
          <template slot-scope="scope">
            <img style="margin-right:5px;width: 50px;height: 50px;border-radius: 50px" :src="scope.row.avatar">{{scope.row.nickname}}(ID:{{scope.row.user_id}})
          </template>
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="noCashUserDialog.show = false">确 定</el-button>
      </span>
    </el-dialog>
    <choose-good-dialog v-if="chooseGoodDialogObj.show" :dialogObj="chooseGoodDialogObj" @changeShow="changeShow"/>
  </div>
</template>

<script>
  import {getSourceListApi,addSourceApi,delSourceApi,updateSourceApi,getUserListApi} from "../../service/api";
  import page from '../framework/page'
  import userPage from '../framework/page'
  import chooseGoodDialog from '../teacherDetail/chooseGoodDialog'
  export default {
    components: {
      page,
      userPage,
      chooseGoodDialog
    },
    data(){
      return {
        nowPage:1,
        total:0,
        limit:10,
        sourceList:[],
        codeSelect:[{
          value:'USER',
          label:'用户'
        },{
          value:'TEACHER',
          label:'老师'
        }],
        dialog:{
          title:'新增来源码',
          show:false,
          rules: {
            title: [
              {required: true, message: '请填写来源码名字', trigger: 'change'},
            ],
            code: [
              {required: true, message: '请填写来源码类型', trigger: 'change'},
            ]
          },
          form:{
            id:'',
            title:'',
            code:'',
            is_withdraw: 0,
            desc:'',
            no_cash_user: ''
          }
        },
        userDialog: {
          total: 0,
          limit: 10,
          nowPage: 1,
          show: false
        },
        userList: [],
        searchUserFrom: {},
        multipleSelection: [],
        noCashUserDialog: {
          total: 0,
          limit: 1000,
          nowPage: 1,
          show: false
        },
        noCashUserList: [],
        chooseGoodDialogObj: {
          show: false,
          code: ''
        }
      }
    },
    filters: {
      sourceType(value){
        if (value.toLowerCase() === 'user'){
           return '用户'
        } else if (value.toLowerCase() === 'teacher') {
           return '老师'
        } else {
            return value
        }
      },
      isWithdraw(value){
        if (value === 1){
          return '是'
        } else {
          return '否'
        }
      }
    },
    created(){
      this.getList()
    },
    methods:{
      getList(){
        let json = {
          limit: this.limit,
          page: this.nowPage
        }
        getSourceListApi(json).then(res=>{
          if (res) {
            this.sourceList = res.list ? res.list : [];
            this.total = res.total;
          }
        })
      },
      onPageChange(val){
        this.nowPage = val
        this.getList()
      },
      onSizeChange(val){
        this.nowPage = 1
        this.limit = val
        this.getList()
      },
      onSelectUser(){
        this.userDialog.show = true;
        if(this.dialog.form.no_cash_user) {
          this.multipleSelection =  this.dialog.form.no_cash_user.split(',');
        } else {
          this.multipleSelection = []
        }
        this.getUser();
      },
      onUserPageChange(val){
        this.userDialog.nowPage = val
        this.getUser()
      },
      onUserSizeChange(val){
        this.userDialog.nowPage = 1
        this.userDialog.limit = val
        this.getUser()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      onConfirm(){
        let _list = this.multipleSelection;

        if(_list.length === 0) {

        } else {
          let _userIds = [];
          _list.forEach((item)=>{
            _userIds.push(item.user_id)
          })
          let _tmp = _userIds
          if (this.dialog.form.no_cash_user) {
            _tmp = _userIds.concat(this.stringToInt(this.dialog.form.no_cash_user.split(',')));
          }
          let _result = this.dedupe(_tmp);
          this.dialog.form.no_cash_user = _result.join(',');
          this.userDialog.show = false;
        }
      },
      stringToInt(list){
        let _list = list || [];
        _list = _list.map((val)=>{
          return parseInt(val, 10)
        })
        return _list;
      },
      dedupe(array){
        return Array.from(new Set(array));
      },
      getUser(){
        let json = {
          page: this.userDialog.nowPage,
          limit: this.userDialog.limit
        };
        if (this.searchUserFrom.userId) {
          json.user_id = this.searchUserFrom.userId
        }
        if (this.searchUserFrom.nickName) {
          json.nickname = this.searchUserFrom.nickName
        }
        if (this.searchUserFrom.mobile) {
          json.mobile = this.searchUserFrom.mobile
        }
        getUserListApi(json).then(res=>{
          this.userList = res.list;
          this.userDialog.total = res.total;
        })
      },
      getNoCashUser(ids){
        let json = {
          page: this.noCashUserDialog.nowPage,
          limit: this.noCashUserDialog.limit
        };
        if (ids) {
          json.user_id = ids
        }
        getUserListApi(json).then(res=>{
          this.noCashUserList = res.list;
          this.noCashUserDialog.total = res.total;
          this.noCashUserDialog.show = true;
        })
      },
      edit(data){
        this.dialog.show = true;
        this.dialog.form.id = data.id;
        this.dialog.title = '编辑来源码';
        this.dialog.form.title = data.title;
        this.dialog.form.code = data.code;
        this.dialog.form.is_withdraw = data.is_withdraw === 1;
        this.dialog.form.desc = data.desc;
        this.dialog.form.no_cash_user = data.no_cash_user;
      },
      add(){
        this.dialog.show = true;
        this.dialog.form.id = '';
        this.dialog.title = '新增来源码';
        this.dialog.form.title = '';
        this.dialog.form.code = 'USER';
        this.dialog.form.is_withdraw = false;
        this.dialog.form.desc = '';
        this.dialog.form.no_cash_user = '';
      },
      del(data){
        this.$confirm('此操作将删除该来源码?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delSourceApi(data.id).then(res=>{
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          });
        });
      },
      sub(){
        this.$refs['form'].validate((valid) => {
          if(valid){
            let dia = this.dialog;
            if(dia.form.id){
              let json = {
                title:dia.form.title,
                code:dia.form.code,
                is_withdraw:dia.form.is_withdraw ? 1 : 0,
                desc:dia.form.desc
              };
              if (dia.form.no_cash_user) {
                json.no_cash_user = dia.form.no_cash_user
              }
              this.$confirm('此操作将修改该来源码?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                updateSourceApi(dia.form.id,json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                  dia.show = false;
                  this.getList()
                })
              })
            }else{
              let json = {
                title:dia.form.title,
                code:dia.form.code,
                no_cash_user:dia.form.no_cash_user,
                is_withdraw:dia.form.is_withdraw ? 1 : 0,
                desc:dia.form.desc
              };
              this.$confirm('此操作将添加来源码?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                addSourceApi(json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
                  dia.show = false;
                  this.getList()
                })
              })
            }
          }
        })
      },
      goToOrder(code){
        this.$router.push('/order?code='+ code);
      },
      changeShow(){
        this.chooseGoodDialogObj.show = false;
        this.chooseGoodDialogObj.code = '';
      },
      createInviteLink(code){
        this.chooseGoodDialogObj.show = true;
        this.chooseGoodDialogObj.code = `CC-${code}`;
      }
    }
  }
</script>

<style scoped lang="less">
  .menu{
  .head{
    margin-bottom: 10px;
  }
  padding: 20px 0;
  .page-div{
    text-align: center;
    padding-top: 20px
  }
  }
  .clear-both{
  &:after{
     content: '';
     display: block;
     clear: both;
   }
  }
</style>

