import NavPath from "@/common/navbar/navbar.vue";
import tableColumDailog from "./components/tableColumDialog.vue";
import integralDailog from "./components/integralDialog.vue";
import gradeDailog from "./components/batchgradeDialog.vue";
import mainstoreDailog from "./components/mainstoreDialog.vue";
import substoreDailog from "./components/substoreDialog.vue";
import batchList from "./components/batchList.vue";
import { doFetch, doFetchqs } from "../../components/axios/api";
import url from "../../components/axios/url";
import { mapState } from "vuex";
import { formatLongTime, paddingBorth, debounce } from "@/utils/utils";
import defaultImg from "../../../static/img/default.png";
import {
  checkFalse,
  checkStatus,
  checkSuccess
} from "../../../static/js/checkStatus";
export default {
  name: "allCustomersList",
  data() {
    return {
      sceneValue: "member", // 人群筛选器场景值
      navpath: [
        { name: "首页", path: "" },
        { name: "客户列表", path: "" },
        { name: "全部客户", path: "" }
      ],
      pageParam: {
        currentPage: 1,
        pageSize: 20,
        phoneNameCard: "", // 搜索字段
        memberSearchStr: -1, // 人群筛选
        sortColName: "", // 排序字段
        sortType: "" // 排序方式
      },
      totalCount: 0,
      loading: false,
      tableData: [],
      multipleList: [], // 列表select选择
      customerType: ["notMember", "wxOpenCarMember", "posMember"],
      oldCustomerType: "",
      showSearch: false, // 高级搜索开关
      toggleTag: false, // 人群筛选器按钮开关
      dialogFieldVisible: false, // 列表字段设置弹窗开关
      memberFields: [], // 列表字段
      checkedFields: [], // 已选列表字段
      memberFieldsName: {}, // 已选列表字段名称
      dialogIntegralVisible: false,
      dialogGradeVisible: false,
      dialogMainstoreVisible: false,
      dialogSubStoreVisible: false,
      selectAll: false, // 列表全选开关
      multipleList: [], // 列表已选客户
      batchOpt: [
        // 批处理选项
        { value: "grade", label: "修改等级" },
        { value: "mainstore", label: "修改服务门店" },
        { value: "store", label: "修改协管门店" },
        { value: "batchImport", label: "批量导入" }
      ],
      isdot: false, // 批量处理记录标记
      processList: [], // 批量处理记录
      defaultImg,
      integralFlag: "", // 积分调整权限
      memberGrade: [], // 商户等级列表
      cliqueMemberGrade: [] // 集团等级列表
    };
  },
  components: {
    NavPath,
    tableColumDailog,
    integralDailog,
    gradeDailog,
    mainstoreDailog,
    substoreDailog,
    batchList
  },
  computed: {
    pageName: function() {
      // 全部客户allCustomer；非会员notMember；会员isMember；微信会员wxOpenCarMember，pos会员posMember
      return this.customerType.join(",");
    },
    selectObj: function() {
      return {
        selectAll: this.selectAll,
        multipleList: this.multipleList,
        totalCount: this.totalCount
      };
    },
    ajaxObj: function() {
      return { ...this.pageParam, pageName: this.pageName };
    },
    ...mapState(["storeImageUrl", "showEditClique", "showHandleScoreBtn"])
  },
  filters: {
    sexFilter: function(v) {
      switch (v) {
        case 1:
          return "男";
          break;
        case 2:
          return "女";
          break;
        default:
          return "性别未知";
          break;
      }
    }
  },
  watch: {
    customerType: {
      handler(newV, oldV) {
        if (newV.length === 0) {
          this.customerType = [].concat(oldV);
          this.$message({
            message: "客户类型不能为空",
            type: "warning"
          });
        }
      },
      immediate: true
    },
    $route: function(n, o) {
      if (n.path === "/allCustomers")
        this.$store.commit("mutations-slide", true);
    }
  },
  created() {
    this.$store.commit("mutations-slide", true);
    this.initialize();
    this.getGradeList();
    this.getCliqueGradeList();
  },
  mounted() {
    this.getFindMemberFields();
    this.getAjaxMembers();
    this.getEnterpriseInfo();
  },
  beforUpdate() {},
  methods: {
    initialize() {
      this.pageParam.phoneNameCard = !!sessionStorage.getItem("phoneNameCard")
        ? sessionStorage.getItem("phoneNameCard")
        : "";
      this.pageParam.currentPage = !!sessionStorage.getItem("currentPage")
        ? sessionStorage.getItem("currentPage")
        : 1;
    },
    handleCurrentChange(val) {
      this.pageParam.currentPage = val;
      sessionStorage.setItem("currentPage", val);
      this.getAjaxMembers();
    },
    handleSizeChange(val) {
      this.pageParam.pageSize = val;
      this.getAjaxMembers();
    },
    onSearch() {
      this.pageParam.currentPage = 1;
      this.getAjaxMembers();
    },
    // 获取列表数据
    getAjaxMembers() {
      this.loading = true;
      this.selectAll = false;
      doFetch(
        url.ajaxMembers,
        Object.assign({}, this.pageParam, {
          pageName: this.pageName,
          showFields: "-1"
        })
      )
        .then(res => {
          this.loading = false;
          if (res.data.errorCode === 0 && res.data.result) {
            this.checkedFields = res.data.result.fieldsStr
              ? res.data.result.fieldsStr.split(",")
              : [
                  "name",
                  "grade",
                  "status",
                  "channel",
                  "costAll",
                  "costTimes",
                  "lastCostTime",
                  "attentionDate"
                ];
            // 首先先保存数据 某些品牌的数据返回的很慢
            const resultData = res.data.result.page
              ? res.data.result.page.result
              : [];
            let tableData = [];
            if (resultData.length) {
              tableData = resultData.map(ele => ({
                ...ele,
                avgNumber: ele.avgNumber.toFixed(2),
                lastCostTime:
                  ele.lastCostTime != -1
                    ? formatLongTime(ele.lastCostTime, 2)
                    : "--", // 最近消费时间
                createTime:
                  ele.createTime != -1
                    ? formatLongTime(ele.createTime, 1)
                    : "--", // 新增时间
                attentionDate:
                  ele.attentionDate != -1
                    ? formatLongTime(ele.attentionDate, 1)
                    : "--", // 关注时间
                cancelAttentionTime:
                  ele.cancelAttentionTime != -1
                    ? formatLongTime(ele.cancelAttentionTime, 1)
                    : "--", // 取关时间
                attentionTime:
                  ele.attentionTime != -1
                    ? formatLongTime(ele.attentionTime, 1)
                    : "--", // 关注时间
                crateCardDateString:
                  ele.crateCardDateString != -1
                    ? formatLongTime(ele.crateCardDateString, 1)
                    : "--", // 开卡
                birthdayMD:
                  ele.birthdayMD != 0 ? paddingBorth(ele.birthdayMD) : "--", // 生日补全
                sex: ele.sex == 0 ? "性别未知" : ele.sex == 1 ? "男" : "女",
                age: !!ele.age ? ele.age : "年龄未知",
                cardNo: !!ele.cardNo ? ele.cardNo : "无会员卡",
                mainStoreName: !!ele.mainStoreName
                  ? ele.mainStoreName
                  : "主门店未知",
                thirdImgUrl: ele.thirdImgUrl
                  ? ele.thirdImgUrl
                  : this.storeImageUrl
              }));
            }
            this.pageParam.currentPage = res.data.result.page.currentPage;
            this.totalCount = res.data.result.page.totalCount;
            this.tableData = [].concat(tableData);
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        })
        .finally(_ => (this.loading = false));
    },
    getFindMemberFields() {
      doFetch(url.findMemberFields, {
        pageName: this.pageName
      })
        .then(res => {
          if (res.data.errorCode === 0 && Array.isArray(res.data.result)) {
            let tempArr = [].concat(res.data.result);
            let memberFields = [];
            let memberFieldsName = [];
            tempArr.forEach(item => {
              memberFieldsName[item.code] = item.name;
              memberFields.push(item);
            });
            this.memberFields = [].concat(memberFields);
            this.memberFieldsName = Object.assign({}, memberFieldsName);
            // this.$nextTick(_ => {
            // });
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    submitMemberFields(v) {
      doFetch(url.updateFields, {
        pageName: this.pageName,
        fields: v
      })
        .then(res => {
          if (res.data.errorCode === 0) {
            checkSuccess();
            this.checkedFields = v.split(",");
            this.getAjaxMembers();
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    // 处理table 全选事件
    handleSelectAlll(val) {
      if (!val.length) this.selectAll = false;
    },
    // 处理table select事件
    handleSelectionChange(val) {
      if (val.length !== this.pageParam.pageSize) this.selectAll = false;
      this.multipleList = val;
    },
    // 处理table 排序事件
    sortChange(column, prop, order) {
      this.pageParam.sortColName = column.prop;
      if (column.order === "descending") {
        this.pageParam.sortType = "desc";
      }
      if (column.order === "ascending") {
        this.pageParam.sortType = "asc";
      }
      this.getAjaxMembers();
    },
    // 人群筛选器 - 校验与提交筛选结果
    getData() {
      this.$refs.peopleFilter.confirmSet();
    },
    // 人群筛选器 - 子组件触发父组件事件,返回过滤条件数据
    findFilter(value) {
      this.pageParam.memberSearchStr = !value ? -1 : value;
      this.onSearch();
    },
    // 人群筛选器 - 显示按钮
    editShow() {
      this.toggleTag = true;
    },
    // 人群筛选器 - 确认好选择条件之后 隐藏按钮
    editHide() {
      this.toggleTag = false;
    },
    // 人群筛选器 - 隐藏保存按钮和确认按钮  (子组件会调用)
    hideBtn(refresh) {
      if (refresh == 0) {
        this.pageParam.memberSearchStr = -1;
        this.getAjaxMembers();
        this.toggleTag = false;
      }
    },
    // 人群筛选器 - 取消人群筛选
    cancelFilter() {
      this.$refs.peopleFilter.cancelSet();
      this.toggleTag = false;
    },
    // 客户列表选择
    selectAllmultipleList() {
      this.selectAll = !this.selectAll;
      if (this.selectAll) {
        this.memberData.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 批量处理
    handleFocusBatch(val) {
      if (this.batchValue == "batchImport") {
        // 批量导入
        this.batchValue = "";
        this.$router.push({ path: "/bulkIntegral" });
      } else if (this.multipleList.length < 1) {
        this.batchValue = "";
        checkFalse("请勾选会员");
        return false;
      }
      if (this.batchValue == "integral") {
        this.dialogIntegralVisible = true;
      } else if (this.batchValue == "grade") {
        this.dialogGradeVisible = true;
      } else if (this.batchValue == "mainstore") {
        this.dialogMainstoreVisible = true;
      } else if (this.batchValue == "store") {
        this.dialogSubStoreVisible = true;
      }
      this.batchValue = "";
    },
    batchRefresh() {
      this.getAjaxMembers();
      this.getProcessList();
    },
    getGradeList() {
      doFetch(url.gradeList)
        .then(res => {
          if (res.data.errorCode === 0) {
            this.memberGrade = 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.cliqueMemberGrade = res.data.result || [];
          } else {
            checkFalse(res.data.message);
            return false;
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    // 在经过批量处理之后调用
    getProcessList() {
      if (this.timer) clearInterval(this.timer);
      doFetch(url.batchProcess)
        .then(res => {
          if (res.data.errorCode === 0) {
            this.isdot = res.data.result.list.length > 0 ? true : false;
            this.popWidth = this.isdot ? this.popWidth : 160;
            if (!this.processList.length && !res.data.result.list.length)
              return;
            this.processList = res.data.result.list.map(ele => ({
              ...ele,
              name: ele.name ? ele.name : "未知"
            }));
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    linkDetail(memberId) {
      this.$router.push({
        path: "/customerDetail",
        query: { memberId }
      });
    },
    getEnterpriseInfo() {
      doFetch(url.enterpriseInfo)
        .then(res => {
          if (res.data.errorCode == 0) {
            this.integralFlag = res.data.result.enterpriseInfo.integralFlag;
          } else {
            checkFalse();
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    }
  }
};
