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 } from "../../components/axios/api";
import url from "../../components/axios/url";
import { mapState } from "vuex";
import { formatLongTime, paddingBorth } from "@/utils/utils";
import defaultImg from "../../../static/img/default.png";
import authMethods from '@/mixins/auth';
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: [],
      customerTypeLabel: "", //  "非会员,微信会员,POS会员",
      customerType: [
        // { id: 1, label: "非会员" },
        // { id: 3, label: "微信会员" },
        // { id: 4, label: "POS会员" }
      ],
      oldCustomerType: "",
      showSearch: false, // 高级搜索开关
      toggleTag: false, // 人群筛选器按钮开关
      dialogFieldVisible: false, // 列表字段设置弹窗开关
      memberFields: [], // 列表字段
      checkedFields: [], // 已选列表字段
      memberFieldsName: {}, // 已选列表字段名称
      isExist: {}, // 该商户表中是否存在列表字段 判断是否支持排序
      multipleList: [],
      dialogIntegralVisible: false,
      dialogGradeVisible: false,
      dialogMainstoreVisible: false,
      dialogSubStoreVisible: false,
      selectAll: false, // 列表全选开关
      batchOpt: [
        // 批处理选项
        { value: "integral", label: "调整积分", code: "memberBatchSetIntegral" },
        { value: "grade", label: "修改等级", code: "memberBatchSetGrade" },
        { value: "mainstore", label: "修改服务门店", code: "memberBatchSetService" },
        { value: "store", label: "修改协管门店", code: "memberBatchSetCustomer" },
        { value: "batchImport", label: "批量导入", code: "memberBatchImport" }
      ],
      isdot: false, // 批量处理记录标记
      processList: [], // 批量处理记录
      defaultImg,
      integralFlag: "", // 积分调整权限
      memberGrade: [], // 商户等级列表
      cliqueMemberGrade: [], // 集团等级列表
      treeData: [
        {
          id: 1,
          label: "非会员",
          disabled: false
        },
        {
          id: 2,
          label: "会员",
          disabled: false,
          children: [
            {
              id: 3,
              label: "微信会员",
              disabled: false
            },
            {
              id: 4,
              label: "POS会员",
              disabled: false
            }
          ]
        }
      ],
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  mixins: [authMethods],
  components: {
    NavPath,
    tableColumDailog,
    integralDailog,
    gradeDailog,
    mainstoreDailog,
    substoreDailog,
    batchList
  },
  computed: {
    pageName: function() {
      // 1-非会员 notMember 3-微信会员 wxOpenCarMember 4-pos会员 posMember
      const filterObj = {
        1: "notMember",
        3: "wxOpenCarMember",
        4: "posMember"
      };
      const list = [];
      this.customerType.forEach(el => {
        list.push(filterObj[el.id]);
      });
      return list.length
        ? list.join(",")
        : "notMember,wxOpenCarMember,posMember";
    },
    selectObj: function() {
      return {
        selectAll: this.selectAll,
        multipleList: this.multipleList,
        totalCount: this.totalCount
      };
    },
    ajaxObj: function() {
      return { ...this.pageParam, pageName: this.pageName };
    },
    ...mapState(["storeImageUrl", "showEditClique"])
  },
  filters: {
    sexFilter: function(v) {
      switch (v) {
        case 1:
          return "男";
        case 2:
          return "女";
        default:
          return "--";
      }
    }
  },
  watch: {
    customerType: {
      handler(newV, oldV) {
        if (newV.length === 0 && this.$refs.tree) {
          this.$message.error("至少选择一个客户类型");
          this.$refs.tree.setChecked(oldV[0].id, true, true);
          this.$nextTick(_ => {
            this.handleCheckChange();
          });
        } else if (oldV.length === 0) {
          return false;
        } else {
          this.onSearch();
        }
      },
      deep: 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();
    // 默认勾选全部客户类型 1-非会员 notMember 3-微信会员 wxOpenCarMember 4-pos会员 posMember
    this.$refs.tree.setCheckedNodes(this.treeData);
    this.$nextTick(_ => {
      this.handleCheckChange();
    });
  },
  beforUpdate() {},
  methods: {
    selectChange(e) {
      const arrNew = [];
      const dataLength = this.customerType.length;
      const eleng = e.length;
      for (let i = 0; i < dataLength; i++) {
        for (let j = 0; j < eleng; j++) {
          if (e[j] === this.customerType[i].label) {
            arrNew.push(this.customerType[i]);
          }
        }
      }
      this.$refs.tree.setCheckedNodes(arrNew);
      this.$nextTick(_ => {
        this.handleCheckChange();
      });
    },
    handleCheckChange(data, nodes) {
      const res = this.$refs.tree.getCheckedNodes(true, true); // 这里两个true，1. 是否只是叶子节点 2. 是否包含半选节点（就是使得选择的时候不包含父节点）
      const arrLabel = [];
      const arr = [];
      res.forEach(item => {
        item.disabled = false;
        arrLabel.push(item.label);
        arr.push(item);
      });
      if (res.length === 1) {
        res[0].disabled = true;
      }
      this.customerType = [].concat(arr);
      this.customerTypeLabel = [].concat(arrLabel);
    },
    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"
                ];
            this.isExist = Object.assign({}, res.data.result.fields || {});
            // 首先先保存数据 某些品牌的数据返回的很慢
            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)) {
            const tempArr = [].concat(res.data.result);
            const memberFields = [];
            const 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.tableData.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;
            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);
        });
    }
  }
};
