<template>
  <div class="app-container">
    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addOrEdit('add')">新增</el-button>
          <el-button size="small" @click="toGetUrl()">获取短链接</el-button>
        </div>
      </div>

      <div class="table">
        <el-table ref="multipleTable" v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>
          <el-table-column align="center" label="短信名称" prop="title"></el-table-column>
          <el-table-column align="center" label="短信内容" prop="content" min-width="200"></el-table-column>
          <el-table-column align="center" label="发送人数" prop="nums"></el-table-column>
          <el-table-column align="center" label="推送状态" prop="status"></el-table-column>
          <el-table-column align="center" label="推送时间" prop="createTime" min-width="160"></el-table-column>
          <el-table-column align="center" label="创建人" prop="createBy"></el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" min-width="160"></el-table-column>
          <el-table-column align="center" label="操作" min-width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="openUserList(scope.row.id)">查看名单</el-button>
              <el-button type="text" @click="handleExport(scope.row.id)">导出</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 新增编辑 -->
    <el-dialog :title="addFormType === 'add' ? '新增':'编辑'" :visible.sync="addFormVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="left" label-width="80px">
        <el-form-item label="短信名称" prop="name">
          <el-input v-model="addForm.name" autocomplete="off" placeholder="请输入短信名称"></el-input>
        </el-form-item>
        <el-form-item label="短信内容" prop="content">
          <el-input v-model="addForm.content" autocomplete="off" placeholder="请输入短信内容"></el-input>
        </el-form-item>
        <el-form-item label="发送用户" prop="type">
          <el-radio-group v-model="addForm.type">
            <el-radio :label="1">指定用户</el-radio>
            <el-radio :label="2">导入用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择用户" prop="memberList" v-if="addForm.type === 1">
          <el-button type="primary" size="small" @click="addMember">添加用户</el-button>
          <el-table :data="memberList" element-loading-text="Loading" border fit highlight-current-row stripe max-height="300px">
            <el-table-column align="center" label="头像" prop="avatar">
              <template slot-scope="scope">
                <el-image style="width: 40px; height: 40px; border-radius: 50%;" :src="$imageUrl + scope.row.avatar" :preview-src-list="[$imageUrl + scope.row.avatar]" fit="cover"></el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" label="名称" prop="nickName"></el-table-column>
            <el-table-column align="center" label="电话" prop="mobile" min-width="120"></el-table-column>
            <el-table-column align="center" label="角色" prop="memberName" min-width="100">
              <template slot-scope="scope">
                {{ scope.row.type | MEMBER_CURRENT_TYPE_FILTER }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" fixed="right">
              <template slot-scope="scope">
                <el-popconfirm title="确定删除吗？" @onConfirm="deleteMember(scope.row.userId)" >
                  <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="导入用户" prop="file" v-if="addForm.type === 2">
          <el-upload
            :action="'import'"
            :http-request="handleImport"
			      :show-file-list="true"
            :on-remove="handleRemove"
          >
            <el-button size="small" type="primary">点击导入</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="获取短链接" :visible.sync="urlFormVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <el-form ref="urlForm" :model="urlForm" label-position="left" label-width="80px">
        <el-form-item label="选择类型" prop="type">
          <el-radio-group v-model="urlForm.type">
            <el-radio :label="1">小程序首页</el-radio>
            <el-radio :label="2">订单列表页</el-radio>
            <el-radio :label="3">工单列表页</el-radio>
            <el-radio :label="4">优惠券列表页</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" prop="">
          <el-button type="primary" size="small" @click="submitUrlForm">生 成</el-button>
        </el-form-item>
        <el-form-item label="短链接" prop="url">
          <span>{{urlForm.url}}</span>
          <el-button size="mini" class="tag-read" style="margin-left: 10px;" @click="copy(urlForm.url)" :data-clipboard-text="urlForm.url" v-if="urlForm.url">复制</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUrlForm">关 闭</el-button>
      </div>
    </el-dialog>


    <!-- 选择会员 -->
    <el-dialog title="选择会员" :visible.sync="addMemberVisible" :show-close="false" width="65%" :close-on-click-modal="false">
      <div class="dialog-container2 clearfix">
        <el-form ref="screenForm" :model="member_screenForm" size="small" label-position="left">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="7">
              <el-form-item label="关键词" prop="keyword" label-width="55px">
                <el-input v-model="member_screenForm.keyword" placeholder="请输入会员名称/电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="7">
              <el-form-item label="注册日期" prop="registerDate" label-width="70px">
                <el-date-picker
                  style="width: 100%"
                  v-model="member_screenForm.registerDate"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="7">
              <el-form-item label="" prop="type" label-width="20px">
                <el-radio-group v-model="member_screenForm.type" :disabled="memberList.length > 0 ? true : false">
                  <el-radio :label="'SERVICE'">业务员</el-radio>
                  <el-radio :label="'GENERAL'">普通用户</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="2" class="tr">
              <el-button size="small" type="primary" @click="getMemberListByScreen">搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
        <div class="table memberTable" style="margin: 10px 0 20px;">
          <el-table 
            v-loading="memberTable_listLoading" 
            :data="memberTable_dataList" 
            element-loading-text="Loading" 
            tooltip-effect="dark" 
            style="width: 100%" 
            max-height="360"
            @selection-change="handleChooseMember">
            <el-table-column align="center" type="selection" :selectable='checkboxSelect' width="45"></el-table-column>
            <el-table-column align="center" prop="nickName" label="名称" min-width="150"></el-table-column>
            <el-table-column align="center" prop="mobile" label="电话" min-width="100"></el-table-column>
            <el-table-column align="center" prop="memberName" label="角色" min-width="100">
              <template slot-scope="scope">
                {{ scope.row.type | MEMBER_CURRENT_TYPE_FILTER }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="memberName" label="状态" min-width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status ? 'success' : 'danger'">{{ scope.row.status | MEMBER_CURRENT_STATUS_FILTER }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination clearfix">
          <div class="fr">
            <el-pagination
              @current-change="memberTableCurrentChange"
              :current-page="memberTable_currentPage"
              :page-size="memberTable_pageSize"
              background
              layout="prev, pager, next"
              :total="memberTable_listTotal">
            </el-pagination>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddMember">保 存</el-button>
        <el-button @click="cancelAddMember">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看名单 -->
    <el-dialog title="查看名单" :visible.sync="userTableDialog" :show-close="false" width="65%" :close-on-click-modal="false">
      <div class="dialog-container2 clearfix">
        <div class="table memberTable" style="margin: 10px 0 20px;">
          <el-table 
            :data="userTableList" 
            tooltip-effect="dark" 
            style="width: 100%" 
            max-height="360">
            <el-table-column align="center" prop="mobile" label="电话" min-width="100"></el-table-column>
          </el-table>
        </div>
        <div class="pagination clearfix">
          <div class="fr">
            <el-pagination
              @current-change="userTableListChange"
              :current-page="userTableListCurPage"
              :page-size="userTableListPageSize"
              background
              layout="prev, pager, next"
              :total="userTableListTotal">
            </el-pagination>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="userTableDialog = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {addData, getList, getMemberList, getUserList, getUrl} from "@/api/message";
import { findElem, handleImport, downloadFiles } from '@/utils/util'
import Clipboard from 'clipboard'

export default {
  data() {
    return {
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      editId:  null,
      addFormType: 'add',
      addFormVisible: false,
      addForm: {
        name: '', // 短信名称
        content: '', // 短信内容
        type: '',
        file: '',
      },
      addFormRules: {
        name: [{ required: true, message: '请输入短信名称', trigger: 'blur' }],
        content: [{ required: true, message: '请输入短信内容', trigger: 'blur' }],
      },

      memberList: [], // 会员数据
      addMemberVisible: false,
      member_screenForm: { // 筛选表单数据
        keyword: '', // 名称
        registerDate: [],
        type: 'SERVICE',
      },
      memberTable_dataList: null, // 列表数据
      memberTable_listLoading: true, // 列表加载loading
      memberTable_currentPage: 1, // 当前页码
      memberTable_pageSize: 10, // 每页数量
      memberTable_listTotal: 0, // 列表总数
      memberTable_choose: [], // table中 当前选择会员

      userTableDialog: false,
      userTableId: null,
      userTableList: [],
      userTableListCurPage: 1,
      userTableListPageSize: 10,
      userTableListTotal: 0,

      urlFormVisible: false,
      urlForm: {
        type: 1,
        url: '',
      },
    }
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      getList({
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },
    // 筛选后重新获取列表
    getListByScreen() {
      this.currentPage = 1;
      this.getList();
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    // 查询重复值并禁选
    checkboxSelect (row, rowIndex) {
      if (row.selected) {
        return false // 禁用
      }else{
        return true // 不禁用
      }
    },

    // 搜索
    getMemberListByScreen() {
      if(this.memberTable_choose.length > 0) {
        return this.$errorMsg('当前已选择会员，不可搜索');
      }
      this.memberTable_currentPage = 1;
      this.getMemberList();
    },

    // 获取会员列表
    getMemberList() {
      getMemberList({
        pageNum: this.memberTable_currentPage,
        pageSize: this.memberTable_pageSize,
        keyword: this.member_screenForm.keyword,
        type: this.member_screenForm.type,
        startTime: this.member_screenForm.registerDate && this.member_screenForm.registerDate[0] ? this.member_screenForm.registerDate[0] + ' 00:00:00' : null,
        endTime: this.member_screenForm.registerDate && this.member_screenForm.registerDate[1] ? this.member_screenForm.registerDate[1] + ' 23:59:59' : null,
      }).then(res => {
        let oldMemberList = this.memberList;
        let newMemberList = res.data.records;
        for(let i = 0; i < oldMemberList.length; i++) {
          let oldItem = oldMemberList[i]
          for(let j = 0; j < newMemberList.length; j++) {
            let newItem = newMemberList[j]
            if(newItem.userId === oldItem.userId){
              newMemberList[j].selected = true;
              break;
            }
          }
        }
        this.memberTable_dataList = newMemberList;
        this.memberTable_listTotal = res.data.total;
        this.memberTable_listLoading = false;
      })
    },

    // 更改列表当前页
    memberTableCurrentChange(val) {
      if(this.memberTable_choose.length > 0) {
        return this.$errorMsg('当前已选择会员，不可切换分页');
      }
      this.memberTable_currentPage = val;
      this.getMemberList();
    },

    // table点击选择会员
    handleChooseMember(val) {
      this.memberTable_choose = val;
    },

    // 添加会员
    addMember() {
      this.addMemberVisible = true;

      if(this.memberList.length > 0) {
        this.member_screenForm.type = this.memberList[0].type;
      }
      
      this.getMemberList();
    },

    // 删除会员
    deleteMember(id) {
      let index = findElem(this.memberList, 'userId', id);
      this.memberList.splice(index, 1);
    },

    // 取消 选择会员
    cancelAddMember(){
      this.addMemberVisible = false;
    },

    // 提交 选择会员
    submitAddMember() {
      let oldMemberList = this.memberList;
      let newMemberList = this.memberTable_choose;
      this.memberList = oldMemberList.concat(newMemberList);
      this.addMemberVisible = false;
    },

    // 导入
    handleImport(param) {
      this.addForm.file = param.file;
    },

    // 删除导入
    handleRemove() {
      this.addForm.file = '';
    },

    // 新增编辑
    addOrEdit(type, id) {
      this.addFormType = type;
      this.addFormVisible = true;
    },

    // 取消 新增编辑
    cancelAddForm(){
      this.addFormVisible = false;
      this.$refs.addForm.resetFields();
    },

    // 提交 新增编辑
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if(this.addForm.type === 1 && this.memberList.length < 1) {
            return this.$errorMsg('请选择用户');
          }
          if(this.addForm.type === 2 && !this.addForm.file) {
            return this.$errorMsg('请导入用户');
          }
          
          if(this.addForm.type === 1) {
            let params = {
              title: this.addForm.name,
              content: this.addForm.content,
              mobiles: this.memberList.map(item => {
                return item.mobile;
              }).join(',')
            }
            addData(params).then(res => {
              this.cancelAddForm();
              this.getList();
              this.$successMsg('新增成功');
            })
          }else {
            const formData = new FormData();
            formData.append("file", this.addForm.file);
            formData.append("title", this.addForm.name);
            formData.append("content", this.addForm.content);
            handleImport('gree/sms/add', formData).then(res => {
              if(res.code == 200) {
                this.cancelAddForm();
                this.getList();
                this.$successMsg('新增成功');
              }else {
                this.$errorMsg(res.message);
              }
            });
            
          }
          
        }
      })
    },

    // 去获取短链接
    toGetUrl() {
      this.urlFormVisible = true;
    },

    cancelUrlForm() {
      this.urlFormVisible = false;
      this.$refs.urlForm.resetFields();
    },

    submitUrlForm() {
      const MAP = {
        1: '',
        2: 'orderList',
        3: 'workOrderList',
        4: 'couponList'
      }
      getUrl({
        param: this.urlForm.type > 1 ? `?otherType=${MAP[this.urlForm.type]}` : ''
      }).then(res => {
        this.urlForm.url = res.data;
      })
    },

    copy() {
      const clipboard = new Clipboard('.tag-read');
      // clipboard.on('success', e => {
      //   this.$successMsg('复制成功');
      // })
      clipboard.on('error', e =>{
        console.log('该浏览器不支持复制');
        return false;
      })
      this.$successMsg('复制成功');
    },

    // 查看名单
    openUserList(id) {
      this.userTableId = id;
      getUserList({
        id: this.userTableId,
        pageNum: this.userTableListCurPage,
        pageSize: this.userTableListPageSize,
      }).then(res => {
        this.userTableDialog = true;
        this.userTableList = res.data.records;
        this.userTableListTotal = res.data.total;
      })
    },

    userTableListChange(val) {
      this.userTableListCurPage = val;
      this.openUserList(this.userTableId);
    },

    // 导出
    handleExport(id) {
      downloadFiles('gree/sms/export', {id});
    },
  }
}
</script>

<style scoped lang="scss">

</style>
