<!--
  我的顾客应用：
  <app-detail ></app-detail>
 -->
<template>
  <div class="app-detail-wrap">
    <div v-if="tabType == 1">
      <!-- <common-detail-top :topMenuData="topMenuData" :activeId="activeId"></common-detail-top> -->
      <div class="common-detail-tab">
        <el-tabs v-model="activeName" class="daily-set-tab" @tab-click="handleTabClick">
          <el-tab-pane label="会员搜索设置" name="first"></el-tab-pane>
          <el-tab-pane label="会员展示设置" name="second"></el-tab-pane>
          <el-tab-pane label="会员分组设置" name="third"></el-tab-pane>
        </el-tabs>
      </div>
      <div v-if="activeName == 'first'" class="app-detail-pane border-box p-20">
        <el-checkbox v-model="myCustomData.searchFlag">允许全品牌搜索</el-checkbox>
        <div class="m-t-46">
          <el-button type="primary" @click="submit('searchFlag')">保 存</el-button>
        </div>
      </div>
      <div v-if="activeName == 'second'" class="app-detail-pane border-box p-20">
        <div class="m-b-20"><el-checkbox v-model="myCustomData.mainStoreFlag">展示服务门店会员</el-checkbox></div>
        <div class="m-b-20"><el-checkbox v-model="myCustomData.minorStoreFlag">展示协管门店会员</el-checkbox></div>
        <div class="m-b-20"><el-checkbox v-model="myCustomData.openCardStoreFlag">展示开卡门店会员</el-checkbox></div>
        <div><el-checkbox v-model="myCustomData.clerkSeeOtherFlag">允许导购查看其他导购会员</el-checkbox></div>
        <div class="m-t-46">
          <el-button type="primary" @click="submit('showFlag')">保 存</el-button>
        </div>
      </div>
      <div v-if="activeName == 'third'" class="app-detail-pane border-box p-20">
        <div class="condition-wrap font-0">
          <el-input placeholder="请输入分组名称搜索" v-model="conditionObj.searchInput" class="w-264" style="width: 264px;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value, conditionObj.searchInput)" clearable @clear="clearInput"></el-input>
          <el-select class="w-105 m-l-10" v-model="conditionObj.classifyName" placeholder="请选择" @change="changeCondition">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="item in classifyList" :key="item" :label="item" :value="item"> </el-option>
          </el-select>
          <el-select class="m-l-10" v-model="conditionObj.effectiveStatus" placeholder="请选择状态" @change="changeCondition">
            <el-option label="全部" value=""></el-option>
            <el-option label="有效" value="1"></el-option>
            <el-option label="失效" value="0"></el-option>
          </el-select>
        </div>
        <div class="condition-tip m-t-20 m-b-20">
          <div role="alert" class="el-alert el-alert--info">
            <i class="el-alert__icon el-icon-info font-12 color-1890ff"></i>
            <div class="el-alert__content"><span class="el-alert__title color-606266 font-14">注：GIC设置分组后，好办会员分组列表次日刷新，每日刷新一次，仅展示GIC中开启【好办展示】的会员分组</span></div>
          </div>
        </div>
        <div>
          <el-table class="select-table" ref="multipleTable" :data="groupListData" tooltip-effect="dark" :style="{ width: '100%' }">
            <el-table-column label="分组名称" width="120" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.groupName }}</template>
            </el-table-column>
            <el-table-column prop="" label="分类">
              <template slot-scope="scope">{{ scope.row.memberTagGroupClassifyName }}</template>
            </el-table-column>
            <el-table-column prop="" label="是否实时" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.isRealTime == 1 ? '是' : '否' }}</template>
            </el-table-column>
            <el-table-column prop="" label="更新频率" show-overflow-tooltip>
              <template slot-scope="scope"
                >{{ scope.row.updateType == 1 ? '每日' : scope.row.updateType == 2 ? '每周' : scope.row.updateType == 3 ? '每月' : '-' }} {{ scope.row.updateType == 1 ? '一次' : scope.row.updateType == 2 ? '周' + scope.row.updateDay : scope.row.updateType == 3 ? scope.row.updateDay + '号' : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="" label="状态" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.effectiveStatus == '1' ? '有效' : '失效' }}</template>
            </el-table-column>
            <el-table-column prop="" label="覆盖人数" show-overflow-tooltip>
              <template slot-scope="scope"
                >{{ scope.row.memberCount || 0 }}人</template
              >
            </el-table-column>
            <el-table-column prop="" label="到期时间" show-overflow-tooltip>
              <template slot-scope="scope">
                <div>{{ scope.row.effectiveDate | formatTimeYMD }}</div>
                <div>{{ scope.row.effectiveDate | formatTimeHMS }}</div>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot="header" slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="仅可编辑能在好办展示的分组" placement="right"> <span>操作</span><i class="el-icon-info font-12 color-606266"></i> </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="toEditGroup(scope.$index, scope.row)">编辑分组可见范围</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block common-wrap__page text-right m-t-24" v-if="groupListData.length != 0">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <div v-if="tabType == 2">
      <common-detail-top :topMenuData="topMenuData" :activeId="activeId"></common-detail-top>
      <div class="app-detail-pane border-box p-20">
        <el-checkbox v-model="myCustomData.chatFlag">在线沟通设置</el-checkbox>
        <div class="m-t-46">
          <el-button type="primary" @click="submit('chatFlag')">保 存</el-button>
        </div>
      </div>
    </div>
    <vue-select-store ref="storeSelector" :currentBrand="activeGroup" :appScene="appScene" :treeSet="storeTreeSet" :selectType="'group-store'" :defaultList="defaultStoreList" @handleSelectedList="handleSelectedList"> </vue-select-store>
  </div>
