import nav from '../../common/navbar/navbar.vue';
import baseinfoDialog from './components/baseinfoDialog.vue';
import babyinfoDialog from './components/babyinfoDialog.vue';
import customergradeDialog from './components/customergradeDialog.vue';
import customermainstoreDialog from './components/customermainstoreDialog.vue';
import customersubstoreDialog from './components/customersubstoreDialog.vue';
import customerlabelDialog from './components/customerlabelDialog.vue';
import defaultImg from '../../../static/img/default.png';
import { mapState } from 'vuex';
import url from '../../components/axios/url';
import { doFetch, doFetchqs } from '../../components/axios/api';
import {
  checkFalse,
  checkStatus,
  checkSuccess,
} from '../../../static/js/checkStatus';
export default {
  name: 'customersDetail',
  data () {
    return {
      navpath: [
        { name: '首页', path: '' },
        { name: '客户列表', path: '/allCustomers' },
        { name: '客户详情', path: '' },
      ],
      pageName: 'allCustomer', // 请求参数
      memberId: '',
      member: {
        // 会员基础信息
        memberProtocolInfo: {
          // 会员协议信息
          visitConsentPrivacyProtocolTime: null, // 微盟访问同意协议的时间
          loginConsentPrivacyProtocolTime: null, // 微盟登录同意协议的时间
          consentPrivacyProtocolTime: null, // 达摩同意协议的时间
        },
        thirdImgUrl: '', // 头像
      },
      memberInfo: {}, // 会员卡信息
      extendInfo: {
        // 开卡字段、扩展字段
        openField: [],
        fieldList: [],
      },
      babyStr: '', // 宝宝信息
      // 标签备注
      tagAndRemarkInfo: {
        // 会员分组
        memberGroup: {
          // 金字塔分层
          memberGradeGroup: {},
          // 客户分组
          memberTagGroupList: {},
        },
        // 手工标签
        tag: {
          tagsList: [], // 导购标签
          otherTagsList: [], // 其他标签
          weimobTagsList: [], // 微盟标签
        },
        // 导购备注
        remarkList: [],
        // 身形字段
        dictFigureList: [],
      },
      tableData: [],
      logPageParam: {
        pageSize: 20,
        currentPage: 1,
      },
      totalCount: 0,
      defaultImg,
      labelTabsActive: 'memberTagGroup',
      fullscreenLoading: false, // 全局loading
      tableLoading: false, // 用户日志列表loading
      imgLoading: false, // 刷新头像loading
      popoverVisible: false, // 修改等级popover
      toggleTag: false, // 拓展信息展开按钮
      showFieldType: 1, // 1开卡拓展字段 2会员信息字段
      showClique: false, // 集团权限
      baseinfoDialogVisible: false, // 修改基本信息弹窗
      gradeDialogVisible: false, // 修改等级弹窗
      mainStoreDialogVisible: false, // 修改服务门店、专属导购弹窗
      subStoreDialogVisible: false, // 修改协管门店弹窗
      labelDialogVisible: false, // 修改手工标签弹窗
      babyDialogVisible: false, // 宝宝信息弹窗
      nationCodeList: [], // 手机区号列表
      gradeList: [], // 等级列表
      count: 0,
      // 模块列表
      customerInfoItemList: [
        { title: '基本信息', name: 'basic', class: 'basic-info-contain' },
        {
          title: '会员卡信息',
          name: 'card',
          class: 'card-info-contain max1600',
        },
        {
          title: '客户记录',
          name: 'customerRecord',
          class: 'customer-record-contain max1600',
          childrenList: {
            // 资产信息
            assets: [
              {
                label: '积分',
                icon: 'icon-jifen1',
                iconTheme: 'integral',
                key: 'accumulatPoints',
                path: '/integralDataPage',
              },
              {
                label: '卡券',
                icon: 'icon-01_kaquanguanli',
                iconTheme: 'coupon',
                key: 'couponCount',
                path: '/cardvoucher',
              },
              {
                label: '储值余额',
                icon: 'icon-chuzhizhanghu',
                iconTheme: 'balance',
                key: 'storedValue',
                path: '',
              },
            ],
            // 交易记录
            transaction: [
              {
                label: '门店订单',
                icon: 'icon-mendianbaojiadan',
                key: 'numOfSale',
                path: '/consumption',
              },
              {
                label: '微盟订单',
                icon: 'icon-a-weimeng2',
                key: 'weimobMallNum',
                path: '/wmDetail',
              },
              {
                label: '达摩商城订单',
                icon: '',
                key: 'wechatMallNum',
                path: '/infoMall',
              },
              {
                label: '其他订单',
                icon: 'icon-dingdan-copy',
                key: 'otherMallNum',
                path: '/otherDetail',
              },
            ],
            // 交互记录
            interactive: [
              {
                label: '营销记录',
                icon: 'icon-yingxiaojilu',
                iconTheme: 'market',
                key: 'numOfMarket',
                path: '',
              },
              {
                label: '通话记录',
                icon: 'icon-tonghuajilu1',
                iconTheme: 'tel',
                key: 'numOfTel',
                path: '/talkLogPage',
              },
            ],
          },
        },
        {
          title: '归属信息',
          name: 'ascription',
          class: 'ascription-info-contain max160',
        },
        {
          title: '标签备注',
          name: 'label',
          class: 'label-remarks-contain',
          childrenList: [
            { title: '导购标签', key: 'tagsList' },
            { title: '其他标签', key: 'otherTagsList' },
            { title: '微盟标签', key: 'weimobTagsList' },
          ],
        },
        { title: '客户日志', name: 'log', class: 'log-info-contain' },
      ],
    };
  },
  watch: {
    count: function (n, o) {
      if (n === 4) this.fullscreenLoading = false;
    },
  },
  filters: {
    customerTypeFilter: v => {
      switch (v) {
        case 'wxOpenCarMember':
          return '微信会员';
        case 'posMember':
          return 'POS会员';
        default:
          return '非会员';
      }
    },
    genderFilter: v => {
      switch (v) {
        case 1:
          return '男';
        case 2:
          return '女';
        default:
          return '--';
      }
    },
  },
  computed: {
    ...mapState(['showEditClique']),
  },
  created () {
    this.$store.commit('mutations-slide', true);
    this.memberId = this.$route.query.memberId;
  },
  mounted () {
    const rightWrap = document.querySelector('.right-maincontainer');
    rightWrap.scrollTo(0, 0);
    this.initData();
    this.getEnterpriseInfo();
    this.getcodeList();
    this.getGradeList();
  },
  methods: {
    initData () {
      this.count = 0;
      this.fullscreenLoading = true;
      this.getAllDetail();
      this.getLogPage();
    },
    getAllDetail () {
      const param = { memberId: this.memberId, pageName: this.pageName };
      const urlArr = [
        'memberLoadBaseDetail',
        'memberLoadmemberInfo',
        'memberLoadTagDetail',
      ];
      urlArr.forEach(api => {
        doFetch(url[api], param)
          .then(res => {
            if (res.data.errorCode === 0) {
              const ret = res.data.result;
              if (api === 'memberLoadBaseDetail') {
                this.member = Object.assign({}, ret.member);
                const babyArr = [];
                Array.isArray(ret.extendInfo.openChildrenField) &&
                  ret.extendInfo.openChildrenField.forEach(el =>
                    babyArr.push(
                      el.sonFields[0].fieldValue&&el.sonFields[0].fieldName==='宝宝名称'
                        ? el.sonFields[0].fieldValue
                        : el.bName,
                    ),
                  );
                this.extendInfo = Object.assign({}, ret.extendInfo);
                this.babyStr = babyArr.join('；');
              }
              if (api === 'memberLoadmemberInfo') {
                this.memberInfo = Object.assign({}, ret.memberInfo);
              }
              if (api === 'memberLoadTagDetail') {
                this.tagAndRemarkInfo = Object.assign(
                  {},
                  {
                    memberGroup: {
                      memberGradeGroup:
                        ret.tagAndRemarkInfo.memberGroup.memberGradeGroup || {},
                      memberTagGroupList:
                        ret.tagAndRemarkInfo.memberGroup.memberTagGroupList ||
                        {},
                    },
                    tag: {
                      tagsList: ret.tagAndRemarkInfo.tag.tagsList || [],
                      otherTagsList:
                        ret.tagAndRemarkInfo.tag.otherTagsList || [],
                      weimobTagsList:
                        ret.tagAndRemarkInfo.tag.weimobTagsList || [],
                    },
                    remarkList: ret.tagAndRemarkInfo.remarkList || [],
                    dictFigureList: ret.tagAndRemarkInfo.dictFigureList || [],
                  },
                );
              }
            } else {
              checkFalse(res.data.message);
            }
          })
          .catch(err => {
            checkStatus(err);
          })
          .finally(_ => this.count++);
      });
    },
    getLogPage () {
      this.tableLoading = true;
      doFetch(url.logPage, {
        ...this.logPageParam,
        memberId: this.memberId,
      })
        .then(res => {
          this.tableLoading = false;
          if (res.data.errorCode === 0) {
            this.tableData = res.data.result.page.result || [];
            this.tableData = this.tableData.map(el => {
              if (typeof el.operRemark == 'string') { el.operRemark = el.operRemark.replace(/\n/g, ' <br />'); }
              return el;
            });
            this.totalCount = res.data.result.page.totalCount;
          } else {
            checkFalse(res.data.message);
            return false;
          }
        })
        .catch(err => {
          this.tableLoading = false;
          checkStatus(err);
        })
        .finally(_ => this.count++);
    },
    updateImgUrl () {
      this.imgLoading = true;
      doFetch(url.updateImgUrl, {
        memberId: this.memberId,
      })
        .then(res => {
          if (res.data.errorCode === 0) {
            checkSuccess();
            const ret = res.data.result;
            this.member = Object.assign({}, this.member, {
              thirdImgUrl: ret.thirdImgUrl ? ret.thirdImgUrl : '',
            });
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        })
        .finally(_ => (this.imgLoading = false));
    },
    changeExtendFieldTab(type){
      this.showFieldType=type;
      this.toggleTag=true;
    },
    goLink (v) {
      if (v) this.$router.push({ path: v, query: { memberId: this.memberId } });
    },
    goStoreValue () {
      if (this.memberInfo.storedValueFlag) {
        this.$router.push({
          path: '/storedValue',
          query: { memberId: this.memberId },
        });
      }
    },
    handleSizeChange (v) {
      this.logPageParam.pageSize = v;
      this.logPageParam.currentPage = 1;
      this.getLogPage();
    },
    handleCurrentChange (v) {
      this.logPageParam.currentPage = v;
      this.getLogPage();
    },
    // 集团配置
    getEnterpriseInfo () {
      doFetchqs(url.enterpriseInfo).then(res => {
        if (res.data.errorCode === 0) {
          this.showClique = res.data.result.enterpriseInfo.showClique;
        }
      });
    },
    // 手机区号列表
    getcodeList () {
      doFetch(url.codeList)
        .then(res => {
          if (res.data.errorCode === 0) {
            this.nationCodeList = res.data.result.nationCodeList.map(item => {
              item.dictName += ` +${item.dictCode}`;
              return {
                dictName: item.dictName,
                dictCode: item.dictCode,
              };
            });
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    // 等级列表
    getGradeList () {
      doFetch(url.gradeList)
        .then(res => {
          if (res.data.errorCode === 0) {
            this.gradeList = res.data.result || [];
          } else {
            checkFalse(res.data.message);
            return false;
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
  },
  components: {
    'v-nav': nav,
    baseinfoDialog,
    babyinfoDialog,
    customergradeDialog,
    customermainstoreDialog,
    customersubstoreDialog,
    customerlabelDialog,
  },
};
