<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs='crumbs'></bread-crumb>
      <el-button  style="float:right;" type="primary" size="small" icon="el-icon-circle-plus-outline" @click="openCreate">添加会员</el-button>
    </div>
    <div class="app-container">
          <div style="margin-bottom: 10px">
            <el-row :gutter="24">
              <el-col :span="8">
                  <el-input style="width: 300px" v-model="listQuery.search" placeholder="请输入您需要搜索的内容"></el-input>
                  <el-button type="primary"  icon="el-icon-search" @click="changeKey">搜索</el-button>
              </el-col>
            </el-row>
          </div>
          <div class="cell clearfix">
            <label class="title"> <span class="name">创建时间</span>: </label>
            <el-date-picker v-model="listQuery.start_time" prefix-icon="el-icon-date"  @change="changeTime" :editable="false" style="width: 196px;" type="date" placeholder="选择日期时间"
            align="right" format="yyyy-MM-dd" value-format="yyyy-MM-dd" ></el-date-picker>
            <span class>-</span>
            <el-date-picker v-model="listQuery.end_time" prefix-icon="el-icon-date" @change="changeTime" :editable="false" style="width: 196px;" type="date" placeholder="选择日期时间"
            align="right" format="yyyy-MM-dd" value-format="yyyy-MM-dd" ></el-date-picker>
        </div>
          <div class="cell clearfix">
            <label class="title"><span class="name">等级</span>:</label>
             <div class="time">
                <ul class="">
                  <li :class="0==levelType?'active':''"  @click="selectLevel(0)">全部</li>
                  <li :class="item.id==levelType?'active':''"  v-for="item in levelCards" :key="item.id"  @click="selectLevel(item.id)">{{item.card_name}}</li>
                </ul>
             </div>
          </div>
          <div class="cell clearfix">
            <label class="title"><span class="name">来源方式</span>:</label>
             <div class="time">
                <ul class="">
                  <li :class="0==sourceType?'active':''"  @click="selectSource(0)">全部</li>
                  <li :class="item.id==sourceType?'active':''"  v-for="item in sourceOptions" :key="item.id"  @click="selectSource(item.id)">{{item.name}}</li>
                </ul>
             </div>
          </div>
          <div class="cell clearfix">
            <label class="title"><span class="name">标签</span>:</label>
             <div class="time">
                <ul class="">
                  <li :class="0==tagType?'active':''"  @click="selectTag(0)">全部</li>
                  <li :class="item.id==tagType?'active':''"  v-for="item in tagOptions" :key="item.id"  @click="selectTag(item.id)">{{item.tag_name}}</li>
                </ul>
             </div>
          </div>
          <div class="filter-container" style="margin-top: 10px;margin-left: 5px">
            <el-checkbox style="width: 30px"  @change="changeCheck" v-model="checkAllStatus">全选</el-checkbox>
            <el-button size="small" icon="el-icon-delete" @click="openDeleteMembers">批量删除</el-button>
            <el-button size="small" icon="el-icon-edit" @click="openAddMembersTags">添加标签</el-button>
            <el-button size="small" icon="el-icon-message" @click="openSendMessage">发送短信</el-button>
          </div>
          <el-table ref="multipleTable"  @selection-change="handleSelectionChange" :cell-class-name="cellStyleName" :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)'}" :data="membersData" border fit highlight-current-row  style="width: 100%;margin-top: 10px;">
             <el-table-column
                align="center"
                type="selection"
                width="55">
             </el-table-column>
             <el-table-column label="会员" align="center" >
               <template slot-scope="scope">
                 <div style="display:flex;align-items: center;">
                   <img :src="memberAvatar(scope.row)" alt="" srcset="" style="width:50px;height:50px; border-radius:50%;margin-right:5px;" >
                    <div>
                     <span>{{scope.row.name}}</span>
                    </div>
                 </div>
               </template>
             </el-table-column>
            <el-table-column label="等级" align="center">
              <template slot-scope="scope">
                <img v-if="scope.row.user_card && scope.row.user_card.card" :src="vip" alt="" srcset="" style="width:16px;height:16px;margin-bottom: -2px;" >
                <span>{{memberLevel(scope.row)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="标签" align="center">
              <template slot-scope="scope">
                <el-tag size="small"  v-for="(tag, index) in scope.row.tags" :key="index">{{tag.tag_name}}</el-tag>

              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center">
              <template slot-scope="scope">
                <span>{{memberCreateTime(scope.row.created_time)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="来源方式" align="center">
              <template slot-scope="scope">
                <span>{{memberSource(scope.row.sources)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                  <el-button size="mini" type="primary" icon="el-icon-edit-outline" @click="openEdit(scope.row, scope.$index)" ></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="标签" placement="top">
                  <el-button size="mini" type="warning" icon="el-icon-edit" @click="openTags(scope.row, scope.$index)" ></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="会员卡" placement="top">
                  <el-button size="mini" type="success" icon="el-icon-tickets" @click="openCard(scope.row, scope.$index)" ></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="openDelete(scope.row, scope.$index)" ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[10,20,50,100]"
            :page-size="10"
            background
            style="margin-top:20px;"
            align="right"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>

          <!--create-member-form 添加会员-->
          <create-member-form ref="createMemberForm" :levelCards="levelCards" :membersData="membersData" :illnessOptions="illnessOptions" :treatTypeOptions="treatTypeOptions" :tagOptions="tagOptions"></create-member-form>
          <!--edit-member-form 编辑会员-->
          <edit-member-form ref="editMemberForm" :levelCards="levelCards" :memberIndex="memberIndex" :form="memberData" :membersData="membersData" :illnessOptions="illnessOptions" :treatTypeOptions="treatTypeOptions" :tagOptions="tagOptions"></edit-member-form>
          <!--edit-member-tags-form 为单个会员编辑标签-->
          <edit-member-tags-form ref="editMemberTagsForm" :memberIndex="memberIndex" :form="memberData" :membersData="membersData" :tagOptions="tagOptions"></edit-member-tags-form>
          <!--add-members-tags-form 为所选会员添加标签-->
          <add-members-tags-form ref="addMembersTagsForm" :form="memberData" :membersData="membersData" :tagOptions="tagOptions"></add-members-tags-form>
          <!--edit-member-card-form 为单个会员设置会员卡-->
          <edit-member-card-form ref="editMemberCardForm" :form="cardFormData" :memberIndex="memberIndex" :membersData="membersData" :cardOptions="levelCards"></edit-member-card-form>
    </div>
  </div>
</template>

<script>
  import {GetMembers,DeleteMembers} from "@/api/member/member";
  import BreadCrumb from '../components/bread-crumb'
  import {uParseTime} from "@/utils/tools";
  import CreateMemberForm from "./components/CreateMemberForm";
  import EditMemberForm from "./components/EditMemberForm";
  import EditMemberTagsForm from "./components/EditMemberTagsForm";
  import AddMembersTagsForm from "./components/AddMembersTagsForm";
  import EditMemberCardForm from "./components/EditMemberCardForm";
  export default {
    name: 'commentList',
    components:{
      BreadCrumb,
      CreateMemberForm,
      EditMemberForm,
      EditMemberTagsForm,
      AddMembersTagsForm,
      EditMemberCardForm,
    },
    data(){
      return{
        crumbs: [
          { path: false, name: '会员管理' },
          { path: false, name: '会员列表' }
        ],
        time: '',
        vip:'https://images.shengws.com/member-ship-card-vip.png',
        checkAllStatus:false,
        active: true,
        levelType: 0,
        levelCards:[],
        sourceType: 0,
        sourceOptions:{},
        treatTypeOptions:{},
        tagType: 0,
        tagOptions:[],
        membersData:[],
        illnessOptions:[],
        memberData:{
            name:'',
            mobile:'',
            gender:0,
            birthday:'',
            city:[],
            province_id:0,
            city_id:0,
            district_id:0,
            illness:[],
            ill_date:'',
            treat_type:'',
            tags:[],
            remark:'',
            avatar:'',
            id:0,
            ids:[],
        },
        cardFormData:{
            id:0,
            card_id:''
        },
        selectedMembers:[],
        memberIndex:-1,
        total:0,
        listQuery:{
            page:1,
            limit:10,
            search:'',
            start_time:'',
            end_time:'',
            source:0,
            tag:0,
            level:0,
            init:1,
        },
      }
    },
    methods:{
        GetMembers(){
            GetMembers(this.listQuery).then(response=>{
                var res = response.data;
                console.log("res是谁？",res)
                if(res.state == 1) {
                    this.membersData = res.data.members;
                    console.log("会员管理的数据",this.membersData)
                    this.total = res.data.total;
                    if(typeof(res.data.cards) != 'undefined') {
                        this.levelCards = res.data.cards;
                        console.log("levelCard是什么",levelCards)
                    }
                    if(typeof(res.data.tags) != 'undefined') {
                        this.tagOptions = res.data.tags;
                    }
                    if(typeof(res.data.illness) != 'undefined') {
                        this.illnessOptions = res.data.illness;
                    }
                    this.listQuery.init = 0;
                }else {
                    this.$message.error(res.msg);
                }
            }).catch(e=>{});
        },
        openSendMessage(){
          
          this.$message.error("功能开发中...");
          return false;
          if (this.selectedMembers.length==0) {
            this.$message.error("请选择要发送短信的会员");
            return false;
          }
          
        },
        openAddMembersTags() {
          if (this.selectedMembers.length==0) {
            this.$message.error("请选择要添加标签的会员");
            return false;
          }
          
          this.memberData.tags = [];
          this.memberData.ids = [];
          for (const index in this.selectedMembers) {
            this.memberData.ids.push(this.selectedMembers[index].id);
          }
          this.$refs.addMembersTagsForm.open();
        },
        openDeleteMembers(){
          if (this.selectedMembers.length==0) {
            this.$message.error("请选择要删除的会员");
            return false;
          }

          this.$confirm('确认要删除所选的会员吗？<br>删除后，会员信息将无法恢复', '删除提示', {
            dangerouslyUseHTMLString:true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            var ids = [];
            var idMap = {};
            for (const index in this.selectedMembers) {
              ids.push(this.selectedMembers[index].id);
              idMap[this.selectedMembers[index].id] = this.selectedMembers[index].id;
            }
            DeleteMembers({ids:ids}).then(response=>{
              var res = response.data;
              if (res.state === 1) {
                var membersDataLength = this.membersData.length;
                for (let index = membersDataLength-1; index >= 0; index--) {
                  if(this.membersData[index].id in idMap) {
                    this.membersData.splice(index, 1);
                  }                  
                }
                this.$message.success("删除会员成功");
              }else {
                this.$message.error(res.msg);
              }
            }).catch(e=>{});
          }).catch(() => {
            return false        
          });

        },
        openDelete(row, index) {
          this.$confirm('确认要删除该会员吗？<br>删除后，该会员信息将无法恢复', '删除提示', {
            dangerouslyUseHTMLString:true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            var ids = [];
            ids.push(row.id);
            DeleteMembers({ids:ids}).then(response=>{
              var res = response.data;
              if (res.state === 1) {
                this.membersData.splice(index, 1);
                this.$message.success("删除会员成功");
              }else {
                this.$message.error(res.msg);
              }
            }).catch(e=>{});
          }).catch(() => {
            return false        
          });
        },
        openCard(row, index){
          this.cardFormData.id = row.id;
          this.cardFormData.card_id = '';
          this.memberIndex = index;
          if (row.user_card && row.user_card.card) {
            this.cardFormData.card_id = row.user_card.card_id;
          }
          this.$refs.editMemberCardForm.open();
        },
        openTags(row, index) {
          this.memberData.tags = [];
          this.memberData.id = row.id;
          let tags = row.tags;
          for (const index in tags) {
              this.memberData.tags.push(tags[index].id);
          }
          
          this.memberIndex = index;
          this.$refs.editMemberTagsForm.open();
        },
        openEdit(row, index){
          this.memberData.illness = [];
          this.memberData.city = [];
          this.memberData.birthday = '';
          this.memberData.ill_date = '';
          this.memberData.treat_type = '';
          for (const key in this.memberData) {
              if (key === "illness" && row.illness) {
                  let illness = row.illness;
                  for (const index in illness) {
                      this.memberData.illness.push(illness[index].illness_id);
                  }
              } else if (key === "tags" && row.tags) {
                  let tags = row.tags;
                  for (const index in tags) {
                      this.memberData.tags.push(tags[index].id);
                  }
              } else if (key === "treat_type" && row.treat_type>0) {
                  this.memberData.treat_type = row.treat_type;
              } else if (key === "city") {
                if (row.province_id > 0) {
                  this.memberData.city.push(row.province_id);
                  this.memberData.city.push(row.city_id);
                  this.memberData.city.push(row.district_id);
                }
              } else if (key === "birthday" && row.birthday!=0) {
                  this.memberData.birthday = uParseTime(row.birthday, "{y}-{m}-{d}");
              } else if (key === "ill_date" && row.ill_date!=0) {
                  this.memberData.ill_date = uParseTime(row.ill_date, "{y}-{m}-{d}");
              } else if (key in row) {
                  this.memberData[key] = row[key];                  
              }            
          }
          // this.memberData = row;
          this.memberIndex = index;
          this.$refs.editMemberForm.open();
        },
        openCreate(){
          this.$refs.createMemberForm.open();
        },
        memberAvatar(row) {
            if(typeof(row.avatar) == "undefined" || !row.avatar || row.avatar.length==0) {
                if(row.gender == 2) {
                    return 'https://images.shengws.com/201809182128222.png';
                }else {
                    return 'https://images.shengws.com/201809182128111.png';
                }
            }else {
                return row.avatar
            }
        },
        memberLevel(row) {
          if(row.user_card && row.user_card.card) {
            return row.user_card.card.card_name;
          } else {
            return '普通会员'
          }
        },
        memberCreateTime(time) {
          return uParseTime(time, "{y}-{m}-{d} {h}:{i}:{s}");
        },
        memberSource(source) {
          if (source in this.sourceOptions) {
            return this.sourceOptions[source].name;
          }else {
            return '--';
          }
        },
        changeCheck(){
          this.$refs.multipleTable.clearSelection();
          if (this.checkAllStatus) {
            this.$refs.multipleTable.toggleAllSelection();
          }
        },
        handleSelectionChange(val){
          this.selectedMembers = val;
        },
        cellStyleName({row, column, rowIndex, columnIndex}){
            if (columnIndex===1) {
                return 'member-name-box';
            }
            return '';
        },
        selectSource(id) {
            this.listQuery.source = id;
            this.sourceType = id;
            this.GetMembers();
        },
        selectLevel(id) {
            this.listQuery.level = id;
            this.levelType = id;
            this.GetMembers();
        },
        selectTag(id) {
            this.listQuery.tag = id;
            this.tagType = id;
            this.GetMembers();
        },
        changeKey(){
            this.GetMembers();
        },
        changeTime(){
            this.GetMembers();
        },
        handleSizeChange(limit) {
            this.listQuery.limit = limit;
            this.GetMembers();
        },
        handleCurrentChange(page) {
            this.listQuery.page = page;
            this.GetMembers();
        }
    },
    created(){
        this.sourceOptions = this.$store.getters.members.sources;
        this.treatTypeOptions = this.$store.getters.members.treat_type;
        this.GetMembers();
    }
  }
</script>

<style scoped>
  .el-tag {
    margin: 1px;
  }
  /*.app-container .cell.clearfix .time ul li {*/
    /*float: left;*/
    /*list-style: none;*/
    /*cursor: pointer;*/
    /*padding: 6px 20px;*/
    /*color: #606266;*/
    /*border-radius: 4px;*/
    /*margin: 0 8px 0 0;*/
    /*font-size: 14px;*/
    /*text-align: center;*/
  /*}*/
</style>

<style>

.member-name-box .cell{
    float: left;
    text-align: left;
};
</style>