</template>
<script>
import commonDetailTop from '@/components/app/common-detail-top.vue';
import vueSelectStore from 'components/common/vueSelectStore';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';
export default {
  name: 'app-detail',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    tabType: {
      type: String,
      default() {
        return '1';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      activeName: 'first',
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      myCustomData: {
        searchFlag: false,
        chatFlag: false,
        mainStoreFlag: false, // 服务门店显示，1显示0不现实
        minorStoreFlag: false, // 协管门店显示，1显示0不显示
        openCardStoreFlag: false, // 开卡门店显示，1显示0不显示
        clerkSeeOtherFlag: false // 导购查看其他导购，1显示0不显示
      },
      topMenuData: [
        {
          id: '1',
          name: '会员搜索设置'
        }
      ],
      activeId: '1',

      // 会员分组设置
      conditionObj: {
        searchInput: '',
        classifyName: '',
        effectiveStatus: ''
      },
      groupListData: [], // 列表数据
      classifyList: [], // 会员分组
      currentPage: 1,
      pageSize: 20,
      total: 0,
      // 门店选择
      appScene: 2,
      defaultStoreList: [],
      storeTreeSet: {
        isSelectPerson: false, // 控制只能选部门(false)
        dialogVisible: false, // 控制显示/隐藏
        isSingle: false // 是否单选
      }
    };
  },
  filters: {
    formatTimeYMD(data) {
      let date = new Date(data);
      let month = date.getMonth() + 1;
      let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      let newMonth = month < 10 ? '0' + month : month;
      return date.getFullYear() + '-' + newMonth + '-' + day;
    },
    formatTimeHMS(data) {
      let date = new Date(data);
      let hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
      let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
      let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return hours + ':' + minutes + ':' + seconds;
    }
  },
  beforeMount() {
    let that = this;
    let host = window.location.origin;
    if (host.indexOf('localhost') != -1) {
      that.baseUrl = 'http://www.gicdev.com';
    } else {
      that.baseUrl = host;
    }
  },
  methods: {
    /* eslint-disable */
    handleTabClick(tab, event) {
      const that = this;
      if (tab.name == 'first') {
        that.getCustomerSet(that.brandId);
      }else if (tab.name == 'second') {
        that.getShowSet(that.brandId);
      }else {
        that.getGroupClassify(that.brandId)
        that.getGroupList(that.brandId)
      }
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getGroupList(that.brandId);
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getGroupList(that.brandId);
    },
    changeCondition() {
      const that = this;
      that.currentPage = 1;
      that.getGroupList(that.brandId);
    },
    /**
     * 获取会员分组分类
     */
    getGroupClassify(brandId) {
      const that = this;
      let para = {
        brandId: brandId
      };
      postRequest('/haoban-app-member-web/memberGroup/get-member-class-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.classifyList = resData.result.list || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 编辑分组可见范围
     *
     */
    toEditGroup(index, row) {
      const that = this;
      that.memberTagGroupId = row.memberTagGroupId;
      that.getGroupSet();
    },
    getGroupSet() {
      const that = this;
      let para = {
        brandId: that.brandId,
        memberTagGroupId: that.memberTagGroupId
      };
      postRequest('/haoban-app-member-web/memberGroup/find-gorup-see-range', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if(resData.result && resData.result.length) {
              resData.result.forEach(ele => {
                if (Number.parseInt(ele.type) === 2) {
                  ele.groupId = ele.id;
                }
                ele.label = ele.name;
              })
            }
            that.defaultStoreList = resData.result || [];
            that.storeTreeSet = {
              dialogVisible: true,
              isSingle: false,
              isSelectPerson: false
            };
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    handleSelectedList(data) {
      console.log(data);
      const that = this;
      that.defaultStoreList = data || [];
      that.saveGorupRange();
    },
    saveGorupRange() {
      const that = this;
      let storeGroups = [];
      let filterStoreIds = [];
      that.defaultStoreList.forEach(ele => {
        if (ele.type == 2) {
          storeGroups.push(ele.groupId);
        }
        if (ele.type == 3) {
          filterStoreIds.push(ele.storeId);
        }
      });
      let para = {
        brandId: that.brandId,
        memberTagGroupId: that.memberTagGroupId,
        groupList: storeGroups || [],
        storeList: filterStoreIds || []
      };
      postRequest('/haoban-app-member-web/memberGroup/save-gorup-see-range', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('编辑成功', 'success');
            that.defaultStoreList = [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.pageSize = val;
      that.getGroupList(that.brandId);
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getGroupList(that.brandId);
    },

    /**
     * 获取会员分组设置列表
     */
    getGroupList(brandId) {
      const that = this;
      let para = {
        brandId: brandId,
        memberGroupName: that.conditionObj.searchInput,
        classifyName: that.conditionObj.classifyName,
        effectiveStatus: that.conditionObj.effectiveStatus,
        pageNum: that.currentPage,
        pageSize: that.pageSize
      };
      postRequest('/haoban-app-member-web/memberGroup/member-tag-group-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.groupListData = resData.result.list || [];
            that.total = resData.result.pageInfo.total;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 保存
     */
    submit: _debounce(function(type) {
      const that = this;
      that.setData(type);
    }, 500),

    /**
     * 保存-API
     */
    setData(type) {
      const that = this;
      let para = {
        brandId: that.brandId,
        enterpriseId: JSON.parse(localStorage.getItem('userInfo')).enterpriseId
      };
      let url;
      if (type != 'showFlag') {
        para[type] = !!that.myCustomData[type] ? 1 : 0;
        url = '/haoban-app-member-web/customer/save-online-chat-setting';
        if (type === 'searchFlag') {
          url = '/haoban-app-member-web/customer/save-customer-setting';
        }
      }else {
        para['mainStoreFlag'] = !!that.myCustomData['mainStoreFlag'] ? 1 : 0;
        para['minorStoreFlag'] = !!that.myCustomData['minorStoreFlag'] ? 1 : 0;
        para['openCardStoreFlag'] = !!that.myCustomData['openCardStoreFlag'] ? 1 : 0;
        para['clerkSeeOtherFlag'] = !!that.myCustomData['clerkSeeOtherFlag'] ? 1 : 0;
        url = '/haoban-app-member-web/customer/save-member-show-setting';
      }

      postRequest(url, para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('保存成功', 'success');
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 获取全品牌搜索设置数据
     */
    getCustomerSet(brandId) {
      const that = this;
      let para = {
        brandId: brandId
      };
      postRequest('/haoban-app-member-web/customer/find-customer-setting', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result) {
              that.myCustomData.searchFlag = !!resData.result.searchFlag ? true : false;
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取会员展示设置数据
     */
    getShowSet(brandId) {
      const that = this;
      let para = {
        brandId: brandId
      };
      postRequest('/haoban-app-member-web/customer/find-member-show-setting', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result) {
              that.myCustomData.mainStoreFlag = !!resData.result.mainStoreFlag ? true : false;
              that.myCustomData.minorStoreFlag = !!resData.result.minorStoreFlag ? true : false;
              that.myCustomData.openCardStoreFlag = !!resData.result.openCardStoreFlag ? true : false;
              that.myCustomData.clerkSeeOtherFlag = !!resData.result.clerkSeeOtherFlag ? true : false;
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取在线沟通设置数据
     */
    getChatSet(brandId) {
      const that = this;
      let para = {
        brandId: brandId
      };
      postRequest('/haoban-app-member-web/customer/find-online-chat-setting', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result) {
              that.myCustomData.chatFlag = !!resData.result.chatFlag ? true : false;
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      that.getChatSet(newData);
      that.getCustomerSet(newData);
      that.getShowSet(newData);
      that.getGroupClassify(newData)
      that.getGroupList(newData)
    },
    activeGroupId: function(newData, oldData) {
      let that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    },
    tabType: function(newData, oldData) {
      const that = this;
      if (newData == 1) {
        that.topMenuData = [
          {
            id: '1',
            name: '会员搜索设置'
          }
        ]
        that.activeId = 1;
      }else {
        that.topMenuData = [
          {
            id: '2',
            name: '在线沟通设置'
          }
        ]
        that.activeId = '2';
      }
    }
  },
  /*  mounted() {
    const that = this;
  },*/
  components: {
    commonDetailTop,
    vueSelectStore
  }
};
</script>
<style lang="less" scoped>
.w-500 {
  width: 500px;
}

.color-1890ff {
  color: #1890ff;
}

.p-20 {
  padding: 20px;
}

.app-detail-wrap {
  height: 100%;
  background: #fff;
  .el-tabs {
    background: #fff;
    /deep/ .el-tabs__nav-wrap {
      /* height: 48px;
      line-height: 48px; */
      &::after {
        height: 1px;
      }
      /* .el-tabs__nav-scroll {
        padding-left: 20px;
      } */
    }
  }
  .condition-tip {
    width: 740px;
    .el-alert--info {
      background: #E6F7FF;
      border: 1px solid rgba(145,213,255,1);
      .el-alert__icon {
        font-size: 12px;
      }
    }
  }
}
</style>
