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 IconLabelValue from './components/icon-label-value.vue';
import defaultImg from '../../../static/img/default.png';
import { mapState } from 'vuex';
import url from '../../components/axios/url';
import { doFetch, doFetchqs, doFetchGet } from '../../components/axios/api';
import authMethods from '@/mixins/auth';
import CustomerLog from './components/customerLog.vue';
import {
  checkFalse,
  checkStatus,
  checkSuccess,
} from '../../../static/js/checkStatus';
export default {
  name: 'customersDetail',
  mixins: [authMethods],
  data () {
    return {
      pageName: 'allCustomer', // 请求参数
      memberId: '',
      member: {
        // 会员基础信息
        memberProtocolInfo: {
          // 会员协议信息
          visitConsentPrivacyProtocolTime: null, // 微盟访问同意协议的时间
          loginConsentPrivacyProtocolTime: null, // 微盟登录同意协议的时间
          consentPrivacyProtocolTime: null, // 达摩同意协议的时间
        },
        thirdImgUrl: '', // 头像
      },
      memberInfo: {}, // 会员卡信息
      extendInfo: {
        // 开卡字段、扩展字段
        openField: [],
        fieldList: [],
        openChildrenField: [],
        babyConfigTemplate:{}
      },
      babyStr: '', // 宝宝信息
      // 标签备注
      tagAndRemarkInfo: {
        // 会员分组
        memberGroup: {
          // 金字塔分层
          memberGradeGroup: {},
          // 客户分组
          memberTagGroupList: {},
        },
        // 手工标签
        tag: {
          tagsList: [], // 导购标签
          otherTagsList: [], // 其他标签
          weimobTagsList: [], // 微盟标签
        },
        // 导购备注
        remarkList: [],
        // 身形字段
        dictFigureList: [],
        activityTag: {
          marketingTagList: [],
          sourceTagList: []
        }
      },
      // 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: [], // 等级列表
      cliqueGradeList: [], // 集团等级列表
      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: {
            // 交易记录
            transaction: [
              { label: '客户订单', key: 'numOfCustomer', path: '/order-list?tab=store&memberId=' + this.memberId, icon: 'icon-mendianbaojiadan' },
              { label: '门店订单', key: 'numOfSale', path: '/order-list?tab=store&memberId=' + this.memberId },
              { label: '达摩微商城', key: 'wechatMallNum', path: '/order-list?tab=demo&memberId=' + this.memberId },
              { label: '微盟订单', key: 'weimobMallNum', path: '/order-list?tab=weimob&memberId=' + this.memberId },
              { label: '天猫订单', key: 'numOfTmall', path: '/order-list?tab=tmall&memberId=' + this.memberId },
              { label: '抖音订单', key: 'numOfDouYin', path: '/order-list?tab=douyin&memberId=' + this.memberId },
              { label: '其它订单', key: 'otherMallNum', path: '/order-list?tab=other&memberId=' + this.memberId },
              // {
              //   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: '/marketing-record',
              },
              {
                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: '渠道标签', key: 'sourceTagList' },
            { title: '营销活动标签', key: 'marketingTagList' },
          ],
        },
        // { title: '客户日志', name: 'log', class: 'log-info-contain' },
      ],
      marketingRecordNum: 0
    };
  },
  watch: {
    count: function (n, o) {
      if (n === 3) {
        this.fullscreenLoading = false;
        if (this.memberInfo.erpIntegralFlag && (this.memberInfo.cardNum || '').length > 0) { // cardNum为空不请求
          doFetchGet(url.getErpIntegral, { cardNo: this.memberInfo.cardNum || ''})
            .then(res => {
              if (res.data.errorCode === 0) {
                if (
                  res.data.result == null ||
                  (res.data.result + "").length <= 0
                ) {
                  this.$message.error(
                    "查询ERP积分失败，当前积分为上次同步积分，实际积分以ERP为准"
                  );
                  return;
                }
                this.memberInfo.totalPoint = res.data.result;
                this.memberInfo.accumulatPoints = res.data.result;
                this.memberInfo.invalidIntegral = 0;
              } else {
                checkFalse(res.data.message);
              }
            })
            .catch(err => {
              checkStatus(err);
            });
        }
      }
    },
  },
  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: {
    toggleShow: function() {
      if (this.showFieldType===2&&this.extendInfo&&this.extendInfo.fieldList&&this.extendInfo.fieldList.length>3)return true;
      if (this.showFieldType===1&&this.extendInfo&&this.extendInfo.openField) {
        return this.babyStr?this.extendInfo.openField.length>2:this.extendInfo.openField.length>3
      }
      return false
    },
    ...mapState(['showEditClique']),
  },
  created () {
    this.$store.commit('mutations-slide', true);
    this.memberId = this.$route.query.memberId;
    this.getMarketingRecordNum();
  },
  mounted () {
    const rightWrap = document.querySelector('.dm-layout-page');
    rightWrap.scrollTo(0, 0);
    this.initData();
    this.getEnterpriseInfo();
    this.getcodeList();
    this.getGradeList();
    this.getCliqueGradeList();
  },
  methods: {
    onCopy() {
      this.$message.success('复制成功');
    },
    initData () {
      this.count = 0;
      this.fullscreenLoading = true;
      this.getAllDetail();
      // this.getLogPage();
    },
    isOverflow(text) {
      const dom = document.createElement('span');
      dom.style.position = 'fixed';
      dom.style.zIndex = -1;
      dom.style.opacity = 0;
      dom.innerText = text;
      document.body.appendChild(dom);
      const result = dom.offsetWidth >= 72;
      // console.log(dom.offsetWidth)
      document.body.removeChild(dom);
      return result;
    },
    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') {
                ret.member.memberNameOverflow = this.isOverflow(ret.member.memberName);
                ret.member.thirdNicknameOverflow = this.isOverflow(ret.member.thirdNickname);
                this.member = Object.assign({}, ret.member);
                if (!Array.isArray(this.member.memberSources)) {
                  this.member.memberSources = [];
                }
                this.member.memberSources = this.member.memberSources.filter(el => el.highlight == 1 || el.highlight == 2);
                const extendInfo={
                  babyConfigTemplate:ret.extendInfo.babyConfigTemplate||{},
                  fieldList:ret.extendInfo.fieldList||[],
                  openChildrenField:ret.extendInfo.openChildrenField||[],
                  openField:ret.extendInfo.openField||[]
                }
                const babyArr = [];
                extendInfo.openChildrenField.forEach(el => {
                  let item = el.sonFields.find(e => e.unifiedIdentification == 'k20301');
                  babyArr.push(
                    item && item.fieldValue ? `${el.bName}（${item.fieldValue}）` : el.bName,
                  )
                });
                this.extendInfo = Object.assign({}, ret.extendInfo);
                this.babyStr = babyArr.join('；');
              }
              if (api === 'memberLoadmemberInfo') {
               
                this.memberInfo = Object.assign({}, ret.memberInfo);
                this.memberInfo.totalPoint= ret.memberInfo.invalidIntegral + ret.memberInfo.accumulatPoints;
                this.memberInfo.totalPointEnterprise= parseInt(ret.memberInfo.cliqueMemberInvalidIntegral) + parseInt(ret.memberInfo.cliqueMemberIntegral);
              }
              if (api === 'memberLoadTagDetail') {
                this.tagAndRemarkInfo = Object.assign(
                  {},
                  {
                    memberGroup: {
                      memberGradeGroup:
                        ret.tagAndRemarkInfo.memberGroup.memberGradeGroup || {},
                      memberTagGroupList:
                        ret.tagAndRemarkInfo.memberGroup.memberTagGroupList ||
                        {},
                      showMemberTagGroupList: ret.tagAndRemarkInfo.memberGroup.showMemberTagGroupList
                    },
                    tag: {
                      tagsList: ret.tagAndRemarkInfo.tag.tagsList || [],
                      otherTagsList:
                        ret.tagAndRemarkInfo.tag.otherTagsList || [],
                      weimobTagsList:
                        ret.tagAndRemarkInfo.tag.weimobTagsList || [],
                    },
                    remarkList: ret.tagAndRemarkInfo.remarkList || [],
                    dictFigureList: ret.tagAndRemarkInfo.dictFigureList || [],
                    activityTag: {
                      marketingTagList: ret.tagAndRemarkInfo.activityTag.marketingTagList || [],
                      sourceTagList: ret.tagAndRemarkInfo.activityTag.sourceTagList || [],
                    }
                  },
                );
              }
            } 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 } });
    },
    goLinkWithClique (v) {
      if (v) this.$router.push({ path: v, query: { memberId: this.memberId ,cliqueMemberId: this.memberInfo.cliqueMemberId || ''} });
    },
    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);
        });
    },
    showGradeDialog(type){
      this.isClique=type
      this.gradeDialogVisible=true;
    },
    // 等级列表
    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);
        });
    },
    // 集团等级列表
    getCliqueGradeList() {
      doFetch(url.cliqueGradeList)
        .then(res => {
          if (res.data.errorCode === 0) {
            this.cliqueGradeList = res.data.result || [];
          } else {
            checkFalse(res.data.message);
            return false;
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    async getMarketingRecordNum() {
      try {
        const param = { memberId: this.memberId };
        const res = await doFetchGet(url.getMarketingRecordNum, param);
        if (res.data.errorCode == 0) {
           this.marketingRecordNum = res.data.result || 0;
          //  console.log(this.marketingRecordNum);
        } else {
          checkFalse(res.data.message);
        }
      }catch(err) {
        checkStatus(err);
      }
    }
  },
  components: {
    baseinfoDialog,
    babyinfoDialog,
    customergradeDialog,
    customermainstoreDialog,
    customersubstoreDialog,
    customerlabelDialog,
    IconLabelValue,
    CustomerLog
  },
};
